text:
<?php namespace SkypeForBusiness;

use SkypeForBusiness\Base;

class InitConnection extends Base
{

	/*************************************************
	//	Constructor
	*************************************************/
	function __construct($fqdn, Array $config = []) {

		// to start with, let's pass any configuration values into the base class
		parent::__construct($config);

		// FQDN
		if ( !empty( $fqdn ) ) {
			$link = parse_url($fqdn);
			self::$ucwa_fqdn = $link["scheme"] . "://" . $link["host"];
		}

		// Do AutoDiscover
		if ( self::autodiscover() ) {
			// Get OAuth URL
			if ( !self::getOauthLink() ) {
				return false;
			}
		} else {
			return false;
		}
	}

	/*************************************************
	//	Main methods
	*************************************************/

	/*
	 *	(bool) autodiscover()
	 *	######################################
	 *
	 *	Discovers the required URL's automatically
	*/
	private static function autodiscover() {
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_HEADER => false,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_URL => self::$ucwa_autodiscover,
			CURLOPT_HTTPHEADER => array(
				"Accept: application/json",
				"X-Ms-Origin: " . self::$ucwa_fqdn,
			),
			CURLOPT_TIMEOUT => 15,
		));

		$response = curl_exec($curl);
		$status = curl_getinfo($curl);
		curl_close($curl);

		if ($status["http_code"] == 200) {
			$data = json_decode($response, true);
			$link_usr = parse_url($data["_links"]["user"]["href"]);
			$link_frm = parse_url($data["_links"]["xframe"]["href"]);

			self::$ucwa_baseserver = $link_usr["scheme"] . "://" . (substr($link_usr["host"], -1) == "/" ? substr($link_usr["host"], 0, -1) : $link_usr["host"]);
			self::$ucwa_path_user = ( substr($link_usr["path"], 0, 1) == "/" ? "" : "/" ) . $link_usr["path"] . "?" . $link_usr["query"];
			self::$ucwa_path_xframe = ( substr($link_frm["path"], 0, 1) == "/" ? "" : "/" ) . $link_frm["path"];

			return true;
		} else {
			self::_error("Can't automatically detect user url. Autodiscover failed.", $status);
		}
	}

	/*
	 *	(bool) getOauthLink()
	 *	######################################
	 *
	 *	Get the OAuth link from the
	 *	(unauthorized) "user" site
	*/
	private static function getOauthLink() {
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_HEADER => true,
			CURLOPT_NOBODY => true,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_URL => self::$ucwa_baseserver . self::$ucwa_path_user,
			CURLOPT_REFERER => self::$ucwa_baseserver . self::$ucwa_path_xframe,
			CURLOPT_HTTPHEADER => array(
				"Accept: application/json",
				"X-Ms-Origin: " . self::$ucwa_fqdn,
			),
			CURLOPT_TIMEOUT => 15,
		));

		$response = curl_exec($curl);
		$status = curl_getinfo($curl);
		curl_close($curl);

		if ($status["http_code"] == 401) {
			preg_match('/href=["\']?([^"\'>]+)["\']?/', $response, $match);
			$link = parse_url( $match[1] );

			self::$ucwa_path_oauth = (substr($link["path"], 0, 1) == "/" ? "" : "/") . $link["path"];
			return true;
		} else {
			self::_error("Can't get OAuth-Link.", $status);
		}
	}

	/*
	 *	(bool) getApplicationLink()
	 *	######################################
	 *
	 *	Get the application link and check,
	 *	if the Skype "Pool" for the authorized
	 *	user is the same as the autodiscover
	 *	pool.
	*/
	private static function getApplicationLink() {
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_HEADER => false,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_URL => self::$ucwa_baseserver . self::$ucwa_path_user,
			CURLOPT_REFERER => self::$ucwa_baseserver . self::$ucwa_path_xframe,
			CURLOPT_HTTPHEADER => array(
				"Accept: application/json",
				"Authorization: Bearer " . self::$ucwa_accesstoken,
				"X-Ms-Origin: " . self::$ucwa_fqdn,
			),
			CURLOPT_TIMEOUT => 15,
		));

		$response = curl_exec($curl);
		$status = curl_getinfo($curl);
		curl_close($curl);

		if ($status["http_code"] == 200) {
			$data = json_decode($response, true);
			$link = parse_url($data["_links"]["applications"]["href"]);

			self::$ucwa_path_application = $link["path"] . (isset($link["query"]) ? '?' . $link["query"] : '');

			// Check if Hostname is the same
			if ( self::$ucwa_baseserver != $link["scheme"] . "://" . ( substr($link["host"], -1) == "/" ? substr($link["host"], 0, -1) : $link["host"] ) ) {
				// Hostname different!
				// New access token
				self::$ucwa_baseserver = $link["scheme"] . "://" . ( substr($link["host"], -1) == "/" ? substr($link["host"], 0, -1) : $link["host"] );

				if ( self::getAccessToken(self::$ucwa_user, self::$ucwa_pass) ) {
					return true;
				} else {
					self::_error("Hostname changed (application resource) => requested new access token => failed.", array());
					return false;
				}
			} else {
				return true;
			}
		} else {
			self::_error("Can't get applications link for Skype UCWA", $status);
			return false;
		}
	}

	/*
	 *	(bool) getAccessToken()
	 *	######################################
	 *
	 *	Authorizes the sender and stores
	 *	the access token.
	*/
	public static function getAccessToken($username, $password) {
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_HEADER => false,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_URL => self::$ucwa_baseserver . self::$ucwa_path_oauth,
			CURLOPT_REFERER => self::$ucwa_baseserver . self::$ucwa_path_xframe,
			CURLOPT_POST => true,
			CURLOPT_POSTFIELDS => array(
				"grant_type" => "password",
				"username" => $username,
				"password" => $password,
			),
			CURLOPT_HTTPHEADER => array(
				"Accept: application/json",
				"X-Ms-Origin: " . self::$ucwa_fqdn,
			),
			CURLOPT_TIMEOUT => 15,
		));

		$response = curl_exec($curl);
		$status = curl_getinfo($curl);
		curl_close($curl);

		if ($status["http_code"] == 200) {
			$data = json_decode($response, true);
			self::$ucwa_accesstoken = $data["access_token"];
			self::$ucwa_user = $username;
			self::$ucwa_pass = $password;

			// Get application link
			return self::getApplicationLink();
		} else {
			self::_error("Can't get an access token for Skype UCWA", $status);
			return false;
		}
	}
}

?>


text:
package store

import (
	"testing"
)

func TestMapStore(t *testing.T) {
	testMap := map[string]interface{}{
		"test1key": "test1value",
	}

	storage := MapStore{}

	// creates the document set in the storage
	_, err := storage.Open("test")

	id, err := storage.PutDocument("test", testMap)
	if err != nil {
		t.Errorf("Expected to store test document without error: %s.", id)
	}

	testMap, err = storage.GetDocument("test", id)
	if err != nil || testMap["test1key"] != "test1value" {
		t.Errorf("Expected to retreieve test document without error.")
	}

	err = storage.DeleteDocument("test", id)
	if err != nil {
		t.Errorf("Expected to retreieve test document without error.")
	}
}

redpajama_set_name: RedPajamaGithub


text:
/*===============================================================================
************   Accordion   ************
===============================================================================*/
/* global Zepto:true */
+function ($) {
  "use strict";

$.accordionToggle = function (item) {
    item = $(item);
    if (item.length === 0) return;
    if (item.hasClass('accordion-item-expanded')) $.accordionClose(item);
    else $.accordionOpen(item);
};
$.accordionOpen = function (item) {
    item = $(item);
    var list = item.parents('.accordion-list').eq(0);
    var content = item.children('.accordion-item-content');
    if (content.length === 0) content = item.find('.accordion-item-content');
    var expandedItem = list.length > 0 && item.parent().children('.accordion-item-expanded');
    if (expandedItem.length > 0) {
        $.accordionClose(expandedItem);
    }
    content.css('height', content[0].scrollHeight + 'px').transitionEnd(function () {
        if (item.hasClass('accordion-item-expanded')) {
            //content.transition(0);
            //content.css('height', 'auto');
            //var clientLeft = content[0].clientLeft;
            //content.transition('');
            item.trigger('opened');
        }
        else {
            content.css('height', '');
            item.trigger('closed');
        }
    });
    item.trigger('open');
    item.addClass('accordion-item-expanded');
};
$.accordionClose = function (item) {
    item = $(item);
    var content = item.children('.accordion-item-content');
    if (content.length === 0) content = item.find('.accordion-item-content');
    item.removeClass('accordion-item-expanded');
    //content.transition(0);
    content.css('height', content[0].scrollHeight + 'px');
    // Relayout
    //var clientLeft = content[0].clientLeft;
    // Close
    //content.transition('');
    content.css('height', '').transitionEnd(function () {
        if (item.hasClass('accordion-item-expanded')) {
            //content.transition(0);
            //content.css('height', 'auto');
            //var clientLeft = content[0].clientLeft;
            //content.transition('');
            item.trigger('opened');
        }
        else {
            content.css('height', '');
            item.trigger('closed');
        }
    });
    item.trigger('close');
};

$(document).on("click", ".accordion-item .item-content, .accordion-item-toggle", function(e) {
    e.preventDefault();
    var clicked = $(this);
    // Accordion
    if (clicked.hasClass('accordion-item-toggle') || (clicked.hasClass('item-link') && clicked.parent().hasClass('accordion-item'))) {
        var accordionItem = clicked.parent('.accordion-item');
        if (accordionItem.length === 0) accordionItem = clicked.parents('.accordion-item');
        if (accordionItem.length === 0) accordionItem = clicked.parents('li');
        $.accordionToggle(accordionItem);
    }
});
}(Zepto);


text:
<?php

/* AcmeJqueryBundle:Default:ajax.html.twig */
class __TwigTemplate_0eebe487cc8922d651f36591dd0c88fc extends Twig_Template
{
    protected $parent;

    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->blocks = array(
            'head' => array($this, 'block_head'),
            'content' => array($this, 'block_content'),
        );
    }

    public function getParent(array $context)
    {
        if (null === $this->parent) {
            $this->parent = $this->env->loadTemplate("AcmeJqueryBundle::layout.html.twig");
        }

        return $this->parent;
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $context = array_merge($this->env->getGlobals(), $context);

        // line 21
        $context['code'] = $this->env->getExtension('demo')->getCode($this);
        $this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_head($context, array $blocks = array())
    {
        // line 4
        echo "    ";
        echo $this->renderParentBlock("head", $context, $blocks);
        echo "

";
    }

    // line 14
    public function block_content($context, array $blocks = array())
    {
        // line 15
        echo "
Ajax

Let AJAX change this text

    <button>Change Content</button>
";
    }

    public function getTemplateName()
    {
        return "AcmeJqueryBundle:Default:ajax.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}


text:
package com.strobel.expressions;

import com.strobel.core.StringUtilities;
import com.strobel.functions.Block;
import com.strobel.reflection.MemberInfo;
import com.strobel.reflection.PrimitiveTypes;
import com.strobel.reflection.Type;
import com.strobel.reflection.Types;
import com.strobel.util.ContractUtils;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.IdentityHashMap;
import java.util.Map;

import static java.lang.String.format;

final class DebugViewWriter extends ExpressionVisitor {
    private final static int FLOW_NONE = 0x0000;
    private final static int FLOW_SPACE = 0x0001;
    private final static int FLOW_NEW_LINE = 0x0002;
    private final static int FLOW_BREAK = 0x8000;

    private final static int TAB_SIZE = 4;
    private final static int MAX_COLUMN = 160;

    private final StringBuilder _out;

    private int _column;
    private int _delta;
    private int _flow;

    private DebugViewWriter(final StringBuilder out) {
        _out = out;
    }

    // All the unique lambda expressions in the ET, will be used for displaying all
    // the lambda definitions.
    private final Deque<LambdaExpression> _lambdas = new ArrayDeque<>();

    // Associate every unique anonymous LambdaExpression in the tree with an integer.
    // The id is used to create a name for the anonymous lambda.
    //
    private final Map<LambdaExpression, Integer> _lambdaIds = new IdentityHashMap<>();

    // Associate every unique anonymous parameter or variable in the tree with an integer.
    // The id is used to create a name for the anonymous parameter or variable.
    //
    private final Map<ParameterExpression, Integer> _paramIds = new IdentityHashMap<>();

    // Associate every unique anonymous LabelTarget in the tree with an integer.
    // The id is used to create a name for the anonymous LabelTarget.
    //
    private final Map<LabelTarget, Integer> _labelIds = new IdentityHashMap<>();

    private final Block<? extends Expression> VISITOR_BLOCK = new Block<Expression>() {
        @Override
        public void accept(final Expression input) {
            visit(input);
        }
    };

    @SuppressWarnings("unchecked")
    private <T extends Expression> Block<T> visitorBlock() {
        return (Block<T>) VISITOR_BLOCK;
    }

    private int base() {
        return 0;
    }

    private int delta() {
        return _delta;
    }

    private int depth() {
        return base() + delta();
    }

    private void indent() {
        _delta += TAB_SIZE;
    }

    private void unindent() {
        _delta = Math.max(0, _delta - TAB_SIZE);
    }

    private void newLine() {
        _flow = FLOW_NEW_LINE;
    }

    // <editor-fold defaultstate="collapsed" desc="Unique ID Management">

    private static <T> int getId(final T e, final Map<T, Integer> ids) {
        Integer id = ids.get(e);
        if (id == null) {
            // e is met the first time
            id = ids.size() + 1;
            ids.put(e, id);
        }
        return id;
    }

    private int getLambdaId(final LambdaExpression le) {
        assert StringUtilities.isNullOrEmpty(le.getName());
        return getId(le, _lambdaIds);
    }

    private int getParamId(final ParameterExpression p) {
        assert StringUtilities.isNullOrEmpty(p.getName());
        return getId(p, _paramIds);
    }

    private int getLabelTargetId(final LabelTarget target) {
        assert StringUtilities.isNullOrEmpty(target.getName());
        return getId(target, _labelIds);
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Output Methods">

    private void out(final char c) {
        out(FLOW_NONE, c, FLOW_NONE);
    }

    private void out(final char c, final int after) {
        out(FLOW_NONE, c, after);
    }

    private void out(final int before, final char c, final int after) {
        switch (getFlow(before)) {
            case FLOW_NONE:
                break;
            case FLOW_SPACE:
                write(" ");
                break;
            case FLOW_NEW_LINE:
                writeLine();
                write(StringUtilities.repeat(' ', depth()));
                break;
        }

        write(c);

        _flow = after;
    }

    private void out(final String s) {
        out(FLOW_NONE, s, FLOW_NONE);
    }

    private void out(final int before, final String s) {
        out(before, s, FLOW_NONE);
    }

    private void out(final String s, final int after) {
        out(FLOW_NONE, s, after);
    }

    private void out(final int before, final String s, final int after) {
        switch (getFlow(before)) {
            case FLOW_NONE:
                break;
            case FLOW_SPACE:
                write(" ");
                break;
            case FLOW_NEW_LINE:
                writeLine();
                write(StringUtilities.repeat(' ', depth()));
                break;
        }

        write(s);

        _flow = after;
    }

    private void outMember(final Expression node, final Expression instance, final MemberInfo member) {
        if (instance != null) {
            parenthesizedVisit(node, instance);
            out("." + member.getName());
        }
        else {
            // For static members, include the type name
            out(member.getDeclaringType().toString() + "." + member.getName());
        }
    }

    private void writeLine() {
        _out.append(System.lineSeparator());
        _column = 0;
    }

    private void write(final String s) {
        _out.append(s);
        _column += s.length();
    }

    private void write(final char c) {
        _out.append(c);
        _column++;
    }

    private int getFlow(int flow) {
        final int last;

        last = checkBreak(_flow);
        flow = checkBreak(flow);

        // Get the biggest flow that is requested None < Space < NewLine
        return Math.max(last, flow);
    }

    private int checkBreak(int flow) {
        if ((flow & FLOW_BREAK) != 0) {
            if (_column > (MAX_COLUMN + depth())) {
                flow = FLOW_NEW_LINE;
            }
            else {
                flow &= ~FLOW_BREAK;
            }
        }
        return flow;
    }

    // </editor-fold>

    static void writeTo(final Expression node, final StringBuilder writer) {
        assert node != null;
        assert writer != null;

        new DebugViewWriter(writer).writeTo(node);
    }

    private void writeTo(final Expression node) {
        if (node instanceof LambdaExpression<?>) {
            writeLambda((LambdaExpression<?>) node);
        }
        else {
            visit(node);
        }

        //
        // Output all lambda expression definitions.
        // in the order of their appearances in the tree.
        //
        while (!_lambdas.isEmpty()) {
            writeLine();
            writeLine();
            writeLambda(_lambdas.removeFirst());
        }
    }

    private void writeLambda(final LambdaExpression lambda) {
        out(
            format(
                ".Lambda %s<%s>",
                getLambdaName(lambda),
                lambda.getType()
            )
        );

        visitDeclarations(lambda.getParameters());

        out(FLOW_SPACE, "{", FLOW_NEW_LINE);
        indent();
        visit(lambda.getBody());
        unindent();
        out(FLOW_NEW_LINE, "}");
    }

    private <T extends Expression> void visitExpressions(final char open, final ExpressionList<T> expressions) {
        visitExpressions(open, ',', expressions);
    }

    private <T extends Expression> void visitExpressions(final char open, final char separator, final ExpressionList<T> expressions) {
        visitExpressions(open, separator, expressions, this.<T>visitorBlock());
    }

    private void visitDeclarations(final ExpressionList<ParameterExpression> expressions) {
        visitExpressions(
            '(', ',',
            expressions,
            new Block<ParameterExpression>() {
                @Override
                public void accept(final ParameterExpression variable) {
                    out(variable.getType().toString());
                    out(" ");
                    visitParameter(variable);
                }
            }
        );
    }

    private <T extends Expression> void visitExpressions(final char open, final char separator, final ExpressionList<T> expressions, final Block<T> visit) {
        out(open);

        if (expressions != null) {
            indent();

            boolean isFirst = true;

            for (final T e : expressions) {
                if (isFirst) {
                    if (open == '{' || expressions.size() > 1) {
                        newLine();
                    }
                    isFirst = false;
                }
                else {
                    out(separator, FLOW_NEW_LINE);
                }
                visit.accept(e);
            }

            unindent();
        }

        final char close;

        switch (open) {
            case '(':
                close = ')';
                break;
            case '{':
                close = '}';
                break;
            case '[':
                close = ']';
                break;
            case '<':
                close = '>';
                break;
            default:
                throw ContractUtils.unreachable();
        }

        if (open == '{') {
            newLine();
        }

        out(close, FLOW_BREAK);
    }

    private void writeLabel(final LabelTarget target) {
        out(format(".LabelTarget %s:", getLabelTargetName(target)));
    }
    // <editor-fold defaultstate="collapsed" desc="Helper Methods">

    private static boolean isSimpleExpression(final Expression node) {
        if (node instanceof BinaryExpression) {
            final BinaryExpression binary = (BinaryExpression) node;

            return !(binary.getLeft() instanceof BinaryExpression ||
                     binary.getRight() instanceof BinaryExpression);
        }

        return false;
    }

    private static String getConstantValueSuffix(final Type<?> type) {
        if (type.isPrimitive()) {
            switch (type.getKind()) {
                case BYTE:
                    return "b";
                case SHORT:
                    return "s";
                case LONG:
                    return "L";
                case FLOAT:
                    return "f";
                case DOUBLE:
                    return "d";
            }
        }
        else if (type == Types.BigDecimal) {
            return "m";
        }
        return null;
    }

    private static boolean containsWhiteSpace(final String name) {
        for (int i = 0, n = name.length(); i < n; i++) {
            if (Character.isWhitespace(name.charAt(i))) {
                return true;
            }
        }
        return false;
    }

    private static String quoteName(final String name) {
        return format("'%s'", name);
    }

    private static String getDisplayName(final String name) {
        if (containsWhiteSpace(name)) {
            //
            // Quote names containing whitespace.
            //
            return quoteName(name);
        }
        else {
            return name;
        }
    }

    private String getLambdaName(final LambdaExpression lambda) {
        if (StringUtilities.isNullOrEmpty(lambda.getName())) {
            return "#Lambda" + getLambdaId(lambda);
        }
        return getDisplayName(lambda.getName());
    }

    private String getLabelTargetName(final LabelTarget target) {
        if (StringUtilities.isNullOrEmpty(target.getName())) {
            // Create the label target name as #Label1, #Label2, etc.
            return format("#Label%s", getLabelTargetId(target));
        }
        else {
            return getDisplayName(target.getName());
        }
    }

    private String arrayToString(final Object value) {
        final Type<Object> type = Type.getType(value);

        if (!type.isArray()) {
            return value.toString();
        }

        switch (type.getKind()) {
            case BOOLEAN:
                return Arrays.toString((boolean[]) value);
            case BYTE:
                return Arrays.toString((byte[])value);
            case SHORT:
                return Arrays.toString((short[])value);
            case INT:
                return Arrays.toString((int[])value);
            case LONG:
                return Arrays.toString((long[])value);
            case CHAR:
                return Arrays.toString((char[])value);
            case FLOAT:
                return Arrays.toString((float[])value);
            case DOUBLE:
                return Arrays.toString((double[])value);
            default:
                return Arrays.toString((Object[])value);
        }
    }

    private void parenthesizedVisit(final Expression parent, final Expression nodeToVisit) {
        if (needsParentheses(parent, nodeToVisit)) {
            out("(");
            visit(nodeToVisit);
            out(")");
        }
        else {
            visit(nodeToVisit);
        }
    }

    private static boolean needsParentheses(final Expression parent, final Expression child) {
        assert parent != null;

        if (child == null) {
            return false;
        }

        //
        // Some nodes always have parentheses because of how they are displayed, for example:
        // ".Unbox(obj.Foo)"
        //
        switch (parent.getNodeType()) {
            case Increment:
            case Decrement:
            case IsTrue:
            case IsFalse:
            case Unbox:
            case Convert:
                return true;
        }

        final int childOpPrecedence = getOperatorPrecedence(child);
        final int parentOpPrecedence = getOperatorPrecedence(parent);

        if (childOpPrecedence == parentOpPrecedence) {
            //
            // When parent op and child op has the same precedence, we want to be a little
            // conservative to have more clarity.  Parentheses are not needed if:
            //
            //   1) Both ops are &&, ||, &, |, or ^, all of them are the only op that has
            //      the precedence.
            //
            //   2) Parent op is + or *, e.g. x + (y - z) can be simplified to x + y - z.
            //
            //   3) Parent op is -, / or %, and the child is the left operand.  In this case,
            //      if left and right operand are the same, we don't remove parenthesis,
            //      e.g., (x + y) - (x + y)
            //
            switch (parent.getNodeType()) {
                case AndAlso:
                case OrElse:
                case And:
                case Or:
                case ExclusiveOr:
                    // Since these ops are the only ones on their precedence,
                    // the child op must be the same.
                    assert child.getNodeType() == parent.getNodeType();
                    // We remove the parenthesis, e.g. x && y && z
                    return false;

                case Add:
                case Multiply:
                    return false;

                case Subtract:
                case Divide:
                case Modulo:
                    assert parent instanceof BinaryExpression;
                    final BinaryExpression binary = (BinaryExpression) parent;
                    // Need to have parenthesis for the right operand.
                    return child == binary.getRight();
            }

            return true;
        }

        //
        // Special case: negate of a constant needs parentheses, to
        // disambiguate it from a negative constant.
        //
        if (child.getNodeType() == ExpressionType.Constant &&
            parent.getNodeType() == ExpressionType.Negate) {

            return true;
        }

        //
        // If the parent op has higher precedence, need parentheses for the child.
        //
        return childOpPrecedence < parentOpPrecedence;
    }

    private static int getOperatorPrecedence(final Expression node) {
        //
        // Roughly matches Java operator precedence, with some additional
        // operators. Also, things which are not binary/unary expressions,
        // such as conditional and type testing, don't use this mechanism.
        //
        switch (node.getNodeType()) {
            // Assignment
            case Assign:
            case ExclusiveOrAssign:
            case AddAssign:
            case SubtractAssign:
            case DivideAssign:
            case ModuloAssign:
            case MultiplyAssign:
            case LeftShiftAssign:
            case RightShiftAssign:
            case AndAssign:
            case OrAssign:
            case Coalesce:
                return 1;

            // Conditional (?:) would go here

            // Conditional OR
            case OrElse:
                return 2;

            // Conditional AND
            case AndAlso:
                return 3;

            // Logical OR
            case Or:
                return 4;

            // Logical XOR
            case ExclusiveOr:
                return 5;

            // Logical AND
            case And:
                return 6;

            // Equality
            case Equal:
            case NotEqual:
                return 7;

            // Relational, type testing
            case GreaterThan:
            case LessThan:
            case GreaterThanOrEqual:
            case LessThanOrEqual:
            case InstanceOf:
            case TypeEqual:
                return 8;

            // Shift
            case LeftShift:
            case RightShift:
            case UnsignedRightShift:
                return 9;

            // Additive
            case Add:
            case Subtract:
                return 10;

            // Multiplicative
            case Divide:
            case Modulo:
            case Multiply:
                return 11;

            // Unary
            case Negate:
            case UnaryPlus:
            case Not:
            case Convert:
            case ConvertChecked:
            case PreIncrementAssign:
            case PreDecrementAssign:
            case OnesComplement:
            case Increment:
            case Decrement:
            case IsTrue:
            case IsFalse:
            case Unbox:
            case Throw:
                return 12;

            // Primary, which includes all other node types:
            //   member access, calls, indexing, new.
            case PostIncrementAssign:
            case PostDecrementAssign:
            default:
                return 14;

            // These aren't expressions, so never need parentheses:
            //   constants, variables
            case Constant:
            case Parameter:
                return 15;
        }
    }

    // </editor-fold>

    @Override
    protected Expression visitBinary(final BinaryExpression node) {
        if (node.getNodeType() == ExpressionType.ArrayIndex) {
            parenthesizedVisit(node, node.getLeft());
            out("[");
            visit(node.getRight());
            out("]");
        }
        else if (node.getNodeType() == ExpressionType.ArrayLength) {
            parenthesizedVisit(node, node.getLeft());
            out(".length");
        }
        else {
            final boolean parenthesizeLeft = needsParentheses(node, node.getLeft());
            final boolean parenthesizeRight = needsParentheses(node, node.getRight());

            final String op;
            int beforeOp = FLOW_SPACE;

            switch (node.getNodeType()) {
                case Assign:
                    op = "=";
                    break;
                case Equal:
                case ReferenceEqual:
                    op = "==";
                    break;
                case NotEqual:
                case ReferenceNotEqual:
                    op = "!=";
                    break;
                case AndAlso:
                    op = "&&";
                    beforeOp = FLOW_BREAK | FLOW_SPACE;
                    break;
                case OrElse:
                    op = "||";
                    beforeOp = FLOW_BREAK | FLOW_SPACE;
                    break;
                case GreaterThan:
                    op = ">";
                    break;
                case LessThan:
                    op = "<";
                    break;
                case GreaterThanOrEqual:
                    op = ">=";
                    break;
                case LessThanOrEqual:
                    op = "<=";
                    break;
                case Add:
                    op = "+";
                    break;
                case AddAssign:
                    op = "+=";
                    break;
                case Subtract:
                    op = "-";
                    break;
                case SubtractAssign:
                    op = "-=";
                    break;
                case Divide:
                    op = "/";
                    break;
                case DivideAssign:
                    op = "/=";
                    break;
                case Modulo:
                    op = "%";
                    break;
                case ModuloAssign:
                    op = "%=";
                    break;
                case Multiply:
                    op = "*";
                    break;
                case MultiplyAssign:
                    op = "*=";
                    break;
                case LeftShift:
                    op = "<<";
                    break;
                case LeftShiftAssign:
                    op = "<<=";
                    break;
                case RightShift:
                    op = ">>";
                    break;
                case UnsignedRightShift:
                    op = ">>>";
                    break;
                case RightShiftAssign:
                    op = ">>=";
                    break;
                case UnsignedRightShiftAssign:
                    op = ">>>=";
                    break;
                case And:
                    op = "&";
                    break;
                case AndAssign:
                    op = "&=";
                    break;
                case Or:
                    op = "|";
                    break;
                case OrAssign:
                    op = "|=";
                    break;
                case ExclusiveOr:
                    op = "^";
                    break;
                case ExclusiveOrAssign:
                    op = "^=";
                    break;
                case Coalesce:
                    op = "??";
                    break;

                default:
                    throw ContractUtils.unreachable();
            }

            if (parenthesizeLeft) {
                out("(", FLOW_NONE);
            }

            visit(node.getLeft());

            if (parenthesizeLeft) {
                out(FLOW_NONE, ")", FLOW_BREAK);
            }

            out(beforeOp, op, FLOW_SPACE | FLOW_BREAK);

            if (parenthesizeRight) {
                out("(", FLOW_NONE);
            }

            visit(node.getRight());

            if (parenthesizeRight) {
                out(FLOW_NONE, ")", FLOW_BREAK);
            }
        }
        return node;
    }

    @Override
    protected Expression visitParameter(final ParameterExpression node) {
        //
        // Have '$' for the DebugView of ParameterExpressions
        //
        out("$");

        if (StringUtilities.isNullOrEmpty(node.getName())) {
            //
            // If no name if provided, generate a name as $var1, $var2.
            // No guarantee for not having name conflicts with user provided variable names.
            //
            final int id = getParamId(node);
            out("var" + id);
        }
        else {
            out(getDisplayName(node.getName()));
        }

        return node;
    }

    @Override
    protected <T> LambdaExpression<T> visitLambda(final LambdaExpression<T> node) {
        out(
            format(
                ".Lambda %s<%s>",
                getLambdaName(node),
                node.getType()
            )
        );

        // N^2 performance, for keeping the order of the lambdas.
        if (!_lambdas.contains(node)) {
            _lambdas.addLast(node);
        }

        return node;
    }

    @Override
    protected Expression visitConditional(final ConditionalExpression node) {
        if (isSimpleExpression(node.getTest())) {
            out(".If (");
            visit(node.getTest());
            out(") {", FLOW_NEW_LINE);
        }
        else {
            out(".If (", FLOW_NEW_LINE);
            indent();
            visit(node.getTest());
            unindent();
            out(FLOW_NEW_LINE, ") {", FLOW_NEW_LINE);
        }
        indent();
        visit(node.getIfTrue());
        unindent();
        out(FLOW_NEW_LINE, "} .Else {", FLOW_NEW_LINE);
        indent();
        visit(node.getIfFalse());
        unindent();
        out(FLOW_NEW_LINE, "}");
        return node;
    }

    @Override
    protected Expression visitConstant(final ConstantExpression node) {
        final Object value = node.getValue();

        if (value == null) {
            out("null");
        }
        else if (value instanceof String &&
                 node.getType() == Types.String) {

            out(StringUtilities.escape((String) value, true));
        }
        else if (value instanceof Character &&
                 node.getType() == PrimitiveTypes.Character) {

            out(StringUtilities.escape((char) value, true));
        }
        else if (value instanceof Integer && node.getType() == PrimitiveTypes.Integer ||
                 value instanceof Boolean && node.getType() == PrimitiveTypes.Boolean) {

            out(value.toString());
        }
        else if (value instanceof Class &&
                 "java/lang/Class".equals(node.getType().getInternalName())) {

            out(((Class<?>) value).getName() + ".class");
        }
        else if (value instanceof Type<?> &&
                 "com/strobel/reflection/Type".equals(node.getType().getInternalName())) {

            out(((Type<?>) value).getFullName() + ".class");
        }
        else {
            final String suffix = getConstantValueSuffix(node.getType());

            if (suffix != null) {
                out(String.valueOf(value));
                out(suffix);
            }
            else {
                final String toString = value.getClass().isArray() ? arrayToString(value)
                                                                   : String.valueOf(value);
                out(
                    format(
                        ".Constant<%s>(%s)",
                        node.getType().toString(),
                        toString
                    )
                );
            }
        }

        return node;
    }

    @Override
    protected Expression visitRuntimeVariables(final RuntimeVariablesExpression node) {
        out(".RuntimeVariables");
        visitExpressions('(', node.getVariables());
        return node;
    }

    @Override
    protected Expression visitMember(final MemberExpression node) {
        outMember(node, node.getTarget(), node.getMember());
        return node;
    }

    @Override
    protected Expression visitInvocation(final InvocationExpression node) {
        out(".Invoke ");
        parenthesizedVisit(node, node.getExpression());
        visitExpressions('(', node.getArguments());
        return node;
    }

    @Override
    protected Expression visitMethodCall(final MethodCallExpression node) {
        out(".Call ");
        if (node.getTarget() != null) {
            parenthesizedVisit(node, node.getTarget());
        }
        else if (node.getMethod().getDeclaringType() != null) {
            out(node.getMethod().getDeclaringType().toString());
        }
        else {
            out("<UnknownType>");
        }
        out(".");
        out(node.getMethod().getName());
        visitExpressions('(', node.getArguments());
        return node;
    }

    @Override
    protected Expression visitNewArray(final NewArrayExpression node) {
        if (node.getNodeType() == ExpressionType.NewArrayBounds) {
            // .NewArray MyType[expr1, expr2]
            out(".NewArray " + node.getType().getElementType().toString());
            visitExpressions('[', node.getExpressions());
        }
        else {
            // .NewArray MyType {expr1, expr2}
            out(".NewArray " + node.getType().toString(), FLOW_SPACE);
            visitExpressions('{', node.getExpressions());
        }
        return node;
    }

    @Override
    protected Expression visitNew(final NewExpression node) {
        out(".New " + node.getType().toString());
        visitExpressions('(', node.getArguments());
        return node;
    }

    @Override
    protected Expression visitDefaultValue(final DefaultValueExpression node) {
        out(".Default(" + node.getType().toString() + ")");
        return node;
    }

    @Override
    protected Expression visitExtension(final Expression node) {
        out(format(".Extension<%s>", node.getClass().getName()));

        if (node.canReduce()) {
            out(FLOW_SPACE, "{", FLOW_NEW_LINE);
            indent();
            visit(node.reduce());
            unindent();
            out(FLOW_NEW_LINE, "}");
        }

        return node;
    }

    @Override
    protected Expression visitLabel(final LabelExpression node) {
        out(".Label", FLOW_NEW_LINE);
        indent();
        visit(node.getDefaultValue());
        unindent();
        newLine();
        writeLabel(node.getTarget());
        return node;
    }

    @Override
    protected LabelTarget visitLabelTarget(final LabelTarget node) {
        writeLabel(node);
        return node;
    }

    @Override
    protected Expression visitGoto(final GotoExpression node) {
        out("." + node.getKind().toString(), FLOW_SPACE);
        out(getLabelTargetName(node.getTarget()), FLOW_SPACE);
        out("{", FLOW_SPACE);
        visit(node.getValue());
        out(FLOW_SPACE, "}");
        return node;
    }

    @Override
    protected Expression visitLoop(final LoopExpression node) {
        out(".Loop", FLOW_SPACE);
        if (node.getContinueTarget() != null) {
            writeLabel(node.getContinueTarget());
        }
        out(" {", FLOW_NEW_LINE);
        indent();
        visit(node.getBody());
        unindent();
        out(FLOW_NEW_LINE, "}");
        if (node.getBreakTarget() != null) {
            out("", FLOW_NEW_LINE);
            writeLabel(node.getBreakTarget());
        }
        return node;
    }

    @Override
    protected Expression visitForEach(final ForEachExpression node) {
        out(".ForEach", FLOW_SPACE);
        out("(");
        visit(node.getVariable());
        out(" in ");
        visit(node.getSequence());
        out(") {", FLOW_NEW_LINE);
        indent();
        visit(node.getBody());
        unindent();
        out(FLOW_NEW_LINE, "}");
        return node;
    }

    @Override
    protected Expression visitFor(final ForExpression node) {
        out(".For", FLOW_SPACE);
        out("(");
        visit(node.getVariable());
        out(" = ");
        visit(node.getInitializer());
        out("; ");
        visit(node.getTest());
        out("; ");
        visit(node.getStep());
        out(") {", FLOW_NEW_LINE);
        indent();
        visit(node.getBody());
        unindent();
        out(FLOW_NEW_LINE, "}");
        return node;
    }

    @Override
    protected Expression visitUnary(final UnaryExpression node) {
        final boolean parenthesize = needsParentheses(node, node.getOperand());

        final String op;
        int beforeOp = FLOW_SPACE;
        boolean trailing = false;
        Type<?> secondOp = null;

        switch (node.getNodeType()) {
            case Negate:
                op = "-";
                break;

            case Convert:
                secondOp = node.getType();
                // fall through...

            case Not:
            case IsFalse:
            case IsTrue:
            case OnesComplement:
            case ArrayLength:
            case IsNull:
            case IsNotNull:
            case Throw:
            case Unbox:
                op = "." + node.getNodeType();
                break;

            case UnaryPlus:
                op = "+";
                break;

            case PostDecrementAssign:
                trailing = true;
            case PreDecrementAssign:
                op = "--";
                break;

            case PostIncrementAssign:
                trailing = true;
            case PreIncrementAssign:
                op = "++";
                break;

            default:
                throw ContractUtils.unreachable();
        }

        if (!trailing) {
            out(beforeOp, op, parenthesize ? FLOW_NONE : FLOW_SPACE | FLOW_BREAK);
        }

        if (parenthesize) {
            out("(", FLOW_NONE);
        }

        visit(node.getOperand());

        if (parenthesize) {
            out(FLOW_NONE, ")", FLOW_BREAK);
        }

        if (trailing) {
            out(beforeOp, op, parenthesize ? FLOW_NONE : FLOW_SPACE | FLOW_BREAK);
        }

        return node;
    }

    @Override
    protected Expression visitTypeBinary(final TypeBinaryExpression node) {
        visit(node.getOperand());
        out(" ");
        out(node.getNodeType() == ExpressionType.InstanceOf ? " .InstanceOf " : " .TypeEqual ");
        out(node.getType().toString());
        return node;
    }

    @Override
    protected Expression visitBlock(final BlockExpression node) {
        out(".Block");

        // Display <type> if the type of the BlockExpression is different from the
        // last expression's type in the block.
        if (node.getType() != node.getExpression(node.getExpressionCount() - 1).getType()) {
            out(format("<%s>", node.getType().toString()));
        }

        visitDeclarations(node.getVariables());
        out(" ");
        // Use ; to separate expressions in the block
        visitExpressions('{', ';', node.getExpressions());

        return node;
    }

    @Override
    protected Expression visitTry(final TryExpression node) {
        out(".Try {", FLOW_NEW_LINE);
        indent();
        visit(node.getBody());
        unindent();

        visit(
            node.getHandlers(),
            new ElementVisitor<CatchBlock>() {
                @Override
                public CatchBlock visit(final CatchBlock node) {
                    return visitCatchBlock(node);
                }
            }
        );

        if (node.getFinallyBlock() != null) {
            out(FLOW_NEW_LINE, "} .Finally {", FLOW_NEW_LINE);
            indent();
            visit(node.getFinallyBlock());
            unindent();
        }

        out(FLOW_NEW_LINE, "}");
        return node;
    }

    @Override
    protected CatchBlock visitCatchBlock(final CatchBlock node) {
        out(FLOW_NEW_LINE, "} .Catch (" + node.getTest().toString());
        if (node.getVariable() != null) {
            out(FLOW_SPACE, "");
            visitParameter(node.getVariable());
        }
        if (node.getFilter() != null) {
            out(") .If (", FLOW_BREAK);
            visit(node.getFilter());
        }
        out(") {", FLOW_NEW_LINE);
        indent();
        visit(node.getBody());
        unindent();
        return node;
    }

    @Override
    protected SwitchCase visitSwitchCase(final SwitchCase node) {
        indent();
        for (final Expression test : node.getTestValues()) {
            out(".Case (");
            visit(test);
            out("):", FLOW_NEW_LINE);
        }
        indent();
        visit(node.getBody());
        unindent();
        unindent();
        newLine();
        return node;
    }

    @Override
    protected Expression visitSwitch(final SwitchExpression node) {
        out(".Switch ");
        out("(");
        visit(node.getSwitchValue());
        out(") {", FLOW_NEW_LINE);

        visit(
            node.getCases(),
            new ElementVisitor<SwitchCase>() {
                @Override
                public SwitchCase visit(final SwitchCase node) {
                    return visitSwitchCase(node);
                }
            }
        );

        if (node.getDefaultBody() != null) {
            indent();
            out(".Default:", FLOW_NEW_LINE);
            indent();
            visit(node.getDefaultBody());
            unindent();
            unindent();
            newLine();
        }

        out("}");
        return node;
    }

    @Override
    protected Expression visitConcat(final ConcatExpression node) {
        final ExpressionList<? extends Expression> operands = node.getOperands();

        boolean first = true;

        for (final Expression operand : operands) {
            if (first) {
                first = false;
            }
            else {
                out(FLOW_SPACE, "+", FLOW_SPACE | FLOW_BREAK);
            }

            final boolean parenthesize = needsParentheses(node, operand);

            if (parenthesize) {
                out("(", FLOW_NONE);
            }

            visit(operand);

            if (parenthesize) {
                out(")", FLOW_NONE);
            }
        }

        return node;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.uwdb.brandonhaynes</groupId>
    <artifactId>pipegen</artifactId>
    <version>0.1</version>

    <repositories>
        <repository>
            <id>project.local</id>
            <name>project.local</name>
            <url>file:${project.basedir}/repo</url>
        </repository>
    </repositories>

    <profiles>
        <profile>
            <id>windows-profile</id>
            <activation>
                <activeByDefault>true</activeByDefault>
                <file>
                    <exists>${java.home}/lib/tools.jar</exists>
                </file>
            </activation>
            <properties>
                <tools-jar>${java.home}/lib/tools.jar</tools-jar>
            </properties>
        </profile>
        <profile>
            <id>mac-profile</id>
            <activation>
                <activeByDefault>false</activeByDefault>
                <file>
                    <exists>${java.home}/../lib/tools.jar</exists>
                </file>
            </activation>
            <properties>
                <tools-jar>${java.home}/../lib/tools.jar</tools-jar>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>com.codahale.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-mapreduce-client-core</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-buffer</artifactId>
            <version>4.0.27.Final</version>
        </dependency>
        <dependency>
            <groupId>org.apache.arrow</groupId>
            <artifactId>apache-arrow-memory</artifactId>
            <version>0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.arrow</groupId>
            <artifactId>apache-arrow-vector</artifactId>
            <version>0.1</version>
        </dependency>
        <dependency>
            <groupId>org.soot</groupId>
            <artifactId>soot</artifactId>
            <version>trunk-post-2.5</version>
        </dependency>
        <dependency>
            <groupId>com.sun.tools.btrace</groupId>
            <artifactId>btrace-client</artifactId>
            <version>1.3.8</version>
        </dependency>
        <dependency>
            <groupId>com.sun.tools.btrace</groupId>
            <artifactId>btrace-boot</artifactId>
            <version>1.3.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>jdk.tools</groupId>
            <artifactId>jdk.tools</artifactId>
            <version>jdk1.8.0</version>
            <scope>system</scope>
            <systemPath>${tools-jar}</systemPath>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgs>
                        <arg>-XDignore.symbol.file</arg>
                    </compilerArgs>
                    <fork>true</fork>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>${tools-jar}</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>org.brandonhaynes.pipegen.PipeGen</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
package script;

import java.awt.Graphics2D;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Set;
import java.util.stream.Collectors;

import editor.Trigger;
import level.Area;
import level.WorldConstants;
import screen.Scene;

/**
 * TriggerData refers to a tile in the Area where one or many {@linkplain Script scripts} can occur
 * throughout the entire game. Depending on the script conditions necessary to trigger the "events"
 * on the same tile, the script will trigger when the player lands on the TriggerData where the
 * script is located.
 *

 * TriggerData stores all possible {@linkplain Script scripts} that occurs on the same exact tile
 * location. Each script should be unique from one another.
 *
 * @author tlee
 */
public class TriggerData {
	private int x;
	private int y;
	private short triggerID;
	private short npcTriggerID;
	private Deque


text:
class PluginsController < ApplicationController
  helper_method :plugins_json

  def index
    redirect_to installed_plugins_path
  end

  def installed
    @plugins = PluginDecorator.decorate_collection(Plugin.installed.reject{|plugin| plugin.processing? })
  end

  def recommended
    @plugins = PluginDecorator.decorate_collection(Plugin.recommended)
  end

  def updated
    @plugins = PluginDecorator.decorate_collection(Plugin.installed.reject{|plugin| plugin.latest_version? })
  end

  def install
    params[:plugins].each do |gem_name|
      GemInstallerJob.perform_later(gem_name)
    end
    respond_to do |format|
      format.html do
        redirect_to plugins_path
      end
      format.json do
        plugins = PluginDecorator.decorate_collection(Plugin.recommended.select {|item| params[:plugins].include?(item.gem_name)})
        render json: plugins.map(&:to_hash).to_json
      end
    end

  end

  def uninstall
    params[:plugins].each do |gem_name|
      GemUninstallerJob.perform_later(gem_name)
    end
    redirect_to plugins_path
  end

  def upgrade
    GemInstallerJob.perform_later(params[:plugins][:name], params[:plugins][:version])
    redirect_to plugins_path
  end

  def bulk_upgrade
    params[:plugins].each do |gem_name|
      pl = Plugin.new(gem_name: gem_name)
      GemInstallerJob.perform_later(gem_name, pl.latest_version)
    end
    redirect_to plugins_path
  end

  private

  def plugins_json
    JSON.pretty_generate(@plugins.map(&:to_hash))
  end
end


text:
module Bosh::AwsCloud
  class TagManager

    MAX_TAG_KEY_LENGTH = 127
    MAX_TAG_VALUE_LENGTH = 255

    # Add a tag to something, make sure that the tag conforms to the
    # AWS limitation of 127 character key and 255 character value
    def self.tag(taggable, key, value)
      return if key.nil? || value.nil?

      create_tags(taggable, key => value)
    end

    def self.create_tags(taggable, tags)
      return if tags.nil? || tags.keys.empty?

      errors = [Aws::EC2::Errors::InvalidAMIIDNotFound,
                Aws::EC2::Errors::InvalidInstanceIDNotFound,
                Aws::EC2::Errors::InvalidVolumeNotFound]

      begin
        Bosh::Common.retryable(tries: 30, on: errors) do
          logger.info("attempting to tag object: #{taggable.id}")
          taggable.create_tags(tags: format_tags(tags))
          true
        end
      rescue Aws::EC2::Errors::InvalidParameterValue => e
        logger.error("could not tag #{taggable.id}: #{e.message}")
      end
    end

    def self.logger
      Bosh::Clouds::Config.logger
    end

    private

    def self.format_tags(tags)
      formatted_tags = tags.map do |k, v|
        next unless !k.nil? && !v.nil?

        trimmed_key = k.to_s.slice(0, MAX_TAG_KEY_LENGTH)
        trimmed_value = v.to_s.slice(0, MAX_TAG_VALUE_LENGTH)

        {
          key: trimmed_key,
          value: trimmed_value
        }
      end

      formatted_tags.compact
    end
  end
end


text:
from datetime import datetime
now = datetime.now()

current_year = now.year
current_month = now.month
current_day = now.day

print now.year
print now.month
print now.day


text:
class AddSnpRankingIndex < ActiveRecord::Migration
  def self.up
    add_index :snps, [:ranking], :name => "index_snps_ranking"
  end

  def self.down
    remove_index :snps, [:ranking]
  end
end


text:
package com.github.neuralnetworks.tensor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.IntStream;

import com.github.neuralnetworks.architecture.Connections;
import com.github.neuralnetworks.architecture.Conv2DConnection;
import com.github.neuralnetworks.architecture.FullyConnected;
import com.github.neuralnetworks.architecture.Layer;
import com.github.neuralnetworks.architecture.NeuralNetwork;
import com.github.neuralnetworks.architecture.RepeaterConnection;
import com.github.neuralnetworks.architecture.Subsampling2DConnection;
import com.github.neuralnetworks.tensor.Tensor.TensorIterator;

public class TensorFactory
{

	@SuppressWarnings("unchecked")
	public static <T extends Tensor> T tensor(int... dimensions)
	{
		float[] elements = new float[IntStream.of(dimensions).reduce(1, (a, b) -> a * b)];
		int[][] dimensionsLimit = new int[2][dimensions.length];
		IntStream.range(0, dimensions.length).forEach(i -> dimensionsLimit[1][i] = dimensions[i] - 1);

		T result = null;
		if (dimensions.length == 2)
		{
			result = (T) new Matrix(0, elements, dimensions, dimensionsLimit);
		} else
		{
			result = (T) new Tensor(0, elements, dimensions, dimensionsLimit);
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	public static <T extends Tensor> T tensor(float[] elements, int offset, int... dimensions)
	{
		int[][] dimensionsLimit = new int[2][dimensions.length];
		IntStream.range(0, dimensions.length).forEach(i -> dimensionsLimit[1][i] = dimensions[i] - 1);

		T result = null;
		if (dimensions.length == 2)
		{
			result = (T) new Matrix(offset, elements, dimensions, dimensionsLimit);
		} else
		{
			result = (T) new Tensor(offset, elements, dimensions, dimensionsLimit);
		}

		return result;
	}

	/**
	 * @param parent
	 * @param dimensionsLimit - limit over the parent dimensions
	 * @param reduceChildDimensions - reduce the child vector dimensions if they are limited to 1
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Tensor> T tensor(Tensor parent, int[][] dimensionsLimit, boolean reduceChildDimensions)
	{
		T result = null;

		long dimensions = 0;
		if (reduceChildDimensions) {
			dimensions = IntStream.range(0, dimensionsLimit[0][0]).filter(i -> dimensionsLimit[0][i] != dimensionsLimit[1][i]).count();
		} else {
			dimensions = parent.getDimensions().length;
		}

		if (dimensions <= 2)
		{
			result = (T) new Matrix(parent, dimensionsLimit);
		} else
		{
			result = (T) new Tensor(parent, dimensionsLimit, reduceChildDimensions);
		}

		return result;
	}

	/**
	 * Create multiple combined tensors using shared elements array
	 *
	 * @param dimensions
	 *          - dimensions for each tensor
	 * @return array of tensors
	 */
	public static Tensor[] tensor(int[]... dimensions)
	{
		Tensor[] result = new Tensor[dimensions.length];
		float[] elements = new float[Arrays.stream(dimensions).map(d -> {
			return IntStream.of(d).reduce(1, (a, b) -> a * b);
		}).reduce(0, (a, b) -> a + b)];

		for (int i = 0, offset = 0; i < dimensions.length; i++)
		{
			int[] d = dimensions[i];
			int[][] dimensionsLimit = new int[2][d.length];
			IntStream.range(0, d.length).forEach(j -> dimensionsLimit[1][j] = d[j] - 1);
			if (d.length == 2)
			{
				result[i] = new Matrix(offset, elements, d, dimensionsLimit);
			} else
			{
				result[i] = new Tensor(offset, elements, d, dimensionsLimit);
			}

			offset += IntStream.of(d).reduce(1, (a, b) -> a * b);
		}

		return result;
	}

	/**
	 * Simplified construction of matrix using values
	 *
	 * @param elements
	 * @return Matrix
	 */
	public static Matrix matrix(float[][] elements)
	{
		Matrix result = tensor(elements[0].length, elements.length);
		IntStream.range(0, elements.length).forEach(i -> IntStream.range(0, elements[i].length).forEach(j -> {
			result.set(elements[i][j], i, j);
		}));

		return result;
	}

	public static Matrix matrix(float[] elements, int columns)
	{
		return tensor(elements, 0, elements.length / columns, columns);
	}

	public static void fill(Tensor t, float value)
	{
		TensorIterator it = t.iterator();
		while (it.hasNext())
		{
			t.getElements()[it.next()] = value;
		}
	}

	/**
	 * @param nn
	 * @param miniBatchSize
	 * @param useSharedMemory
	 * @return Tensor provider based on neural network
	 */
	public static ValuesProvider tensorProvider(NeuralNetwork nn, int miniBatchSize, boolean useSharedMemory)
	{
		ValuesProvider result = new ValuesProvider(useSharedMemory);

		createNNTensors(nn, result, miniBatchSize);

		return result;
	}

	/**
	 * @param miniBatchSize
	 * @param useSharedMemory
	 * @param nns
	 * @return Tensor provider based on multiple neural networks - common layers use shared tensors
	 */
	public static ValuesProvider tensorProvider(int miniBatchSize, boolean useSharedMemory, NeuralNetwork... nns)
	{
		ValuesProvider result = new ValuesProvider(useSharedMemory);

		for (NeuralNetwork nn : nns)
		{
			createNNTensors(nn, result, miniBatchSize);
		}

		return result;
	}

	/**
	 * @param sibling
	 * @param nn
	 * @return Tensor provider based on neural network
	 */
	public static ValuesProvider tensorProvider(ValuesProvider sibling, NeuralNetwork nn)
	{

		ValuesProvider result = new ValuesProvider(sibling);

		createNNTensors(nn, result, batchSize(sibling));

		return result;
	}

	public static void copy(Tensor src, Tensor dest)
	{
		if (!Arrays.equals(src.getDimensions(), dest.getDimensions()))
		{
			throw new IllegalArgumentException("Dimensions don't match");
		}

		TensorIterator srcIt = src.iterator();
		TensorIterator destIt = dest.iterator();
		while (srcIt.hasNext() && destIt.hasNext())
		{
			dest.getElements()[destIt.next()] = src.getElements()[srcIt.next()];
		}
	}

	/**
	 * Copy the contents of src to destination. The two providers must have equal keys and tensors
	 *
	 * @param src
	 * @param dest
	 */
	public static void copy(ValuesProvider src, ValuesProvider dest)
	{
		for (Entry<Object, List<Tensor>> e : src.values.entrySet())
		{
			for (int i = 0; i < e.getValue().size(); i++)
			{
				copy(e.getValue().get(i), dest.values.get(e.getKey()).get(i));
			}
		}
	}

	public static Tensor duplicate(Tensor src, float[] elements)
	{
		int[][] gdl = new int[src.globalDimensionsLimit.length][src.globalDimensionsLimit[0].length];
		IntStream.range(0, gdl.length).forEach(i -> IntStream.range(0, gdl[i].length).forEach(j -> gdl[i][j] = src.globalDimensionsLimit[i][j]));

		if (elements == null)
		{
			elements = new float[src.elements.length];
		}

		Tensor result = new Tensor(src.startOffset, elements, Arrays.copyOf(src.globalDimensions, src.globalDimensions.length), gdl);

		return result;
	}

	/**
	 * Duplicate of the source values provider. The keys are the same as in "source" and the tensors are new
	 *
	 * @param source
	 *          - source values provider
	 */
	public static ValuesProvider duplicate(ValuesProvider source)
	{
		ValuesProvider result = new ValuesProvider(source.useSharedMemory());
		Map<float[], float[]> elementsMap = new HashMap<>();
		for (Entry<Object, List<Tensor>> e : source.values.entrySet())
		{
			List<Tensor> r = new ArrayList<>();
			result.values.put(e.getKey(), r);

			for (Tensor st : e.getValue())
			{
				if (!elementsMap.containsKey(st.getElements()))
				{
					elementsMap.put(st.getElements(), new float[st.getElements().length]);
				}

				Tensor t = duplicate(st, elementsMap.get(st.getElements()));
				result.tensors.add(t);
				r.add(t);
			}
		}

		return result;
	}

	/**
	 * @return mini batch size for TensorProvider
	 */
	public static int batchSize(ValuesProvider tp)
	{
		Tensor t = tp.getTensors().iterator().next();
		return t.getDimensions()[0];
	}

	/**
	 * @return Tensor for connections. The connections must have a common layer and they must have the same dimensions.
	 */
	public static <T extends Tensor> T tensor(Layer targetLayer, Collection<Connections> connections, ValuesProvider tp)
	{
		return tp.get(targetLayer, getLayerDimensions(targetLayer, connections, batchSize(tp)));
	}

	/**
	 * @return Tensor for connections. The connections must have a common layer and they must have the same dimensions.
	 */
	public static <T extends Tensor> T tensor(Layer targetLayer, Connections c, ValuesProvider tp)
	{
		return tp.get(targetLayer, getLayerDimensions(targetLayer, Arrays.asList(new Connections[] { c }), batchSize(tp)));
	}

	/**
	 * tensor max element index
	 */
	public static int max(Tensor t)
	{
		int result = 0, i;
		float max = t.getElements()[t.getStartIndex()];
		TensorIterator it = t.iterator();
		while (it.hasNext())
		{
			i = it.next();
			if (t.getElements()[i] > max)
			{
				result = i;
				max = t.getElements()[i];
			}
		}

		return result;
	}

	/**
	 * tensor min element index
	 */
	public static int min(Tensor t)
	{
		int result = 0, i;
		float min = t.getElements()[t.getStartIndex()];
		TensorIterator it = t.iterator();
		while (it.hasNext())
		{
			i = it.next();
			if (t.getElements()[i] < min)
			{
				result = i;
				min = t.getElements()[i];
			}
		}

		return result;
	}

	/**
	 * average value of tensor elements
	 */
	public static float avg(Tensor t)
	{
		double result = 0;
		TensorIterator it = t.iterator();
		while (it.hasNext())
		{
			result += t.getElements()[it.next()];
		}

		return (float) (result / t.getSize());
	}

	/**
	 * @param targetLayer
	 * @param connections
	 * @return
	 */
	private static int[] getLayerDimensions(Layer targetLayer, Collection<Connections> connections, int miniBatchSize)
	{
		int[] result = null;
		boolean hasFullyConnected = false, hasSubsampling = false, hasConvolutional = false;
		for (Connections c : connections)
		{
			if (c instanceof FullyConnected)
			{
				hasFullyConnected = true;
			} else if (c instanceof Conv2DConnection)
			{
				hasConvolutional = true;
			} else if (c instanceof Subsampling2DConnection)
			{
				hasSubsampling = true;
			}
		}

		if (hasFullyConnected && (hasSubsampling || hasConvolutional))
		{
			throw new IllegalArgumentException("Cannot have fully connected and subsampling connections");
		}

		if (hasFullyConnected)
		{
			result = new int[] { miniBatchSize, targetLayer.getUnitCount(connections) };
		} else if (hasSubsampling)
		{
			Subsampling2DConnection c = (Subsampling2DConnection) connections.iterator().next();
			if (c.getOutputLayer() == targetLayer)
			{
				result = new int[] { miniBatchSize, c.getFilters(), c.getOutputFeatureMapRows(), c.getOutputFeatureMapColumns() };
			} else if (c.getInputLayer() == targetLayer)
			{
				result = new int[] { miniBatchSize, c.getFilters(), c.getInputFeatureMapRows(), c.getInputFeatureMapColumns() };
			}
		} else if (hasConvolutional)
		{
			Conv2DConnection c = (Conv2DConnection) connections.iterator().next();
			if (c.getOutputLayer() == targetLayer)
			{
				result = new int[] { miniBatchSize, c.getOutputFilters(), c.getOutputFeatureMapRows(), c.getOutputFeatureMapColumns() };
			} else if (c.getInputLayer() == targetLayer)
			{
				result = new int[] { miniBatchSize, c.getInputFilters(), c.getInputFeatureMapRows(), c.getInputFeatureMapColumns() };
			}
		}

		return result;
	}

	private static void createNNTensors(NeuralNetwork neuralNetwork, ValuesProvider vp, int miniBatchSize)
	{
		for (Connections c : neuralNetwork.getConnections())
		{
			if (c instanceof FullyConnected)
			{
				FullyConnected fc = (FullyConnected) c;

				int[] inputDim = new int[] { miniBatchSize, fc.getInputUnitCount() };
				if (vp.get(fc.getInputLayer(), inputDim) == null)
				{
					vp.add(fc.getInputLayer(), true, inputDim);
				}

				int[] outputDim = new int[] { miniBatchSize, fc.getOutputUnitCount() };
				if (vp.get(fc.getOutputLayer(), outputDim) == null)
				{
					vp.add(fc.getOutputLayer(), true, outputDim);
				}
			} else if (c instanceof Conv2DConnection)
			{
				Conv2DConnection cc = (Conv2DConnection) c;
				int[] inputDim = new int[] { miniBatchSize, cc.getInputFilters(), cc.getInputFeatureMapRows(), cc.getInputFeatureMapColumns() };
				if (vp.get(cc.getInputLayer(), inputDim) == null)
				{
					vp.add(cc.getInputLayer(), true, inputDim);
				}

				int[] outputDim = new int[] { miniBatchSize, cc.getOutputFilters(), cc.getOutputFeatureMapRows() + 2 * cc.getOutputRowPadding(),
						cc.getOutputFeatureMapColumns() + 2 * cc.getOutputColumnPadding() };
				if (cc.getOutputRowPadding() > 0 || cc.getOutputColumnPadding() > 0)
				{
					if (vp.get(cc.getOutputLayer(), outputDim) == null)
					{
						vp.add(cc.getOutputLayer(), true, outputDim);
						Tensor parent = vp.get(cc.getOutputLayer(), outputDim);

						int[] pd = parent.getDimensions();
						Tensor child = tensor(parent, new int[][] { { 0, 0, cc.getOutputRowPadding(), cc.getOutputColumnPadding() }, { pd[0] - 1, pd[1] - 1, pd[2] - cc.getOutputRowPadding() - 1, pd[3] - cc.getOutputColumnPadding() - 1 } }, false);
						vp.add(cc.getOutputLayer(), child);
					}
				} else if (vp.get(cc.getOutputLayer(), outputDim) == null)
				{
					vp.add(cc.getOutputLayer(), true, outputDim);
				}
			} else if (c instanceof Subsampling2DConnection)
			{
				Subsampling2DConnection cc = (Subsampling2DConnection) c;
				int[] inputDim = new int[] { miniBatchSize, cc.getFilters(), cc.getInputFeatureMapRows(), cc.getInputFeatureMapColumns() };
				if (vp.get(cc.getInputLayer(), inputDim) == null)
				{
					vp.add(cc.getInputLayer(), true, inputDim);
				}

				int[] outputDim = new int[] { miniBatchSize, cc.getFilters(), cc.getOutputFeatureMapRows() + 2 * cc.getOutputRowPadding(), cc.getOutputFeatureMapColumns() + 2 * cc.getOutputColumnPadding() };
				if (cc.getOutputRowPadding() > 0 || cc.getOutputColumnPadding() > 0)
				{
					if (vp.get(cc.getOutputLayer(), outputDim) == null)
					{
						vp.add(cc.getOutputLayer(), true, outputDim);
						Tensor parent = vp.get(cc.getOutputLayer(), outputDim);

						int[] pd = parent.getDimensions();
						Tensor child = tensor(parent, new int[][] { { 0, 0, cc.getOutputRowPadding(), cc.getOutputColumnPadding() }, { pd[0] - 1, pd[1] - 1, pd[2] - cc.getOutputRowPadding() - 1, pd[3] - cc.getOutputColumnPadding() - 1 } }, false);
						vp.add(cc.getOutputLayer(), child);
					}
				} else if (vp.get(cc.getOutputLayer(), outputDim) == null)
				{
					vp.add(cc.getOutputLayer(), true, outputDim);
				}
			} else if (c instanceof RepeaterConnection)
			{
				if (vp.get(c.getInputLayer()) != null)
				{
					int[] sourceDim = vp.get(c.getInputLayer()).getDimensions();
					if (vp.get(c.getOutputLayer(), sourceDim) == null)
					{
						vp.add(c.getOutputLayer(), true, sourceDim);
					}
				}

				if (vp.get(c.getOutputLayer()) != null)
				{
					int[] sourceDim = vp.get(c.getOutputLayer()).getDimensions();
					if (vp.get(c.getInputLayer(), sourceDim) == null)
					{
						vp.add(c.getInputLayer(), true, sourceDim);
					}
				}
			}
		}
	}
}


text:
Code Samples for Chapter 3
==========================
This file contains instructions for running the sample project associated with Chapter 3 of RESTful Java Web Services.

General instructions
--------------------
The examples used in this book are built using the following:

- Java SE Development Kit 8 or newer
- NetBeans IDE 8.0.2 or newer
- Glassfish Server 4.1 or newer(installed along with  NetBeans IDE)
- Maven 3.2.3 or newer
- Oracle Database 11.2 Express Edition or newer (Example uses HR Schema)

Detailed instructions for setting up all the required tools for running the
examples used in this book are discussed in Appendix section of this book

Core classes used in this example
---------------------------------
- <rest-chapter3-service>
    - com.packtpub.rest.ch3.model
        - Departments : JPA entity mapped to DEPARTMENTS table
    - com.packtpub.rest.ch3.service
        - DepartmentService: REST resource class which demonstrates CRUD operations on department resource
        - RestAppConfig : Application configuration class, sub classed form javax.ws.rs.core.Application
- <rest-chapter3-client>
    - com.packtpub.rest.ch3.client
       -  DepartmentServiceJAXRSClient: JAX-RS client for accessing RESTful web APIs exposed by <rest-chapter3-service>

Before you begin
----------------
- If you are not familiar with NetBeans IDE and GlassFish, move back and refer to the section 'Building your first RESTful web service with JAX-RS' in Chapter 3 of this book. Please follow the detailed steps that you will find in this section and complete the sample application before trying out any other examples. This will make sure your IDE and GlassFish Server is configured properly to run all the examples given in this book.

How to run this example ?
-------------------------
- If you are not familiar with NetBeans IDE and GlassFish, move back and refer to the section 'Building your first RESTful web service with JAX-RS' in Chapter 3 of this book. Please follow the detailed steps that you will find in this section and complete the sample application before trying out any other examples. This will make sure your IDE and GlassFish Server is configured properly to run all the examples given in this book.

- Extract the zip file to your local file system. You may see **rest-chapter3-jaxrs** folder in the extracted location.
- This is a maven project and it has two sub projects
    - rest-chapter3-service : This project contains REST service implementation
    - rest-chapter3-client : This is the REST client implementation
- Open the rest-chapter3-jaxrs project in NetBeans IDE 8.0.2 or higher
    - In main tool bar,choose File > Open Project > rest-chapter3-jaxrs
    - In the project pane, expand 'Modules' element in rest-chapter3-jaxrs project and then double click rest-chapter3-service project to open in the IDE
    - Note that this example uses HR schema that usually comes with Oracle as sample schema. So we need to change the connection details to reflect your local settings as explained in next step.
    - In rest-chapter3-service project,
        - Go to src/main/resources folder and open META-INF/persistence.xml file. Modify the jta-data-source entry to match with Oracle data base that you have. You can either choose a an already existing data source(which connects to HR schema in Oracle DB) in GlassFish server or define a new JNDI data source in GlassFish and set it as 'jta-data-source' in persistence.xml. To know how to define data source in GlassFish, see this page: http://www.jobinesh.com/2015/09/configuring-jndi-data-source-for-oralce.html.

    - In the project pane, expand rest-chapter3-jaxrs project and double click rest-chapter3-client project to open in the IDE.
    - Right click rest-chapter3-service and choose Run. This action deploys the REST services.
    - To test the API from browser try the following URI http://<server>:<port>/rest-chapter3-service/webresources/departments
    - To test REST APIs, open  rest-chapter3-client project, and then select DepartmentServiceJAXRSClient.java.
        - Change the BASE_URI string in DepartmentServiceJAXRSClient.java to reflect the server URL where you have deployed the application
        - Right click DepartmentServiceJAXRSClient.java and choose Run to test client APIs. This client exercises GET

What next?
----------------------------
Both rest-chapter3-service and rest-chapter3-client contains basic examples for REST API server and client implementations.
Go through the source and try adding more more features to these examples  as and when you learn new JAX-RS APIs.


text:
set -e

# Show explicitly which commands are currently running.
set -x

ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE:-$0}")"; pwd)

platform="unknown"
unamestr="$(uname)"
if [[ "$unamestr" == "Linux" ]]; then
  echo "Platform is linux."
  platform="linux"
elif [[ "$unamestr" == "Darwin" ]]; then
  echo "Platform is macosx."
  platform="macosx"
else
  echo "Unrecognized platform."
  exit 1
fi

TEST_SCRIPT=$ROOT_DIR/../test/microbenchmarks.py

if [[ "$platform" == "linux" ]]; then
  # First test Python 2.7.

  # Install miniconda.
  wget https://repo.continuum.io/miniconda/Miniconda2-latest-Linux-x86_64.sh -O miniconda2.sh
  bash miniconda2.sh -b -p $HOME/miniconda2

  # Find the right wheel by grepping for the Python version.
  PYTHON_WHEEL=$(find $ROOT_DIR/../.whl -type f -maxdepth 1 -print | grep -m1 '27')

  # Install the wheel.
  $HOME/miniconda2/bin/pip install $PYTHON_WHEEL

  # Run a simple test script to make sure that the wheel works.
  $HOME/miniconda2/bin/python $TEST_SCRIPT

  # Now test Python 3.6.

  # Install miniconda.
  wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda3.sh
  bash miniconda3.sh -b -p $HOME/miniconda3

  # Find the right wheel by grepping for the Python version.
  PYTHON_WHEEL=$(find $ROOT_DIR/../.whl -type f -maxdepth 1 -print | grep -m1 '36')

  # Install the wheel.
  $HOME/miniconda3/bin/pip install $PYTHON_WHEEL

  # Run a simple test script to make sure that the wheel works.
  $HOME/miniconda3/bin/python $TEST_SCRIPT

  # Check that the other wheels are present.
  NUMBER_OF_WHEELS=$(ls -1q $ROOT_DIR/../.whl/*.whl | wc -l)
  if [[ "$NUMBER_OF_WHEELS" != "5" ]]; then
    echo "Wrong number of wheels found."
    ls -l $ROOT_DIR/../.whl/
    exit 1
  fi

elif [[ "$platform" == "macosx" ]]; then
  MACPYTHON_PY_PREFIX=/Library/Frameworks/Python.framework/Versions
  PY_MMS=("2.7"
          "3.4"
          "3.5"
          "3.6")
  # This array is just used to find the right wheel.
  PY_WHEEL_VERSIONS=("27"
                     "34"
                     "35"
                     "36")

  for ((i=0; i<${#PY_MMS[@]}; ++i)); do
    PY_MM=${PY_MMS[i]}
    PY_WHEEL_VERSION=${PY_WHEEL_VERSIONS[i]}

    PYTHON_EXE=$MACPYTHON_PY_PREFIX/$PY_MM/bin/python$PY_MM
    PIP_CMD="$(dirname $PYTHON_EXE)/pip$PY_MM"

    # Find the appropriate wheel by grepping for the Python version.
    PYTHON_WHEEL=$(find $ROOT_DIR/../.whl -type f -maxdepth 1 -print | grep -m1 "$PY_WHEEL_VERSION")

    # Install the wheel.
    $PIP_CMD install $PYTHON_WHEEL

    # Run a simple test script to make sure that the wheel works.
    $PYTHON_EXE $TEST_SCRIPT
  done
else
  echo "Unrecognized environment."
  exit 1
fi


text:
import unittest

from programy.mappings.person import PersonCollection

class PersonTests(unittest.TestCase):

    def test_load_persons(self):
        person_text = """
        " with you "," with me2 "
        " with me "," with you2 "
        """

        collection = PersonCollection()
        self.assertIsNotNone(collection)

        collection.load_from_text(person_text)

        self.assertEqual(collection.personalise_string(" with me "), "with you2")

    def test_replace_person(self):
        person_text = """
        " with me "," with you2 "
        " are you "," am I2 "
        """

        collection = PersonCollection()
        self.assertIsNotNone(collection)

        collection.load_from_text(person_text)

        self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am I2 with you2")


text:
<?php

namespace Updater\Package;

/**
 * Update informations represented as a class
 *
 * @author Paweł Mikołajczuk <mikolajczuk.private@gmail.com>
 */
class Package
{
    /**
     * Version name
     * @var string
     */
    private $version;

    /**
     * Short description for package
     * @var string
     */
    private $description;

    /**
     * Type of update
     * @var string
     */
    private $updateType;

    /**
     * Chnagelog
     * @var array
     */
    private $changelog;

    /**
     * Name of package maintainer
     * @var string
     */
    private $maintainer;

    /**
     * Array with files mapping
     * @var array
     */
    private $filemapping;

    /**
     * Path for directory with migrations
     * @var string
     */
    private $migrationsDir;

    /**
     * Composer action
     * @var string
     */
    private $composerAction;

    /**
     * Package dir
     * @var string
     */
    private $packageDir;

    /**
     * Gets the Version name.
     *
     * @return string
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * Sets the Version name.
     *
     * @param string $version the version
     *
     * @return self
     */
    public function setVersion($version)
    {
        $this->version = $version;

        return $this;
    }

    /**
     * Gets the Short description for package.
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Sets the Short description for package.
     *
     * @param string $description the description
     *
     * @return self
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Gets the Type of update.
     *
     * @return string
     */
    public function getUpdateType()
    {
        return $this->updateType;
    }

    /**
     * Sets the Type of update.
     *
     * @param string $updateType the update type
     *
     * @return self
     */
    public function setUpdateType($updateType)
    {
        $this->updateType = $updateType;

        return $this;
    }

    /**
     * Gets the Chnagelog.
     *
     * @return array
     */
    public function getChangelog()
    {
        return $this->changelog;
    }

    /**
     * Sets the Chnagelog.
     *
     * @param array $changelog the changelog
     *
     * @return self
     */
    public function setChangelog(array $changelog)
    {
        $this->changelog = $changelog;

        return $this;
    }

    /**
     * Gets the Name of package mainatainer.
     *
     * @return string
     */
    public function getMaintainer()
    {
        return $this->maintainer;
    }

    /**
     * Sets the Name of package mainatainer.
     *
     * @param string $maintainer the maintainer
     *
     * @return self
     */
    public function setMaintainer($maintainer)
    {
        $this->maintainer = $maintainer;

        return $this;
    }

    /**
     * Gets the Array with files mapping.
     *
     * @return array
     */
    public function getFilemapping()
    {
        return $this->filemapping;
    }

    /**
     * Sets the Array with files mapping.
     *
     * @param array $filemapping the filemapping
     *
     * @return self
     */
    public function setFilemapping(array $filemapping)
    {
        foreach ($filemapping as $file) {
            $fileDefinition = substr($file, strpos($file, " ") + 1);
            $type = null;
            if ($file[0] == 'A') {
                $type = 'add';
            } elseif ($file[0] == 'D') {
                $type = 'remove';
            } elseif ($file[0] == 'M') {
                $type = 'update';
            }

            $this->addFileToFileMapping($type, trim($fileDefinition));
        }

        return $this;
    }

    /**
     * Add new file to filemapping
     *
     * @param string $type
     * @param string $file
     *
     * @return self
     */
    public function addFileToFileMapping($type, $file)
    {
        $this->filemapping[] = array(
            'type' => $type,
            'file' => $file
        );

        return $this;
    }

    /**
     * Gets the Path for directory with migrations.
     *
     * @return string
     */
    public function getMigrationsDir()
    {
        return $this->migrationsDir;
    }

    /**
     * Sets the Path for directory with migrations.
     *
     * @param string $migrationsDir the migrations dir
     *
     * @return self
     */
    public function setMigrationsDir($migrationsDir)
    {
        $this->migrationsDir = $migrationsDir;

        return $this;
    }

    /**
     * Gets the Composer action.
     *
     * @return string
     */
    public function getComposerAction()
    {
        return $this->composerAction;
    }

    /**
     * Sets the Composer action.
     *
     * @param string $composerAction the composer action
     *
     * @return self
     */
    public function setComposerAction($composerAction)
    {
        $this->composerAction = $composerAction;

        return $this;
    }

    /**
     * Gets the Package dir.
     *
     * @return string
     */
    public function getPackageDir()
    {
        return $this->packageDir;
    }

    /**
     * Sets the Package dir.
     *
     * @param string $packageDir the package dir
     *
     * @return self
     */
    public function setPackageDir($packageDir)
    {
        $this->packageDir = $packageDir;

        return $this;
    }
}


text:
				<img class="img-logo" src="<?php echo base_url() ?>assets/img/titulo-sub.png">
				<?php $c = 0; ?>
					<?php foreach ($photos as $photo) : ?>
					<div class="item <?php echo $c++ ? '' : 'active' ?>">

						<img src="<?php echo base_url() . 'assets/files/pages/photos/' . $photo->filename;?>" alt="First slide">

<?php echo $photo->description ?>

					<?php endforeach; ?>

					<img class="img-logo logo-right" src="<?php echo base_url() ?>assets/img/titulo-sub.png">
			<?php
				$dir = base_url('assets/img/umsa');
				$directorio = opendir('assets/img/umsa'); //ruta actual

				$array = array();
				while ($archivo = readdir($directorio)) {
					if (!is_dir($archivo) && strpos($archivo, '.JPG') !== FALSE)//verificamos si es o no un directorio
					{
						$array[] = $archivo;
					}
				}

				$c = 0;
				$max = 4;
				$num = count($array);
				$random = array();
				while ($c < $num && $c < $max) {
					$pos = rand(0, $num-1);
					if (empty($random[$pos])) {
						$random[$pos] = $array[$pos];
						$c++;
					}
				}

				$c = 0;
				foreach ($random as $img) { ?>
					<div class="item <?php echo $c++ ? '' : 'active' ?>">
						<img src="<?php echo $dir . '/' . $img;?>" alt="First slide">

					<?php
				} ?>

<?php echo $page->body ?>

Atractivos turísticos

<img src="<?php echo base_url() ?>assets/img/spinner.gif">

	<input type="hidden" id="pks" value="">


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

package com.centurylink.cloud.sdk;

import com.centurylink.cloud.sdk.core.config.SdkConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableClcSdk
public class TestConfig {

    @Bean
    public SdkConfiguration clcSdkConfig() {
        return SdkConfiguration.DEFAULT;
    }

}


text:
package slacker

import (
	"net/http"
	"net/http/httptest"
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func TestRTM(t *testing.T) {
	Convey("RTM Methods", t, func() {
		Convey("rtm.start success", func() {
			server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				_, err := w.Write([]byte(`{"ok": true, "url": "wss:\/\/ms100.slack-msgs.com\/websocket\/bunk"}`))
				if err != nil {
					panic(err)
				}
			}))
			Reset(func() { server.Close() })

			client := NewAPIClient("my-token", server.URL)
			result, err := client.RTMStart()
			So(err, ShouldBeNil)
			So(result.URL, ShouldEqual, "wss://ms100.slack-msgs.com/websocket/bunk")
		})
	})
}


text:
import RX = require("reactxp");
import Styles = require("../../styles/main");
import {PickerPropsItem} from "reactxp/dist/common/Types";
import {ButtonBar, ButtonProps} from "../../ButtonBar";
import {OnlinePlayerMetadata, RgbaColor} from "../../io/OnlinePlayerMetadata";
import {PickerPromptDialog} from "../../PickerPromptDialog";
import {TextPromptDialog} from "../../TextPromptDialog";
import {YesNoDialog} from "../../YesNoDialog";
import {TabView} from "../TabView";
import {BlacklistWhitelistPromptDialog} from "./BlacklistWhitelistPromptDialog";
import {UserManagementTabController} from "./UserManagementTabController";
import {UserManagementTabState} from "./UserManagementTabState";

export class UserManagementTabView extends TabView<UserManagementTabState> {

  public render() {
    const controller: UserManagementTabController = this.props.model.getController() as UserManagementTabController;
    const listFunctions: Array<((userId: string) => void)> = [controller.addToBlacklist, controller.removeFromBlacklist,
      controller.addToWhitelist, controller.removeFromWhitelist];
    const showBlackListWhitelist = () => BlacklistWhitelistPromptDialog.show("Blacklist/Whitelist Management",
      this.state.onlinePlayers, this.state.blacklist, this.state.whitelist, listFunctions, this);
    return (
      <RX.ScrollView>
        <RX.Button style={Styles.okButton} onPress={showBlackListWhitelist}>
          <RX.Text>Blacklist/Whitelist Management</RX.Text>
        </RX.Button>
        <RX.Text>There are currently {this.state.onlinePlayers.length} players online on this server:</RX.Text>
        {this.renderPlayerAndPermissionList(controller)}
        <RX.Text/>
      </RX.ScrollView>
    );
  }

  private renderPlayerAndPermissionList(controller: UserManagementTabController) {
    const renderColorString = (color: RgbaColor) => "rgba(" + color.r + "," + color.g + "," + color.b + "," + color.a + ")";
    const createColorStyle = (color: RgbaColor) => RX.Styles.createTextStyle({color: renderColorString(color)});
    return(
      this.state.onlinePlayers.map((player) => (
        <RX.View key={player.id}>
          <RX.Text style={createColorStyle(player.color)}>{player.name}</RX.Text>
          <ButtonBar buttons={this.createButtons(player, controller)}/>
        </RX.View>
    )));
  }

  private createButtons(player: OnlinePlayerMetadata, controller: UserManagementTabController): ButtonProps[] {
    const permissionItems: PickerPropsItem[] = [
      {label: "chat", value: "chat"}, {label: "cheat", value: "cheat"}, {label: "userManagement", value: "userManagement"},
      {label: "serverManagement", value: "serverManagement"}, {label: "debug", value: "debug"},
    ];
    const addPermissionPrompt = "Enter the permission to give (chat, cheat, userManagement, serverManagement, or debug).\n" +
      "NOTE: this is for console commands only";
    const removePermissionPrompt = "Enter the permission to remove (chat, cheat, userManagement, serverManagement, or debug).\n" +
      "NOTE: this is for console commands only";
    const kickUserPrompt = "Are you sure you want to kick " + player.name + "?";
    const renameUserPrompt = "Enter the new name for " + player.name + "\nWARNING: this command is buggy. Use at your own risk!";
    const showAddPermission = (playerName: string) => PickerPromptDialog
      .show(addPermissionPrompt, permissionItems, (permission) => controller.addPermission(playerName, permission));
    const showRemovePermission = (playerName: string) => PickerPromptDialog
      .show(removePermissionPrompt, permissionItems, (permission) => controller.removePermission(playerName, permission));
    const showRenameUser = (playerName: string) => TextPromptDialog
      .show(renameUserPrompt, (newName) => controller.renameUser(playerName, newName));
    const showKickUser = (playerName: string) => YesNoDialog
      .show(kickUserPrompt, () => controller.kickUser(playerName));
    return([
      {label: "Add Permission", style: "GREEN", onClick: () => showAddPermission(player.name)},
      {label: "Remove Permission", style: "GREEN", onClick: () => showRemovePermission(player.name)},
      {label: "Rename User", style: "GREEN", onClick: () => showRenameUser(player.name)},
      {label: "Kick User", style: "RED", onClick: () => showKickUser(player.name)},
    ]);
  }
}


text:
=============================
Write partitioning properties
=============================

``use-preferred-write-partitioning``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* **Type:** ``boolean``
* **Default value:** ``true``

Enable preferred write partitioning. When set to ``true`` and more than the
minimum number of partitions, set in ``preferred-write-partitioning-min-number-of-partitions``,
are written, each partition is written by a separate writer. As a result, for some connectors such as the
Hive connector, only a single new file is written per partition, instead of
multiple files. Partition writer assignments are distributed across worker
nodes for parallel processing.

``preferred-write-partitioning-min-number-of-partitions``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* **Type:** ``integer``
* **Default value:** ``50``

The minimum number of written partitions that is required to use connector
``preferred write partitioning``. If the number of partitions cannot be
estimated from the statistics, then preferred write partitioning is not used.
If the threshold value is ``1`` then ``preferred write partitioning`` is always
used.


text:
{% extends "_admin/templates/base.html" %}
{% block content %}

                Home

 Home

                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

 Welcome!

                    You are running a very early version of Findex ({{ version }}).

                        Keep an eye out on our Github to see if new versions are available.

            Version 2.3.1

        zzz. zzz

{% endblock %}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Caeoma cinctum Nees

### Remarks
null