text:
import Vue from 'vue';
import Vuex from 'vuex';
import VueResource from 'vue-resource'
import createLogger from 'vuex/dist/logger'
import loader from './modules/loader/index'
import lists from './modules/lists/index'
import shoppingList from './modules/shoping-list/index'

Vue.use(Vuex)
Vue.use(VueResource)

const debug = process.env.NODE_ENV !== 'production'

Vue.config.debug = debug

export default new Vuex.Store({
  modules: {
    loader,
    lists,
    shoppingList
  },
  strict: false,
  middlewares: debug ? [createLogger()] : []
})


text:
<?php

declare(strict_types=1);

namespace Vision\Http;

use Vision\DataStructures\Arrays\Mutator\SquareBracketNotation;
use Vision\Url\Url;

class Request extends Message implements RequestInterface
{
    /** @var Url */
    private $url;

    /** @var SquareBracketNotation $queryParams */
    private $queryParams;

    /** @var SquareBracketNotation $bodyParams */
    private $bodyParams;

    /** @var SquareBracketNotation $serverParams */
    private $serverParams;

    /** @var SquareBracketNotation $files */
    private $files;

    /** @var SquareBracketNotation $cookies */
    private $cookies;

    /** @var string|null $method */
    private $method;

    /** @var string|null $basePath */
    private $basePath;

    /** @var string|null $pathInfo */
    private $pathInfo;

    /**
     * @param Url $url
     * @param array $queryParams
     * @param array $bodyParams
     * @param array $serverParams
     * @param array $files
     * @param array $cookies
     */
    public function __construct(
        Url $url,
        array $queryParams,
        array $bodyParams,
        array $serverParams,
        array $files,
        array $cookies
    ) {
        $this->url = $url;
        $this->queryParams = new SquareBracketNotation($queryParams);
        $this->bodyParams = new SquareBracketNotation($bodyParams);
        $this->serverParams = new SquareBracketNotation($serverParams);
        $this->files = new SquareBracketNotation($files);
        $this->cookies = new SquareBracketNotation($cookies);

        if (isset($this->serverParams['REQUEST_METHOD'])) {
            $this->method = strtoupper($this->serverParams['REQUEST_METHOD']);
        }

        $this->initBasePath()
             ->initPathInfo();
    }

    /**
     * @return Url
     */
    public function getUrl(): Url
    {
        return $this->url;
    }

    /**
     * @return SquareBracketNotation
     */
    public function getQueryParams(): SquareBracketNotation
    {
        return $this->queryParams;
    }

    /**
     * @return SquareBracketNotation
     */
    public function getBodyParams(): SquareBracketNotation
    {
        return $this->bodyParams;
    }

    /**
     * @return SquareBracketNotation
     */
    public function getServerParams(): SquareBracketNotation
    {
        return $this->serverParams;
    }

    /**
     * @return SquareBracketNotation
     */
    public function getFiles(): SquareBracketNotation
    {
        return $this->files;
    }

    /**
     * @return SquareBracketNotation
     */
    public function getCookies(): SquareBracketNotation
    {
        return $this->cookies;
    }

    /**
     * @return bool
     */
    public function isPost(): bool
    {
        return $this->method === 'POST';
    }

    /**
     * @return bool
     */
    public function isGet(): bool
    {
        return $this->method === 'GET';
    }

    /**
     * @return bool
     */
    public function isHead(): bool
    {
        return $this->method === 'HEAD';
    }

    /**
     * @return bool
     */
    public function isPut(): bool
    {
        return $this->method === 'PUT';
    }

    /**
     * @return bool
     */
    public function isDelete(): bool
    {
        return $this->method === 'DELETE';
    }

    /**
     * @return bool
     */
    public function isSecure(): bool
    {
        return $this->getUrl()->getScheme() === 'https';
    }

    /**
     * Returns the current request method.
     *
     * @return string
     */
    public function getMethod(): string
    {
        return $this->method;
    }

    /**
     * @return string
     */
    public function getBaseUrl(): string
    {
        return (clone $this->getUrl())
            ->setPath($this->getBasePath() . '/')
            ->setQuery(null)
            ->setFragment(null)
            ->__toString();
    }

    /**
     * Get base path of current url.
     *
     * Example: http://www.example.com/foo/index.php/bar
     * Result: "/foo"
     *
     * @return string
     */
    public function getBasePath(): string
    {
        return $this->basePath;
    }

    /**
     * Get path info of current url.
     *
     * Example: http://www.example.com/foo/index.php/bar
     * Result: "/bar"
     *
     * @return string
     */
    public function getPathInfo(): string
    {
        return $this->pathInfo;
    }

    /**
     * @return Request
     */
    private function initBasePath(): self
    {
        $basePath = '';

        if (isset($this->serverParams['SCRIPT_NAME'])) {
            $basePath = dirname($this->serverParams['SCRIPT_NAME']);
        }

        if ($basePath === '.') {
            $basePath = '';
        }

        if (DIRECTORY_SEPARATOR === '\\') {
            $basePath = str_replace('\\', '/', $basePath);
        }

        $this->basePath = rtrim($basePath, '/');

        return $this;
    }

    /**
     * @return Request
     */
    private function initPathInfo(): self
    {
        if (isset($this->serverParams['PATH_INFO'])) {
            $this->pathInfo = $this->serverParams['PATH_INFO'];
        } elseif (isset($this->serverParams['REQUEST_URI'])) {
            $scriptName = $this->serverParams['SCRIPT_NAME'] ?? '';
            $pathInfo = str_replace($scriptName, '', $this->serverParams['REQUEST_URI']);
            $pathInfoWithoutQueryString = strstr($pathInfo, '?', true);
            $this->pathInfo = $pathInfoWithoutQueryString ?: $pathInfo;
        }

        return $this;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.jmeter.protocol.http.util;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.http.config.GraphQLRequestParams;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

import com.fasterxml.jackson.core.JsonProcessingException;

class TestGraphQLRequestParamUtils {

    private static final String OPERATION_NAME = "";

    private static final String QUERY =
            "query($id: ID!) {\n"
            + "  droid(id: $id) {\n"
            + "    id\n"
            + "    name\n"
            + "    friends {\n"
            + "      id\n"
            + "      name\n"
            + "      appearsIn\n"
            + "    }\n"
            + "  }\n"
            + "}\n";

    private static final String VARIABLES =
            "{\n"
            + "  \"id\": \"2001\"\n"
            + "}\n";

    private static final String EXPECTED_QUERY_GET_PARAM_VALUE =
            "query($id: ID!) { droid(id: $id) { id name friends { id name appearsIn } } }";

    private static final String EXPECTED_VARIABLES_GET_PARAM_VALUE = "{\"id\":\"2001\"}";

    private static final String EXPECTED_POST_BODY =
            "{"
            + "\"operationName\":null,"
            + "\"variables\":" + EXPECTED_VARIABLES_GET_PARAM_VALUE + ","
            + "\"query\":\"" + StringUtils.replace(QUERY.trim(), "\n", "\\n") + "\""
            + "}";

    private GraphQLRequestParams params;

    @BeforeEach
    void setUp() {
        params = new GraphQLRequestParams(OPERATION_NAME, QUERY, VARIABLES);
    }

    @ParameterizedTest
    @ValueSource(strings = { "application/json", "application/json;charset=utf-8", "application/json; charset=utf-8" })
    void testIsGraphQLContentType(String contentType) throws Exception {
        assertTrue(GraphQLRequestParamUtils.isGraphQLContentType(contentType));
    }

    // null can't be used in a ValueSource directly, so we need to use a MethodSource
    static Stream<String> invalidContentTypes() {
        return Stream.of("application/vnd.api+json", "application/json-patch+json", "",
            null);
    }

    @ParameterizedTest
    @MethodSource("invalidContentTypes")
    void testInvalidGraphQLContentType(String contentType) {
        assertFalse(GraphQLRequestParamUtils.isGraphQLContentType(contentType));
    }

    @Test
    void testToPostBodyString() throws Exception {
        assertEquals(EXPECTED_POST_BODY, GraphQLRequestParamUtils.toPostBodyString(params));
    }

    @Test
    void testQueryToGetParamValue() throws Exception {
        assertEquals(EXPECTED_QUERY_GET_PARAM_VALUE, GraphQLRequestParamUtils.queryToGetParamValue(params.getQuery()));
    }

    @Test
    void testVariablesToGetParamValue() throws Exception {
        assertEquals(EXPECTED_VARIABLES_GET_PARAM_VALUE,
                GraphQLRequestParamUtils.variablesToGetParamValue(params.getVariables()));
    }

    @Test
    void testToGraphQLRequestParamsWithPostData() throws Exception {
        GraphQLRequestParams params = GraphQLRequestParamUtils
                .toGraphQLRequestParams(EXPECTED_POST_BODY.getBytes(StandardCharsets.UTF_8), null);
        assertNull(params.getOperationName());
        assertEquals(QUERY.trim(), params.getQuery());
        assertEquals(EXPECTED_VARIABLES_GET_PARAM_VALUE, params.getVariables());

        params = GraphQLRequestParamUtils.toGraphQLRequestParams(
                "{\"operationName\":\"op1\",\"variables\":{\"id\":123},\"query\":\"query { droid { id }}\"}"
                        .getBytes(StandardCharsets.UTF_8),
                null);
        assertEquals("op1", params.getOperationName());
        assertEquals("query { droid { id }}", params.getQuery());
        assertEquals("{\"id\":123}", params.getVariables());
    }

    @ParameterizedTest
    @ValueSource(strings = { "", "{}"})
    void testInvalidJsonData(String postDataAsString) throws JsonProcessingException, UnsupportedEncodingException {
        byte[] postData = postDataAsString.getBytes(StandardCharsets.UTF_8);
        assertThrows(IllegalArgumentException.class,
                () -> {
                    GraphQLRequestParamUtils.toGraphQLRequestParams(postData, null);
                });
    }

    @ParameterizedTest
    @ValueSource(strings = { "{\"query\":\"select * from emp\"}",
            "{\"operationName\":{\"id\":123},\"query\":\"query { droid { id }}\"}",
            "{\"variables\":\"r2d2\",\"query\":\"query { droid { id }}\"}" })
    void testInvalidGraphQueryParam(String postDataAsString)
            throws JsonProcessingException, UnsupportedEncodingException {
        byte[] postData = postDataAsString.getBytes(StandardCharsets.UTF_8);
        assertThrows(IllegalArgumentException.class, () -> {
            GraphQLRequestParamUtils.toGraphQLRequestParams(postData, null);
        });
    }

    @Test
    void testToGraphQLRequestParamsWithHttpArguments() throws Exception {
        Arguments args = new Arguments();
        args.addArgument(new HTTPArgument("query", "query { droid { id }}", "=", false));
        GraphQLRequestParams params = GraphQLRequestParamUtils.toGraphQLRequestParams(args, null);
        assertNull(params.getOperationName());
        assertEquals("query { droid { id }}", params.getQuery());
        assertNull(params.getVariables());

        args = new Arguments();
        args.addArgument(new HTTPArgument("operationName", "op1", "=", false));
        args.addArgument(new HTTPArgument("query", "query { droid { id }}", "=", false));
        args.addArgument(new HTTPArgument("variables", "{\"id\":123}", "=", false));
        params = GraphQLRequestParamUtils.toGraphQLRequestParams(args, null);
        assertEquals("op1", params.getOperationName());
        assertEquals("query { droid { id }}", params.getQuery());
        assertEquals("{\"id\":123}", params.getVariables());

        args = new Arguments();
        args.addArgument(new HTTPArgument("query", "query+%7B+droid+%7B+id+%7D%7D", "=", true));
        params = GraphQLRequestParamUtils.toGraphQLRequestParams(args, null);
        assertNull(params.getOperationName());
        assertEquals("query { droid { id }}", params.getQuery());
        assertNull(params.getVariables());

        args = new Arguments();
        args.addArgument(new HTTPArgument("query", "query%20%7B%20droid%20%7B%20id%20%7D%7D", "=", true));
        params = GraphQLRequestParamUtils.toGraphQLRequestParams(args, null);
        assertNull(params.getOperationName());
        assertEquals("query { droid { id }}", params.getQuery());
        assertNull(params.getVariables());
    }

    @Test
    void testMissingParams() throws UnsupportedEncodingException {
        Arguments args = new Arguments();
        assertThrows(IllegalArgumentException.class,
                () -> GraphQLRequestParamUtils.toGraphQLRequestParams(args, null));
    }

    @Test
    void testInvalidQueryParam() throws UnsupportedEncodingException {
        Arguments args = new Arguments();
        args.addArgument(new HTTPArgument("query", "select * from emp", "=", false));
        assertThrows(IllegalArgumentException.class,
                () -> GraphQLRequestParamUtils.toGraphQLRequestParams(args, null));
    }

    @Test
    void testInvalidQueryParamVariables() throws UnsupportedEncodingException {
        Arguments args = new Arguments();
        args.addArgument(new HTTPArgument("query", "query { droid { id }}", "=", false));
        args.addArgument(new HTTPArgument("variables", "r2d2", "=", false));
        assertThrows(IllegalArgumentException.class,
                () -> GraphQLRequestParamUtils.toGraphQLRequestParams(args, null));
    }
}


text:
<?php

namespace RachidLaasri\LaravelInstaller\Controllers;

use Illuminate\Routing\Controller;

class WelcomeController extends Controller
{
    /**
     * Display the installer welcome page.
     *
     * @return \Illuminate\View\View
     */
    public function welcome()
    {
        return view('vendor.installer.welcome');
    }
}


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('problem', '0004_populate_attachment_field'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='problem',
            name='attachments',
        ),
        migrations.AlterField(
            model_name='problemattachment',
            name='problem',
            field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='problem.Problem'),
            preserve_default=False,
        ),
    ]


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="bankroll">
        <note>
            Frames file for 'bankroll' based on sentences in wsj.  No Verbnet
            entry.
        </note>

        <roleset id="bankroll.01" name="provide funding for" vncls="-">
            <roles>
                <role descr="financ(i)er" n="0"/>
                <role descr="thing financed" n="1"/>
                <role descr="money" n="2"/>
            </roles>

            <example name="hollywood glitz">
                <inflection aspect="ns" form="infinitive" person="ns" tense="ns" voice="ns"/>
                <text>
                    Their stock in trade as ``executive producers'' is sniffing out
                    hot properties, locking them up and then getting big studios to
                    bankroll and distribute them.
                </text>
                <arg n="0">big studios</arg>
                <rel>bankroll</rel>
                <arg n="1">them</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
#import "NSObject.h"

// Not exported
@interface CHXCategoryAxis : NSObject
{
}

+ (id)chdAxisFromXmlAxisElement:(struct _xmlNode *)arg1 state:(id)arg2;

@end


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

<feed xmlns="http://www.w3.org/2005/Atom"
      xmlns:g="http://base.google.com/ns/1.0">

  <title>expiration_date_time test case 1</title>
  <link href="http://base.google.com/base/attribute_list.html" />
  <updated>2003-12-13T18:30:02Z</updated>
  <id>http://feedvalidator.org/gbase</id>
  <author><name>Google</name></author>

  <entry>
    <title>expiration_date_time test case 1</title>
    <id>tag:base.google.com,2005:expiration_date_time_1</id>
    <link href="http://base.google.com/base/attribute_list.html#expiration_date_time" />
    <updated>2003-12-13T18:30:02Z</updated>

      From expiration_date_time

    <g:expiration_date_time>2005-12-20T11:59:59</g:expiration_date_time>
  </entry>
</feed>


text:
// Provides control sap.m.MultiInput.
sap.ui.define(['jquery.sap.global', './Input', './Token', './library', 'sap/ui/core/Item'],
	function(jQuery, Input, Token, library, Item) {
	"use strict";

	/**
	 * Constructor for a new MultiInput.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * MultiInput provides functionality to add / remove / enter tokens
	 * @extends sap.m.Input
	 *
	 * @author SAP SE
	 * @version 1.38.4
	 *
	 * @constructor
	 * @public
	 * @alias sap.m.MultiInput
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var MultiInput = Input.extend("sap.m.MultiInput", /** @lends sap.m.MultiInput.prototype */ { metadata : {

		library : "sap.m",
		properties : {

			/**
			 * If set to true, the MultiInput will be displayed in multi-line display mode.
			 * In multi-line display mode, all tokens can be fully viewed and easily edited in the MultiInput.
			 * The default value is false.
			 * @since 1.28
			 */
			enableMultiLineMode : {type : "boolean", group : "Behavior", defaultValue : false},

			/**
			 * The max number of tokens that is allowed in MultiInput.
			 * @since 1.36
			 */
			maxTokens: {type : "int", group : "Behavior"}
		},
		aggregations : {

			/**
			 * The currently displayed tokens
			 */
			tokens : {type : "sap.m.Token", multiple : true, singularName : "token"},

			/**
			 * The tokenizer which displays the tokens
			 */
			tokenizer : {type : "sap.m.Tokenizer", multiple : false, visibility : "hidden"}
		},
		events : {

			/**
			 * Fired when the tokens aggregation changed (add / remove token)
			 */
			tokenChange : {
				parameters : {

					/**
					 * Type of tokenChange event.
					 * There are four TokenChange types: "added", "removed", "removedAll", "tokensChanged".
					 * Use Tokenizer.TokenChangeType.Added for "added",	Tokenizer.TokenChangeType.Removed for "removed", Tokenizer.TokenChangeType.RemovedAll for "removedAll" and Tokenizer.TokenChangeType.TokensChanged for "tokensChanged".
					 */
					type: { type : "string"},

					/**
					 * The added token or removed token.
					 * This parameter is used when tokenChange type is "added" or "removed".
					 */
					token: { type: "sap.m.Token"},

					/**
					 * The array of removed tokens.
					 * This parameter is used when tokenChange type is "removedAll".
					 */
					tokens: { type: "sap.m.Token[]"},

					/**
					 * The array of tokens that are added.
					 * This parameter is used when tokenChange type is "tokenChanged".
					 */
					addedTokens :  { type: "sap.m.Token[]"},

					/**
					 * The array of tokens that are removed.
					 * This parameter is used when tokenChange type is "tokenChanged".
					 */
					removedTokens :  { type: "sap.m.Token[]"}
				}
			}
		}
	}});

	var oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m");

	// create an ARIA announcement and remember its ID for later use in the renderer:
	MultiInput.prototype._sAriaMultiInputContainTokenId = new sap.ui.core.InvisibleText({
		text: oRb.getText("MULTIINPUT_ARIA_CONTAIN_TOKEN")
	}).toStatic().getId();

	// **
	// * This file defines behavior for the control,
	// */
	MultiInput.prototype.init = function() {
		var that = this;
		this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m");

		Input.prototype.init.call(this);

		this._bIsValidating = false;
		this._tokenizer = new sap.m.Tokenizer();

		this.setAggregation("tokenizer", this._tokenizer);
		this._tokenizer.attachTokenChange(function(args) {

			that.fireTokenChange(args.getParameters());
			that.invalidate();

			if (that._bUseDialog && that._tokenizerInPopup && that._tokenizer.getParent() instanceof sap.m.Dialog) {
				that._showAllTokens(that._tokenizerInPopup);
				return;
			} else {

				that._setContainerSizes();

				// check if active element is part of MultiInput
				var bFocusOnMultiInput = jQuery.sap.containsOrEquals(that.getDomRef(), document.activeElement);
				if (args.getParameter("type") === "tokensChanged" && args.getParameter("removedTokens").length > 0 && bFocusOnMultiInput) {
					that.focus();
				}

				if (args.getParameter("type") === "removed" && that._isMultiLineMode ) {

					var iLength = that.getTokens().length;
					if (iLength > 1) {
						that.getTokens()[iLength - 1].setVisible(true);
					} else {
						//all tokens are deleted, indicator do not show
						that._showAllTokens(that._tokenizer);
					}
				}

			}
		});

		this.setShowValueHelp(true);
		this.setShowSuggestion(true);

		this.addStyleClass("sapMMultiInput");

		this.attachSuggestionItemSelected(function(eventArgs) {
			var item = null;
			var token = null;
			if (this._hasTabularSuggestions()) {
				item = eventArgs.getParameter("selectedRow");
			} else {
				item = eventArgs.getParameter("selectedItem");
				if (item) {
					token = new Token({
						text : item.getText(),
						key : item.getKey()
					});
				}
			}

			//length of tokens before validating
			var iOldLength = that._tokenizer.getTokens().length;

			if (item) {
				var text = this.getValue();
				that._tokenizer.addValidateToken({
					text : text,
					token : token,
					suggestionObject : item,
					validationCallback : function(validated) {
						if (validated) {
							that.setValue("");
						}
					}
				});
			}

			//dialog opens
			if (that._bUseDialog && that._tokenizerInPopup && that._tokenizerInPopup.getParent() instanceof sap.m.Dialog) {
				//clone newly added token to tokenizerinpopup to display in popup
				var iNewLength = that._tokenizer.getTokens().length;
				if ( iOldLength < iNewLength ) {
					var oNewToken = that._tokenizer.getTokens()[iNewLength - 1];
					that._updateTokenizerInPopup(oNewToken);
					that.setValue("");
				}

				if (that._tokenizerInPopup.getVisible() === false){
					that._tokenizerInPopup.setVisible(true);
				}

				that._setAllTokenVisible(that._tokenizerInPopup);

				if (that._oList instanceof sap.m.Table) {
					// CSN# 1421140/2014: hide the table for empty/initial results to not show the table columns
					that._oList.addStyleClass("sapMInputSuggestionTableHidden");
				} else {
					that._oList.destroyItems();
				}

				var oScroll = that._oSuggestionPopup.getScrollDelegate();
				if (oScroll) {
					oScroll.scrollTo(0, 0, 0);
				}

				that._oPopupInput.focus();

			}
		});

		this.attachLiveChange(function(eventArgs) {
			that._tokenizer.removeSelectedTokens();

			if (that._bUseDialog && that._isMultiLineMode) {
				var sValue = eventArgs.getParameter("newValue");

				// hide tokens while typing when there is suggestions
				if ( that._oSuggestionPopup && that._oSuggestionPopup.getContent().length > 1 && sValue.length > 0) {
					that._tokenizerInPopup.setVisible(false);
				} else {
					that._tokenizerInPopup.setVisible(true);
					that._setAllTokenVisible(that._tokenizerInPopup);
				}
			} else {
				that._setContainerSizes();
				that._tokenizer.scrollToStart();
			}

		});

		sap.ui.Device.orientation.attachHandler(this._onOrientationChange, this);

		this._sResizeHandlerId = sap.ui.core.ResizeHandler.register(this, function() {
			// we could have more or less space to our disposal, thus calculate size of input again
			that._setContainerSizes();
		});

		if (!(this._bUseDialog && this._oSuggestionPopup)) {
			// attach SuggestionItemSelected event to set value after item selected, not after popup is closed.
			this.attachSuggestionItemSelected(function() {
				setTimeout(function() {
					that._tokenizer.scrollToEnd();
				}, 0);
			});
		}
	};

	/**
	 * Update tokens in tokenizer which is created in suggestion popup in multi-line mode.
	 *
	 * @param {sap.m.Token} token that needed added to tokenizer in popup.
	 * @since 1.28
	 * @private
	 */
	MultiInput.prototype._updateTokenizerInPopup = function(oToken) {
		//addToken to tokenizerInPopup, just to display tokens in popup, the actual token is still in multiinput._tokenizer
		var oNewTokenInPopup = oToken.clone();
		oNewTokenInPopup.attachDelete(this._tokenizerInPopup._onDeleteToken, this._tokenizerInPopup);
		oNewTokenInPopup.attachPress(this._tokenizerInPopup._onTokenPress, this._tokenizerInPopup);
		this._tokenizerInPopup.insertToken(oNewTokenInPopup, 0);
	};

	/**
	 * Update tokens in tokenizer which is child of MultiInput, to sync with the tokenizer in popup in multi-line mode
	 *
	 * @since 1.28
	 * @private
	 */
	MultiInput.prototype._updateTokenizerInMultiInput = function() {
		var iTokenizerLength =  this._tokenizer.getTokens().length;
		var iTokenizerInPopupLength = this._tokenizerInPopup.getTokens().length;
		var i = 0, aRemoveTokens = [];

		for ( i = 0; i < iTokenizerLength; i++ ){
			var oToken = this._tokenizer.getTokens()[i];
			var j = 0;
			while ( j < iTokenizerInPopupLength && this._tokenizerInPopup.getTokens()[j].getId().indexOf(oToken.getId()) < 0 ){
				j++;
			}
			if ( j === iTokenizerInPopupLength) {
				aRemoveTokens.push(oToken);
			}

		}

		if (aRemoveTokens.length > 0) {
			for ( i = 0; i < aRemoveTokens.length; i++ ){
				this._tokenizer.removeToken(aRemoveTokens[i]);
			}

			this.fireTokenChange({
				addedTokens : [],
				removedTokens : [aRemoveTokens],
				type : sap.m.Tokenizer.TokenChangeType.TokensChanged
			});
		}

	};

	/**
	 * Set all tokens in tokenizer visible in multi-line mode.
	 *
	 * @since 1.28
	 * @private
	 */
	MultiInput.prototype._setAllTokenVisible = function(oTokenizer) {
		if (oTokenizer.getVisible() === false){
			oTokenizer.setVisible(true);
		}

		var aTokens = oTokenizer.getTokens();
		if ( aTokens.length > 0 ) {
			var i = 0;
			for (i = 0; i < aTokens.length; i++) {
				aTokens[i].setVisible(true);
			}
		}
	};

	/**
	 * Set all tokens in tokenizer invisible in multi-line mode.
	 *
	 * @since 1.28
	 * @private
	 */
	MultiInput.prototype._setAllTokenInvisible = function() {

		var aTokens = this.getTokens();
		if ( aTokens.length > 0 ) {
			var i = 0;
			for (i = 0; i < aTokens.length; i++) {
				aTokens[i].setVisible(false);
			}
		}
	};

	/**
	 * Show indicator in multi-line mode
	 *
	 * @since 1.28
	 * @private
	 */
	MultiInput.prototype._showIndicator = function() {

		var aTokens = this.getTokens(),
		    iToken = aTokens.length;

		this._tokenizer.setVisible(true);

		if (iToken > 1) {

			var i = 0;
			for ( i = 0; i < iToken - 1; i++ ) {
				aTokens[i].setVisible(false);
			}

			// remove the old tokenizer indicator
			if (this.$().find(".sapMMultiInputIndicator").length !== 0) {
				this._removeIndicator();
			}
			var oMessageBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m");
			var sSpanText = "" + oMessageBundle.getText("MULTIINPUT_SHOW_MORE_TOKENS", iToken - 1) + "";

			this.$().find(".sapMTokenizer").after(sSpanText);
			this._setValueInvisible();
		}

		this._bShowIndicator = true;
	};

	/**
	 * Set value in input field invisible.
	 *
	 * @since 1.38
	 * @private
	 */
	MultiInput.prototype._setValueInvisible = function() {
		this.$("inner").css("opacity", "0");
	};

	/**
	 * Show value in input field
	 *
	 * @since 1.38
	 * @private
	 */
	MultiInput.prototype._setValueVisible = function() {
		this.$("inner").css("opacity", "1");
	};

	/**
	 * Show all tokens in multi-line mode
	 *
	 * @since 1.28
	 * @private
	 */
	MultiInput.prototype._showAllTokens = function(oTokenizer) {

		this._setAllTokenVisible(oTokenizer);
		this._removeIndicator();
	};

	/**
	 * Remove tokenizer indicator
	 *
	 * @since 1.30
	 * @private
	 */
	MultiInput.prototype._removeIndicator = function() {
		this.$().find(".sapMMultiInputIndicator").remove();
		this._bShowIndicator = false;

	};

	/**
	 * Setter for property enableMultiLineMode.
	 *
	 * @since 1.28
	 * @public
	 */
	MultiInput.prototype.setEnableMultiLineMode = function(bMultiLineMode) {
		this.setProperty("enableMultiLineMode", bMultiLineMode, true);

		this.closeMultiLine();
		var that = this;

		//only show multiline mode in phone mode
		if (this._bUseDialog) {
			bMultiLineMode = true;
		}

		if (bMultiLineMode){

			this._showIndicator();
			this._isMultiLineMode = true;

			if (this.getDomRef()) {
				setTimeout(function() {
					that._setContainerSizes();
				}, 0);
			}

		} else {
			this._isMultiLineMode = false;

			this._showAllTokens(this._tokenizer);
			this.setValue("");

			if (this.getDomRef()) {
				setTimeout(function() {
					that._setContainerSizes();
					that._scrollAndFocus();
				}, 0);
			}
		}

		return this;
	};

	/**
	 * Expand multi-line MultiInput in multi-line mode
	 *
	 * @since 1.28
	 * @public
	 */
	MultiInput.prototype.openMultiLine = function(){
		this._setValueVisible();
		this.$("border").addClass("sapMMultiInputMultiModeBorder");
		if (this._$input) {
			this._$input.parent().addClass("sapMMultiInputMultiModeInputContainer");
		}

		//need this attribute to enable value help icon focusable
		this.$().find(".sapMInputValHelp").attr("tabindex","-1");

		// necessary to display expanded MultiInput which is inside layout
		var oParent = this.getParent();
		this._originalOverflow = null;
		if (oParent && oParent.$ && oParent.$().css("overflow") === "hidden") {
			this._originalOverflow = oParent.$().css("overflow");
			oParent.$().css("overflow", "visible");
		}

		// necessary to display expanded MultiInput which is inside SimpleForm
		var $Parent;
		if (this.$().closest('.sapUiVlt').length !== 0) {
			$Parent = this.$().closest('.sapUiVlt');
		} else if (this.$().parent('[class*="sapUiRespGridSpan"]').length !== 0) {
			$Parent = this.$().parent('[class*="sapUiRespGridSpan"]');
		} else if (this.$().parents(".sapUiRFLContainer").length !== 0) {
			$Parent = this.$().parents(".sapUiRFLContainer");
		}

		if ($Parent && $Parent.length > 0 && $Parent.css("overflow") === "hidden") {
			$Parent.css("overflow", "visible");
		}

	};

	/**
	 * Close multi-line MultiInput in multi-line mode
	 *
	 * @since 1.28
	 * @public
	 */
	MultiInput.prototype.closeMultiLine = function(){
			this.$("border").removeClass("sapMMultiInputMultiModeBorder");
			if (this._$input) {
				this._$input.parent().removeClass("sapMMultiInputMultiModeInputContainer");
			}

			//remove this attribute to set value help icon back not focusable
			this.$().find(".sapMInputValHelp").removeAttr("tabindex");

			// set overflow back
			if (this._originalOverflow) {
				var oParent = this.getParent();
				oParent.$().css("overflow", this._originalOverflow);
			}
	};

	/**
	 * Function gets called when orientation of mobile devices changes, triggers recalculation of layout
	 *
	 * @private
	 *
	 */
	MultiInput.prototype._onOrientationChange = function() {
		this._setContainerSizes();
	};

	/**
	 * Returns the sap.ui.core.ScrollEnablement delegate which is used with this control.
	 *
	 * @private
	 */
	MultiInput.prototype.getScrollDelegate = function() {
		return this._tokenizer._oScroller;
	};

	/**
	 * Function cleans up registered eventhandlers
	 *
	 * @private
	 */
	MultiInput.prototype.exit = function() {
		if (this._sResizeHandlerId) {
			sap.ui.core.ResizeHandler.deregister(this._sResizeHandlerId);
			delete this._sResizeHandlerId;
		}

		Input.prototype.exit.apply(this, arguments);
	};

	/**
	 * Function calculates and sets width of tokenizer and input field
	 *
	 * @private
	 *
	 */
	MultiInput.prototype._setContainerSizes = function() {

		var thisDomRef = this.getDomRef();
		if (!thisDomRef) {
			return;
		}
		var $this = this.$();

		if (this.getTokens().length > 0) {
			$this.find(".sapMMultiInputBorder").addClass("sapMMultiInputNarrowBorder");
		} else {
			$this.find(".sapMMultiInputBorder").removeClass("sapMMultiInputNarrowBorder");
		}

		this.$("inner").css("width", "");

		// we go to the sapMMultiInputBorder child elements, this makes the computations easier
		var availableWidth = $this.find(".sapMMultiInputBorder").width();

		// calculate minimal needed width for input field
		var shadowDiv = $this.children(".sapMMultiInputShadowDiv")[0];
		var $indicator = $this.find(".sapMMultiInputBorder").find(".sapMMultiInputIndicator");

		jQuery(shadowDiv).text(this.getValue());

		var inputWidthMinimalNeeded = jQuery(shadowDiv).width();
		var iIndicatorWidth = jQuery($indicator).width();

		var tokenizerWidth = this._tokenizer.getScrollWidth();

		// the icon
		var iconWidth = $this.find(".sapMInputValHelp").outerWidth(true);

		if (iIndicatorWidth !== null && this._isMultiLineMode && this._bShowIndicator) {
			inputWidthMinimalNeeded = iIndicatorWidth;
		}

		var totalNeededWidth = tokenizerWidth + inputWidthMinimalNeeded + iconWidth;
		var inputWidth;
		var additionalWidth = 1;

		if (!this._bUseDialog && this._isMultiLineMode && !this._bShowIndicator && this.$().find(".sapMMultiInputBorder").length > 0) {

			var $border = this.$().find(".sapMMultiInputBorder"),
				iMaxHeight = parseInt(($border.css("max-height") || 0), 10),
				iScrollHeight = $border[0].scrollHeight,
				iTokenizerWidth = availableWidth - iconWidth;

			if (iMaxHeight < iScrollHeight) {
				//if scroll height exceeds maxHeight, scroll bar also takes width
				iTokenizerWidth = iTokenizerWidth - 17; // 17px is scroll bar width
			}

			this._tokenizer.setPixelWidth(iTokenizerWidth); // 17px is scroll bar width
			this.$("inner").css("width", iTokenizerWidth + "px");

		} else {
			if (totalNeededWidth < availableWidth) {
				inputWidth = inputWidthMinimalNeeded + availableWidth - totalNeededWidth;
			} else {
				if (tokenizerWidth === 0 && inputWidthMinimalNeeded > availableWidth) {
				//if there is no token in multiinput, the innerinput width should not exceed multiinput width
					inputWidth = availableWidth;
				} else {
					inputWidth = inputWidthMinimalNeeded + additionalWidth;
					tokenizerWidth = availableWidth - inputWidth - iconWidth;
				}

			}

			jQuery($this.find(".sapMInputBaseInner")[0]).css("width", inputWidth + "px");

			this._tokenizer.setPixelWidth(tokenizerWidth);
		}

		if (this.getPlaceholder()) {
			this._sPlaceholder = this.getPlaceholder();
		}

		if (this.getTokens().length > 0) {
			this.setPlaceholder("");
		} else {
			this.setPlaceholder(this._sPlaceholder);
		}

		//truncate token in multi-line mode
		if (this._bUseDialog
				&& this._isMultiLineMode
					&& this._oSuggestionPopup
						&& this._oSuggestionPopup.isOpen()
							&& this._tokenizerInPopup
								&& this._tokenizerInPopup.getTokens().length > 0) {

			var iPopupTokens = this._tokenizerInPopup.getTokens().length,
				oLastPopupToken = this._tokenizerInPopup.getTokens()[iPopupTokens - 1],
				$oLastPopupToken = oLastPopupToken.$(),
				iTokenWidth = oLastPopupToken.$().outerWidth(),
				iPopupContentWidth = this._oSuggestionPopup.$().find(".sapMDialogScrollCont").width(),
				iBaseFontSize = parseFloat(sap.m.BaseFontSize) || 16,
				iTokenizerWidth = iPopupContentWidth - 2 * iBaseFontSize; //padding left and right

			if (iTokenizerWidth < iTokenWidth) {
				$oLastPopupToken.outerWidth(iTokenizerWidth, true);
				$oLastPopupToken.css("overflow", "hidden");
				$oLastPopupToken.css("text-overflow", "ellipsis");
				$oLastPopupToken.css("white-space", "nowrap");
			}

		}

	};

	/**
	 * Called after the control is rendered.
	 *
	 * @private
	 */
	MultiInput.prototype.onAfterRendering = function() {

		Input.prototype.onAfterRendering.apply(this, arguments);

		this._setContainerSizes();

	};

	/**
	 * Function adds an validation callback called before any new token gets added to the tokens aggregation
	 *
	 * @param {function} fValidator
	 * @public
	 */
	MultiInput.prototype.addValidator = function(fValidator) {
		this._tokenizer.addValidator(fValidator);
	};

	/**
	 * Function removes an validation callback
	 *
	 * @param {function} fValidator
	 * @public
	 */
	MultiInput.prototype.removeValidator = function(fValidator) {
		this._tokenizer.removeValidator(fValidator);
	};

	/**
	 * Function removes all validation callbacks
	 *
	 * @public
	 */
	MultiInput.prototype.removeAllValidators = function() {
		this._tokenizer.removeAllValidators();
	};

	/**
	 * Called when the user presses the down arrow key
	 * @param {jQuery.Event} oEvent The event triggered by the user
	 * @private
	 */
	MultiInput.prototype.onsapnext = function(oEvent) {

		if (oEvent.isMarked()) {
			return;
		}

		// find focused element
		var oFocusedElement = jQuery(document.activeElement).control()[0];

		if (!oFocusedElement) {
			// we cannot rule out that the focused element does not correspond to a SAPUI5 control in which case oFocusedElement
			// is undefined
			return;
		}

		if (this._tokenizer === oFocusedElement || this._tokenizer.$().find(oFocusedElement.$()).length > 0) {
			// focus is on the tokenizer or on some descendant of the tokenizer and the event was not handled ->
			// we therefore handle the event and focus the input element
			this._scrollAndFocus();
		}

	};

	/**
	 * Function is called on keyboard backspace, if cursor is in front of an token, token gets selected and deleted
	 *
	 * @private
	 * @param {jQuery.event}
	 *          oEvent
	 */
	MultiInput.prototype.onsapbackspace = function(oEvent) {
		if (this.getCursorPosition() > 0 || !this.getEditable() || this.getValue().length > 0) {
			// deleting characters, not
			return;
		}

		sap.m.Tokenizer.prototype.onsapbackspace.apply(this._tokenizer, arguments);

		oEvent.preventDefault();
		oEvent.stopPropagation();
	};

	/**
	 * Function is called on delete keyboard input, deletes selected tokens
	 *
	 * @private
	 * @param {jQuery.event}
	 *          oEvent
	 */
	MultiInput.prototype.onsapdelete = function(oEvent) {
		if (!this.getEditable()) {
			return;
		}

		if (this.getValue() && !this._completeTextIsSelected()) { // do not return if everything is selected
			return;
		}

		sap.m.Tokenizer.prototype.onsapdelete.apply(this._tokenizer, arguments);
	};

	/**
	 * Handle the key down event for Ctrl + A
	 *
	 * @param {jQuery.Event}
	 *            oEvent - the occuring event
	 * @private
	 */
	MultiInput.prototype.onkeydown = function(oEvent) {

		if (oEvent.ctrlKey || oEvent.metaKey) {

			if (oEvent.which === jQuery.sap.KeyCodes.A) {
				var sValue = this.getValue();

				if (document.activeElement === this._$input[0]) {

					if (this._$input.getSelectedText() !== sValue){

						// if text are not selected, then selected all text
						this.selectText(0, sValue.length);
					} else if (this._tokenizer){

						// if text are selected, then selected all tokens
						if (!sValue && this._tokenizer.getTokens().length) {
							this._tokenizer.focus();
						}
						this._tokenizer.selectAllTokens(true);
					}
				} else if (document.activeElement === this._tokenizer.$()[0]) {

					// if the tokens were not selected before select all in tokenizer was called, then let tokenizer select all tokens.
					if (this._tokenizer._iSelectedToken === this._tokenizer.getTokens().length) {

						// if tokens are all selected, then select all tokens
						this.selectText(0, sValue.length);
					}
				}

				oEvent.preventDefault();
			}

		}

	};

	/**
	 * Handle the paste event
	 *
	 * @param {jQuery.Event}
	 *            oEvent - the occurring event
	 * @private
	 */
	MultiInput.prototype.onpaste = function (oEvent) {

		var sOriginalText;
		// for the purpose to copy from column in excel and paste in MultiInput/MultiComboBox
		if (window.clipboardData) {
			//IE
			sOriginalText = window.clipboardData.getData("Text");
		} else {
			// Chrome, Firefox, Safari
			sOriginalText =  oEvent.originalEvent.clipboardData.getData('text/plain');
		}

		var aSeparatedText = this._tokenizer._parseString(sOriginalText);
		setTimeout(function() {
			if (aSeparatedText) {
				if (this.fireEvent("_validateOnPaste", {texts: aSeparatedText}, true)) {
					var i = 0;
					for ( i = 0; i < aSeparatedText.length; i++) {
						this.updateDomValue(aSeparatedText[i]);
						this._validateCurrentText();
					}
				}
				this.cancelPendingSuggest();
			}
		}.bind(this), 0);

	};

	/**
	 * Handle the backspace button, gives backspace to tokenizer if text cursor was on first character
	 *
	 * @param {jQuery.Event}
	 *            oEvent - the occurring event
	 * @private
	 */
	MultiInput.prototype.onsapprevious = function(oEvent) {

		if (this._getIsSuggestionPopupOpen()) {
			return;
		}

		if (this.getCursorPosition() === 0) {
			if (oEvent.srcControl === this) {
				sap.m.Tokenizer.prototype.onsapprevious.apply(this._tokenizer, arguments);

				// we need this otherwise navigating with the left arrow key will trigger a scroll an the Tokens
				oEvent.preventDefault();
			}
		}
	};

	/**
	 * Function scrolls the tokens to the end and focuses the input field.
	 *
	 * @private
	 */
	MultiInput.prototype._scrollAndFocus = function() {
		this._tokenizer.scrollToEnd();
		// we set the focus back via jQuery instead of this.focus() since the latter on phones lead to unwanted opening of the
		// suggest popup
		this.$().find("input").focus();
	};

	/**
	 * Handle the home button, gives control to tokenizer to move to first token
	 *
	 * @param {jQuery.Event}
	 *            oEvent - the occuring event
	 * @private
	 */
	MultiInput.prototype.onsaphome = function(oEvent) {
		sap.m.Tokenizer.prototype.onsaphome.apply(this._tokenizer, arguments);
	};

	/**
	 * Handle the end button, gives control to tokenizer to move to last token
	 *
	 * @param {jQuery.Event}
	 *            oEvent - the occuring event
	 * @private
	 */
	MultiInput.prototype.onsapend = function(oEvent) {
		sap.m.Tokenizer.prototype.onsapend.apply(this._tokenizer, arguments);

		oEvent.preventDefault();
	};

	/**
	 * Function is called on keyboard enter, if possible, adds entered text as new token
	 *
	 * @private
	 * @param {jQuery.event}
	 *          oEvent
	 */
	MultiInput.prototype.onsapenter = function(oEvent) {
		this._validateCurrentText();

		if (Input.prototype.onsapenter) {
			Input.prototype.onsapenter.apply(this, arguments);
		}

		this.focus();
	};

	/**
	 * Checks whether the MultiInput or one of its internal DOM elements has the focus.
	 *
	 * @private
	 */
	MultiInput.prototype._checkFocus = function() {
		return this.getDomRef() && jQuery.sap.containsOrEquals(this.getDomRef(), document.activeElement);
	};

	/**
	 * Event handler called when control is losing the focus, checks if token validation is necessary
	 *
	 * @param {jQuery.Event}
	 * 			oEvent
	 * @private
	 */
	MultiInput.prototype.onsapfocusleave = function(oEvent) {
		var oPopup = this._oSuggestionPopup;
		var bNewFocusIsInSuggestionPopup = false;
		var bNewFocusIsInTokenizer = false;
		var bNewFocusIsInMultiInput = this._checkFocus();
		if (oPopup instanceof sap.m.Popover) {
			if (oEvent.relatedControlId) {
				bNewFocusIsInSuggestionPopup = jQuery.sap.containsOrEquals(oPopup.getFocusDomRef(), sap.ui.getCore().byId(
						oEvent.relatedControlId).getFocusDomRef());
				bNewFocusIsInTokenizer = jQuery.sap.containsOrEquals(this._tokenizer.getFocusDomRef(), sap.ui.getCore().byId(
						oEvent.relatedControlId).getFocusDomRef());
			}
		}

		// setContainerSize of multi-line mode in the end
		if (!bNewFocusIsInTokenizer && !bNewFocusIsInSuggestionPopup && !this._isMultiLineMode) {
			this._setContainerSizes();
			this._tokenizer.scrollToEnd();
		}

		if (this._bIsValidating) { // an asynchronous validation is running, no need to trigger validation again
			if (Input.prototype.onsapfocusleave) {
				Input.prototype.onsapfocusleave.apply(this, arguments);
			}
			return;
		}

		if (Input.prototype.onsapfocusleave) {
			Input.prototype.onsapfocusleave.apply(this, arguments);
		}

		if (!this._bUseDialog && !bNewFocusIsInSuggestionPopup && oEvent.relatedControlId !== this.getId()
				&& oEvent.relatedControlId !== this._tokenizer.getId() && !bNewFocusIsInTokenizer
					&& !(this._isMultiLineMode && this._bShowIndicator)
					) { // leaving control, validate latest text, not validate the indicator
				this._validateCurrentText(true);
		}

		if (!this._bUseDialog && this._isMultiLineMode && !this._bShowIndicator) {

			if (bNewFocusIsInMultiInput || bNewFocusIsInSuggestionPopup) {
				return;
			}

			this.closeMultiLine();
			this._showIndicator();

			var that = this;
			setTimeout(function() {
				that._setContainerSizes();
			}, 0);
		}

		sap.m.Tokenizer.prototype.onsapfocusleave.apply(this._tokenizer, arguments);

		if (!this._bUseDialog && this._isMultiLineMode && this._bShowIndicator) {
			var $multiInputScroll = this.$().find(".sapMMultiInputBorder");
			$multiInputScroll.scrollTop(0);
		}
	};

	MultiInput.prototype.cloneTokenizer = function(oTokenizer) {
		var oClone = new sap.m.Tokenizer();

		var aTokens = oTokenizer.getTokens();
		if (aTokens.length > 0) {
			for (var i = aTokens.length - 1; i >= 0; i--){
				var newToken = aTokens[i].clone();
				oClone.addToken(newToken);
			}
		}

		return oClone;
	};

	/**
	 * Process multi-line display in edit mode. This function is used when MultiInput gets focus.
	 *
	 * @param {jQuery.Event}
	 * 			oEvent
	 * @private
	 */
	MultiInput.prototype._processMultiLine = function(oEvent) {
			if ( this._bUseDialog ) {

				if ( oEvent.target === this._$input[0]
					||  oEvent.target.className.indexOf("sapMToken") > -1 && oEvent.target.className.indexOf("sapMTokenIcon") < 0
						||  oEvent.target.className.indexOf("sapMTokenText") > -1) {

					this._removeIndicator();
					this._oSuggestionPopup.open();
					this._tokenizerInPopup = this.cloneTokenizer(this._tokenizer);
					var sValue = this._oPopupInput.getValue();

					// keep input value in input field in popup.
					// do not show token and suggestion table at same time, which is the same logic as live change.
					if ( this._oSuggestionPopup && this._oSuggestionPopup.getContent().length > 0 && sValue.length > 0) {
						this._tokenizerInPopup.setVisible(false);
					} else {
						this._tokenizerInPopup.setVisible(true);
						this._setAllTokenVisible(this._tokenizerInPopup);
					}

					this._tokenizerInPopup._oScroller.setHorizontal(false);
					this._tokenizerInPopup.addStyleClass("sapMTokenizerMultiLine");

					//add token when no suggestion item
					if (this._oSuggestionTable.getItems().length === 0) {
						var that = this;
						this._oPopupInput.onsapenter = function(oEvent){
								that._validateCurrentText();
								that._setValueInvisible();
						};
					}

					this._oSuggestionPopup.insertContent(this._tokenizerInPopup, 0);
				}

			} else {
					//desktop and click on input field
					if ( oEvent.target === this._$input[0]
							||  oEvent.target.className.indexOf("sapMToken") > -1 && oEvent.target.className.indexOf("sapMTokenIcon") < 0
								||  oEvent.target.className.indexOf("sapMTokenText") > -1){

						this.openMultiLine();
						this._showAllTokens(this._tokenizer);

						var that = this;
						setTimeout(function() {
							that._setContainerSizes();
							that._tokenizer.scrollToStart();
						}, 0);
					}
			}
	};

	/**
	 * When tap on text field, deselect all tokens
	 * @public
	 * @param {jQuery.Event} oEvent
	 */
	MultiInput.prototype.ontap = function(oEvent) {
		//deselect tokens when focus is on text field
		if (document.activeElement === this._$input[0]) {
			this._tokenizer.selectAllTokens(false);
		}

		Input.prototype.ontap.apply(this, arguments);
	};

	/**
	 * Focus is on MultiInput
	 * @public
	 * @param {jQuery.Event} oEvent
	 */
	MultiInput.prototype.onfocusin = function(oEvent) {

		if ( this._isMultiLineMode ) {
			this._processMultiLine(oEvent);
		}

		if ( oEvent.target === this.getFocusDomRef() ){
			Input.prototype.onfocusin.apply(this, arguments);
		}

	};

	/**
	 * When press ESC, deselect all tokens and all texts
	 * @public
	 * @param {jQuery.Event} oEvent
	 */
	MultiInput.prototype.onsapescape = function(oEvent) {

		//deselect everything
		this._tokenizer.selectAllTokens(false);
		this.selectText(0, 0);

		Input.prototype.onsapescape.apply(this, arguments);
	};

	/**
	 * Function tries to turn current text into a token
	 *
	 * @private
	 */
	MultiInput.prototype._validateCurrentText = function(bExactMatch) {
		var iOldLength = this._tokenizer.getTokens().length;
		var text = this.getValue();
		if (!text || !this.getEditable()) {
			return;
		}

		text = text.trim();

		if (!text) {
			return;
		}

		var item = null;

		if (bExactMatch || this._getIsSuggestionPopupOpen()) { // only take item from suggestion list if popup is open, otherwise it can be
			if (this._hasTabularSuggestions()) {
				//if there is suggestion table, select the correct item, to avoid selecting the wrong item but with same text.
				item = this._oSuggestionTable._oSelectedItem;
			} else {
				// impossible to enter other text
				item = this._getSuggestionItem(text, bExactMatch);
			}
		}

		var token = null;
		if (item && item.getText && item.getKey) {
			token = new Token({
				text : item.getText(),
				key : item.getKey()
			});
		}

		var that = this;

		this._bIsValidating = true;
		this._tokenizer.addValidateToken({
			text : text,
			token : token,
			suggestionObject : item,
			validationCallback : function(validated) {
				that._bIsValidating = false;
				if (validated) {
					that.setValue("");
					if (that._bUseDialog && that._isMultiLineMode && that._oSuggestionTable.getItems().length === 0) {
						var iNewLength = that._tokenizer.getTokens().length;
						if ( iOldLength < iNewLength ) {
							var oNewToken = that._tokenizer.getTokens()[iNewLength - 1];
							that._updateTokenizerInPopup(oNewToken);
							that._oPopupInput.setValue("");
						}
						if (that._tokenizerInPopup.getVisible() === false){
							that._tokenizerInPopup.setVisible(true);
						}
						that._setAllTokenVisible(that._tokenizerInPopup);
					}

				}
			}
		});
	};

	/**
	 * Functions returns the current input field's cursor position
	 *
	 * @private
	 * @return {int} the cursor position
	 */
	MultiInput.prototype.getCursorPosition = function() {
		return this._$input.cursorPos();
	};

	/**
	 * Functions returns true if the input's text is completely selected
	 *
	 * @private
	 * @return {boolean} true if text is selected, otherwise false,
	 */
	MultiInput.prototype._completeTextIsSelected = function() {
		var input = this._$input[0];
		if (input.selectionStart !== 0) {
			return false;
		}

		if (input.selectionEnd !== this.getValue().length) {
			return false;
		}

		return true;
	};

	/**
	 * Functions selects the complete input text
	 *
	 * @private
	 * @return {sap.m.MultiInput} this - for chaining
	 */
	MultiInput.prototype._selectAllInputText = function() {
		var input = this._$input[0];
		input.selectionStart = 0;
		input.selectionEnd = this.getValue().length;
		return this;
	};

	/**
	 * Functions returns true if the suggestion popup is currently open
	 *
	 * @private
	 */
	MultiInput.prototype._getIsSuggestionPopupOpen = function() {
		return this._oSuggestionPopup && this._oSuggestionPopup.isOpen();
	};

	MultiInput.prototype.setEditable = function(bEditable) {
		if (bEditable === this.getEditable()) {
			return this;
		}

		if (Input.prototype.setEditable) {
			Input.prototype.setEditable.apply(this, arguments);
		}

		this._tokenizer.setEditable(bEditable);

		if (bEditable) {
			this.removeStyleClass("sapMMultiInputNotEditable");
		} else {
			this.addStyleClass("sapMMultiInputNotEditable");
		}

		return this;
	};

	/**
	 * Function returns an item which's text starts with the given text within the given items array
	 *
	 * @private
	 * @param {string}
	 *          sText
	 * @param {array}
	 *          aItems
	 * @param {boolean}
	 *          bExactMatch
	 * @param {function}
	 *          fGetText - function to extract text from a single item
	 * @return {object} a found item or null
	 */
	MultiInput.prototype._findItem = function(sText, aItems, bExactMatch, fGetText) {
		if (!sText) {
			return;
		}

		if (!(aItems && aItems.length)) {
			return;
		}

		sText = sText.toLowerCase();

		var length = aItems.length;
		for (var i = 0; i < length; i++) {
			var item = aItems[i];
			var compareText = fGetText(item);
			if (!compareText) {
				continue;
			}

			compareText = compareText.toLowerCase();
			if (compareText === sText) {
				return item;
			}

			if (!bExactMatch && compareText.indexOf(sText) === 0) {
				return item;
			}
		}
	};

	/**
	 * Function searches for an item with the given text within the suggestion items
	 *
	 * @private
	 * @param {string}
	 *          sText
	 * @param {boolean}
	 *          bExactMatch - if true, only items will be returned which exactly matches the text
	 * @return {sap.ui.core.Item} a found item or null
	 */
	MultiInput.prototype._getSuggestionItem = function(sText, bExactMatch) {
		var items = null;
		var item = null;
		if (this._hasTabularSuggestions()) {
			items = this.getSuggestionRows();
			item = this._findItem(sText, items, bExactMatch, function(oRow) {
				var cells = oRow.getCells();
				var foundText = null;
				if (cells) {
					var i;
					for (i = 0; i < cells.length; i++) {
						if (cells[i].getText) {
							foundText = cells[i].getText();
							break;
						}
					}
				}
				return foundText;
			});
		} else {
			items = this.getSuggestionItems();
			item = this._findItem(sText, items, bExactMatch, function(item) {
				return item.getText();
			});
		}
		return item;
	};

	MultiInput.prototype.addToken = function(oToken) {
		return this._tokenizer.addToken(oToken);
	};

	MultiInput.prototype.removeToken = function(oToken) {
		return this._tokenizer.removeToken(oToken);
	};

	MultiInput.prototype.removeAllTokens = function() {
		return this._tokenizer.removeAllTokens();
	};

	MultiInput.prototype.getTokens = function() {
		return this._tokenizer.getTokens();
	};

	MultiInput.prototype.insertToken = function(oToken, iIndex) {
		return this._tokenizer.insertToken(oToken, iIndex);
	};

	MultiInput.prototype.indexOfToken = function(oToken) {
		return this._tokenizer.indexOfToken(oToken);
	};

	MultiInput.prototype.destroyTokens = function() {
		return this._tokenizer.destroyTokens();
	};

	MultiInput.prototype.updateTokens = function() {
		this.destroyTokens();
		return this.updateAggregation("tokens");
	};

	/**
	 * Function overwrites clone function to add tokens to MultiInput
	 *
	 * @public
	 * @return {sap.ui.core.Element} reference to the newly created clone
	 */
	MultiInput.prototype.clone = function() {
        var oClone = Input.prototype.clone.apply(this, arguments);

        var aTokens = this.getTokens();
        var i;
        for (i = 0; i < aTokens.length; i++){
              var newToken = aTokens[i].clone();
              oClone.addToken(newToken);
        }

        return oClone;
  };

	/**
	 * Function returns domref which acts as reference point for the opening suggestion menu
	 *
	 * @public
	 * @returns {domRef}
	 *          the domref at which to open the suggestion menu
	 */
	MultiInput.prototype.getPopupAnchorDomRef = function(){
		return this.getDomRef("border");
	};

	/**
	 * Function sets an array of tokens, existing tokens will get overridden
	 *
	 * @param {sap.m.Token[]}
	 *          aTokens - the new token set
	 * @public
	 */
	MultiInput.prototype.setTokens = function(aTokens) {
		this._tokenizer.setTokens(aTokens);
	};

	MultiInput.TokenChangeType = {
		Added : "added",
		Removed : "removed",
		RemovedAll : "removedAll",
		TokensChanged : "tokensChanged"
	};

	MultiInput.WaitForAsyncValidation = "sap.m.Tokenizer.WaitForAsyncValidation";

	/**
	 * Get the reference element which the message popup should dock to
	 *
	 * @return {DOMRef} Dom Element which the message popup should dock to
	 * @protected
	 * @function
	 */
	MultiInput.prototype.getDomRefForValueStateMessage = MultiInput.prototype.getPopupAnchorDomRef;

	/**
	 * @see {sap.ui.core.Control#getAccessibilityInfo}
	 * @protected
	 */
	MultiInput.prototype.getAccessibilityInfo = function() {
		var sText = this.getTokens().map(function(oToken) {
			return oToken.getText();
		}).join(" ");

		var oInfo = Input.prototype.getAccessibilityInfo.apply(this, arguments);
		oInfo.type = sap.ui.getCore().getLibraryResourceBundle("sap.m").getText("ACC_CTR_TYPE_MULTIINPUT");
		oInfo.description = ((oInfo.description || "") + " " + sText).trim();
		return oInfo;
	};

	return MultiInput;

}, /* bExport= */ true);


text:
package io.cucumber.pro.environment;

import io.cucumber.pro.config.Config;
import io.cucumber.pro.config.loaders.EnvironmentVariablesConfigLoader;
import org.junit.Test;

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

import static io.cucumber.pro.Keys.createConfig;
import static org.junit.Assert.assertEquals;

public class EnvFilterTest {
    @Test
    public void filters_and_sorts_keys() {
        Map<String, String> env = new HashMap<String, String>() {{
            put("my_secret__token", "abcd");
            put("MY_SECRET_TOKEN", "abcd");
            put("A_KEY_TO_A_DOOR", "clef");
            put("FOO", "BAR");
            put("ALPHA", "BETA");
            put("DOO", "dar");
            put("PASSWORD_A", "drowssap");
        }};

        Config config = createConfig();
        new EnvironmentVariablesConfigLoader(env).load(config);
        EnvFilter envFilter = new EnvFilter(config);

        Map<String, String> expectedEnv = new HashMap<String, String>() {{
            put("FOO", "BAR");
            put("ALPHA", "BETA");
            put("DOO", "dar");
        }};

        assertEquals(expectedEnv, envFilter.filter(env));
    }

    @Test
    public void allows_overriding_mask() {
        Map<String, String> env = new HashMap<String, String>() {{
            put("CUCUMBERPRO_ENVMASK", "KEY|TOKEN"); // But not SECRET|PASSWORD
            put("my_secret__token", "abcd");
            put("MY_SECRET_TOKEN", "abcd");
            put("A_KEY_TO_A_DOOR", "clef");
            put("FOO", "BAR");
            put("ALPHA", "BETA");
            put("DOO", "dar");
            put("PASSWORD_A", "drowssap");
        }};

        Config config = createConfig();
        new EnvironmentVariablesConfigLoader(env).load(config);
        EnvFilter envFilter = new EnvFilter(config);

        Map<String, String> expectedEnv = new HashMap<String, String>() {{
            put("CUCUMBERPRO_ENVMASK", "KEY|TOKEN");
            put("FOO", "BAR");
            put("ALPHA", "BETA");
            put("DOO", "dar");
            put("PASSWORD_A", "drowssap");
        }};
        assertEquals(expectedEnv, envFilter.filter(env));
    }
}


text:
require 'rubygems'
require 'minitest/autorun'
require 'rails/all'
require 'rails/generators'
require 'rails/generators/test_case'
require 'rabl/generators'

class TestApp < Rails::Application
  config.root = File.dirname(__FILE__)
end
Rails.application = TestApp

module Rails
  def self.root
    @root ||= File.expand_path(File.join(File.dirname(__FILE__), '..', 'tmp', 'rails'))
  end
end
Rails.application.config.root = Rails.root

# Call configure to load the settings from
# Rails.application.config.generators to Rails::Generators
Rails::Generators.configure! Rails.application.config.generators

Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

def copy_routes
  routes = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'routes.rb'))
  destination = File.join(Rails.root, "config")
  FileUtils.mkdir_p(destination)
  FileUtils.cp File.expand_path(routes), destination
end


text:
layout: post
title: Some tests
---

2018-7-20-Some-Tests.md

__no underline__
*italic*
**bold**

```
fn init --runtime kotlin myfunc
```

```kotlin
package com.fn.example

fun hello(input: String) = when {
    input.isEmpty() -> ("Hello, world!")
        else -> ("Hello, ${input}")
}
```

![email](/images/blog/mail_pic.jpg#center)

## GIST inclusion

#### embed
">

```kotlin
package com.fn.example
import com.fnproject.fn.testing.*
import org.junit.*
import kotlin.test.assertEquals

class HelloFunctionTest {

        @Rule @JvmField
        val fn = FnTestingRule.createDefault()

        @Test
        fun `should return default greeting`() {
                with (fn) {
                        givenEvent().enqueue()
                        thenRun("com.fn.example.HelloFunctionKt","hello")
                        assertEquals("Hello, world!", getOnlyResult().getBodyAsString())
                }
        }

        @Test
        fun `should return personalized greeting`() {
                with (fn) {
                        givenEvent().withBody("Jhonny").enqueue()
                        thenRun("com.fn.example.HelloFunctionKt","hello")
                        assertEquals("Hello, Jhonny", getOnlyResult().getBodyAsString())
                }
        }

}
```

```
mvn test
...
[INFO] --- kotlin-maven-plugin:1.2.51:test-compile (test-compile) @ hello ---
...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.fn.example.HelloFunctionTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.518 sec
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
```

```
fn run myfunc
```


text:
package org.spongepowered.common.mixin.core.world.gen.populators;

import static com.google.common.base.Preconditions.checkNotNull;

import com.flowpowered.math.vector.Vector3i;
import com.google.common.base.MoreObjects;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenVines;
import net.minecraft.world.gen.feature.WorldGenerator;
import org.spongepowered.api.util.weighted.VariableAmount;
import org.spongepowered.api.world.extent.Extent;
import org.spongepowered.api.world.gen.PopulatorType;
import org.spongepowered.api.world.gen.PopulatorTypes;
import org.spongepowered.api.world.gen.populator.Vine;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import java.util.Random;

@Mixin(WorldGenVines.class)
public abstract class MixinWorldGenVines extends WorldGenerator implements Vine {

    private VariableAmount count;

    @Inject(method = "<init>", at = @At("RETURN") )
    public void onConstructed(CallbackInfo ci) {
        this.count = VariableAmount.fixed(50);
    }

    @Override
    public PopulatorType getType() {
        return PopulatorTypes.VINE;
    }

    @Override
    public void populate(org.spongepowered.api.world.World worldIn, Extent extent, Random random) {
        Vector3i min = extent.getBlockMin();
        Vector3i size = extent.getBlockSize();
        World world = (World) worldIn;
        BlockPos position = new BlockPos(min.getX(), min.getY(), min.getZ());
        int x, z;
        int n = this.count.getFlooredAmount(random);
        for (int i = 0; i < n; i++) {
            x = random.nextInt(size.getX());
            z = random.nextInt(size.getX());
            generate(world, random, position.add(x, 128, z));
        }
    }

    @Override
    public VariableAmount getVinesPerChunk() {
        return this.count;
    }

    @Override
    public void setVinesPerChunk(VariableAmount count) {
        this.count = checkNotNull(count);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("Type", "Vine")
                .add("PerChunk", this.count)
                .toString();
    }

}


text:
/* sidebar.directive.js */
(function() {

  'use strict';

  /**
   * sidebarDirective
   *
   * @description The sidebar directive is used for displaying the sidebar with
   * dynamic navigation links, depending on user auth state.
   * @return {Object} The directive
   */
  angular
    .module('app')
    .directive('sidebarDirective', sidebarDirective);

  function sidebarDirective() {
    var directive = {
      restrict: 'E',
      scope: {},
      templateUrl: 'components/sidebar/sidebar.directive.html',
      link: link
    };

    return directive;

    function link(scope, elem, attrs) {

    }
  }

})();


text:
using System.Threading;
using System.Threading.Tasks;

namespace SonarLint.VisualStudio.Progress.Controller
{
    /// <summary>
    /// The interface represents the actual operation that needed to be executed in a <see cref="IProgressStep"/>
    /// <seealso cref="ProgressControllerStep"/>
    /// </summary>
    public interface IProgressStepOperation
    {
        /// <summary>
        /// The <see cref="IProgressStep"/> associated with this operation
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Step", Justification = "NA")]
        IProgressStep Step { get; }

        /// <summary>
        /// Execute the operation
        /// </summary>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <param name="progressCallback">Allows to update the <see cref="IProgressController"/> with the execution progress and cancellation support. <seealso cref="IProgressEvents"/></param>
        /// <returns>An awaitable task that returns a <see cref="StepExecutionState"/> result</returns>
        Task<StepExecutionState> RunAsync(CancellationToken cancellationToken, IProgressStepExecutionEvents progressCallback);
    }
}


text:
(function () {
  'use strict';
  var active = false, attribute = 'data-delay';

  if (window === window.top) {
    safari.self.tab.dispatchMessage('requestSettings', JSON.stringify({
      'location': window.location
    }));
    window.onblur = function () {
      active = false;
    };
    window.onfocus = function () {
      active = true;
    };
  }

  safari.self.addEventListener('message', function (event) {
    if (event.name === 'receiveSettings') {
      receiveSettings(event);
    }
  }, false);

  function receiveSettings (event) {
    var delay, elapsed, intervalID, tick, timer;

    active = event.message.active;

    delay = event.message.delay;
    elapsed = 0;
    tick = event.message.tick;
    timer = event.message.timer;

    document.documentElement.setAttribute(attribute,
      timer ? Math.round(delay / tick) : '\u231b');

    intervalID = window.setInterval(function () {
      if (!active) {
        return;
      }

      elapsed += tick;

      if (timer) {
        document.documentElement.setAttribute(attribute,
          Math.round((delay - elapsed) / tick));
      }

      if (Math.round((delay - elapsed) / tick) <= 0) {
        document.documentElement.removeAttribute(attribute);
        window.clearInterval(intervalID);

        safari.self.tab.dispatchMessage('finishedDelaying', JSON.stringify({
          'location': window.location
        }));
      }
    }, tick);
  }
}());


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>OPTRAJ: Référence de la classe systeme.Systeme.Systeme</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

OPTRAJ

Page principale

Paquetages

Classes

Fichiers

          <input type="text" id="MSearchField" value="Recherche" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Liste des classes

Index des classes

Hiérarchie des classes

Membres de classe

 Tout Classes Espaces de nommage Fichiers Fonctions Variables

systeme

Systeme

Systeme

Fonctions membres publiques |
Attributs privés |
Liste de tous les membres

Référence de la classe systeme.Systeme.Systeme

Created on 7 nov.
 Plus de détails...

Fonctions membres publiques

def 	__init__

 	Constructor.  Plus de détails...

def 	ouvriers

def 	ouvriers

def 	chantiers

def 	chantiers

def 	getWorkerById

 	retourne l'ouvrier du systeme avec le numéros numWorker si il existe, None sinon  Plus de détails...

Attributs privés

 	_chantiers

 	_ouvriers

Description détaillée

Created on 7 nov.

2013

Auteur

: Sacapuces

Documentation des constructeurs et destructeur

          def systeme.Systeme.Systeme.__init__
          (

          self,

          chantiers = set(),

          ouvriers = set()

          )

Constructor.

Documentation des fonctions membres

          def systeme.Systeme.Systeme.chantiers
          (

          self	)

Voici le graphe des appelants de cette fonction :

          def systeme.Systeme.Systeme.chantiers
          (

          self,

          value

          )

Voici le graphe d'appel pour cette fonction :

          def systeme.Systeme.Systeme.getWorkerById
          (

          self,

          numWorker

          )

retourne l'ouvrier du systeme avec le numéros numWorker si il existe, None sinon

Paramètres

numWorker	le numéro de l'ouvrier à chercher

Voici le graphe d'appel pour cette fonction :

          def systeme.Systeme.Systeme.ouvriers
          (

          self	)

Voici le graphe des appelants de cette fonction :

          def systeme.Systeme.Systeme.ouvriers
          (

          self,

          value

          )

Voici le graphe d'appel pour cette fonction :

Documentation des données membres

          systeme.Systeme.Systeme._chantiers

private

          systeme.Systeme.Systeme._ouvriers

private

La documentation de cette classe a été générée à partir du fichier suivant :

D:/Users/Sacapuces/Documents/Travail/M1/optraj.istic.univ-rennes1.fr/src/systeme/Systeme.py

<address class="footer">
Généré le Samedi Novembre 23 2013 23:24:44 pour OPTRAJ par

 1.8.5
</address>


text:
<?php

/*
 *
 *  ____            _        _   __  __ _                  __  __ ____
 * |  _ \ ___   ___| | _____| |_|  \/  (_)_ __   ___      |  \/  |  _ \
 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
 * |  __/ (_) | (__|   <  __/ |_| |  | | | | | |  __/_____| |  | |  __/
 * |_|   \___/ \___|_|\_\___|\__|_|  |_|_|_| |_|\___|     |_|  |_|_|
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * @author PocketMine Team
 * @link http://www.pocketmine.net/
 *
 *
*/

namespace pocketmine\level\format\mcregion;

use pocketmine\level\format\FullChunk;
use pocketmine\level\format\LevelProvider;
use pocketmine\nbt\NBT;
use pocketmine\nbt\tag\Byte;
use pocketmine\nbt\tag\ByteArray;
use pocketmine\nbt\tag\Compound;
use pocketmine\nbt\tag\Enum;
use pocketmine\nbt\tag\Int;
use pocketmine\nbt\tag\IntArray;
use pocketmine\nbt\tag\Long;
use pocketmine\utils\Binary;
use pocketmine\utils\ChunkException;
use pocketmine\utils\MainLogger;

class RegionLoader{
	const VERSION = 1;
	const COMPRESSION_GZIP = 1;
	const COMPRESSION_ZLIB = 2;
	const MAX_SECTOR_LENGTH = 256 << 12; //256 sectors, (1 MiB)
	public static $COMPRESSION_LEVEL = 7;

	protected $x;
	protected $z;
	protected $filePath;
	protected $filePointer;
	protected $lastSector;
	/** @var LevelProvider */
	protected $levelProvider;
	protected $locationTable = [];

	public $lastUsed;

	public function __construct(LevelProvider $level, $regionX, $regionZ){
		$this->x = $regionX;
		$this->z = $regionZ;
		$this->levelProvider = $level;
		$this->filePath = $this->levelProvider->getPath() . "region/r.$regionX.$regionZ.mcr";
		$exists = \file_exists($this->filePath);
		\touch($this->filePath);
		$this->filePointer = \fopen($this->filePath, "r+b");
		\stream_set_read_buffer($this->filePointer, 1024 * 16); //16KB
		\stream_set_write_buffer($this->filePointer, 1024 * 16); //16KB
		if(!$exists){
			$this->createBlank();
		}else{
			$this->loadLocationTable();
		}

		$this->lastUsed = \time();
	}

	public function __destruct(){
		if(\is_resource($this->filePointer)){
			$this->writeLocationTable();
			\fclose($this->filePointer);
		}
	}

	protected function isChunkGenerated($index){
		return !($this->locationTable[$index][0] === 0 or $this->locationTable[$index][1] === 0);
	}

	public function readChunk($x, $z, $generate = \true, $forward = \false){
		$index = self::getChunkOffset($x, $z);
		if($index < 0 or $index >= 4096){
			return \null;
		}

		$this->lastUsed = \time();

		if(!$this->isChunkGenerated($index)){
			if($generate === \true){
				//Allocate space
				$this->locationTable[$index][0] = ++$this->lastSector;
				$this->locationTable[$index][1] = 1;
				\fseek($this->filePointer, $this->locationTable[$index][0] << 12);
				\fwrite($this->filePointer, \str_pad(\pack("N", 0) . \chr(self::COMPRESSION_ZLIB), 4096, "\x00", STR_PAD_RIGHT));
				$this->writeLocationIndex($index);
			}else{
				return \null;
			}
		}

		\fseek($this->filePointer, $this->locationTable[$index][0] << 12);
		$length = (\PHP_INT_SIZE === 8 ? \unpack("N", \fread($this->filePointer, 4))[1] << 32 >> 32 : \unpack("N", \fread($this->filePointer, 4))[1]);
		$compression = \ord(\fgetc($this->filePointer));

		if($length <= 0 or $length > self::MAX_SECTOR_LENGTH){ //Not yet generated / corrupted
			if($length >= self::MAX_SECTOR_LENGTH){
				$this->locationTable[$index][0] = ++$this->lastSector;
				$this->locationTable[$index][1] = 1;
				MainLogger::getLogger()->error("Corrupted chunk header detected");
			}
			$this->generateChunk($x, $z);
			\fseek($this->filePointer, $this->locationTable[$index][0] << 12);
			$length = (\PHP_INT_SIZE === 8 ? \unpack("N", \fread($this->filePointer, 4))[1] << 32 >> 32 : \unpack("N", \fread($this->filePointer, 4))[1]);
			$compression = \ord(\fgetc($this->filePointer));
		}

		if($length > ($this->locationTable[$index][1] << 12)){ //Invalid chunk, bigger than defined number of sectors
			MainLogger::getLogger()->error("Corrupted bigger chunk detected");
			$this->locationTable[$index][1] = $length >> 12;
			$this->writeLocationIndex($index);
		}elseif($compression !== self::COMPRESSION_ZLIB and $compression !== self::COMPRESSION_GZIP){
			MainLogger::getLogger()->error("Invalid compression type");

			return \null;
		}

		$chunk = Chunk::fromBinary(\fread($this->filePointer, $length - 1), $this->levelProvider);
		if($chunk instanceof Chunk){
			return $chunk;
		}elseif($forward === \false){
			MainLogger::getLogger()->error("Corrupted chunk detected");
			$this->generateChunk($x, $z);

			return $this->readChunk($x, $z, $generate, \true);
		}else{
			return \null;
		}
	}

	public function chunkExists($x, $z){
		return $this->isChunkGenerated(self::getChunkOffset($x, $z));
	}

	public function generateChunk($x, $z){
		$nbt = new Compound("Level", []);
		$nbt->xPos = new Int("xPos", ($this->getX() * 32) + $x);
		$nbt->zPos = new Int("zPos", ($this->getZ() * 32) + $z);
		$nbt->LastUpdate = new Long("LastUpdate", 0);
		$nbt->LightPopulated = new Byte("LightPopulated", 0);
		$nbt->TerrainPopulated = new Byte("TerrainPopulated", 0);
		$nbt->V = new Byte("V", self::VERSION);
		$nbt->InhabitedTime = new Long("InhabitedTime", 0);
		$nbt->Biomes = new ByteArray("Biomes", \str_repeat(\chr(-1), 256));
		$nbt->HeightMap = new IntArray("HeightMap", \array_fill(0, 256, 127));
		$nbt->BiomeColors = new IntArray("BiomeColors", \array_fill(0, 256, (\PHP_INT_SIZE === 8 ? \unpack("N", "\x00\x85\xb2\x4a")[1] << 32 >> 32 : \unpack("N", "\x00\x85\xb2\x4a")[1])));

		$nbt->Blocks = new ByteArray("Blocks", \str_repeat("\x00", 32768));
		$nbt->Data = new ByteArray("Data", $half = \str_repeat("\x00", 16384));
		$nbt->SkyLight = new ByteArray("SkyLight", $half);
		$nbt->BlockLight = new ByteArray("BlockLight", $half);

		$nbt->Entities = new Enum("Entities", []);
		$nbt->Entities->setTagType(NBT::TAG_Compound);
		$nbt->TileEntities = new Enum("TileEntities", []);
		$nbt->TileEntities->setTagType(NBT::TAG_Compound);
		$nbt->TileTicks = new Enum("TileTicks", []);
		$nbt->TileTicks->setTagType(NBT::TAG_Compound);
		$writer = new NBT(NBT::BIG_ENDIAN);
		$nbt->setName("Level");
		$writer->setData(new Compound("", ["Level" => $nbt]));
		$chunkData = $writer->writeCompressed(ZLIB_ENCODING_DEFLATE, self::$COMPRESSION_LEVEL);

		if($chunkData !== \false){
			$this->saveChunk($x, $z, $chunkData);
		}
	}

	protected function saveChunk($x, $z, $chunkData){
		$length = \strlen($chunkData) + 1;
		if($length + 4 > self::MAX_SECTOR_LENGTH){
			throw new ChunkException("Chunk is too big! ".($length + 4)." > ".self::MAX_SECTOR_LENGTH);
		}
		$sectors = (int) \ceil(($length + 4) / 4096);
		$index = self::getChunkOffset($x, $z);
		if($this->locationTable[$index][1] < $sectors){
			$this->lastSector += $sectors; //The GC will clean this shift "later"
			$this->locationTable[$index][0] = $this->lastSector;
		}
		$this->locationTable[$index][1] = $sectors;
		$this->locationTable[$index][2] = \time();

		\fseek($this->filePointer, $this->locationTable[$index][0] << 12);
		\fwrite($this->filePointer, \str_pad(\pack("N", $length) . \chr(self::COMPRESSION_ZLIB) . $chunkData, $sectors << 12, "\x00", STR_PAD_RIGHT));
		$this->writeLocationIndex($index);
	}

	public function removeChunk($x, $z){
		$index = self::getChunkOffset($x, $z);
		$this->locationTable[$index][0] = 0;
		$this->locationTable[$index][1] = 0;
	}

	public function writeChunk(FullChunk $chunk){
		$this->lastUsed = \time();
		$chunkData = $chunk->toBinary();
		if($chunkData !== \false){
			$this->saveChunk($chunk->getX() - ($this->getX() * 32), $chunk->getZ() - ($this->getZ() * 32), $chunkData);
		}
	}

	protected static function getChunkOffset($x, $z){
		return $x + ($z << 5);
	}

	public function close(){
		$this->writeLocationTable();
		\fclose($this->filePointer);
		$this->levelProvider = \null;
	}

	public function doSlowCleanUp(){
		for($i = 0; $i < 1024; ++$i){
			if($this->locationTable[$i][0] === 0 or $this->locationTable[$i][1] === 0){
				continue;
			}
			\fseek($this->filePointer, $this->locationTable[$i][0] << 12);
			$chunk = \fread($this->filePointer, $this->locationTable[$i][1] << 12);
			$length = (\PHP_INT_SIZE === 8 ? \unpack("N", \substr($chunk, 0, 4))[1] << 32 >> 32 : \unpack("N", \substr($chunk, 0, 4))[1]);
			if($length <= 1){
				$this->locationTable[$i] = [0, 0, 0]; //Non-generated chunk, remove it from index
			}

			try{
				$chunk = \zlib_decode(\substr($chunk, 5));
			}catch(\Exception $e){
				$this->locationTable[$i] = [0, 0, 0]; //Corrupted chunk, remove it
				continue;
			}

			$chunk = \chr(self::COMPRESSION_ZLIB) . \zlib_encode($chunk, ZLIB_ENCODING_DEFLATE, 9);
			$chunk = \pack("N", \strlen($chunk)) . $chunk;
			$sectors = (int) \ceil(\strlen($chunk) / 4096);
			if($sectors > $this->locationTable[$i][1]){
				$this->locationTable[$i][0] = $this->lastSector += $sectors;
			}
			\fseek($this->filePointer, $this->locationTable[$i][0] << 12);
			\fwrite($this->filePointer, \str_pad($chunk, $sectors << 12, "\x00", STR_PAD_RIGHT));
		}
		$this->writeLocationTable();
		$n = $this->cleanGarbage();
		$this->writeLocationTable();

		return $n;
	}

	private function cleanGarbage(){
		$sectors = [];
		foreach($this->locationTable as $index => $data){ //Calculate file usage
			if($data[0] === 0 or $data[1] === 0){
				$this->locationTable[$index] = [0, 0, 0];
				continue;
			}
			for($i = 0; $i < $data[1]; ++$i){
				$sectors[$data[0]] = $index;
			}
		}

		if(\count($sectors) === ($this->lastSector - 2)){ //No collection needed
			return 0;
		}

		\ksort($sectors);
		$shift = 0;
		$lastSector = 1; //First chunk - 1

		\fseek($this->filePointer, 8192);
		$sector = 2;
		foreach($sectors as $sector => $index){
			if(($sector - $lastSector) > 1){
				$shift += $sector - $lastSector - 1;
			}
			if($shift > 0){
				\fseek($this->filePointer, $sector << 12);
				$old = \fread($this->filePointer, 4096);
				\fseek($this->filePointer, ($sector - $shift) << 12);
				\fwrite($this->filePointer, $old, 4096);
			}
			$this->locationTable[$index][0] -= $shift;
			$lastSector = $sector;
		}
		\ftruncate($this->filePointer, ($sector + 1) << 12); //Truncate to the end of file written
		return $shift;
	}

	protected function loadLocationTable(){
		\fseek($this->filePointer, 0);
		$this->lastSector = 1;
		$table = \fread($this->filePointer, 4 * 1024 * 2); //1024 records * 4 bytes * 2 times
		for($i = 0; $i < 1024; ++$i){
			$index = \unpack("N", \substr($table, $i << 2, 4))[1];
			$this->locationTable[$i] = [$index >> 8, $index & 0xff, \unpack("N", \substr($table, 4096 + ($i << 2), 4))[1]];
			if(($this->locationTable[$i][0] + $this->locationTable[$i][1] - 1) > $this->lastSector){
				$this->lastSector = $this->locationTable[$i][0] + $this->locationTable[$i][1] - 1;
			}
		}
	}

	private function writeLocationTable(){
		$write = [];

		for($i = 0; $i < 1024; ++$i){
			$write[] = (($this->locationTable[$i][0] << 8) | $this->locationTable[$i][1]);
		}
		for($i = 0; $i < 1024; ++$i){
			$write[] = $this->locationTable[$i][2];
		}
		\fseek($this->filePointer, 0);
		\fwrite($this->filePointer, \pack("N*", ...$write), 4096 * 2);
	}

	protected function writeLocationIndex($index){
		\fseek($this->filePointer, $index << 2);
		\fwrite($this->filePointer, \pack("N", ($this->locationTable[$index][0] << 8) | $this->locationTable[$index][1]), 4);
		\fseek($this->filePointer, 4096 + ($index << 2));
		\fwrite($this->filePointer, \pack("N", $this->locationTable[$index][2]), 4);
	}

	protected function createBlank(){
		\fseek($this->filePointer, 0);
		\ftruncate($this->filePointer, 0);
		$this->lastSector = 1;
		$table = "";
		for($i = 0; $i < 1024; ++$i){
			$this->locationTable[$i] = [0, 0];
			$table .= \pack("N", 0);
		}

		$time = \time();
		for($i = 0; $i < 1024; ++$i){
			$this->locationTable[$i][2] = $time;
			$table .= \pack("N", $time);
		}

		\fwrite($this->filePointer, $table, 4096 * 2);
	}

	public function getX(){
		return $this->x;
	}

	public function getZ(){
		return $this->z;
	}

}


text:
package versioned

import (
	"fmt"

	"strings"

	rbacv1 "k8s.io/api/rbac/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/kubectl/pkg/generate"
)

// ClusterRoleBindingGeneratorV1 supports stable generation of a clusterRoleBinding.
type ClusterRoleBindingGeneratorV1 struct {
	// Name of clusterRoleBinding (required)
	Name string
	// ClusterRole for the clusterRoleBinding (required)
	ClusterRole string
	// Users to derive the clusterRoleBinding from (optional)
	Users []string
	// Groups to derive the clusterRoleBinding from (optional)
	Groups []string
	// ServiceAccounts to derive the clusterRoleBinding from in namespace:name format(optional)
	ServiceAccounts []string
}

// Ensure it supports the generator pattern that uses parameter injection.
var _ generate.Generator = &ClusterRoleBindingGeneratorV1{}

// Ensure it supports the generator pattern that uses parameters specified during construction.
var _ generate.StructuredGenerator = &ClusterRoleBindingGeneratorV1{}

// Generate returns a clusterRoleBinding using the specified parameters.
func (s ClusterRoleBindingGeneratorV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	err := generate.ValidateParams(s.ParamNames(), genericParams)
	if err != nil {
		return nil, err
	}
	delegate := &ClusterRoleBindingGeneratorV1{}
	userStrings, found := genericParams["user"]
	if found {
		fromFileArray, isArray := userStrings.([]string)
		if !isArray {
			return nil, fmt.Errorf("expected []string, found :%v", userStrings)
		}
		delegate.Users = fromFileArray
		delete(genericParams, "user")
	}
	groupStrings, found := genericParams["group"]
	if found {
		fromLiteralArray, isArray := groupStrings.([]string)
		if !isArray {
			return nil, fmt.Errorf("expected []string, found :%v", groupStrings)
		}
		delegate.Groups = fromLiteralArray
		delete(genericParams, "group")
	}
	saStrings, found := genericParams["serviceaccount"]
	if found {
		fromLiteralArray, isArray := saStrings.([]string)
		if !isArray {
			return nil, fmt.Errorf("expected []string, found :%v", saStrings)
		}
		delegate.ServiceAccounts = fromLiteralArray
		delete(genericParams, "serviceaccount")
	}
	params := map[string]string{}
	for key, value := range genericParams {
		strVal, isString := value.(string)
		if !isString {
			return nil, fmt.Errorf("expected string, saw %v for '%s'", value, key)
		}
		params[key] = strVal
	}
	delegate.Name = params["name"]
	delegate.ClusterRole = params["clusterrole"]
	return delegate.StructuredGenerate()
}

// ParamNames returns the set of supported input parameters when using the parameter injection generator pattern.
func (s ClusterRoleBindingGeneratorV1) ParamNames() []generate.GeneratorParam {
	return []generate.GeneratorParam{
		{Name: "name", Required: true},
		{Name: "clusterrole", Required: false},
		{Name: "user", Required: false},
		{Name: "group", Required: false},
		{Name: "serviceaccount", Required: false},
	}
}

// StructuredGenerate outputs a clusterRoleBinding object using the configured fields.
func (s ClusterRoleBindingGeneratorV1) StructuredGenerate() (runtime.Object, error) {
	if err := s.validate(); err != nil {
		return nil, err
	}
	clusterRoleBinding := &rbacv1.ClusterRoleBinding{}
	clusterRoleBinding.Name = s.Name
	clusterRoleBinding.RoleRef = rbacv1.RoleRef{
		APIGroup: rbacv1.GroupName,
		Kind:     "ClusterRole",
		Name:     s.ClusterRole,
	}
	for _, user := range sets.NewString(s.Users...).List() {
		clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1.Subject{
			Kind:     rbacv1.UserKind,
			APIGroup: rbacv1.GroupName,
			Name:     user,
		})
	}
	for _, group := range sets.NewString(s.Groups...).List() {
		clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1.Subject{
			Kind:     rbacv1.GroupKind,
			APIGroup: rbacv1.GroupName,
			Name:     group,
		})
	}
	for _, sa := range sets.NewString(s.ServiceAccounts...).List() {
		tokens := strings.Split(sa, ":")
		if len(tokens) != 2 || tokens[0] == "" || tokens[1] == "" {
			return nil, fmt.Errorf("serviceaccount must be <namespace>:<name>")
		}
		clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1.Subject{
			Kind:      rbacv1.ServiceAccountKind,
			APIGroup:  "",
			Namespace: tokens[0],
			Name:      tokens[1],
		})
	}

	return clusterRoleBinding, nil
}

// validate validates required fields are set to support structured generation.
func (s ClusterRoleBindingGeneratorV1) validate() error {
	if len(s.Name) == 0 {
		return fmt.Errorf("name must be specified")
	}
	if len(s.ClusterRole) == 0 {
		return fmt.Errorf("clusterrole must be specified")
	}
	return nil
}


text:
from django.utils.translation import ugettext as _

QUESTION = _(u'Question')
ANSWER = _(u'Answer')
UP_VOTE = _(u'Up vote')
UP_VOTE_PLURAL = _(u'Up votes')
DOWN_VOTE = _(u'Down vote')
DOWN_VOTE_PLURAL = _(u'Down votes')
VOTE_RESULT = _(u'Votes result')
BODY = _(u'Body')
COMMENT = _(u'Comment')
COMMENT_PLURAL = _(u'Comments')
ANSWER_COUNT = _(u'Number of answers')
QUESTION_CREATED = _(u'Your question was created')
ANSWER_SAVED = _(u'Your answer was saved')
YOU_HAVE_TO_LOGIN = _(u'You have to be logged in to do that.')
VOTE_CASTED = _(u'Your vote was saved')
INVALID_VOTE = _(u'Invalid vote value')
BEST_ANSWER = _(u'Looking for a best answer')
CONVERSATION = _(u'This is a conversation thread')


text:
/**
 *
 */
package com.github.nest.arcteryx.meta.beans.internal.validators.hibernate.convertors;

import org.hibernate.validator.cfg.ConstraintDef;
import org.hibernate.validator.cfg.defs.LengthDef;

import com.github.nest.arcteryx.meta.beans.constraints.LengthConstraint;
import com.github.nest.arcteryx.meta.beans.internal.validators.hibernate.HibernateErrorCodeRegistry;

/**
 * length convertor
 *
 * @author brad.wu
 */
public class LengthConvertor extends AbstractHibernateConstraintConvertor<LengthConstraint> {
	/**
	 * (non-Javadoc)
	 *
	 * @see com.github.nest.arcteryx.meta.beans.internal.validators.hibernate.convertors.AbstractHibernateConstraintConvertor#registerErrorCode()
	 */
	@Override
	protected void registerErrorCode() {
		HibernateErrorCodeRegistry.registerErrorCode(org.hibernate.validator.constraints.Length.class,
				LengthConstraint.class.getSimpleName());
	}

	/**
	 * (non-Javadoc)
	 *
	 * @see com.github.nest.arcteryx.meta.beans.internal.validators.hibernate.convertors.AbstractHibernateConstraintConvertor#createConstraintDef(com.github.nest.arcteryx.meta.beans.IConstraint)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	protected ConstraintDef createConstraintDef(LengthConstraint constraint) {
		return new LengthDef().min(constraint.getMin()).max(constraint.getMax());
	}

	/**
	 * (non-Javadoc)
	 *
	 * @see com.github.nest.arcteryx.meta.beans.internal.validators.hibernate.IHibernateConstraintConvertor#getSupportedConstraintType()
	 */
	@Override
	public Class<LengthConstraint> getSupportedConstraintType() {
		return LengthConstraint.class;
	}
}


text:
=begin
Write your code for the 'Acronym' exercise in this file. Make the tests in
`acronym_test.rb` pass.

To get started with TDD, see the `README.md` file in your
`ruby/acronym` directory.
=end


text:
location-transmit
=================


text:
package org.datavec.spark.transform.filter;

import org.apache.spark.api.java.function.Function;
import org.datavec.api.transform.metadata.ColumnMetaData;
import org.datavec.api.writable.NullWritable;
import org.datavec.api.writable.Text;
import org.datavec.api.writable.Writable;

public class FilterWritablesBySchemaFunction implements Function<Writable, Boolean> {

    private final ColumnMetaData meta;
    private final boolean keepValid; //If true: keep valid. If false: keep invalid
    private final boolean excludeMissing; //If true: remove/exclude any

    public FilterWritablesBySchemaFunction(ColumnMetaData meta, boolean keepValid) {
        this(meta, keepValid, false);
    }

    /**
     *
     * @param meta              Column meta data
     * @param keepValid         If true: keep only the valid writables. If false: keep only the invalid writables
     * @param excludeMissing    If true: don't return any missing values, regardless of keepValid setting (i.e., exclude any NullWritable or empty string values)
     */
    public FilterWritablesBySchemaFunction(ColumnMetaData meta, boolean keepValid, boolean excludeMissing) {
        this.meta = meta;
        this.keepValid = keepValid;
        this.excludeMissing = excludeMissing;
    }

    @Override
    public Boolean call(Writable v1) throws Exception {
        boolean valid = meta.isValid(v1);
        if (excludeMissing && (v1 instanceof NullWritable
                        || v1 instanceof Text && (v1.toString() == null || v1.toString().isEmpty())))
            return false; //Remove (spark)
        if (keepValid)
            return valid; //Spark: return true to keep
        else
            return !valid;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

Chat!

      <input id="websocket" type="checkbox" value="websocket" checked="checked">
      websocket

      <input id="xhr-streaming" type="checkbox" value="xhr-streaming" checked="checked">
      xhr-streaming

      <input id="iframe-eventsource" type="checkbox" value="iframe-eventsource"
             checked="checked">
      iframe-eventsource

      <input id="iframe-htmlfile" type="checkbox" value="iframe-htmlfile"
             checked="checked">
      iframe-htmlfile

      <input id="xhr-polling" type="checkbox" value="xhr-polling" checked="checked">
      xhr-polling

      <input id="iframe-xhr-polling" type="checkbox" value="iframe-xhr-polling"
             checked="checked">
      iframe-xhr-polling

      <input id="jsonp-polling" type="checkbox" value="jsonp-polling" checked="checked">
      jsonp-polling

  Connect | Status: disconnected

<form id="chatform">
  <input id="text" type="text" />
  <input type="submit" />
</form>


text:
using System;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Factories;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Common;
using C5;
using AutonomousCar.Entities;
using Microsoft.Xna.Framework;

namespace AutonomousCar.Simulation
{
    /// <summary>
    /// The Environment class defines the obstacles in an environment as well as parameters for the obstacle grid.
    /// </summary>
    public class Environment
    {
        public LinkedList<Obstacle> Obstacles { get; set; }
        public LinkedList<CompositeObstacle> CompositeObstacles { get; set; }

        public float GridResolution { get; set; }
        public float GridWidth { get; set; }
        public float GridHeight { get; set; }
        public Vector2 GridOrigin { get; set; }

        public Environment()
        {
            Obstacles = new LinkedList<Obstacle>();
            CompositeObstacles = new LinkedList<CompositeObstacle>();

            GridResolution = 0.75f;
            GridWidth = 150f;
            GridHeight = 150f;
            GridOrigin = Vector2.Zero;
        }
    }

    /// <summary>
    /// The RandomEnvironment class describes an environment with some number of randomly generated obstacles.
    /// </summary>
    public class RandomEnvironment : Environment
    {
        public RandomEnvironment(World world, int numBoxes, Vector2 start, Vector2 destination, float envWidth, float envHeight)
        {
            GridWidth = envWidth;
            GridHeight = envHeight;

            generateEnvironment(world, numBoxes, start, destination);
        }

        public RandomEnvironment(World world, int numBoxes, Vector2 start, Vector2 destination)
        {
            generateEnvironment(world, numBoxes, start, destination);
        }

        private void generateEnvironment(World world, int numBoxes, Vector2 start, Vector2 destination)
        {
            Random r = new Random();

            Vector2 pos;
            float size;
            float orientation;
            for (int i = 0; i < numBoxes; i++)
            {
                do
                {
                    size = (float)r.NextDouble() * 3f + 1f;
                    pos = new Vector2((float)r.NextDouble() * GridWidth, (float)r.NextDouble() * GridHeight);
                    orientation = (float)r.NextDouble() * MathHelper.TwoPi;
                } while ((pos - start).LengthSquared() < 100f || (pos - destination).LengthSquared() < 100f || !checkObstacle(size, pos, orientation));
                Obstacles.Add(new BoxObstacle(world, size, size, pos, orientation));
            }
        }

        private bool checkObstacle(float size, Vector2 pos, float orientation)
        {
            PolygonShape shape = new PolygonShape(1f);
            shape.SetAsBox(size, size);
            Transform xform = new Transform();
            xform.Set(pos, orientation);

            foreach (Obstacle obs in Obstacles)
            {
                Body obsBody = obs.Body;
                Transform obstXform;
                obsBody.GetTransform(out obstXform);
                if (obsBody.FixtureList != null && AABB.TestOverlap(shape, 0, obsBody.FixtureList[0].Shape, 0, ref xform, ref obstXform))
                    return false;
            }

            return true;
        }
    }

    /// <summary>
    /// The ParkingEnvironment class describes a basic parking lot type environment.
    /// </summary>
    public class ParkingEnvironment : Environment
    {
        public ParkingEnvironment(World world) : base()
        {
            Random r = new Random();

            for (int i = 0; i < 50; i++)
                if (r.NextDouble() < 0.98)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(-10 + i * 2.5f, 30)));
            for (int i = 0; i < 50; i++)
                if (r.NextDouble() < 0.98)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(-10 + i * 2.5f, 35)));

            for (int i = 0; i < 20; i++)
                if (r.NextDouble() < 0.98)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(20 + i * 2.5f, 60)));
            for (int i = 0; i < 20; i++)
                if (r.NextDouble() < 0.98)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(20 + i * 2.5f, 55)));

            for (int i = 0; i < 40; i++)
                if (r.NextDouble() < 0.98)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(80 + i * 2.5f, 60)));
            for (int i = 0; i < 40; i++)
                if (r.NextDouble() < 0.98)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(80 + i * 2.5f, 55)));

            for (int i = 0; i < 40; i++)
                if (r.NextDouble() < 0.95)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(-10 + i * 2.5f, 90)));
            for (int i = 0; i < 40; i++)
                if (r.NextDouble() < 0.95)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(-10 + i * 2.5f, 85)));

            for (int i = 0; i < 40; i++)
                if (r.NextDouble() < 0.95)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(90f + i * 2.5f, 90)));
            for (int i = 0; i < 40; i++)
                if (r.NextDouble() < 0.95)
                    Obstacles.Add(new BoxObstacle(world, 2 * Car.HALF_CAR_WIDTH, 2 * Car.HALF_CAR_LENGTH, new Vector2(92.5f + i * 2.5f, 85)));
        }
    }
}