text:
"""
Support for information about the German trans system.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.deutsche_bahn/
"""
import logging
from datetime import timedelta, datetime
from homeassistant.util import Throttle
from homeassistant.helpers.entity import Entity

_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['schiene==0.17']
ICON = 'mdi:train'

# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120)

def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Setup the Deutsche Bahn Sensor."""
    start = config.get('from')
    goal = config.get('to')

    if start is None:
        _LOGGER.error('Missing required variable: "from"')
        return False

    if goal is None:
        _LOGGER.error('Missing required variable: "to"')
        return False

    dev = []
    dev.append(DeutscheBahnSensor(start, goal))
    add_devices_callback(dev)

# pylint: disable=too-few-public-methods
class DeutscheBahnSensor(Entity):
    """Implementation of a Deutsche Bahn sensor."""

    def __init__(self, start, goal):
        """Initialize the sensor."""
        self._name = start + ' to ' + goal
        self.data = SchieneData(start, goal)
        self.update()

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def icon(self):
        """Return the icon for the frontend."""
        return ICON

    @property
    def state(self):
        """Return the departure time of the next train."""
        return self._state

    @property
    def state_attributes(self):
        """Return the state attributes."""
        return self.data.connections[0]

    def update(self):
        """Get the latest delay from bahn.de and updates the state."""
        self.data.update()
        self._state = self.data.connections[0].get('departure', 'Unknown')
        if self.data.connections[0]['delay'] != 0:
            self._state += " + {}".format(
                self.data.connections[0]['delay']
            )

# pylint: disable=too-few-public-methods
class SchieneData(object):
    """Pull data from the bahn.de web page."""

    def __init__(self, start, goal):
        """Initialize the sensor."""
        import schiene
        self.start = start
        self.goal = goal
        self.schiene = schiene.Schiene()
        self.connections = [{}]

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Update the connection data."""
        self.connections = self.schiene.connections(self.start,
                                                    self.goal,
                                                    datetime.now())
        for con in self.connections:
            # Details info is not useful.
            # Having a more consistent interface simplifies
            # usage of Template sensors later on
            if 'details' in con:
                con.pop('details')
                delay = con.get('delay',
                                {'delay_departure': 0,
                                 'delay_arrival': 0})
                # IMHO only delay_departure is usefull
                con['delay'] = delay['delay_departure']
                con['ontime'] = con.get('ontime', False)


text:
<?php

namespace aurora\saml;

use aurora\util\uuid;

class authnrequest
{
	public static function encode($acsUrl, $issuer)
	{
		$now = gmdate("Y-m-d\TH:i:s\Z");
		$id  = uuid::v4();

		return <<<XML
<samlp:AuthnRequest
 AssertionConsumerServiceURL="$acsUrl"
 ID="_$id"
 IssueInstant="$now"
 Version="2.0"
 xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
 xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<saml:Issuer>$issuer</saml:Issuer>
<samlp:NameIDPolicy
 AllowCreate="true"
 Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"/>
</samlp:AuthnRequest>
XML;
	}
}

redpajama_set_name: RedPajamaGithub


text:
import {Context} from '@rundeck/testdeck/context'
import {Page} from '@rundeck/testdeck/page'
import {By, until} from 'selenium-webdriver'

export enum Elems {
    username= '//*[@id="login"]',
    password = '//*[@id="password"]',
    /** @todo This button could use an id */
    loginBtn = '//*[@id="btn-login"]',
}

export class LoginPage extends Page {
    path = '/'

    constructor(readonly ctx: Context) {
        super(ctx)
    }

    async get() {
        const {driver} = this.ctx
        await driver.get(this.ctx.urlFor('/'))
    }

    async sendLogin(username: string, password: string){
        await this.get()
        const {driver} = this.ctx

        // Fetches the elements concurrently
        const [usernameFld, passwordFld, loginBtn] = await Promise.all([
            driver.findElement(By.xpath(Elems.username)),
            driver.findElement(By.xpath(Elems.password)),
            driver.findElement(By.xpath(Elems.loginBtn)),
        ])

        // Fills in the fields concurrently
        await Promise.all([
            usernameFld.sendKeys(username),
            passwordFld.sendKeys(password),
        ])

        await loginBtn.click()
    }
    async login(username: string, password: string) {
        const {driver} = this.ctx
        await this.sendLogin(username, password)

        await driver.wait(until.titleMatches(/^((?!Login).)*$/i), 5000)
    }

    async badLogin(username: string, password: string) {
        const {driver} = this.ctx
        await this.sendLogin(username, password)

        await driver.wait(until.urlContains('/user/error'), 5000)
    }
}


text:
..
    Warning: Do not edit this file. It is automatically generated from the
    software project's code and your changes will be overwritten.

    The tool to generate this file lives in openstack-doc-tools repository.

    Please make any changes needed in the code, then run the
    autogenerate-config-doc tool from the openstack-doc-tools repository, or
    ask for help on the documentation mailing list, IRC channel or meeting.

.. _trove-guestagent:

.. list-table:: Description of guest agent configuration options
   :header-rows: 1
   :class: config-ref-table

   * - Configuration option = Default value
     - Description
   * - **[DEFAULT]**
     -
   * - ``agent_call_high_timeout`` = ``60``
     - (Integer) Maximum time (in seconds) to wait for Guest Agent 'slow' requests (such as restarting the database).
   * - ``agent_call_low_timeout`` = ``5``
     - (Integer) Maximum time (in seconds) to wait for Guest Agent 'quick'requests (such as retrieving a list of users or databases).
   * - ``agent_heartbeat_expiry`` = ``60``
     - (Integer) Time (in seconds) after which a guest is considered unreachable
   * - ``agent_heartbeat_time`` = ``10``
     - (Integer) Maximum time (in seconds) for the Guest Agent to reply to a heartbeat request.
   * - ``agent_replication_snapshot_timeout`` = ``36000``
     - (Integer) Maximum time (in seconds) to wait for taking a Guest Agent replication snapshot.
   * - ``guest_config`` = ``/etc/trove/trove-guestagent.conf``
     - (String) Path to the Guest Agent config file to be injected during instance creation.
   * - ``guest_id`` = ``None``
     - (String) ID of the Guest Instance.
   * - ``guest_info`` = ``guest_info.conf``
     - (String) The guest info filename found in the injected config location. If a full path is specified then it will be used as the path to the guest info file
   * - ``guest_log_container_name`` = ``database_logs``
     - (String) Name of container that stores guest log components.
   * - ``guest_log_expiry`` = ``2592000``
     - (Integer) Expiry (in seconds) of objects in guest log container.
   * - ``guest_log_limit`` = ``1000000``
     - (Integer) Maximum size of a chunk saved in guest log container.
   * - ``mount_options`` = ``defaults,noatime``
     - (String) Options to use when mounting a volume.
   * - ``storage_namespace`` = ``trove.common.strategies.storage.swift``
     - (String) Namespace to load the default storage strategy from.
   * - ``storage_strategy`` = ``SwiftStorage``
     - (String) Default strategy to store backups.
   * - ``usage_sleep_time`` = ``5``
     - (Integer) Time to sleep during the check for an active Guest.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Example</title>

      Server value:

      <input id='my_value'/>


text:
<?php

namespace a3mg\RussianPostBundle\Model\Rtm02Parameter;

/**
 * Коды причин не доставки отправлений ДМ
 *
 * Class NonCommit
 * @package a3mg\RussianPostBundle\Model\Rtm02Parameter
 */
class NonCommit extends AbstractRtm02Parameter
{
    const LACK_OF_MAILBOX = 1; // Отсутствие п/я
    const ABSENCE_OF_STREETS_HOUSES_APARTMENTS = 2; // Отсутствие улицы, дома, квартиры
    const MISMATCH_INDEX_OPS_EXTRADITION = 3; // Несоответствие индекса ОПС выдачи
    const INCORRECT_ADDRESS = 4; // Неверный адрес/адрес не существует

    /** @return string */
    public static function getType() {
        return 'NonCommit';
    }

    /** @return string */
    public static function getDescription() {
        return 'Коды причин не доставки отправлений ДМ';
    }

    protected $dic = array (
        self::LACK_OF_MAILBOX => array ( 'name' => 'Отсутствие п/я', 'translation' => 'Lack of mailbox', 'relatedAttributeType' => '' ),
        self::ABSENCE_OF_STREETS_HOUSES_APARTMENTS => array ( 'name' => 'Отсутствие улицы, дома, квартиры', 'translation' => 'The absence of streets, houses, apartments', 'relatedAttributeType' => '' ),
        self::MISMATCH_INDEX_OPS_EXTRADITION => array ( 'name' => 'Несоответствие индекса ОПС выдачи ', 'translation' => 'Mismatch index OPS extradition', 'relatedAttributeType' => '' ),
        self::INCORRECT_ADDRESS => array ( 'name' => 'Неверный адрес/адрес не существует', 'translation' => 'Incorrect address / address does not exist', 'relatedAttributeType' => '' ),
    );
}


text:
usage()
{
cat << EOF
usage: sudo $0 <linux-variant>
This script installs all dependencies for opencv-workbench

EOF
}

#Require the script to be run as root
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
    echo "This script must be run as root because libraries will be installed."
    usage
    exit
fi

# Grab username of caller for later
ORIGINAL_USER=$(who am i | awk '{print $1}')

if [ ! -d ../third-party-build ];
then
su $ORIGINAL_USER -m -c 'mkdir ../third-party-build'
fi

# Install dependencies through the package manager first:
./install-bin-deps.sh

# -----------------------------------------------------------------------------
# Build x264
# -----------------------------------------------------------------------------
su $ORIGINAL_USER -m -c './build-x264.sh'
./build-x264.sh install
ldconfig

# -----------------------------------------------------------------------------
# Build ffmpeg
# -----------------------------------------------------------------------------
su $ORIGINAL_USER -m -c './build-ffmpeg.sh'
./build-ffmpeg.sh install
ldconfig

# -----------------------------------------------------------------------------
# Build yaml-cpp
# -----------------------------------------------------------------------------
su $ORIGINAL_USER -m -c './build-yaml-cpp.sh'
./build-yaml-cpp.sh install
ldconfig

## -----------------------------------------------------------------------------
## Build OpenCV
## -----------------------------------------------------------------------------
su $ORIGINAL_USER -m -c './build-opencv.sh'
./build-opencv.sh install
ldconfig


text:
using System;

namespace UniRx
{
    public static partial class DisposableExtensions
    {
        /// <summary>Add disposable(self) to CompositeDisposable(or other ICollection). Return value is self disposable.</summary>

        // IModel
        public static T AddTo<T>(this T disposable, Service.Events.CommandsBase commandBase)
            where T : IDisposable
        {
            if (disposable == null) throw new ArgumentNullException("disposable");
            if (commandBase == null) throw new ArgumentNullException("commandBase");

            commandBase.AddDisposable(disposable);

            return disposable;
        }
    }
}


text:
#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER_KERNEL_BUILDER(Name("LogicalAnd").Device(DEVICE_CPU),
                        BinaryOp<CPUDevice, functor::logical_and>);
#if GOOGLE_CUDA
REGISTER_KERNEL_BUILDER(Name("LogicalAnd").Device(DEVICE_GPU),
                        BinaryOp<GPUDevice, functor::logical_and>);
#endif
}  // namespace tensorflow


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.06.05 at 08:50:12 PM SAMT
//

package ru.fsrar.wegais.replyformb;

import javax.xml.bind.annotation.XmlRegistry;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the ru.fsrar.wegais.replyformb package.
 *
An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: ru.fsrar.wegais.replyformb
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link ReplyFormB }
     *
     */
    public ReplyFormB createReplyFormB() {
        return new ReplyFormB();
    }

}


text:
package org.liangbl.solr.analysis;

import java.io.IOException;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionLengthAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.analysis.util.CharacterUtils;

/**
 * Tokenizes the given token into n-grams of given size(s).
 *

 * This {@link TokenFilter} create n-grams from the beginning edge of a input
 * token.
 *

 * As of Lucene 4.4, this filter handles correctly
 * supplementary characters.
 */
public final class PinyinNGramTokenFilter extends TokenFilter {
	public static final int DEFAULT_MAX_GRAM_SIZE = 1;
	public static final int DEFAULT_MIN_GRAM_SIZE = 1;

	private final CharacterUtils charUtils;
	private final int minGram;
	private final int maxGram;
	private char[] curTermBuffer;
	private int curTermLength;
	private int curCodePointCount;
	private int curGramSize;
//	private int tofStart;
//	private int tofEnd; // only used if the length changed before this filter
	private int savePosIncr;
	private int savePosLen;

	private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
	private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
	private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
	private final PositionLengthAttribute posLenAtt = addAttribute(PositionLengthAttribute.class);
	private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class); // 类型属性

	private boolean hasCurOut = false; // 当前输入是否已输出back

	protected PinyinNGramTokenFilter(TokenStream input) {
		super(input);
		this.charUtils = CharacterUtils.getInstance();
		this.minGram = DEFAULT_MIN_GRAM_SIZE;
		this.maxGram = DEFAULT_MAX_GRAM_SIZE;
	}

	/**
	 * Creates EdgeNGramTokenFilter that can generate n-grams in the sizes of
	 * the given range
	 *
	 * @param input
	 *            {@link TokenStream} holding the input to be tokenized
	 * @param side
	 *            the {@link Side} from which to chop off an n-gram
	 * @param minGram
	 *            the smallest n-gram to generate
	 * @param maxGram
	 *            the largest n-gram to generate
	 */
	public PinyinNGramTokenFilter(TokenStream input, int minGram, int maxGram) {
		super(input);

		if (minGram < 1) {
			throw new IllegalArgumentException("minGram must be greater than zero");
		}

		if (minGram > maxGram) {
			throw new IllegalArgumentException("minGram must not be greater than maxGram");
		}

		this.charUtils = CharacterUtils.getInstance();
		this.minGram = minGram;
		this.maxGram = maxGram;
	}

	@Override
	public final boolean incrementToken() throws IOException {
		while (true) {
			if (curTermBuffer == null) {
				if (!input.incrementToken()) {
					return false;
				} else {
					curTermBuffer = termAtt.buffer().clone();
					curTermLength = termAtt.length();
					curCodePointCount = charUtils.codePointCount(termAtt);
					curGramSize = minGram;
					// tofStart = offsetAtt.startOffset();
					// tofStart =side == Side.FRONT ? 0 : curTermLength -
					// curGramSize;
					// tofEnd = offsetAtt.endOffset();
					// tofEnd = tofStart + curGramSize;
					savePosIncr += posIncrAtt.getPositionIncrement();
					savePosLen = posLenAtt.getPositionLength();
				}
			}
			if (curGramSize <= maxGram) { // if we have hit the end of our
											// n-gram
				// size range, quit
				if (curGramSize <= curCodePointCount) { // if the remaining
														// input is
					// too short, we can't
					// generate any n-grams
					// grab gramSize chars from front or back
					clearAttributes();
					// offsetAtt.setOffset(tofStart, tofEnd);
					// first ngram gets increment, others don't
					if (curGramSize == minGram) {
						posIncrAtt.setPositionIncrement(savePosIncr);
						savePosIncr = 0;
					} else {
						posIncrAtt.setPositionIncrement(0);
					}
					posLenAtt.setPositionLength(savePosLen);
					// final int charLength =
					// charUtils.offsetByCodePoints(curTermBuffer, 0,
					// curTermLength, 0, curGramSize);
					// termAtt.copyBuffer(curTermBuffer, tofStart, curGramSize);

					if (!hasCurOut) {
						hasCurOut = true;
						//back
						int start =  curTermLength - curGramSize;
						int end = start + curGramSize;
						offsetAtt.setOffset(start, end);
						termAtt.copyBuffer(curTermBuffer, start, curGramSize);
						this.typeAtt.setType("NGram");
						return true;
					}
					else {
						//front
						hasCurOut = false;
						int start = 0;
						int end = start + curGramSize;
						offsetAtt.setOffset(start, end);
						termAtt.copyBuffer(curTermBuffer, start, curGramSize);
						this.typeAtt.setType("NGram");
					}

					curGramSize++;
					return true;
				}
			}

			curTermBuffer = null;
		}
	}

	@Override
	public void reset() throws IOException {
		super.reset();
		curTermBuffer = null;
		savePosIncr = 0;
	}
}


text:
using Ghostware.GPS.NET.Enums;

namespace Ghostware.GPS.NET.Models.ConnectionInfo
{
    public class FileGpsInfo : BaseGpsInfo
    {
        public string FilePath { get; set; } = "test";
        public FileType FileType { get; set; } = FileType.Nmea;

        public FileGpsInfo()
        {
            ReadFrequenty = 1000;
        }

        public FileGpsInfo(string filePath, FileType fileType = FileType.Nmea, int readFrequenty = 1000)
        {
            FilePath = filePath;
            FileType = fileType;
            ReadFrequenty = readFrequenty;
        }
    }
}


text:
import java.io.File;
import java.net.URL;

import net.sf.saxon.dom.DocumentOverNodeInfo;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;

import org.daisy.pipeline.webservice.xml.XmlValidator;

import org.junit.Assert;
import org.junit.Test;

import org.w3c.dom.Document;

public class SampleXmlFormatsTest {

	@Test
	public void validateSampleXmlFormats() throws SaxonApiException {
		assertValid("alive.xml",                 XmlValidator.ALIVE_SCHEMA_URL);
		assertValid("client.xml",                XmlValidator.CLIENT_SCHEMA_URL);
		assertValid("clients.xml",               XmlValidator.CLIENTS_SCHEMA_URL);
		assertValid("error.xml",                 XmlValidator.ERROR_SCHEMA_URL);
		assertValid("job.xml",                   XmlValidator.JOB_SCHEMA_URL);
		assertValid("jobRequest1.localmode.xml", XmlValidator.JOB_REQUEST_SCHEMA_URL);
		assertValid("jobRequest1.xml",           XmlValidator.JOB_REQUEST_SCHEMA_URL);
		assertValid("jobRequest2.xml",           XmlValidator.JOB_REQUEST_SCHEMA_URL);
		assertValid("jobs.xml",                  XmlValidator.JOBS_SCHEMA_URL);
		assertValid("queue.xml",                 XmlValidator.QUEUE_SCHEMA_URL);
		assertValid("script.xml",                XmlValidator.SCRIPT_SCHEMA_URL);
		assertValid("scripts.xml",               XmlValidator.SCRIPTS_SCHEMA_URL);
		assertValid("sizes.xml",                 XmlValidator.SIZES_SCHEMA_URL);
	}

	private static void assertValid(String sample, URL schema) throws SaxonApiException {
		Assert.assertTrue(sample + " is not valid",
		                  XmlValidator.validate(
			                  (Document)DocumentOverNodeInfo.wrap(
				                  new Processor(false).newDocumentBuilder().build(
					                  new File(SampleXmlFormatsTest.class.getResource("xml-formats/" + sample).getFile())
				                  ).getUnderlyingNode()),
			                  schema));
	}
}


text:
/**
 * ExistingSentenceState.java
 */

package uk.co.bluettduncanj.model.state.states;

/**
 * @author Jonathan Bluett-Duncan
 */
public class ExistingSentenceState {

}


text:
package com.myandroid.activity;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.myandroid.message.R;
import com.myandroid.util.Tools;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class FileAcitivity extends Activity {
	private Button shouYe = null;
	private Button shangYe = null;
	private Button duoXuan = null;
	private TextView state = null;
	private ListView listView = null;
	SimpleAdapter simpleAdapter = null;
	View popuView = null;
	PopupWindow popWin = null;
	public static final String ADDRESS = "/mnt";
	private int[] pic = new int[] { R.drawable.img_dir, R.drawable.img_file };
	private String choosePath;// ¼Ç¼ѡÖеÄÎļþ
	private String startPath = Tools.startPath;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file_choose);
		init();
		showDir(startPath);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		if(choosePath!=null&&(new File(choosePath)).isFile()){
			menu.setHeaderTitle("²Ù×÷²Ëµ¥");
			menu.add(Menu.NONE, Menu.FIRST + 1, 1, "·¢ËÍ");
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			// ·µ»ØÖ÷ºÃÓÑÔÚÏß½çÃæ È¡»ØÑ¡ÖеÄÎļþ·¾¶
			Intent it = FileAcitivity.this.getIntent();
			it.putExtra("path", choosePath);
			FileAcitivity.this.setResult(RESULT_OK, it);
			Tools.startPath=FileAcitivity.getStartPath(this.choosePath);
			FileAcitivity.this.finish();
		}
		return false;
	}

	@Override
	public void onContextMenuClosed(Menu menu) {
		// TODO Auto-generated method stub
		super.onContextMenuClosed(menu);
	}

	// ³õ'
	public void init() {
		shouYe = (Button) super.findViewById(R.id.shouYe);
		shangYe = (Button) super.findViewById(R.id.shangYe);
		duoXuan = (Button) super.findViewById(R.id.duoXuan);
		state = (TextView) super.findViewById(R.id.state);
		listView = (ListView) super.findViewById(R.id.listView);
		duoXuan.setVisibility(8);
		// ΪlistView×¢²á²Ëµ¥
		super.registerForContextMenu(this.listView);
		// ÓÐÒ°°´Å¥¼àÌý
		shouYe.setOnClickListener(new OnClickListenerIter());
		// Éϲ㰴ť¼àÌý
		shangYe.setOnClickListener(new OnClickListenerIterShangYe());
		// ¼àÌýÁбíÏî
		listView.setOnItemClickListener(new OnItemClickListenerIter());
		// ÁбíÏ°´¼àÌý
		listView.setOnItemLongClickListener(new OnItemLongClickListenerml());
	}

	// ÁбíÏ°´¼àÌý
	class OnItemLongClickListenerml implements OnItemLongClickListener {

		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			Map<String, String> map = (Map<String, String>) arg0.getAdapter()
					.getItem(arg2);
			String name = state.getText().toString() + "/" + map.get("name");
			if (name.equals("/mnt/secure") || name.equals("/mnt/usb_storage")
					|| name.equals("/mnt/sdcard/.android_secure")) {
				Toast.makeText(FileAcitivity.this, "ÎÞ·¨´ò¿ª", Toast.LENGTH_SHORT)
						.show();
				return false;
			}
			choosePath = name;
			// Toast.makeText(FileChoose.this, "×¼±¸·¢ËÍÎļþ£º" + choosePath,
			// Toast.LENGTH_SHORT).show();
			return false;
		}

	}

	// Éϲ㰴ť¼àÌý
	class OnClickListenerIterShangYe implements OnClickListener {

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			String p = state.getText().toString();
			if (p.equals("/mnt")) {
				return;
			} else {
				p = new File(p).getParent();
				choosePath=p;
				showDir(p);
			}
		}

	}

	// ÁбíÏî¼àÌý
	class OnItemClickListenerIter implements OnItemClickListener {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Map<String, String> map = (Map<String, String>) arg0.getAdapter()
					.getItem(arg2);
			String name = state.getText().toString() + "/" + map.get("name");
			if (name.equals("/mnt/secure") || name.equals("/mnt/usb_storage")
					|| name.equals("/mnt/sdcard/.android_secure")) {
				Toast.makeText(FileAcitivity.this, "ÎÞ·¨´ò¿ª", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			File f = new File(name);
			if (f.isFile()) {// Èç¹ûÑ¡ÖеÄÊÇÎļþ
				FileAcitivity.openFile(FileAcitivity.this,f);
				return;
			} else {// Èç¹ûÑ¡ÖеÄÊÇÎļþ¼Ð
					// state.setText(f.getPath());
				choosePath=f.getPath();
				showDir(f.getPath());
			}
		}

	}

	class OnClickListenerIter implements android.view.View.OnClickListener {
		public void onClick(View v) {
			choosePath=ADDRESS;
			showDir(ADDRESS);
		}
	}

	// ÏÔʾĿ¼
	public void showDir(String path) {
		state.setText(path);
		File f = new File(path);
		File[] fileList = f.listFiles();
		fileList = this.fileStyle(fileList);
		List list = new ArrayList<Map<String, String>>();
		for (int i = 0; i < fileList.length; i++) {
			Map<String, String> map = new HashMap<String, String>();
			if (fileList[i].isDirectory()) {
				map.put("img", String.valueOf(pic[0]));
				map.put("size", "Îļþ¼Ð");

			} else {
				map.put("img", String.valueOf(pic[1]));
				map.put("size", "´óС£º" + getFormatSize(fileList[i].length()));
			}
			map.put("name", fileList[i].getName());
			map.put("time", "ʱ¼ä£º" + timeFormat(fileList[i].lastModified()));
			list.add(map);

		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(FileAcitivity.this, list,
				R.layout.file_show, new String[] { "img", "name", "size",
						"time" }, new int[] { R.id.img, R.id.name, R.id.size,
						R.id.time });
		FileAcitivity.this.listView.setAdapter(simpleAdapter);
	}

	// Îļþ·ÖÀà
	public File[] fileStyle(File[] files) {
		List<File> fileList = new ArrayList<File>();
		List<File> dirList = new ArrayList<File>();

		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {// Èç¹ûÊÇÎļþ¼ÐÔòremove
				dirList.add(files[i]);// ¼ÓÈëÎļþ¼Ðlist
			} else {
				fileList.add(files[i]);// ɾ³ý³öÎļþlist
			}
		}
		dirList = this.fileOrder(dirList);
		fileList = this.fileOrder(fileList);
		dirList.addAll(fileList);
		for (int i = 0; i < dirList.size(); i++) {
			files[i] = dirList.get(i);
		}
		// ((ArrayList<File>) dirList).trimToSize();
		return files;
	}

	// ÎļþÅÅÐò
	public List<File> fileOrder(List<File> list) {
		for (int i = 0; i < list.size() - 1; i++) {
			for (int j = 0; j < list.size() - i - 1; j++) {
				if (list.get(j).getName().charAt(0) > list.get(j + 1).getName()
						.charAt(0)) {
					list.add(j + 2, list.get(j));
					list.remove(j);
				}
			}
		}
		return list;
	}

	// ¸ñʽ»¯Ê±¼ä
	public String timeFormat(long date) {
		Date d = new Date(date);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		return sdf.format(d);
	}

	// ¼ÆËãÎļþ´óС
	public static String getFormatSize(double size) {
		double kiloByte = size / 1024;
		if (kiloByte < 1) {
			return size + "Byte(s)";
		}

		double megaByte = kiloByte / 1024;
		if (megaByte < 1) {
			BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
			return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "KB";
		}

		double gigaByte = megaByte / 1024;
		if (gigaByte < 1) {
			BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
			return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "MB";
		}

		double teraBytes = gigaByte / 1024;
		if (teraBytes < 1) {
			BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
			return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "GB";
		}
		BigDecimal result4 = new BigDecimal(teraBytes);
		return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
				+ "TB";
	}
	public void onBackPressed() {
		Tools.startPath=FileAcitivity.getStartPath(choosePath);
		FileAcitivity.this.finish();
	}
	// »ñµÃ³õ'Ŀ¼-ʵÏÖµÚ¶þ´Î´ò¿ªÊǾͽüµÄĿ¼
	public static String getStartPath(String startPath) {
		if (startPath == null) {
			return FileAcitivity.ADDRESS;
		} else {
			File file = new File(startPath);
			if (file.isFile()) {
				return file.getParent();
			} else {
				return startPath;
			}
		}
	}
	public static void openFile(Activity a,File file){

	    Intent intent = new Intent();
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    //ÉèÖÃintentµÄActionÊôÐÔ
	    intent.setAction(Intent.ACTION_VIEW);
	    //»ñÈ¡ÎļþfileµÄMIMEÀàÐÍ
	    String type = getMIMEType(file);
	    //ÉèÖÃintentµÄdataºÍTypeÊôÐÔ¡£
	    intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
	    //Ìøת
	    a.startActivity(intent);

	}
	private static String getMIMEType(File file) {

	    String type="*/*";
	    String fName = file.getName();
	    //»ñÈ¡ºó׺ÃûÇ°µÄ·Ö¸ô·û"."ÔÚfNameÖеÄλÖᣠ
	    int dotIndex = fName.lastIndexOf(".");
	    if(dotIndex < 0){
	        return type;
	    }
	    /* »ñÈ¡ÎļþµÄºó׺Ãû*/
	    String end=fName.substring(dotIndex,fName.length()).toLowerCase();
	    if(end=="")return type;
	    //ÔÚMIMEºÍÎļþÀàÐ͵ÄÆ¥Åä±íÖÐÕÒµ½¶ÔÓ¦µÄMIMEÀàÐÍ¡£
	    for(int i=0;i<MIME_MapTable.length;i++){ //MIME_MapTable??ÔÚÕâÀïÄãÒ»¶¨ÓÐÒÉÎÊ£¬Õâ¸öMIME_MapTableÊÇʲô£¿
	        if(end.equals(MIME_MapTable[i][0]))
	            type = MIME_MapTable[i][1];
	    }
	    return type;
	}
	private static final String[][] MIME_MapTable={
        //{ºó׺Ãû£¬MIMEÀàÐÍ}
        {".3gp",    "video/3gpp"},
        {".apk",    "application/vnd.android.package-archive"},
        {".asf",    "video/x-ms-asf"},
        {".avi",    "video/x-msvideo"},
        {".bin",    "application/octet-stream"},
        {".bmp",    "image/bmp"},
        {".c",  "text/plain"},
        {".class",  "application/octet-stream"},
        {".conf",   "text/plain"},
        {".cpp",    "text/plain"},
        {".doc",    "application/msword"},
        {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".xls",    "application/vnd.ms-excel"},
        {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".exe",    "application/octet-stream"},
        {".gif",    "image/gif"},
        {".gtar",   "application/x-gtar"},
        {".gz", "application/x-gzip"},
        {".h",  "text/plain"},
        {".htm",    "text/html"},
        {".html",   "text/html"},
        {".jar",    "application/java-archive"},
        {".java",   "text/plain"},
        {".jpeg",   "image/jpeg"},
        {".jpg",    "image/jpeg"},
        {".js", "application/x-javascript"},
        {".log",    "text/plain"},
        {".m3u",    "audio/x-mpegurl"},
        {".m4a",    "audio/mp4a-latm"},
        {".m4b",    "audio/mp4a-latm"},
        {".m4p",    "audio/mp4a-latm"},
        {".m4u",    "video/vnd.mpegurl"},
        {".m4v",    "video/x-m4v"},
        {".mov",    "video/quicktime"},
        {".mp2",    "audio/x-mpeg"},
        {".mp3",    "audio/x-mpeg"},
        {".mp4",    "video/mp4"},
        {".mpc",    "application/vnd.mpohun.certificate"},
        {".mpe",    "video/mpeg"},
        {".mpeg",   "video/mpeg"},
        {".mpg",    "video/mpeg"},
        {".mpg4",   "video/mp4"},
        {".mpga",   "audio/mpeg"},
        {".msg",    "application/vnd.ms-outlook"},
        {".ogg",    "audio/ogg"},
        {".pdf",    "application/pdf"},
        {".png",    "image/png"},
        {".pps",    "application/vnd.ms-powerpoint"},
        {".ppt",    "application/vnd.ms-powerpoint"},
        {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".prop",   "text/plain"},
        {".rc", "text/plain"},
        {".rmvb",   "audio/x-pn-realaudio"},
        {".rtf",    "application/rtf"},
        {".sh", "text/plain"},
        {".tar",    "application/x-tar"},
        {".tgz",    "application/x-compressed"},
        {".txt",    "text/plain"},
        {".wav",    "audio/x-wav"},
        {".wma",    "audio/x-ms-wma"},
        {".wmv",    "audio/x-ms-wmv"},
        {".wps",    "application/vnd.ms-works"},
        {".xml",    "text/plain"},
        {".z",  "application/x-compress"},
        {".zip",    "application/x-zip-compressed"},
        {"",        "*/*"}
    };
}


text:
<?php

namespace Cqrs\Collection\Expression;

/**
 * Comparison of a field with a value by the given operator.
 *
 * @author      Iqbal Maulana <iq.bluejack@gmail.com>
 * @created     4/26/15
 */
class Comparison implements ExpressionInterface {

    /**
     * Operator Constant
     */
    const EQUAL                 = "=";
    const NOT_EQUAL             = "<>";
    const LOWER_THAN            = "<";
    const LOWER_THAN_EQUAL      = "<=";
    const GREATER_THAN          = ">";
    const GREATER_THAN_EQUAL    = ">=";
    const IS_NULL               = "IS NULL";
    const IS_NOT_NULL           = "IS NOT NULL";
    const IN                    = "IN";
    const NOT_IN                = "NOT IN";
    const EXISTS                = "EXISTS";
    const NOT_EXISTS            = "NOT EXISTS";
    const LIKE                  = "LIKE";
    const NOT_LIKE              = "NOT LIKE";

    /**
     * Field to be compare.
     *
     * @var string
     */
    private $field;

    /**
     * One of logical operator.
     *
     * @var string
     */
    private $operator;

    /**
     * Value to be compare.
     *
     * @var mixed
     */
    private $value;

    /**
     * @param string|integer $field
     * @param string $operator
     * @param mixed $value
     */
    public function __construct($field, $operator, $value) {

	    $value =
		    is_object($value) && method_exists($value, '__toString')
		    ? (string) $value
		    : $value;

        $this->field    = $field;
        $this->operator = $operator;
        $this->value    = $value;
    }

    /**
     * @return integer|string
     */
    public function getField() {

        return $this->field;
    }

    /**
     * @return string
     */
    public function getOperator() {

        return $this->operator;
    }

    /**
     * @return mixed
     */
    public function getValue() {

        return $this->value;
    }
}


text:
package org.apache.ignite.internal.processors.authentication;

import java.util.concurrent.Callable;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

/**
 * Test for disabled {@link IgniteAuthenticationProcessor}.
 */
public class AuthenticationConfigurationClusterTest extends GridCommonAbstractTest {
    /**
     * @param idx Node index.
     * @param authEnabled Authentication enabled.
     * @param client Client node flag.
     * @return Ignite configuration.
     * @throws Exception On error.
     */
    private IgniteConfiguration configuration(int idx, boolean authEnabled, boolean client) throws Exception {
        IgniteConfiguration cfg = getConfiguration(getTestIgniteInstanceName(idx));

        cfg.setClientMode(client);

        cfg.setAuthenticationEnabled(authEnabled);

        cfg.setDataStorageConfiguration(new DataStorageConfiguration()
            .setDefaultDataRegionConfiguration(new DataRegionConfiguration()
                .setMaxSize(200L * 1024 * 1024)
                .setPersistenceEnabled(true)));

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        GridTestUtils.setFieldValue(User.class, "bCryptGensaltLog2Rounds", 4);
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        super.afterTestsStopped();

        GridTestUtils.setFieldValue(User.class, "bCryptGensaltLog2Rounds", 10);
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        stopAllGrids();

        super.afterTest();
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        super.beforeTest();

        U.resolveWorkDirectory(U.defaultWorkDirectory(), "db", true);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testServerNodeJoinDisabled() throws Exception {
        checkNodeJoinDisabled(false);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testClientNodeJoinDisabled() throws Exception {
        checkNodeJoinDisabled(true);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testServerNodeJoinEnabled() throws Exception {
        checkNodeJoinEnabled(false);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testClientNodeJoinEnabled() throws Exception {
        checkNodeJoinEnabled(true);
    }

    /**
     * @param client Is joining node client.
     * @throws Exception If failed.
     */
    private void checkNodeJoinDisabled(boolean client) throws Exception {
        startGrid(configuration(0, true, false));

        startGrid(configuration(1, false, client));

        grid(0).cluster().active(true);

        AuthorizationContext actx = grid(1).context().authentication().authenticate("ignite", "ignite");

        assertNotNull(actx);

        assertEquals("ignite", actx.userName());
    }

    /**
     * @param client Is joining node client.
     * @throws Exception If failed.
     */
    private void checkNodeJoinEnabled(boolean client) throws Exception {
        startGrid(configuration(0, false, false));

        GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    startGrid(configuration(1, true, client));

                    return null;
                }
            },
            IgniteCheckedException.class,
            "User authentication is disabled on cluster");
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDisabledAuthentication() throws Exception {
        startGrid(configuration(0, false, false));

        grid(0).cluster().active(true);

        GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    grid(0).context().authentication().addUser("test", "test");

                    return null;
                }
            }, IgniteException.class,
            "Can not perform the operation because the authentication is not enabled for the cluster");

        GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    grid(0).context().authentication().removeUser("test");

                    return null;
                }
            }, IgniteException.class,
            "Can not perform the operation because the authentication is not enabled for the cluster");

        GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    grid(0).context().authentication().updateUser("test", "test");

                    return null;
                }
            }, IgniteException.class,
            "Can not perform the operation because the authentication is not enabled for the cluster");

        GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    grid(0).context().authentication().authenticate("test", "test");

                    return null;
                }
            }, IgniteException.class,
            "Can not perform the operation because the authentication is not enabled for the cluster");
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testEnableAuthenticationWithoutPersistence() throws Exception {
        GridTestUtils.assertThrowsAnyCause(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    startGrid(configuration(0, true, false).setDataStorageConfiguration(null));

                    return null;
                }
            },
            IgniteCheckedException.class,
            "Authentication can be enabled only for cluster with enabled persistence");
    }
}


text:
package org.jclouds.openstack.nova.ec2.features;

import org.jclouds.ec2.features.AMIApiLiveTest;
import org.testng.annotations.Test;

@Test(groups = "live", singleThreaded = true, testName = "NovaEC2AMIApiLiveTest")
public class NovaEC2AMIApiLiveTest extends AMIApiLiveTest {
   public NovaEC2AMIApiLiveTest() {
      provider = "openstack-nova-ec2";
   }

}


text:
#include "config.h"
#include "core/editing/VisibleUnits.h"

#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "core/HTMLNames.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/Position.h"
#include "core/dom/Text.h"
#include "core/editing/RenderedPosition.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/htmlediting.h"
#include "core/editing/iterators/BackwardsCharacterIterator.h"
#include "core/editing/iterators/CharacterIterator.h"
#include "core/editing/iterators/SimplifiedBackwardsTextIterator.h"
#include "core/editing/iterators/TextIterator.h"
#include "core/html/HTMLBRElement.h"
#include "core/layout/LayoutBlockFlow.h"
#include "core/layout/LayoutObject.h"
#include "core/layout/line/InlineTextBox.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/heap/Handle.h"
#include "platform/text/TextBoundaries.h"

namespace blink {

using namespace HTMLNames;
using namespace WTF::Unicode;

static Node* previousLeafWithSameEditability(Node* node, EditableType editableType)
{
    bool editable = node->hasEditableStyle(editableType);
    node = node->previousLeafNode();
    while (node) {
        if (editable == node->hasEditableStyle(editableType))
            return node;
        node = node->previousLeafNode();
    }
    return 0;
}

static Node* nextLeafWithSameEditability(Node* node, EditableType editableType = ContentIsEditable)
{
    if (!node)
        return 0;

    bool editable = node->hasEditableStyle(editableType);
    node = node->nextLeafNode();
    while (node) {
        if (editable == node->hasEditableStyle(editableType))
            return node;
        node = node->nextLeafNode();
    }
    return 0;
}

// FIXME: consolidate with code in previousLinePosition.
static Position previousRootInlineBoxCandidatePosition(Node* node, const VisiblePosition& visiblePosition, EditableType editableType)
{
    ContainerNode* highestRoot = highestEditableRoot(visiblePosition.deepEquivalent(), editableType);
    Node* previousNode = previousLeafWithSameEditability(node, editableType);

    while (previousNode && (!previousNode->layoutObject() || inSameLine(VisiblePosition(firstPositionInOrBeforeNode(previousNode)), visiblePosition)))
        previousNode = previousLeafWithSameEditability(previousNode, editableType);

    while (previousNode && !previousNode->isShadowRoot()) {
        if (highestEditableRoot(firstPositionInOrBeforeNode(previousNode), editableType) != highestRoot)
            break;

        Position pos = isHTMLBRElement(*previousNode) ? positionBeforeNode(previousNode) :
            createLegacyEditingPosition(previousNode, caretMaxOffset(previousNode));

        if (pos.isCandidate())
            return pos;

        previousNode = previousLeafWithSameEditability(previousNode, editableType);
    }
    return Position();
}

static Position nextRootInlineBoxCandidatePosition(Node* node, const VisiblePosition& visiblePosition, EditableType editableType)
{
    ContainerNode* highestRoot = highestEditableRoot(visiblePosition.deepEquivalent(), editableType);
    Node* nextNode = nextLeafWithSameEditability(node, editableType);
    while (nextNode && (!nextNode->layoutObject() || inSameLine(VisiblePosition(firstPositionInOrBeforeNode(nextNode)), visiblePosition)))
        nextNode = nextLeafWithSameEditability(nextNode, ContentIsEditable);

    while (nextNode && !nextNode->isShadowRoot()) {
        if (highestEditableRoot(firstPositionInOrBeforeNode(nextNode), editableType) != highestRoot)
            break;

        Position pos;
        pos = createLegacyEditingPosition(nextNode, caretMinOffset(nextNode));

        if (pos.isCandidate())
            return pos;

        nextNode = nextLeafWithSameEditability(nextNode, editableType);
    }
    return Position();
}

class CachedLogicallyOrderedLeafBoxes {
public:
    CachedLogicallyOrderedLeafBoxes();

    const InlineTextBox* previousTextBox(const RootInlineBox*, const InlineTextBox*);
    const InlineTextBox* nextTextBox(const RootInlineBox*, const InlineTextBox*);

    size_t size() const { return m_leafBoxes.size(); }
    const InlineBox* firstBox() const { return m_leafBoxes[0]; }

private:
    const Vector<InlineBox*>& collectBoxes(const RootInlineBox*);
    int boxIndexInLeaves(const InlineTextBox*) const;

    const RootInlineBox* m_rootInlineBox;
    Vector<InlineBox*> m_leafBoxes;
};

CachedLogicallyOrderedLeafBoxes::CachedLogicallyOrderedLeafBoxes() : m_rootInlineBox(0) { };

const InlineTextBox* CachedLogicallyOrderedLeafBoxes::previousTextBox(const RootInlineBox* root, const InlineTextBox* box)
{
    if (!root)
        return 0;

    collectBoxes(root);

    // If box is null, root is box's previous RootInlineBox, and previousBox is the last logical box in root.
    int boxIndex = m_leafBoxes.size() - 1;
    if (box)
        boxIndex = boxIndexInLeaves(box) - 1;

    for (int i = boxIndex; i >= 0; --i) {
        if (m_leafBoxes[i]->isInlineTextBox())
            return toInlineTextBox(m_leafBoxes[i]);
    }

    return 0;
}

const InlineTextBox* CachedLogicallyOrderedLeafBoxes::nextTextBox(const RootInlineBox* root, const InlineTextBox* box)
{
    if (!root)
        return 0;

    collectBoxes(root);

    // If box is null, root is box's next RootInlineBox, and nextBox is the first logical box in root.
    // Otherwise, root is box's RootInlineBox, and nextBox is the next logical box in the same line.
    size_t nextBoxIndex = 0;
    if (box)
        nextBoxIndex = boxIndexInLeaves(box) + 1;

    for (size_t i = nextBoxIndex; i < m_leafBoxes.size(); ++i) {
        if (m_leafBoxes[i]->isInlineTextBox())
            return toInlineTextBox(m_leafBoxes[i]);
    }

    return 0;
}

const Vector<InlineBox*>& CachedLogicallyOrderedLeafBoxes::collectBoxes(const RootInlineBox* root)
{
    if (m_rootInlineBox != root) {
        m_rootInlineBox = root;
        m_leafBoxes.clear();
        root->collectLeafBoxesInLogicalOrder(m_leafBoxes);
    }
    return m_leafBoxes;
}

int CachedLogicallyOrderedLeafBoxes::boxIndexInLeaves(const InlineTextBox* box) const
{
    for (size_t i = 0; i < m_leafBoxes.size(); ++i) {
        if (box == m_leafBoxes[i])
            return i;
    }
    return 0;
}

static const InlineTextBox* logicallyPreviousBox(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
    bool& previousBoxInDifferentBlock, CachedLogicallyOrderedLeafBoxes& leafBoxes)
{
    const InlineBox* startBox = textBox;

    const InlineTextBox* previousBox = leafBoxes.previousTextBox(&startBox->root(), textBox);
    if (previousBox)
        return previousBox;

    previousBox = leafBoxes.previousTextBox(startBox->root().prevRootBox(), 0);
    if (previousBox)
        return previousBox;

    while (1) {
        Node* startNode = startBox->layoutObject().nonPseudoNode();
        if (!startNode)
            break;

        Position position = previousRootInlineBoxCandidatePosition(startNode, visiblePosition, ContentIsEditable);
        if (position.isNull())
            break;

        RenderedPosition renderedPosition(position, DOWNSTREAM);
        RootInlineBox* previousRoot = renderedPosition.rootBox();
        if (!previousRoot)
            break;

        previousBox = leafBoxes.previousTextBox(previousRoot, 0);
        if (previousBox) {
            previousBoxInDifferentBlock = true;
            return previousBox;
        }

        if (!leafBoxes.size())
            break;
        startBox = leafBoxes.firstBox();
    }
    return 0;
}

static const InlineTextBox* logicallyNextBox(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
    bool& nextBoxInDifferentBlock, CachedLogicallyOrderedLeafBoxes& leafBoxes)
{
    const InlineBox* startBox = textBox;

    const InlineTextBox* nextBox = leafBoxes.nextTextBox(&startBox->root(), textBox);
    if (nextBox)
        return nextBox;

    nextBox = leafBoxes.nextTextBox(startBox->root().nextRootBox(), 0);
    if (nextBox)
        return nextBox;

    while (1) {
        Node* startNode =startBox->layoutObject().nonPseudoNode();
        if (!startNode)
            break;

        Position position = nextRootInlineBoxCandidatePosition(startNode, visiblePosition, ContentIsEditable);
        if (position.isNull())
            break;

        RenderedPosition renderedPosition(position, DOWNSTREAM);
        RootInlineBox* nextRoot = renderedPosition.rootBox();
        if (!nextRoot)
            break;

        nextBox = leafBoxes.nextTextBox(nextRoot, 0);
        if (nextBox) {
            nextBoxInDifferentBlock = true;
            return nextBox;
        }

        if (!leafBoxes.size())
            break;
        startBox = leafBoxes.firstBox();
    }
    return 0;
}

static TextBreakIterator* wordBreakIteratorForMinOffsetBoundary(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
    int& previousBoxLength, bool& previousBoxInDifferentBlock, Vector<UChar, 1024>& string, CachedLogicallyOrderedLeafBoxes& leafBoxes)
{
    previousBoxInDifferentBlock = false;

    // FIXME: Handle the case when we don't have an inline text box.
    const InlineTextBox* previousBox = logicallyPreviousBox(visiblePosition, textBox, previousBoxInDifferentBlock, leafBoxes);

    int len = 0;
    string.clear();
    if (previousBox) {
        previousBoxLength = previousBox->len();
        previousBox->layoutObject().text().appendTo(string, previousBox->start(), previousBoxLength);
        len += previousBoxLength;
    }
    textBox->layoutObject().text().appendTo(string, textBox->start(), textBox->len());
    len += textBox->len();

    return wordBreakIterator(string.data(), len);
}

static TextBreakIterator* wordBreakIteratorForMaxOffsetBoundary(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
    bool& nextBoxInDifferentBlock, Vector<UChar, 1024>& string, CachedLogicallyOrderedLeafBoxes& leafBoxes)
{
    nextBoxInDifferentBlock = false;

    // FIXME: Handle the case when we don't have an inline text box.
    const InlineTextBox* nextBox = logicallyNextBox(visiblePosition, textBox, nextBoxInDifferentBlock, leafBoxes);

    int len = 0;
    string.clear();
    textBox->layoutObject().text().appendTo(string, textBox->start(), textBox->len());
    len += textBox->len();
    if (nextBox) {
        nextBox->layoutObject().text().appendTo(string, nextBox->start(), nextBox->len());
        len += nextBox->len();
    }

    return wordBreakIterator(string.data(), len);
}

static bool isLogicalStartOfWord(TextBreakIterator* iter, int position, bool hardLineBreak)
{
    bool boundary = hardLineBreak ? true : iter->isBoundary(position);
    if (!boundary)
        return false;

    iter->following(position);
    // isWordTextBreak returns true after moving across a word and false after moving across a punctuation/space.
    return isWordTextBreak(iter);
}

static bool islogicalEndOfWord(TextBreakIterator* iter, int position, bool hardLineBreak)
{
    bool boundary = iter->isBoundary(position);
    return (hardLineBreak || boundary) && isWordTextBreak(iter);
}

enum CursorMovementDirection { MoveLeft, MoveRight };

static VisiblePosition visualWordPosition(const VisiblePosition& visiblePosition, CursorMovementDirection direction,
    bool skipsSpaceWhenMovingRight)
{
    if (visiblePosition.isNull())
        return VisiblePosition();

    TextDirection blockDirection = directionOfEnclosingBlock(visiblePosition.deepEquivalent());
    InlineBox* previouslyVisitedBox = 0;
    VisiblePosition current = visiblePosition;
    TextBreakIterator* iter = 0;

    CachedLogicallyOrderedLeafBoxes leafBoxes;
    Vector<UChar, 1024> string;

    while (1) {
        VisiblePosition adjacentCharacterPosition = direction == MoveRight ? current.right(true) : current.left(true);
        if (adjacentCharacterPosition == current || adjacentCharacterPosition.isNull())
            return VisiblePosition();

        InlineBox* box;
        int offsetInBox;
        adjacentCharacterPosition.deepEquivalent().getInlineBoxAndOffset(UPSTREAM, box, offsetInBox);

        if (!box)
            break;
        if (!box->isInlineTextBox()) {
            current = adjacentCharacterPosition;
            continue;
        }

        InlineTextBox* textBox = toInlineTextBox(box);
        int previousBoxLength = 0;
        bool previousBoxInDifferentBlock = false;
        bool nextBoxInDifferentBlock = false;
        bool movingIntoNewBox = previouslyVisitedBox != box;

        if (offsetInBox == box->caretMinOffset())
            iter = wordBreakIteratorForMinOffsetBoundary(visiblePosition, textBox, previousBoxLength, previousBoxInDifferentBlock, string, leafBoxes);
        else if (offsetInBox == box->caretMaxOffset())
            iter = wordBreakIteratorForMaxOffsetBoundary(visiblePosition, textBox, nextBoxInDifferentBlock, string, leafBoxes);
        else if (movingIntoNewBox) {
            iter = wordBreakIterator(textBox->layoutObject().text(), textBox->start(), textBox->len());
            previouslyVisitedBox = box;
        }

        if (!iter)
            break;

        iter->first();
        int offsetInIterator = offsetInBox - textBox->start() + previousBoxLength;

        bool isWordBreak;
        bool boxHasSameDirectionalityAsBlock = box->direction() == blockDirection;
        bool movingBackward = (direction == MoveLeft && box->direction() == LTR) || (direction == MoveRight && box->direction() == RTL);
        if ((skipsSpaceWhenMovingRight && boxHasSameDirectionalityAsBlock)
            || (!skipsSpaceWhenMovingRight && movingBackward)) {
            bool logicalStartInRenderer = offsetInBox == static_cast<int>(textBox->start()) && previousBoxInDifferentBlock;
            isWordBreak = isLogicalStartOfWord(iter, offsetInIterator, logicalStartInRenderer);
        } else {
            bool logicalEndInRenderer = offsetInBox == static_cast<int>(textBox->start() + textBox->len()) && nextBoxInDifferentBlock;
            isWordBreak = islogicalEndOfWord(iter, offsetInIterator, logicalEndInRenderer);
        }

        if (isWordBreak)
            return adjacentCharacterPosition;

        current = adjacentCharacterPosition;
    }
    return VisiblePosition();
}

VisiblePosition leftWordPosition(const VisiblePosition& visiblePosition, bool skipsSpaceWhenMovingRight)
{
    VisiblePosition leftWordBreak = visualWordPosition(visiblePosition, MoveLeft, skipsSpaceWhenMovingRight);
    leftWordBreak = visiblePosition.honorEditingBoundaryAtOrBefore(leftWordBreak);

    // FIXME: How should we handle a non-editable position?
    if (leftWordBreak.isNull() && isEditablePosition(visiblePosition.deepEquivalent())) {
        TextDirection blockDirection = directionOfEnclosingBlock(visiblePosition.deepEquivalent());
        leftWordBreak = blockDirection == LTR ? startOfEditableContent(visiblePosition) : endOfEditableContent(visiblePosition);
    }
    return leftWordBreak;
}

VisiblePosition rightWordPosition(const VisiblePosition& visiblePosition, bool skipsSpaceWhenMovingRight)
{
    VisiblePosition rightWordBreak = visualWordPosition(visiblePosition, MoveRight, skipsSpaceWhenMovingRight);
    rightWordBreak = visiblePosition.honorEditingBoundaryAtOrBefore(rightWordBreak);

    // FIXME: How should we handle a non-editable position?
    if (rightWordBreak.isNull() && isEditablePosition(visiblePosition.deepEquivalent())) {
        TextDirection blockDirection = directionOfEnclosingBlock(visiblePosition.deepEquivalent());
        rightWordBreak = blockDirection == LTR ? endOfEditableContent(visiblePosition) : startOfEditableContent(visiblePosition);
    }
    return rightWordBreak;
}

enum BoundarySearchContextAvailability { DontHaveMoreContext, MayHaveMoreContext };

typedef unsigned (*BoundarySearchFunction)(const UChar*, unsigned length, unsigned offset, BoundarySearchContextAvailability, bool& needMoreContext);

static VisiblePosition previousBoundary(const VisiblePosition& c, BoundarySearchFunction searchFunction)
{
    Position pos = c.deepEquivalent();
    Node* boundary = pos.parentEditingBoundary();
    if (!boundary)
        return VisiblePosition();

    Document& d = boundary->document();
    Position start = createLegacyEditingPosition(boundary, 0).parentAnchoredEquivalent();
    Position end = pos.parentAnchoredEquivalent();

    Vector<UChar, 1024> string;
    unsigned suffixLength = 0;

    TrackExceptionState exceptionState;
    if (requiresContextForWordBoundary(c.characterBefore())) {
        RefPtrWillBeRawPtr<Range> forwardsScanRange(d.createRange());
        forwardsScanRange->setEndAfter(boundary, exceptionState);
        forwardsScanRange->setStart(end.deprecatedNode(), end.deprecatedEditingOffset(), exceptionState);
        TextIterator forwardsIterator(forwardsScanRange->startPosition(), forwardsScanRange->endPosition());
        while (!forwardsIterator.atEnd()) {
            Vector<UChar, 1024> characters;
            forwardsIterator.appendTextTo(characters);
            int i = endOfFirstWordBoundaryContext(characters.data(), characters.size());
            string.append(characters.data(), i);
            suffixLength += i;
            if (static_cast<unsigned>(i) < characters.size())
                break;
            forwardsIterator.advance();
        }
    }

    ASSERT(!exceptionState.hadException());
    if (exceptionState.hadException())
        return VisiblePosition();

    SimplifiedBackwardsTextIterator it(start, end);
    unsigned next = 0;
    bool needMoreContext = false;
    while (!it.atEnd()) {
        bool inTextSecurityMode = it.node() && it.node()->layoutObject() && it.node()->layoutObject()->style()->textSecurity() != TSNONE;
        // iterate to get chunks until the searchFunction returns a non-zero value.
        if (!inTextSecurityMode)
            it.prependTextTo(string);
        else {
            // Treat bullets used in the text security mode as regular characters when looking for boundaries
            Vector<UChar, 1024> iteratorString;
            iteratorString.fill('x', it.length());
            string.prepend(iteratorString.data(), iteratorString.size());
        }
        next = searchFunction(string.data(), string.size(), string.size() - suffixLength, MayHaveMoreContext, needMoreContext);
        if (next)
            break;
        it.advance();
    }
    if (needMoreContext) {
        // The last search returned the beginning of the buffer and asked for more context,
        // but there is no earlier text. Force a search with what's available.
        next = searchFunction(string.data(), string.size(), string.size() - suffixLength, DontHaveMoreContext, needMoreContext);
        ASSERT(!needMoreContext);
    }

    if (!next)
        return VisiblePosition(it.atEnd() ? it.startPosition() : pos, DOWNSTREAM);

    Node* node = it.startContainer();
    if ((node->isTextNode() && static_cast<int>(next) <= node->maxCharacterOffset()) || (node->layoutObject() && node->layoutObject()->isBR() && !next))
        // The next variable contains a usable index into a text node
        return VisiblePosition(createLegacyEditingPosition(node, next), DOWNSTREAM);

    // Use the character iterator to translate the next value into a DOM position.
    BackwardsCharacterIterator charIt(start, end);
    charIt.advance(string.size() - suffixLength - next);
    // FIXME: charIt can get out of shadow host.
    return VisiblePosition(charIt.endPosition(), DOWNSTREAM);
}

static VisiblePosition nextBoundary(const VisiblePosition& c, BoundarySearchFunction searchFunction)
{
    Position pos = c.deepEquivalent();
    Node* boundary = pos.parentEditingBoundary();
    if (!boundary)
        return VisiblePosition();

    Document& d = boundary->document();
    Position start(pos.parentAnchoredEquivalent());

    Vector<UChar, 1024> string;
    unsigned prefixLength = 0;

    if (requiresContextForWordBoundary(c.characterAfter())) {
        RefPtrWillBeRawPtr<Range> backwardsScanRange(d.createRange());
        backwardsScanRange->setEnd(start.deprecatedNode(), start.deprecatedEditingOffset(), IGNORE_EXCEPTION);
        SimplifiedBackwardsTextIterator backwardsIterator(backwardsScanRange.get());
        while (!backwardsIterator.atEnd()) {
            Vector<UChar, 1024> characters;
            backwardsIterator.prependTextTo(characters);
            int length = characters.size();
            int i = startOfLastWordBoundaryContext(characters.data(), length);
            string.prepend(characters.data() + i, length - i);
            prefixLength += length - i;
            if (i > 0)
                break;
            backwardsIterator.advance();
        }
    }

    Position searchStart = createLegacyEditingPosition(start.deprecatedNode(), start.deprecatedEditingOffset());
    RangeBoundaryPoint searchEndPoint(boundary);
    searchEndPoint.setToEndOfNode(*boundary);
    Position searchEnd = searchEndPoint.toPosition();
    TextIterator it(searchStart, searchEnd, TextIteratorEmitsCharactersBetweenAllVisiblePositions);
    const unsigned invalidOffset = static_cast<unsigned>(-1);
    unsigned next = invalidOffset;
    bool needMoreContext = false;
    while (!it.atEnd()) {
        // Keep asking the iterator for chunks until the search function
        // returns an end value not equal to the length of the string passed to it.
        bool inTextSecurityMode = it.node() && it.node()->layoutObject() && it.node()->layoutObject()->style()->textSecurity() != TSNONE;
        if (!inTextSecurityMode)
            it.appendTextTo(string);
        else {
            // Treat bullets used in the text security mode as regular characters when looking for boundaries
            Vector<UChar, 1024> iteratorString;
            iteratorString.fill('x', it.length());
            string.append(iteratorString.data(), iteratorString.size());
        }
        next = searchFunction(string.data(), string.size(), prefixLength, MayHaveMoreContext, needMoreContext);
        if (next != string.size())
            break;
        it.advance();
    }
    if (needMoreContext) {
        // The last search returned the end of the buffer and asked for more context,
        // but there is no further text. Force a search with what's available.
        next = searchFunction(string.data(), string.size(), prefixLength, DontHaveMoreContext, needMoreContext);
        ASSERT(!needMoreContext);
    }

    if (it.atEnd() && next == string.size()) {
        pos = it.startPositionInCurrentContainer();
    } else if (next != invalidOffset && next != prefixLength) {
        // Use the character iterator to translate the next value into a DOM position.
        CharacterIterator charIt(searchStart, searchEnd, TextIteratorEmitsCharactersBetweenAllVisiblePositions);
        charIt.advance(next - prefixLength - 1);
        pos = charIt.endPosition();

        if (charIt.characterAt(0) == '\n') {
            // FIXME: workaround for collapsed range (where only start position is correct) emitted for some emitted newlines (see rdar://5192593)
            VisiblePosition visPos = VisiblePosition(pos);
            if (visPos == VisiblePosition(charIt.startPosition())) {
                charIt.advance(1);
                pos = charIt.startPosition();
            }
        }
    }

    // generate VisiblePosition, use UPSTREAM affinity if possible
    return VisiblePosition(pos, VP_UPSTREAM_IF_POSSIBLE);
}

// ---------

static unsigned startWordBoundary(const UChar* characters, unsigned length, unsigned offset, BoundarySearchContextAvailability mayHaveMoreContext, bool& needMoreContext)
{
    ASSERT(offset);
    if (mayHaveMoreContext && !startOfLastWordBoundaryContext(characters, offset)) {
        needMoreContext = true;
        return 0;
    }
    needMoreContext = false;
    int start, end;
    U16_BACK_1(characters, 0, offset);
    findWordBoundary(characters, length, offset, &start, &end);
    return start;
}

VisiblePosition startOfWord(const VisiblePosition &c, EWordSide side)
{
    // FIXME: This returns a null VP for c at the start of the document
    // and side == LeftWordIfOnBoundary
    VisiblePosition p = c;
    if (side == RightWordIfOnBoundary) {
        // at paragraph end, the startofWord is the current position
        if (isEndOfParagraph(c))
            return c;

        p = c.next();
        if (p.isNull())
            return c;
    }
    return previousBoundary(p, startWordBoundary);
}

static unsigned endWordBoundary(const UChar* characters, unsigned length, unsigned offset, BoundarySearchContextAvailability mayHaveMoreContext, bool& needMoreContext)
{
    ASSERT(offset <= length);
    if (mayHaveMoreContext && endOfFirstWordBoundaryContext(characters + offset, length - offset) == static_cast<int>(length - offset)) {
        needMoreContext = true;
        return length;
    }
    needMoreContext = false;
    return findWordEndBoundary(characters, length, offset);
}

VisiblePosition endOfWord(const VisiblePosition &c, EWordSide side)
{
    VisiblePosition p = c;
    if (side == LeftWordIfOnBoundary) {
        if (isStartOfParagraph(c))
            return c;

        p = c.previous();
        if (p.isNull())
            return c;
    } else if (isEndOfParagraph(c))
        return c;

    return nextBoundary(p, endWordBoundary);
}

static unsigned previousWordPositionBoundary(const UChar* characters, unsigned length, unsigned offset, BoundarySearchContextAvailability mayHaveMoreContext, bool& needMoreContext)
{
    if (mayHaveMoreContext && !startOfLastWordBoundaryContext(characters, offset)) {
        needMoreContext = true;
        return 0;
    }
    needMoreContext = false;
    return findNextWordFromIndex(characters, length, offset, false);
}

VisiblePosition previousWordPosition(const VisiblePosition &c)
{
    VisiblePosition prev = previousBoundary(c, previousWordPositionBoundary);
    return c.honorEditingBoundaryAtOrBefore(prev);
}

static unsigned nextWordPositionBoundary(const UChar* characters, unsigned length, unsigned offset, BoundarySearchContextAvailability mayHaveMoreContext, bool& needMoreContext)
{
    if (mayHaveMoreContext && endOfFirstWordBoundaryContext(characters + offset, length - offset) == static_cast<int>(length - offset)) {
        needMoreContext = true;
        return length;
    }
    needMoreContext = false;
    return findNextWordFromIndex(characters, length, offset, true);
}

VisiblePosition nextWordPosition(const VisiblePosition &c)
{
    VisiblePosition next = nextBoundary(c, nextWordPositionBoundary);
    return c.honorEditingBoundaryAtOrAfter(next);
}

// ---------

enum LineEndpointComputationMode { UseLogicalOrdering, UseInlineBoxOrdering };
static VisiblePosition startPositionForLine(const VisiblePosition& c, LineEndpointComputationMode mode)
{
    if (c.isNull())
        return VisiblePosition();

    RootInlineBox* rootBox = RenderedPosition(c).rootBox();
    if (!rootBox) {
        // There are VisiblePositions at offset 0 in blocks without
        // RootInlineBoxes, like empty editable blocks and bordered blocks.
        Position p = c.deepEquivalent();
        if (p.deprecatedNode()->layoutObject() && p.deprecatedNode()->layoutObject()->isLayoutBlock() && !p.deprecatedEditingOffset())
            return c;

        return VisiblePosition();
    }

    Node* startNode;
    InlineBox* startBox;
    if (mode == UseLogicalOrdering) {
        startNode = rootBox->getLogicalStartBoxWithNode(startBox);
        if (!startNode)
            return VisiblePosition();
    } else {
        // Generated content (e.g. list markers and CSS :before and :after pseudoelements) have no corresponding DOM element,
        // and so cannot be represented by a VisiblePosition. Use whatever follows instead.
        startBox = rootBox->firstLeafChild();
        while (true) {
            if (!startBox)
                return VisiblePosition();

            startNode = startBox->layoutObject().nonPseudoNode();
            if (startNode)
                break;

            startBox = startBox->nextLeafChild();
        }
    }

    return VisiblePosition(startNode->isTextNode() ? Position(toText(startNode), toInlineTextBox(startBox)->start()) : positionBeforeNode(startNode));
}

static VisiblePosition startOfLine(const VisiblePosition& c, LineEndpointComputationMode mode)
{
    // TODO: this is the current behavior that might need to be fixed.
    // Please refer to https://bugs.webkit.org/show_bug.cgi?id=49107 for detail.
    VisiblePosition visPos = startPositionForLine(c, mode);

    if (mode == UseLogicalOrdering) {
        if (ContainerNode* editableRoot = highestEditableRoot(c.deepEquivalent())) {
            if (!editableRoot->contains(visPos.deepEquivalent().containerNode()))
                return VisiblePosition(firstPositionInNode(editableRoot));
        }
    }

    return c.honorEditingBoundaryAtOrBefore(visPos);
}

// FIXME: Rename this function to reflect the fact it ignores bidi levels.
VisiblePosition startOfLine(const VisiblePosition& currentPosition)
{
    return startOfLine(currentPosition, UseInlineBoxOrdering);
}

VisiblePosition logicalStartOfLine(const VisiblePosition& currentPosition)
{
    return startOfLine(currentPosition, UseLogicalOrdering);
}

static VisiblePosition endPositionForLine(const VisiblePosition& c, LineEndpointComputationMode mode)
{
    if (c.isNull())
        return VisiblePosition();

    RootInlineBox* rootBox = RenderedPosition(c).rootBox();
    if (!rootBox) {
        // There are VisiblePositions at offset 0 in blocks without
        // RootInlineBoxes, like empty editable blocks and bordered blocks.
        Position p = c.deepEquivalent();
        if (p.deprecatedNode()->layoutObject() && p.deprecatedNode()->layoutObject()->isLayoutBlock() && !p.deprecatedEditingOffset())
            return c;
        return VisiblePosition();
    }

    Node* endNode;
    InlineBox* endBox;
    if (mode == UseLogicalOrdering) {
        endNode = rootBox->getLogicalEndBoxWithNode(endBox);
        if (!endNode)
            return VisiblePosition();
    } else {
        // Generated content (e.g. list markers and CSS :before and :after pseudoelements) have no corresponding DOM element,
        // and so cannot be represented by a VisiblePosition. Use whatever precedes instead.
        endBox = rootBox->lastLeafChild();
        while (true) {
            if (!endBox)
                return VisiblePosition();

            endNode = endBox->layoutObject().nonPseudoNode();
            if (endNode)
                break;

            endBox = endBox->prevLeafChild();
        }
    }

    Position pos;
    if (isHTMLBRElement(*endNode))
        pos = positionBeforeNode(endNode);
    else if (endBox->isInlineTextBox() && endNode->isTextNode()) {
        InlineTextBox* endTextBox = toInlineTextBox(endBox);
        int endOffset = endTextBox->start();
        if (!endTextBox->isLineBreak())
            endOffset += endTextBox->len();
        pos = Position(toText(endNode), endOffset);
    } else
        pos = positionAfterNode(endNode);

    return VisiblePosition(pos, VP_UPSTREAM_IF_POSSIBLE);
}

static bool inSameLogicalLine(const VisiblePosition& a, const VisiblePosition& b)
{
    return a.isNotNull() && logicalStartOfLine(a) == logicalStartOfLine(b);
}

static VisiblePosition endOfLine(const VisiblePosition& c, LineEndpointComputationMode mode)
{
    // TODO: this is the current behavior that might need to be fixed.
    // Please refer to https://bugs.webkit.org/show_bug.cgi?id=49107 for detail.
    VisiblePosition visPos = endPositionForLine(c, mode);

    if (mode == UseLogicalOrdering) {
        // Make sure the end of line is at the same line as the given input position. For a wrapping line, the logical end
        // position for the not-last-2-lines might incorrectly hand back the logical beginning of the next line.
        // For example, <div contenteditable dir="rtl" style="line-break:before-white-space">abcdefg abcdefg abcdefg
        // a abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg </div>
        // In this case, use the previous position of the computed logical end position.
        if (!inSameLogicalLine(c, visPos))
            visPos = visPos.previous();

        if (ContainerNode* editableRoot = highestEditableRoot(c.deepEquivalent())) {
            if (!editableRoot->contains(visPos.deepEquivalent().containerNode()))
                return VisiblePosition(lastPositionInNode(editableRoot));
        }

        return c.honorEditingBoundaryAtOrAfter(visPos);
    }

    // Make sure the end of line is at the same line as the given input position. Else use the previous position to
    // obtain end of line. This condition happens when the input position is before the space character at the end
    // of a soft-wrapped non-editable line. In this scenario, endPositionForLine would incorrectly hand back a position
    // in the next line instead. This fix is to account for the discrepancy between lines with webkit-line-break:after-white-space style
    // versus lines without that style, which would break before a space by default.
    if (!inSameLine(c, visPos)) {
        visPos = c.previous();
        if (visPos.isNull())
            return VisiblePosition();
        visPos = endPositionForLine(visPos, UseInlineBoxOrdering);
    }

    return c.honorEditingBoundaryAtOrAfter(visPos);
}

// FIXME: Rename this function to reflect the fact it ignores bidi levels.
VisiblePosition endOfLine(const VisiblePosition& currentPosition)
{
    return endOfLine(currentPosition, UseInlineBoxOrdering);
}

VisiblePosition logicalEndOfLine(const VisiblePosition& currentPosition)
{
    return endOfLine(currentPosition, UseLogicalOrdering);
}

bool inSameLine(const VisiblePosition &a, const VisiblePosition &b)
{
    return a.isNotNull() && startOfLine(a) == startOfLine(b);
}

bool isStartOfLine(const VisiblePosition &p)
{
    return p.isNotNull() && p == startOfLine(p);
}

bool isEndOfLine(const VisiblePosition &p)
{
    return p.isNotNull() && p == endOfLine(p);
}

bool isLogicalEndOfLine(const VisiblePosition &p)
{
    return p.isNotNull() && p == logicalEndOfLine(p);
}

static inline LayoutPoint absoluteLineDirectionPointToLocalPointInBlock(RootInlineBox* root, LayoutUnit lineDirectionPoint)
{
    ASSERT(root);
    LayoutBlockFlow& containingBlock = root->block();
    FloatPoint absoluteBlockPoint = containingBlock.localToAbsolute(FloatPoint());
    if (containingBlock.hasOverflowClip())
        absoluteBlockPoint -= containingBlock.scrolledContentOffset();

    if (root->block().isHorizontalWritingMode())
        return LayoutPoint(lineDirectionPoint - absoluteBlockPoint.x(), root->blockDirectionPointInLine());

    return LayoutPoint(root->blockDirectionPointInLine(), lineDirectionPoint - absoluteBlockPoint.y());
}

VisiblePosition previousLinePosition(const VisiblePosition &visiblePosition, LayoutUnit lineDirectionPoint, EditableType editableType)
{
    Position p = visiblePosition.deepEquivalent();
    Node* node = p.deprecatedNode();

    if (!node)
        return VisiblePosition();

    node->document().updateLayoutIgnorePendingStylesheets();

    LayoutObject* renderer = node->layoutObject();
    if (!renderer)
        return VisiblePosition();

    RootInlineBox* root = 0;
    InlineBox* box;
    int ignoredCaretOffset;
    visiblePosition.getInlineBoxAndOffset(box, ignoredCaretOffset);
    if (box) {
        root = box->root().prevRootBox();
        // We want to skip zero height boxes.
        // This could happen in case it is a TrailingFloatsRootInlineBox.
        if (!root || !root->logicalHeight() || !root->firstLeafChild())
            root = 0;
    }

    if (!root) {
        Position position = previousRootInlineBoxCandidatePosition(node, visiblePosition, editableType);
        if (position.isNotNull()) {
            RenderedPosition renderedPosition((VisiblePosition(position)));
            root = renderedPosition.rootBox();
            if (!root)
                return VisiblePosition(position);
        }
    }

    if (root) {
        // FIXME: Can be wrong for multi-column layout and with transforms.
        LayoutPoint pointInLine = absoluteLineDirectionPointToLocalPointInBlock(root, lineDirectionPoint);
        LayoutObject& renderer = root->closestLeafChildForPoint(pointInLine, isEditablePosition(p))->layoutObject();
        Node* node = renderer.node();
        if (node && editingIgnoresContent(node))
            return VisiblePosition(positionInParentBeforeNode(*node));
        return VisiblePosition(renderer.positionForPoint(pointInLine));
    }

    // Could not find a previous line. This means we must already be on the first line.
    // Move to the start of the content in this block, which effectively moves us
    // to the start of the line we're on.
    Element* rootElement = node->hasEditableStyle(editableType) ? node->rootEditableElement(editableType) : node->document().documentElement();
    if (!rootElement)
        return VisiblePosition();
    return VisiblePosition(firstPositionInNode(rootElement), DOWNSTREAM);
}

VisiblePosition nextLinePosition(const VisiblePosition &visiblePosition, LayoutUnit lineDirectionPoint, EditableType editableType)
{
    Position p = visiblePosition.deepEquivalent();
    Node* node = p.deprecatedNode();

    if (!node)
        return VisiblePosition();

    node->document().updateLayoutIgnorePendingStylesheets();

    LayoutObject* renderer = node->layoutObject();
    if (!renderer)
        return VisiblePosition();

    RootInlineBox* root = 0;
    InlineBox* box;
    int ignoredCaretOffset;
    visiblePosition.getInlineBoxAndOffset(box, ignoredCaretOffset);
    if (box) {
        root = box->root().nextRootBox();
        // We want to skip zero height boxes.
        // This could happen in case it is a TrailingFloatsRootInlineBox.
        if (!root || !root->logicalHeight() || !root->firstLeafChild())
            root = 0;
    }

    if (!root) {
        // FIXME: We need do the same in previousLinePosition.
        Node* child = NodeTraversal::childAt(*node, p.deprecatedEditingOffset());
        node = child ? child : &NodeTraversal::lastWithinOrSelf(*node);
        Position position = nextRootInlineBoxCandidatePosition(node, visiblePosition, editableType);
        if (position.isNotNull()) {
            RenderedPosition renderedPosition((VisiblePosition(position)));
            root = renderedPosition.rootBox();
            if (!root)
                return VisiblePosition(position);
        }
    }

    if (root) {
        // FIXME: Can be wrong for multi-column layout and with transforms.
        LayoutPoint pointInLine = absoluteLineDirectionPointToLocalPointInBlock(root, lineDirectionPoint);
        LayoutObject& renderer = root->closestLeafChildForPoint(pointInLine, isEditablePosition(p))->layoutObject();
        Node* node = renderer.node();
        if (node && editingIgnoresContent(node))
            return VisiblePosition(positionInParentBeforeNode(*node));
        return VisiblePosition(renderer.positionForPoint(pointInLine));
    }

    // Could not find a next line. This means we must already be on the last line.
    // Move to the end of the content in this block, which effectively moves us
    // to the end of the line we're on.
    Element* rootElement = node->hasEditableStyle(editableType) ? node->rootEditableElement(editableType) : node->document().documentElement();
    if (!rootElement)
        return VisiblePosition();
    return VisiblePosition(lastPositionInNode(rootElement), DOWNSTREAM);
}

// ---------

static unsigned startSentenceBoundary(const UChar* characters, unsigned length, unsigned, BoundarySearchContextAvailability, bool&)
{
    TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
    // FIXME: The following function can return -1; we don't handle that.
    return iterator->preceding(length);
}

VisiblePosition startOfSentence(const VisiblePosition &c)
{
    return previousBoundary(c, startSentenceBoundary);
}

static unsigned endSentenceBoundary(const UChar* characters, unsigned length, unsigned, BoundarySearchContextAvailability, bool&)
{
    TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
    return iterator->next();
}

// FIXME: This includes the space after the punctuation that marks the end of the sentence.
VisiblePosition endOfSentence(const VisiblePosition &c)
{
    return nextBoundary(c, endSentenceBoundary);
}

static unsigned previousSentencePositionBoundary(const UChar* characters, unsigned length, unsigned, BoundarySearchContextAvailability, bool&)
{
    // FIXME: This is identical to startSentenceBoundary. I'm pretty sure that's not right.
    TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
    // FIXME: The following function can return -1; we don't handle that.
    return iterator->preceding(length);
}

VisiblePosition previousSentencePosition(const VisiblePosition &c)
{
    VisiblePosition prev = previousBoundary(c, previousSentencePositionBoundary);
    return c.honorEditingBoundaryAtOrBefore(prev);
}

static unsigned nextSentencePositionBoundary(const UChar* characters, unsigned length, unsigned, BoundarySearchContextAvailability, bool&)
{
    // FIXME: This is identical to endSentenceBoundary. This isn't right, it needs to
    // move to the equivlant position in the following sentence.
    TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
    return iterator->following(0);
}

VisiblePosition nextSentencePosition(const VisiblePosition &c)
{
    VisiblePosition next = nextBoundary(c, nextSentencePositionBoundary);
    return c.honorEditingBoundaryAtOrAfter(next);
}

VisiblePosition startOfParagraph(const VisiblePosition& c, EditingBoundaryCrossingRule boundaryCrossingRule)
{
    Position p = c.deepEquivalent();
    Node* startNode = p.deprecatedNode();

    if (!startNode)
        return VisiblePosition();

    if (isRenderedAsNonInlineTableImageOrHR(startNode))
        return VisiblePosition(positionBeforeNode(startNode));

    Element* startBlock = enclosingBlock(startNode);

    Node* node = startNode;
    ContainerNode* highestRoot = highestEditableRoot(p);
    int offset = p.deprecatedEditingOffset();
    Position::AnchorType type = p.anchorType();

    Node* n = startNode;
    bool startNodeIsEditable = startNode->hasEditableStyle();
    while (n) {
        if (boundaryCrossingRule == CannotCrossEditingBoundary && !Position::nodeIsUserSelectAll(n) && n->hasEditableStyle() != startNodeIsEditable)
            break;
        if (boundaryCrossingRule == CanSkipOverEditingBoundary) {
            while (n && n->hasEditableStyle() != startNodeIsEditable)
                n = NodeTraversal::previousPostOrder(*n, startBlock);
            if (!n || !n->isDescendantOf(highestRoot))
                break;
        }
        LayoutObject* r = n->layoutObject();
        if (!r) {
            n = NodeTraversal::previousPostOrder(*n, startBlock);
            continue;
        }
        const ComputedStyle& style = r->styleRef();
        if (style.visibility() != VISIBLE) {
            n = NodeTraversal::previousPostOrder(*n, startBlock);
            continue;
        }

        if (r->isBR() || isBlock(n))
            break;

        if (r->isText() && toLayoutText(r)->renderedTextLength()) {
            ASSERT_WITH_SECURITY_IMPLICATION(n->isTextNode());
            type = Position::PositionIsOffsetInAnchor;
            if (style.preserveNewline()) {
                LayoutText* text = toLayoutText(r);
                int i = text->textLength();
                int o = offset;
                if (n == startNode && o < i)
                    i = max(0, o);
                while (--i >= 0) {
                    if ((*text)[i] == '\n')
                        return VisiblePosition(Position(toText(n), i + 1), DOWNSTREAM);
                }
            }
            node = n;
            offset = 0;
            n = NodeTraversal::previousPostOrder(*n, startBlock);
        } else if (editingIgnoresContent(n) || isRenderedTableElement(n)) {
            node = n;
            type = Position::PositionIsBeforeAnchor;
            n = n->previousSibling() ? n->previousSibling() : NodeTraversal::previousPostOrder(*n, startBlock);
        } else {
            n = NodeTraversal::previousPostOrder(*n, startBlock);
        }
    }

    if (type == Position::PositionIsOffsetInAnchor) {
        ASSERT(type == Position::PositionIsOffsetInAnchor || !offset);
        return VisiblePosition(Position(node, offset, type), DOWNSTREAM);
    }

    return VisiblePosition(Position(node, type), DOWNSTREAM);
}

VisiblePosition endOfParagraph(const VisiblePosition &c, EditingBoundaryCrossingRule boundaryCrossingRule)
{
    if (c.isNull())
        return VisiblePosition();

    Position p = c.deepEquivalent();
    Node* startNode = p.deprecatedNode();

    if (isRenderedAsNonInlineTableImageOrHR(startNode))
        return VisiblePosition(positionAfterNode(startNode));

    Element* startBlock = enclosingBlock(startNode);
    Element* stayInsideBlock = startBlock;

    Node* node = startNode;
    ContainerNode* highestRoot = highestEditableRoot(p);
    int offset = p.deprecatedEditingOffset();
    Position::AnchorType type = p.anchorType();

    Node* n = startNode;
    bool startNodeIsEditable = startNode->hasEditableStyle();
    while (n) {
        if (boundaryCrossingRule == CannotCrossEditingBoundary && !Position::nodeIsUserSelectAll(n) && n->hasEditableStyle() != startNodeIsEditable)
            break;
        if (boundaryCrossingRule == CanSkipOverEditingBoundary) {
            while (n && n->hasEditableStyle() != startNodeIsEditable)
                n = NodeTraversal::next(*n, stayInsideBlock);
            if (!n || !n->isDescendantOf(highestRoot))
                break;
        }

        LayoutObject* r = n->layoutObject();
        if (!r) {
            n = NodeTraversal::next(*n, stayInsideBlock);
            continue;
        }
        const ComputedStyle& style = r->styleRef();
        if (style.visibility() != VISIBLE) {
            n = NodeTraversal::next(*n, stayInsideBlock);
            continue;
        }

        if (r->isBR() || isBlock(n))
            break;

        // FIXME: We avoid returning a position where the renderer can't accept the caret.
        if (r->isText() && toLayoutText(r)->renderedTextLength()) {
            ASSERT_WITH_SECURITY_IMPLICATION(n->isTextNode());
            int length = toLayoutText(r)->textLength();
            type = Position::PositionIsOffsetInAnchor;
            if (style.preserveNewline()) {
                LayoutText* text = toLayoutText(r);
                int o = n == startNode ? offset : 0;
                for (int i = o; i < length; ++i) {
                    if ((*text)[i] == '\n')
                        return VisiblePosition(Position(toText(n), i), DOWNSTREAM);
                }
            }
            node = n;
            offset = r->caretMaxOffset();
            n = NodeTraversal::next(*n, stayInsideBlock);
        } else if (editingIgnoresContent(n) || isRenderedTableElement(n)) {
            node = n;
            type = Position::PositionIsAfterAnchor;
            n = NodeTraversal::nextSkippingChildren(*n, stayInsideBlock);
        } else {
            n = NodeTraversal::next(*n, stayInsideBlock);
        }
    }

    if (type == Position::PositionIsOffsetInAnchor)
        return VisiblePosition(Position(node, offset, type), DOWNSTREAM);

    return VisiblePosition(Position(node, type), DOWNSTREAM);
}

// FIXME: isStartOfParagraph(startOfNextParagraph(pos)) is not always true
VisiblePosition startOfNextParagraph(const VisiblePosition& visiblePosition)
{
    VisiblePosition paragraphEnd(endOfParagraph(visiblePosition, CanSkipOverEditingBoundary));
    VisiblePosition afterParagraphEnd(paragraphEnd.next(CannotCrossEditingBoundary));
    // The position after the last position in the last cell of a table
    // is not the start of the next paragraph.
    if (isFirstPositionAfterTable(afterParagraphEnd))
        return afterParagraphEnd.next(CannotCrossEditingBoundary);
    return afterParagraphEnd;
}

bool inSameParagraph(const VisiblePosition &a, const VisiblePosition &b, EditingBoundaryCrossingRule boundaryCrossingRule)
{
    return a.isNotNull() && startOfParagraph(a, boundaryCrossingRule) == startOfParagraph(b, boundaryCrossingRule);
}

bool isStartOfParagraph(const VisiblePosition &pos, EditingBoundaryCrossingRule boundaryCrossingRule)
{
    return pos.isNotNull() && pos == startOfParagraph(pos, boundaryCrossingRule);
}

bool isEndOfParagraph(const VisiblePosition &pos, EditingBoundaryCrossingRule boundaryCrossingRule)
{
    return pos.isNotNull() && pos == endOfParagraph(pos, boundaryCrossingRule);
}

VisiblePosition previousParagraphPosition(const VisiblePosition& p, LayoutUnit x)
{
    VisiblePosition pos = p;
    do {
        VisiblePosition n = previousLinePosition(pos, x);
        if (n.isNull() || n == pos)
            break;
        pos = n;
    } while (inSameParagraph(p, pos));
    return pos;
}

VisiblePosition nextParagraphPosition(const VisiblePosition& p, LayoutUnit x)
{
    VisiblePosition pos = p;
    do {
        VisiblePosition n = nextLinePosition(pos, x);
        if (n.isNull() || n == pos)
            break;
        pos = n;
    } while (inSameParagraph(p, pos));
    return pos;
}

// ---------

VisiblePosition startOfBlock(const VisiblePosition& visiblePosition, EditingBoundaryCrossingRule rule)
{
    Position position = visiblePosition.deepEquivalent();
    Element* startBlock = position.containerNode() ? enclosingBlock(position.containerNode(), rule) : 0;
    return startBlock ? VisiblePosition(firstPositionInNode(startBlock)) : VisiblePosition();
}

VisiblePosition endOfBlock(const VisiblePosition& visiblePosition, EditingBoundaryCrossingRule rule)
{
    Position position = visiblePosition.deepEquivalent();
    Element* endBlock = position.containerNode() ? enclosingBlock(position.containerNode(), rule) : 0;
    return endBlock ? VisiblePosition(lastPositionInNode(endBlock)) : VisiblePosition();
}

bool inSameBlock(const VisiblePosition &a, const VisiblePosition &b)
{
    return !a.isNull() && enclosingBlock(a.deepEquivalent().containerNode()) == enclosingBlock(b.deepEquivalent().containerNode());
}

bool isStartOfBlock(const VisiblePosition &pos)
{
    return pos.isNotNull() && pos == startOfBlock(pos, CanCrossEditingBoundary);
}

bool isEndOfBlock(const VisiblePosition &pos)
{
    return pos.isNotNull() && pos == endOfBlock(pos, CanCrossEditingBoundary);
}

// ---------

VisiblePosition startOfDocument(const Node* node)
{
    if (!node || !node->document().documentElement())
        return VisiblePosition();

    return VisiblePosition(firstPositionInNode(node->document().documentElement()), DOWNSTREAM);
}

VisiblePosition startOfDocument(const VisiblePosition &c)
{
    return startOfDocument(c.deepEquivalent().deprecatedNode());
}

VisiblePosition endOfDocument(const Node* node)
{
    if (!node || !node->document().documentElement())
        return VisiblePosition();

    Element* doc = node->document().documentElement();
    return VisiblePosition(lastPositionInNode(doc), DOWNSTREAM);
}

VisiblePosition endOfDocument(const VisiblePosition &c)
{
    return endOfDocument(c.deepEquivalent().deprecatedNode());
}

bool isStartOfDocument(const VisiblePosition &p)
{
    return p.isNotNull() && p.previous(CanCrossEditingBoundary).isNull();
}

bool isEndOfDocument(const VisiblePosition &p)
{
    return p.isNotNull() && p.next(CanCrossEditingBoundary).isNull();
}

// ---------

VisiblePosition startOfEditableContent(const VisiblePosition& visiblePosition)
{
    ContainerNode* highestRoot = highestEditableRoot(visiblePosition.deepEquivalent());
    if (!highestRoot)
        return VisiblePosition();

    return VisiblePosition(firstPositionInNode(highestRoot));
}

VisiblePosition endOfEditableContent(const VisiblePosition& visiblePosition)
{
    ContainerNode* highestRoot = highestEditableRoot(visiblePosition.deepEquivalent());
    if (!highestRoot)
        return VisiblePosition();

    return VisiblePosition(lastPositionInNode(highestRoot));
}

bool isEndOfEditableOrNonEditableContent(const VisiblePosition &p)
{
    return p.isNotNull() && p.next().isNull();
}

VisiblePosition leftBoundaryOfLine(const VisiblePosition& c, TextDirection direction)
{
    return direction == LTR ? logicalStartOfLine(c) : logicalEndOfLine(c);
}

VisiblePosition rightBoundaryOfLine(const VisiblePosition& c, TextDirection direction)
{
    return direction == LTR ? logicalEndOfLine(c) : logicalStartOfLine(c);
}

LayoutRect localCaretRectOfPosition(const PositionWithAffinity& position, LayoutObject*& renderer)
{
    if (position.position().isNull()) {
        renderer = nullptr;
        return LayoutRect();
    }
    Node* node = position.position().anchorNode();

    renderer = node->layoutObject();
    if (!renderer)
        return LayoutRect();

    InlineBox* inlineBox;
    int caretOffset;
    position.position().getInlineBoxAndOffset(position.affinity(), inlineBox, caretOffset);

    if (inlineBox)
        renderer = &inlineBox->layoutObject();

    return renderer->localCaretRect(inlineBox, caretOffset);
}

}


text:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

from multiprocessing import Pool
#multiprocessing.freeze_support() # <- may be required on windows

def first_try(x, y):

    plt.scatter(x, y)
    plt.legend()
    plt.show()

def second_try(x, y):

    plt.scatter(x, y)
    plt.legend()
    plt.show()

def multiP():
    p = Pool(3)
    for i in range(3):
        p.apply_async(second_try, args=(i, i))
    p.close()
    p.join()

if __name__ == "__main__":
    first_try(1,1)
    # input('Value: ')
    multiP()