text:
package com.evolveum.midpoint.web.component.wizard;

import java.io.Serializable;

/**
 * @author lazyman
 */
public class WizardStepDto implements Serializable {

    private String name;
    private boolean enabled = true;
    private boolean visible = true;
    private boolean active;

    public WizardStepDto(String name) {
        this(name, true, true);
    }

    public WizardStepDto(String name, boolean enabled, boolean visible) {
        this.name = name;
        this.enabled = enabled;
        this.visible = visible;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getName() {
        return name;
    }

    public boolean isVisible() {
        return visible;
    }

    public void setVisible(boolean visible) {
        this.visible = visible;
    }
}


text:
<md-content layout-padding>

Book a Pickup

	<form flex ng-submit="submit()">

            <md-input-container class="md-block" flex-gt-sm>
                Service Type
                <md-select name="type" ng-model="booking.type" required>
                    <md-option value="standard">Standard</md-option>
                    <md-option value="express">Express</md-option>
                    <md-option value="overnight">Overnight</md-option>
                    <md-option value="dangerous">Dangerous Goods</md-option>
                </md-select>
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm ng-if="booking.type === 'dangerous'">
                Dangerous Goods Type
                <md-select name="type" ng-model="booking.dangerous" required>
                    <md-option value="none">No Dangerous Goods</md-option>
                    <md-option value="explosives">Explosives</md-option>
                    <md-option value="gases">Gases</md-option>
                    <md-option value="flammable">Flammable Substances</md-option>
                    <md-option value="oxidizing">Oxidizing Substances</md-option>
                    <md-option value="toxic">Toxic Substances</md-option>
                    <md-option value="corrosives">Corrosives</md-option>
                    <md-option value="misc">Miscellaneous</md-option>
                </md-select>
            </md-input-container>

        Pickup Address

            <md-input-container class="md-block" flex-gt-sm>
                Business Name
                <input ng-model="booking.pickup.businessName">
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                Contact Name
                <input ng-model="booking.pickup.contactName" required>
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Phone
                <input name="phone" ng-model="booking.pickup.phone" ng-pattern="/^[0-9]{4} [0-9]{3} [0-9]{3}$/" required>

#### ### ###

            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Email
                <input name="email" ng-model="booking.pickup.email" ng-pattern="/^.+@.+\..+$/" required>
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                Street Name and Number
                <input name="text" ng-model="booking.pickup.street" required>
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Suburb
                <input name="text" ng-model="booking.pickup.suburb" required>
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                State
                <md-select name="type" ng-model="booking.pickup.state" required>
                    <md-option value="act">ACT</md-option>
                    <md-option value="new_south_wales">New South Wales</md-option>
                    <md-option value="queensland">Queensland</md-option>
                    <md-option value="victoria">Victoria</md-option>
                    <md-option value="south_australia">South Australia</md-option>
                    <md-option value="western_australia">Western Australia</md-option>
                    <md-option value="tasmania">Tasmania</md-option>
                    <md-option value="northern_territory">Northern Territory</md-option>
                </md-select>
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Post Code
                <input name="postalCode" ng-model="booking.pickup.postCode" ng-pattern="/^[0-9]{4}$/" md-maxlength="4" required>
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                Pickup Date
                <md-datepicker ng-model="booking.pickup.date" md-placeholder="Enter date" required></md-datepicker>
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Pickup Time
                <input type="time" ng-model="booking.pickup.time" placeholder="00:00 AM/PM" required>
            </md-input-container>

		Delivery Address

            <md-input-container class="md-block" flex-gt-sm>
                Business Name
                <input ng-model="booking.delivery.businessName">
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                Contact Name
                <input ng-model="booking.delivery.contactName" required>
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Phone
                <input name="phone" ng-model="booking.delivery.phone" ng-pattern="/^[0-9]{4} [0-9]{3} [0-9]{3}$/" required>

#### ### ###

            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Email
                <input name="email" ng-model="booking.delivery.email" ng-pattern="/^.+@.+\..+$/" required>
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                Street Name and Number
                <input name="text" ng-model="booking.delivery.street" required>
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Suburb
                <input name="text" ng-model="booking.delivery.suburb" required>
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                State
                <md-select name="type" ng-model="booking.delivery.state" required>
                    <md-option value="act">ACT</md-option>
                    <md-option value="new_south_wales">New South Wales</md-option>
                    <md-option value="queensland">Queensland</md-option>
                    <md-option value="victoria">Victoria</md-option>
                    <md-option value="south_australia">South Australia</md-option>
                    <md-option value="western_australia">Western Australia</md-option>
                    <md-option value="tasmania">Tasmania</md-option>
                    <md-option value="northern_territory">Northern Territory</md-option>
                </md-select>
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm>
                Post Code
                <input name="postalCode" ng-model="booking.delivery.postCode" ng-pattern="/^[0-9]{4}$/" md-maxlength="4" required>
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                Fragile
                <md-select name="type" ng-model="booking.fragile" required>
                    <md-option value="no">No</md-option>
                    <md-option value="yes">Yes</md-option>
                </md-select>
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                Payment Type
                <md-select name="type" ng-model="booking.paymentType" required>
                    <md-option value="account">Account</md-option>
                    <md-option value="credit">Credit Card</md-option>
                    <md-option value="cash">Cash</md-option>
                </md-select>
            </md-input-container>

            <md-input-container class="md-block" flex-gt-sm>
                Customer Comments
                <textarea ng-model="booking.customerComments" md-maxlength="300" rows="5" md-select-on-focus></textarea>
            </md-input-container>

Packages:

				Weight (kg)
				Length (cm)
				Width (cm)
				Height (cm)

                    <md-input-container class="md-block" flex-gt-sm>
                        <input name="number" ng-model="package.weight" required>
                    </md-input-container>

                    <md-input-container class="md-block" flex-gt-sm>
                        <input name="number" ng-model="package.length" required>
                    </md-input-container>

                    <md-input-container class="md-block" flex-gt-sm>
                        <input name="number" ng-model="package.width" required>
                    </md-input-container>

                    <md-input-container class="md-block" flex-gt-sm>
                        <input name="number" ng-model="package.height" required>
                    </md-input-container>

                    <md-button class="md-raised" ng-click="removePackage($index)"><md-icon>clear</md-icon></md-button>

            <md-button class="md-raised" ng-click="addPackage()"><md-icon>add</md-icon></md-button>

            <md-button class="md-raised" type="submit">Make a Booking</md-button>

	</form>
</md-content>

redpajama_set_name: RedPajamaGithub


text:
var BaseApp = require('rendr/shared/app')
  , handlebarsHelpers = require('./lib/handlebarsHelpers');
var Backbone = require('backbone');
var BackbonePouch = require('backbone-pouch');
var PouchDB = require('backbone-pouch/node_modules/pouchdb');
var TodoList = require("./collections/todos");
var TodoAppView = require("./views/todos/index");
var ReplicationList = require("./collections/replications");
var ReplicationAppView = require("./views/repos/index");

/**
 * Extend the `BaseApp` class, adding any custom methods or overrides.
 */
module.exports = BaseApp.extend({

  /**
   * Client and server.
   *
   * `initialize` is called on app initialize, both on the client and server.
   * On the server, an app is instantiated once for each request, and in the
   * client, it's instantiated once on page load.
   *
   * This is a good place to initialize any code that needs to be available to
   * app on both client and server.
   */
  initialize: function() {
    /**
     * Register our Handlebars helpers.
     *
     * `this.templateAdapter` is, by default, the `rendr-handlebars` module.
     * It has a `registerHelpers` method, which allows us to register helper
     * modules that can be used on both client & server.
     */
    this.templateAdapter.registerHelpers(handlebarsHelpers);

    var dbname = 'todos-sync-backbone-0.0.12';

    // Save all of the todo items in the `"todos-backbone"` database.
    Backbone.sync = BackbonePouch.sync({
      // We currently suffix by the PouchDB version here
      // because at the moment PouchDB does not support upgrade
      db: new PouchDB(dbname),
      listen: true,
      fetch: 'query'
    });

    // Adjust id attribute to the one PouchDB uses
    Backbone.Model.prototype.idAttribute = '_id';

    var Todos, TodoApp, Replications, ReplicationApp;

    // Create our global collection of **Todos**.
    Todos = new TodoList;

    // Finally, we kick things off by creating the **App**.
    TodoApp = new TodoAppView;

    // Create global collection of **Replications**.
    Replications = new ReplicationList;

    // Finally, we kick things off by creating the **App**.
    ReplicationApp = new ReplicationAppView;
  },

  /**
   * Client-side only.
   *
   * `start` is called at the bottom of `__layout.hbs`. Calling this kicks off
   * the router and initializes the application.
   *
   * Override this method (remembering to call the superclass' `start` method!)
   * in order to do things like bind events to the router, as shown below.
   */
  start: function() {
    // Show a loading indicator when the app is fetching.
    this.router.on('action:start', function() { this.set({loading: true});  }, this);
    this.router.on('action:end',   function() { this.set({loading: false}); }, this);

    // Call 'super'.
    BaseApp.prototype.start.call(this);
  }
});


text:
package iptables_test

import (
	"io"
	"io/ioutil"
	"os"
	"time"

	. "github.com/projectcalico/felix/iptables"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("SharedLock", func() {
	var lock *SharedLock
	var mockIptablesLock *mockLock
	var mockErr error

	mockGrabLock := func(lockFilePath, socketName string, timeout, probeInterval time.Duration) (io.Closer, error) {
		return mockIptablesLock, mockErr
	}

	BeforeEach(func() {
		mockErr = nil
		mockIptablesLock = &mockLock{}
		lock = NewSharedLock("/foo/bar.lock", time.Second, time.Millisecond)
		lock.GrabIptablesLocks = mockGrabLock
	})

	It("should close the lock after final unlock call", func() {
		lock.Lock()
		Expect(mockIptablesLock.Closed).To(BeFalse())
		lock.Unlock()
		Expect(mockIptablesLock.Closed).To(BeTrue())
	})
	It("should allow multiple holders", func() {
		lock.Lock()
		lock.Lock()
		Expect(mockIptablesLock.Closed).To(BeFalse())
		lock.Unlock()
		Expect(mockIptablesLock.Closed).To(BeFalse())
		lock.Unlock()
		Expect(mockIptablesLock.Closed).To(BeTrue())
	})
	It("should panic on misuse", func() {
		Expect(lock.Unlock).To(Panic())
	})
	It("should panic on failure to acquire", func() {
		mockErr = Err14LockTimeout
		Expect(lock.Lock).To(Panic())
	})
	It("should panic on failure to close", func() {
		lock.Lock()
		mockIptablesLock.Err = Err14LockTimeout
		Expect(lock.Unlock).To(Panic())
	})
})

type mockLock struct {
	Closed bool
	Err    error
}

func (l *mockLock) Close() error {
	Expect(l.Closed).To(BeFalse())
	l.Closed = true
	return l.Err
}

var _ = Describe("GrabIptablesLocks FV", func() {
	var fileName string

	BeforeEach(func() {
		f, err := ioutil.TempFile("", "iptlocktest")
		Expect(err).NotTo(HaveOccurred())
		fileName = f.Name()
		f.Close()
	})
	AfterEach(func() {
		os.Remove(fileName)
	})

	It("should block concurrent invocations", func() {
		l, err := GrabIptablesLocks(fileName, "@dummytables", 1*time.Second, 50*time.Millisecond)
		Expect(err).NotTo(HaveOccurred())
		defer l.Close()

		l2, err := GrabIptablesLocks(fileName, "@dummytables", 100*time.Millisecond, 10*time.Millisecond)
		Expect(err).To(Equal(Err16LockTimeout))
		Expect(l2).To(BeNil())
	})
	It("should allow access after being released", func() {
		l, err := GrabIptablesLocks(fileName, "@dummytables", 1*time.Second, 50*time.Millisecond)
		Expect(err).NotTo(HaveOccurred())
		l.Close()

		l2, err := GrabIptablesLocks(fileName, "@dummytables", 1*time.Second, 50*time.Millisecond)
		Expect(err).NotTo(HaveOccurred())
		l2.Close()
	})
	It("should block concurrent invocations using only iptables 1.4 version of lock", func() {
		l, err := GrabIptablesLocks(fileName, "@dummytables", 1*time.Second, 50*time.Millisecond)
		// Sneakily remove the lockfile after it's been locked so that we fall through to
		// the v1.4 lock.
		os.Remove(fileName)
		Expect(err).NotTo(HaveOccurred())
		defer l.Close()

		l2, err := GrabIptablesLocks(fileName, "@dummytables", 100*time.Millisecond, 10*time.Millisecond)
		Expect(err).To(Equal(Err14LockTimeout))
		Expect(l2).To(BeNil())
	})
	It("should allow access after being released using only iptables 1.4 version of lock", func() {
		l, err := GrabIptablesLocks(fileName, "@dummytables", 1*time.Second, 50*time.Millisecond)
		// Sneakily remove the lockfile after it's been locked so that we fall through to
		// the v1.4 lock.
		os.Remove(fileName)
		Expect(err).NotTo(HaveOccurred())
		l.Close()

		l2, err := GrabIptablesLocks(fileName, "@dummytables", 1*time.Second, 50*time.Millisecond)
		Expect(err).NotTo(HaveOccurred())
		l2.Close()
	})
})

var _ = Describe("locker", func() {
	var l *Locker
	var lock14 mockCloser
	var lock16 mockCloser

	BeforeEach(func() {
		lock14 = mockCloser{}
		lock16 = mockCloser{}
		l = &Locker{
			Lock14: &lock14,
			Lock16: &lock16,
		}
	})

	It("should return nil with no err", func() {
		Expect(l.Close()).NotTo(HaveOccurred())
	})
	It("should return lock16 err", func() {
		lock16.Err = Err16LockTimeout
		Expect(l.Close()).To(Equal(Err16LockTimeout))
	})
	It("should return lock14 err", func() {
		lock14.Err = Err14LockTimeout
		Expect(l.Close()).To(Equal(Err14LockTimeout))
	})
})

type mockCloser struct {
	Err error
}

func (c *mockCloser) Close() error {
	return c.Err
}


text:
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    sha1 = require('sha1');

mongoose.connect('mongodb://localhost/admin-panel');

var adminsSchema = new Schema({
  login: {type: String, required: true, unique: true},
  password: {type: String, required: true},
  email: {type: String, required: true, unique: true},
  createdAt: {type: Date, default: Date.now},
  updatedAt: {type: Date, default: Date.now}
});

var usersSchema = new Schema({
  name: {type: String, required: true},
  surname: {type: String},
  phone: {type: String},
  email: {type: String, required: true},
  photo: {
    original: String,
    preview: String
  },
  createdAt: {type: Date, default: Date.now},
  updatedAt: {type: Date, default: Date.now}
});

usersSchema.pre('save', function(done) {
  this.updatedAt = new Date();
  done();
});

adminsSchema.pre('save', function(done) {
  this.updatedAt = new Date();

  if(this.isModified('password')) {
    this.password = sha1(this.password);
  }

  done();
});

var adminModel = mongoose.model('Admin', adminsSchema);

adminModel.findOne({}).exec(function(err, foundAdmin) {
  if(err) {
    throw err;
  }

  if(!foundAdmin) {
    new adminModel({
      login: 'admin',
      password: '123',
      email: 'admin@example.com'
    }).save(function(err) {
      if(err) {
        throw err;
      }

      console.log('Admin with login `admin` and password `123` created.');
    });
  }
});

module.exports = {
  Admin: adminModel,
  User: mongoose.model('User', usersSchema),
  mongoose: mongoose
};


text:
<?php

namespace Rax\Helper;

use Rax\Helper\Base\BaseInflector;

/**
 * {@inheritdoc}
 */
class Inflector extends BaseInflector
{
}


text:
<?php

namespace Aliyun\Api\Sms\Request\V20170525;

use Aliyun\Core\RpcAcsRequest;

class SendSmsRequest extends RpcAcsRequest
{
	public function  __construct()
	{
		parent::__construct("Dysmsapi", "2017-05-25", "SendSms");
		$this->setMethod("POST");
	}

	private  $templateCode;

	private  $phoneNumbers;

	private  $signName;

	private  $resourceOwnerAccount;

	private  $templateParam;

	private  $resourceOwnerId;

	private  $ownerId;

	private  $outId;

    private  $smsUpExtendCode;

	public function getTemplateCode() {
		return $this->templateCode;
	}

	public function setTemplateCode($templateCode) {
		$this->templateCode = $templateCode;
		$this->queryParameters["TemplateCode"]=$templateCode;
	}

	public function getPhoneNumbers() {
		return $this->phoneNumbers;
	}

	public function setPhoneNumbers($phoneNumbers) {
		$this->phoneNumbers = $phoneNumbers;
		$this->queryParameters["PhoneNumbers"]=$phoneNumbers;
	}

	public function getSignName() {
		return $this->signName;
	}

	public function setSignName($signName) {
		$this->signName = $signName;
		$this->queryParameters["SignName"]=$signName;
	}

	public function getResourceOwnerAccount() {
		return $this->resourceOwnerAccount;
	}

	public function setResourceOwnerAccount($resourceOwnerAccount) {
		$this->resourceOwnerAccount = $resourceOwnerAccount;
		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
	}

	public function getTemplateParam() {
		return $this->templateParam;
	}

	public function setTemplateParam($templateParam) {
		$this->templateParam = $templateParam;
		$this->queryParameters["TemplateParam"]=$templateParam;
	}

	public function getResourceOwnerId() {
		return $this->resourceOwnerId;
	}

	public function setResourceOwnerId($resourceOwnerId) {
		$this->resourceOwnerId = $resourceOwnerId;
		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
	}

	public function getOwnerId() {
		return $this->ownerId;
	}

	public function setOwnerId($ownerId) {
		$this->ownerId = $ownerId;
		$this->queryParameters["OwnerId"]=$ownerId;
	}

	public function getOutId() {
		return $this->outId;
	}

	public function setOutId($outId) {
		$this->outId = $outId;
		$this->queryParameters["OutId"]=$outId;
	}

    public function getSmsUpExtendCode() {
        return $this->smsUpExtendCode;
    }

    public function setSmsUpExtendCode($smsUpExtendCode) {
        $this->smsUpExtendCode = $smsUpExtendCode;
        $this->queryParameters["SmsUpExtendCode"]=$smsUpExtendCode;
    }
}


text:
var projectsController = require('./projectController.js');

module.exports = function (app) {

  app.param('projectId', projectsController.findProjectById);

  app.route('/')
    .get(projectsController.list)
    .post(projectsController.create);

  app.route('/fakesubmit')
      .get(projectsController.fakeSubmit);

  app.route('/fakeapprove')
      .get(projectsController.fakeApprove);

  app.route('/:projectId')
    .get(projectsController.read)
    .post(projectsController.update);

  app.route('/:projectId/accept')
  	.post(projectsController.acceptProject);

};


text:
{% load staticfiles %}
<!DOCTYPE html>

    <meta name="description"
          content="Wisely is an online social platform connecting massive online open course students with each other to motivate and learn together. Get motivated through pledging, collaborative learning, and social networking. For coursera, edx, and udemy."/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Wisely</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/foundation.min.css' %}"/>
    <link rel="stylesheet" type="text/css" href="{% static 'css/normalize.css' %}"/>
    <link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="{% static 'css/auth-buttons.css' %}" rel="stylesheet">

    <meta property="og:title" content="Wisely - Learn Together">
    <meta property="og:description"
          content="Wisely incentivizes you to meet your personal learning goals on Stay on track and get rewarded for your hard work.">
    <meta property="og:url" content="https://projectwisely.com/"/>
    <meta property="og:image" content="https://projectwisely.com/static/images/logo.png"/>

    <link rel="stylesheet" type="text/css" href="{% static 'css/style-anim.css' %}" cache="false"/>
    {% block headers_css %}
    {% endblock %}

        {% block nav-bar %}
            {% include 'nav-bar-alt.html' %}
        {% endblock %}

        {% block content %}
        {% endblock %}

                    Contact Us

                    Privacy Policy

Contact Us

                <input style="font-size: 1.2em" type="email" name="email" id='contact-email'
                       placeholder="Your Email Address">

                <textarea id="contact-mail" style="font-size: 1.2em; font-family: Dist-light"
                          placeholder="Your Message"></textarea>

                <button id="contact-send">Send</button>

        {% for message in messages %}
            {{ message }}
        {% endfor %}

{% block additionalScripts %}
{% endblock %}


text:
package com.geccocrawler.gecco.monitor;

import org.apache.commons.lang3.time.DateFormatUtils;

import com.geccocrawler.gecco.GeccoEngine;

public class GeccoMonitor {

	/**
	 * 爬虫启动时间
	 */
	private static String startTime;

	/**
	 * 初始抓取地址数量
	 */
	private static int starUrlCount;

	/**
	 * 线程数量
	 */
	private static int threadCount;

	/**
	 * 抓取间隔时间
	 */
	private static int interval;

	public static String getStartTime() {
		return startTime;
	}

	public static void setStartTime(String startTime) {
		GeccoMonitor.startTime = startTime;
	}

	public static int getStarUrlCount() {
		return starUrlCount;
	}

	public static void setStarUrlCount(int starUrlCount) {
		GeccoMonitor.starUrlCount = starUrlCount;
	}

	public static int getThreadCount() {
		return threadCount;
	}

	public static void setThreadCount(int threadCount) {
		GeccoMonitor.threadCount = threadCount;
	}

	public static int getInterval() {
		return interval;
	}

	public static void setInterval(int interval) {
		GeccoMonitor.interval = interval;
	}

	public static void monitor(GeccoEngine engine) {
		setStartTime(DateFormatUtils.format(engine.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
		setStarUrlCount(engine.getStartRequests().size());
		setThreadCount(engine.getThreadCount());
		setInterval(engine.getInterval());
	}
}


text:
package org.jkiss.dbeaver.model.sql.parser;

import org.eclipse.jface.text.IDocument;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLSyntaxManager;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.text.parser.TPRuleBasedScanner;
import org.jkiss.dbeaver.runtime.DBWorkbench;

/**
 * Parser context
 */
public class SQLParserContext {

    @Nullable
    private final DBPDataSource dataSource;
    @NotNull
    private final SQLSyntaxManager syntaxManager;
    @NotNull
    private final SQLRuleManager ruleManager;
    @NotNull
    private final IDocument document;
    private TPRuleBasedScanner scanner;

    @Nullable
    private DBPPreferenceStore preferenceStore;

    public SQLParserContext(@Nullable DBPDataSource dataSource, @NotNull SQLSyntaxManager syntaxManager, @NotNull SQLRuleManager ruleManager, @NotNull IDocument document) {
        this.dataSource = dataSource;
        this.syntaxManager = syntaxManager;
        this.ruleManager = ruleManager;
        this.document = document;
    }

    @Nullable
    public DBPDataSource getDataSource() {
        return dataSource;
    }

    @NotNull
    public SQLSyntaxManager getSyntaxManager() {
        return syntaxManager;
    }

    @NotNull
    public SQLRuleManager getRuleManager() {
        return ruleManager;
    }

    @NotNull
    public IDocument getDocument() {
        return document;
    }

    public SQLDialect getDialect() {
        return SQLUtils.getDialectFromDataSource(getDataSource());
    }

    public TPRuleBasedScanner getScanner() {
        if (scanner == null) {
            scanner = new TPRuleBasedScanner();
            scanner.setRules(ruleManager.getAllRules());
        }
        return scanner;
    }

    public DBPPreferenceStore getPreferenceStore() {
        if (preferenceStore != null) {
            return preferenceStore;
        }
        DBPDataSource dataSource = getDataSource();
        return dataSource == null ?
            DBWorkbench.getPlatform().getPreferenceStore() :
            dataSource.getContainer().getPreferenceStore();
    }

    public void setPreferenceStore(@Nullable DBPPreferenceStore preferenceStore) {
        this.preferenceStore = preferenceStore;
    }

    void startScriptEvaluation() {
        getScanner().startEval();
    }

    void endScriptEvaluation() {
        getScanner().endEval();
    }

}


text:
.ifndef ::_RANDOM_H_
::_RANDOM_H_ = 1

.setcpu "65816"

.include "includes/import_export.inc"
.include "includes/synthetic.inc"
.include "includes/structure.inc"

;; This module is a Linear congruential pseudo random number generator.
;;
;; In order to increase the observed randomness of this module,
;; the function `AddJoypadEntropy` should be called once every frame.
;; This will cycle the random number generator once or twice, depending
;; on the state of JOY1.

IMPORT_MODULE Random

	UINT32	seed

	;; Runs the random seed through a single pass of the seed
	;; REQUIRE: 8 bit A
	;; RETURN: bits 16-23 of seed
	ROUTINE Rnd

	;; Adds entropy to the random seed by calling `Rnd`
	;;	* twice if the state of JOY1 has changed since the last call.
	;;	* once if the joypad hasn't changed.
	;;
	;; This can add a bit of variety to the random number generator.
	;;
	;; REQUIRE: 8 bit A, 16 bit Index, AutoJoy Enabled, not in AutoJoy time
	ROUTINE AddJoypadEntropy

	;; Generates a random number between 0 and 3 (inclusive)
	;; REQUIRE: 8 bit A
	;; RETURN:
	;;	A: random number between 0 and 3 (inclusive)
	;;	z: set if A is 0
	ROUTINE	Rnd_4

	;; Generates a random number between 0 and 2 (inclusive)
	;;
	;; It is skewed towards 1.
	;;
	;; REQUIRE: 8 bit A
	;; RETURN:
	;;	A: random number between 0 and 2 (inclusive)
	;;	z: set if A is 0
	ROUTINE	Rnd_3

	;; Generates a random number between 0 and 1 (inclusive)
	;;
	;; REQUIRE: 8 bit A
	;; RETURN:
	;;	A: random number between 0 and 1 (inclusive)
	;;	z: set if A is 0
	ROUTINE	Rnd_2

	;; Generates a 16 bit random number between 0 and A (non-inclusive)
	;;
	;; Skewed towards smaller numbers
	;;
	;; REQUIRE: 8 bit A
	;; INPUT:
	;;	A: unsigned 8 bit value.
	;; OUTPUT:
	;;	A: unsigned 8 bit value between 0 and (A-1) (inclusive).
	ROUTINE	Rnd_U8A

	;; Generates a 16 bit random number between 0 and Y (non-inclusive)
	;;
	;; Skewed towards smaller numbers.
	;;
	;; Note: If Y < 256, using Rnd_U8A will return more random numbers.
	;;
	;; REQUIRE: 8 bit A, 16 bit Index
	;; INPUT:
	;;	Y: unsigned 16 bit value.
	;; OUTPUT:
	;;	Y: unsigned 16 bit value between 0 and (Y-1) (inclusive).
	ROUTINE	Rnd_U16Y

	;; Generates a 16 bit random number between X and Y (non-inclusive)
	;;
	;; Skewed towards smaller numbers.
	;;
	;; REQUIRE: 8 bit A, 16 bit Index
	;; INPUT:
	;;	X: unsigned 16 bit min
	;;	Y: unsigned 16 bit max
	;; OUTPUT:
	;;	Y: unsigned 16 bit value.
	ROUTINE	Rnd_U16X_U16Y

ENDMODULE

.endif ; ::_RANDOM_H_

; vim: set ft=asm:


text:
using System;

namespace Tests
{
	[AttributeUsage(AttributeTargets.Method)]
	public class IncludeDataContextSourceAttribute : BaseDataContextSourceAttribute
	{
		public IncludeDataContextSourceAttribute(params string[] include)
			: this(false, include)
		{
		}

		public IncludeDataContextSourceAttribute(bool includeLinqService, params string[] include)
			: base(includeLinqService, include)
		{
		}
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<?php
	include_once(dirname(__FILE__)."/../../lib/include_js_css.php");
	include_once(dirname(__FILE__)."/../../lib/site_config.php");
	include_once("../../lib/session_manager.php");
	include_once("../../test/lib/tbl_question.php");
	include_once('../../database/mcat_db.php');

	// - - - - - - - - - - - - - - - - -
	// On Session Expire Load ROOT_URL
	// - - - - - - - - - - - - - - - - -
	CSessionManager::OnSessionExpire();
	// - - - - - - - - - - - - - - - - -

	$objDB = new CMcatDB();

	$user_id = CSessionManager::Get(CSessionManager::STR_USER_ID);
	$objIncludeJsCSS = new IncludeJSCSS();

	$menu_id = CSiteConfig::UAMM_SNEAK_PEEK;
	$page_id = CSiteConfig::UAP_SNEAK_PEEK_PERSONAL;
?>

<meta charset="UTF-8">
<meta name="Generator" content="Mastishka Intellisys Private Limited">
<meta name="Author" content="Mastishka Intellisys Private Limited">
<meta name="Keywords" content="">
<meta name="Description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo(CConfig::SNC_SITE_NAME);?>: Personal Knowledge Base</title>
<?php
$objIncludeJsCSS->IncludeDatatablesBootstrapCSS("../../");
$objIncludeJsCSS->IncludeDatatablesResponsiveCSS("../../");
$objIncludeJsCSS->CommonIncludeCSS("../../");
$objIncludeJsCSS->IncludeMipcatCSS("../../");
$objIncludeJsCSS->IncludeIconFontCSS("../../");
$objIncludeJsCSS->CommonIncludeJS("../../");
$objIncludeJsCSS->IncludeJqueryDatatablesMinJS("../../");
$objIncludeJsCSS->IncludeDatatablesTabletoolsMinJS("../../");
$objIncludeJsCSS->IncludeDatatablesBootstrapJS("../../");
$objIncludeJsCSS->IncludeDatatablesResponsiveJS("../../");
$objIncludeJsCSS->IncludeJqueryDatatablesRowGroupingJS("../../");
?>

	<?php
	include_once(dirname(__FILE__)."/../../lib/header.php");
	?>

			<?php
			include_once(dirname(__FILE__)."/../../lib/sidebar.php");
			?>

							Subject
							Topic
							Language
							Easy Questions
							Moderate Questions
							Hard Questions

					<?php
						$QuesInfoAry = $objDB->GetQuestionsInfo($user_id);

						/*echo("
");
						print_r($QuesInfoAry);
						echo("
");*/

						foreach ($QuesInfoAry as $subject_id => $topics)
						{
							foreach($topics as $topic_id => $languages)
							{
								foreach($languages as $lang => $questions)
								{
									$subject_name = ucwords($objDB->GetSubjectName($subject_id));
									$topic_name   = ucwords($objDB->GetTopicName($topic_id));
									$language	  = ucwords($lang);
									if(!empty($subject_name) && !empty($topic_name))
									{
										echo("
");
										printf("%s	 %s	 %s	 %s	 %s	 %s	", ucwords($objDB->GetSubjectName($subject_id)), ucwords($objDB->GetTopicName($topic_id)), $language, empty($questions[1]) ? 0 : $questions[1],
																	empty($questions[2]) ? 0 : $questions[2],
																	empty($questions[3]) ? 0 : $questions[3]);
										echo("
\n");
									}
								}
							}
						}
					?>

							Subject
							Topic
							Language
							Easy Questions
							Moderate Questions
							Hard Questions

		    <?php
			include_once (dirname ( __FILE__ ) . "/../../lib/footer.php");
			?>


text:
.class public final Landroid/support/v4/text/BidiFormatter;
.super Ljava/lang/Object;
.source "BidiFormatter.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/support/v4/text/BidiFormatter$1;,
        Landroid/support/v4/text/BidiFormatter$DirectionalityEstimator;,
        Landroid/support/v4/text/BidiFormatter$Builder;
    }
.end annotation

# static fields
.field private static final DEFAULT_FLAGS:I = 0x2

.field private static final DEFAULT_LTR_INSTANCE:Landroid/support/v4/text/BidiFormatter; = null

.field private static final DEFAULT_RTL_INSTANCE:Landroid/support/v4/text/BidiFormatter; = null

.field private static DEFAULT_TEXT_DIRECTION_HEURISTIC:Landroid/support/v4/text/TextDirectionHeuristicCompat; = null

.field private static final DIR_LTR:I = -0x1

.field private static final DIR_RTL:I = 0x1

.field private static final DIR_UNKNOWN:I = 0x0

.field private static final EMPTY_STRING:Ljava/lang/String; = ""

.field private static final FLAG_STEREO_RESET:I = 0x2

.field private static final LRE:C = '\u202a'

.field private static final LRM:C = '\u200e'

.field private static final LRM_STRING:Ljava/lang/String; = null

.field private static final PDF:C = '\u202c'

.field private static final RLE:C = '\u202b'

.field private static final RLM:C = '\u200f'

.field private static final RLM_STRING:Ljava/lang/String;

# instance fields
.field private final mDefaultTextDirectionHeuristicCompat:Landroid/support/v4/text/TextDirectionHeuristicCompat;

.field private final mFlags:I

.field private final mIsRtlContext:Z

# direct methods
.method static constructor <clinit>()V
    .locals 4

    .prologue
    const/4 v3, 0x2

    .line 83
    sget-object v0, Landroid/support/v4/text/TextDirectionHeuristicsCompat;->FIRSTSTRONG_LTR:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    sput-object v0, Landroid/support/v4/text/BidiFormatter;->DEFAULT_TEXT_DIRECTION_HEURISTIC:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    .line 113
    const/16 v0, 0x200e

    invoke-static {v0}, Ljava/lang/Character;->toString(C)Ljava/lang/String;

    move-result-object v0

    sput-object v0, Landroid/support/v4/text/BidiFormatter;->LRM_STRING:Ljava/lang/String;

    .line 118
    const/16 v0, 0x200f

    invoke-static {v0}, Ljava/lang/Character;->toString(C)Ljava/lang/String;

    move-result-object v0

    sput-object v0, Landroid/support/v4/text/BidiFormatter;->RLM_STRING:Ljava/lang/String;

    .line 215
    new-instance v0, Landroid/support/v4/text/BidiFormatter;

    const/4 v1, 0x0

    sget-object v2, Landroid/support/v4/text/BidiFormatter;->DEFAULT_TEXT_DIRECTION_HEURISTIC:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    invoke-direct {v0, v1, v3, v2}, Landroid/support/v4/text/BidiFormatter;-><init>(ZILandroid/support/v4/text/TextDirectionHeuristicCompat;)V

    sput-object v0, Landroid/support/v4/text/BidiFormatter;->DEFAULT_LTR_INSTANCE:Landroid/support/v4/text/BidiFormatter;

    .line 220
    new-instance v0, Landroid/support/v4/text/BidiFormatter;

    const/4 v1, 0x1

    sget-object v2, Landroid/support/v4/text/BidiFormatter;->DEFAULT_TEXT_DIRECTION_HEURISTIC:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    invoke-direct {v0, v1, v3, v2}, Landroid/support/v4/text/BidiFormatter;-><init>(ZILandroid/support/v4/text/TextDirectionHeuristicCompat;)V

    sput-object v0, Landroid/support/v4/text/BidiFormatter;->DEFAULT_RTL_INSTANCE:Landroid/support/v4/text/BidiFormatter;

    return-void
.end method

.method private constructor <init>(ZILandroid/support/v4/text/TextDirectionHeuristicCompat;)V
    .locals 0
    .parameter "isRtlContext"
    .parameter "flags"
    .parameter "heuristic"

    .prologue
    .line 260
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 261
    iput-boolean p1, p0, Landroid/support/v4/text/BidiFormatter;->mIsRtlContext:Z

    .line 262
    iput p2, p0, Landroid/support/v4/text/BidiFormatter;->mFlags:I

    .line 263
    iput-object p3, p0, Landroid/support/v4/text/BidiFormatter;->mDefaultTextDirectionHeuristicCompat:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    .line 264
    return-void
.end method

.method synthetic constructor <init>(ZILandroid/support/v4/text/TextDirectionHeuristicCompat;Landroid/support/v4/text/BidiFormatter$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"
    .parameter "x2"
    .parameter "x3"

    .prologue
    .line 78
    invoke-direct {p0, p1, p2, p3}, Landroid/support/v4/text/BidiFormatter;-><init>(ZILandroid/support/v4/text/TextDirectionHeuristicCompat;)V

    return-void
.end method

.method static synthetic access$000(Ljava/util/Locale;)Z
    .locals 1
    .parameter "x0"

    .prologue
    .line 78
    invoke-static {p0}, Landroid/support/v4/text/BidiFormatter;->isRtlLocale(Ljava/util/Locale;)Z

    move-result v0

    return v0
.end method

.method static synthetic access$100()Landroid/support/v4/text/TextDirectionHeuristicCompat;
    .locals 1

    .prologue
    .line 78
    sget-object v0, Landroid/support/v4/text/BidiFormatter;->DEFAULT_TEXT_DIRECTION_HEURISTIC:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    return-object v0
.end method

.method static synthetic access$200()Landroid/support/v4/text/BidiFormatter;
    .locals 1

    .prologue
    .line 78
    sget-object v0, Landroid/support/v4/text/BidiFormatter;->DEFAULT_RTL_INSTANCE:Landroid/support/v4/text/BidiFormatter;

    return-object v0
.end method

.method static synthetic access$300()Landroid/support/v4/text/BidiFormatter;
    .locals 1

    .prologue
    .line 78
    sget-object v0, Landroid/support/v4/text/BidiFormatter;->DEFAULT_LTR_INSTANCE:Landroid/support/v4/text/BidiFormatter;

    return-object v0
.end method

.method private static getEntryDir(Ljava/lang/String;)I
    .locals 2
    .parameter "str"

    .prologue
    .line 479
    new-instance v0, Landroid/support/v4/text/BidiFormatter$DirectionalityEstimator;

    const/4 v1, 0x0

    invoke-direct {v0, p0, v1}, Landroid/support/v4/text/BidiFormatter$DirectionalityEstimator;-><init>(Ljava/lang/String;Z)V

    invoke-virtual {v0}, Landroid/support/v4/text/BidiFormatter$DirectionalityEstimator;->getEntryDir()I

    move-result v0

    return v0
.end method

.method private static getExitDir(Ljava/lang/String;)I
    .locals 2
    .parameter "str"

    .prologue
    .line 462
    new-instance v0, Landroid/support/v4/text/BidiFormatter$DirectionalityEstimator;

    const/4 v1, 0x0

    invoke-direct {v0, p0, v1}, Landroid/support/v4/text/BidiFormatter$DirectionalityEstimator;-><init>(Ljava/lang/String;Z)V

    invoke-virtual {v0}, Landroid/support/v4/text/BidiFormatter$DirectionalityEstimator;->getExitDir()I

    move-result v0

    return v0
.end method

.method public static getInstance()Landroid/support/v4/text/BidiFormatter;
    .locals 1

    .prologue
    .line 234
    new-instance v0, Landroid/support/v4/text/BidiFormatter$Builder;

    invoke-direct {v0}, Landroid/support/v4/text/BidiFormatter$Builder;-><init>()V

    invoke-virtual {v0}, Landroid/support/v4/text/BidiFormatter$Builder;->build()Landroid/support/v4/text/BidiFormatter;

    move-result-object v0

    return-object v0
.end method

.method public static getInstance(Ljava/util/Locale;)Landroid/support/v4/text/BidiFormatter;
    .locals 1
    .parameter "locale"

    .prologue
    .line 252
    new-instance v0, Landroid/support/v4/text/BidiFormatter$Builder;

    invoke-direct {v0, p0}, Landroid/support/v4/text/BidiFormatter$Builder;-><init>(Ljava/util/Locale;)V

    invoke-virtual {v0}, Landroid/support/v4/text/BidiFormatter$Builder;->build()Landroid/support/v4/text/BidiFormatter;

    move-result-object v0

    return-object v0
.end method

.method public static getInstance(Z)Landroid/support/v4/text/BidiFormatter;
    .locals 1
    .parameter "rtlContext"

    .prologue
    .line 243
    new-instance v0, Landroid/support/v4/text/BidiFormatter$Builder;

    invoke-direct {v0, p0}, Landroid/support/v4/text/BidiFormatter$Builder;-><init>(Z)V

    invoke-virtual {v0}, Landroid/support/v4/text/BidiFormatter$Builder;->build()Landroid/support/v4/text/BidiFormatter;

    move-result-object v0

    return-object v0
.end method

.method private static isRtlLocale(Ljava/util/Locale;)Z
    .locals 2
    .parameter "locale"

    .prologue
    const/4 v0, 0x1

    .line 437
    invoke-static {p0}, Landroid/support/v4/text/TextUtilsCompat;->getLayoutDirectionFromLocale(Ljava/util/Locale;)I

    move-result v1

    if-ne v1, v0, :cond_0

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method private markAfter(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;)Ljava/lang/String;
    .locals 3
    .parameter "str"
    .parameter "heuristic"

    .prologue
    .line 297
    const/4 v1, 0x0

    invoke-virtual {p1}, Ljava/lang/String;->length()I

    move-result v2

    invoke-interface {p2, p1, v1, v2}, Landroid/support/v4/text/TextDirectionHeuristicCompat;->isRtl(Ljava/lang/CharSequence;II)Z

    move-result v0

    .line 299
    .local v0, isRtl:Z
    iget-boolean v1, p0, Landroid/support/v4/text/BidiFormatter;->mIsRtlContext:Z

    if-nez v1, :cond_1

    if-nez v0, :cond_0

    invoke-static {p1}, Landroid/support/v4/text/BidiFormatter;->getExitDir(Ljava/lang/String;)I

    move-result v1

    const/4 v2, 0x1

    if-ne v1, v2, :cond_1

    .line 300
    :cond_0
    sget-object v1, Landroid/support/v4/text/BidiFormatter;->LRM_STRING:Ljava/lang/String;

    .line 305
    :goto_0
    return-object v1

    .line 302
    :cond_1
    iget-boolean v1, p0, Landroid/support/v4/text/BidiFormatter;->mIsRtlContext:Z

    if-eqz v1, :cond_3

    if-eqz v0, :cond_2

    invoke-static {p1}, Landroid/support/v4/text/BidiFormatter;->getExitDir(Ljava/lang/String;)I

    move-result v1

    const/4 v2, -0x1

    if-ne v1, v2, :cond_3

    .line 303
    :cond_2
    sget-object v1, Landroid/support/v4/text/BidiFormatter;->RLM_STRING:Ljava/lang/String;

    goto :goto_0

    .line 305
    :cond_3
    const-string v1, ""

    goto :goto_0
.end method

.method private markBefore(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;)Ljava/lang/String;
    .locals 3
    .parameter "str"
    .parameter "heuristic"

    .prologue
    .line 324
    const/4 v1, 0x0

    invoke-virtual {p1}, Ljava/lang/String;->length()I

    move-result v2

    invoke-interface {p2, p1, v1, v2}, Landroid/support/v4/text/TextDirectionHeuristicCompat;->isRtl(Ljava/lang/CharSequence;II)Z

    move-result v0

    .line 326
    .local v0, isRtl:Z
    iget-boolean v1, p0, Landroid/support/v4/text/BidiFormatter;->mIsRtlContext:Z

    if-nez v1, :cond_1

    if-nez v0, :cond_0

    invoke-static {p1}, Landroid/support/v4/text/BidiFormatter;->getEntryDir(Ljava/lang/String;)I

    move-result v1

    const/4 v2, 0x1

    if-ne v1, v2, :cond_1

    .line 327
    :cond_0
    sget-object v1, Landroid/support/v4/text/BidiFormatter;->LRM_STRING:Ljava/lang/String;

    .line 332
    :goto_0
    return-object v1

    .line 329
    :cond_1
    iget-boolean v1, p0, Landroid/support/v4/text/BidiFormatter;->mIsRtlContext:Z

    if-eqz v1, :cond_3

    if-eqz v0, :cond_2

    invoke-static {p1}, Landroid/support/v4/text/BidiFormatter;->getEntryDir(Ljava/lang/String;)I

    move-result v1

    const/4 v2, -0x1

    if-ne v1, v2, :cond_3

    .line 330
    :cond_2
    sget-object v1, Landroid/support/v4/text/BidiFormatter;->RLM_STRING:Ljava/lang/String;

    goto :goto_0

    .line 332
    :cond_3
    const-string v1, ""

    goto :goto_0
.end method

# virtual methods
.method public getStereoReset()Z
    .locals 1

    .prologue
    .line 278
    iget v0, p0, Landroid/support/v4/text/BidiFormatter;->mFlags:I

    and-int/lit8 v0, v0, 0x2

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public isRtl(Ljava/lang/String;)Z
    .locals 3
    .parameter "str"

    .prologue
    .line 343
    iget-object v0, p0, Landroid/support/v4/text/BidiFormatter;->mDefaultTextDirectionHeuristicCompat:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    const/4 v1, 0x0

    invoke-virtual {p1}, Ljava/lang/String;->length()I

    move-result v2

    invoke-interface {v0, p1, v1, v2}, Landroid/support/v4/text/TextDirectionHeuristicCompat;->isRtl(Ljava/lang/CharSequence;II)Z

    move-result v0

    return v0
.end method

.method public isRtlContext()Z
    .locals 1

    .prologue
    .line 270
    iget-boolean v0, p0, Landroid/support/v4/text/BidiFormatter;->mIsRtlContext:Z

    return v0
.end method

.method public unicodeWrap(Ljava/lang/String;)Ljava/lang/String;
    .locals 2
    .parameter "str"

    .prologue
    .line 427
    iget-object v0, p0, Landroid/support/v4/text/BidiFormatter;->mDefaultTextDirectionHeuristicCompat:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    const/4 v1, 0x1

    invoke-virtual {p0, p1, v0, v1}, Landroid/support/v4/text/BidiFormatter;->unicodeWrap(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;Z)Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public unicodeWrap(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;)Ljava/lang/String;
    .locals 1
    .parameter "str"
    .parameter "heuristic"

    .prologue
    .line 403
    const/4 v0, 0x1

    invoke-virtual {p0, p1, p2, v0}, Landroid/support/v4/text/BidiFormatter;->unicodeWrap(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;Z)Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public unicodeWrap(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;Z)Ljava/lang/String;
    .locals 4
    .parameter "str"
    .parameter "heuristic"
    .parameter "isolate"

    .prologue
    .line 374
    const/4 v2, 0x0

    invoke-virtual {p1}, Ljava/lang/String;->length()I

    move-result v3

    invoke-interface {p2, p1, v2, v3}, Landroid/support/v4/text/TextDirectionHeuristicCompat;->isRtl(Ljava/lang/CharSequence;II)Z

    move-result v0

    .line 375
    .local v0, isRtl:Z
    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    .line 376
    .local v1, result:Ljava/lang/StringBuilder;
    invoke-virtual {p0}, Landroid/support/v4/text/BidiFormatter;->getStereoReset()Z

    move-result v2

    if-eqz v2, :cond_0

    if-eqz p3, :cond_0

    .line 377
    if-eqz v0, :cond_2

    sget-object v2, Landroid/support/v4/text/TextDirectionHeuristicsCompat;->RTL:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    :goto_0
    invoke-direct {p0, p1, v2}, Landroid/support/v4/text/BidiFormatter;->markBefore(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 380
    :cond_0
    iget-boolean v2, p0, Landroid/support/v4/text/BidiFormatter;->mIsRtlContext:Z

    if-eq v0, v2, :cond_4

    .line 381
    if-eqz v0, :cond_3

    const/16 v2, 0x202b

    :goto_1
    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 382
    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 383
    const/16 v2, 0x202c

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 387
    :goto_2
    if-eqz p3, :cond_1

    .line 388
    if-eqz v0, :cond_5

    sget-object v2, Landroid/support/v4/text/TextDirectionHeuristicsCompat;->RTL:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    :goto_3
    invoke-direct {p0, p1, v2}, Landroid/support/v4/text/BidiFormatter;->markAfter(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 391
    :cond_1
    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    return-object v2

    .line 377
    :cond_2
    sget-object v2, Landroid/support/v4/text/TextDirectionHeuristicsCompat;->LTR:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    goto :goto_0

    .line 381
    :cond_3
    const/16 v2, 0x202a

    goto :goto_1

    .line 385
    :cond_4
    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    goto :goto_2

    .line 388
    :cond_5
    sget-object v2, Landroid/support/v4/text/TextDirectionHeuristicsCompat;->LTR:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    goto :goto_3
.end method

.method public unicodeWrap(Ljava/lang/String;Z)Ljava/lang/String;
    .locals 1
    .parameter "str"
    .parameter "isolate"

    .prologue
    .line 416
    iget-object v0, p0, Landroid/support/v4/text/BidiFormatter;->mDefaultTextDirectionHeuristicCompat:Landroid/support/v4/text/TextDirectionHeuristicCompat;

    invoke-virtual {p0, p1, v0, p2}, Landroid/support/v4/text/BidiFormatter;->unicodeWrap(Ljava/lang/String;Landroid/support/v4/text/TextDirectionHeuristicCompat;Z)Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
package plan

import (
	"math"

	log "github.com/Sirupsen/logrus"
	"github.com/juju/errors"
	"github.com/pingcap/tidb/context"
	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/expression/aggregation"
	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/model"
	"github.com/pingcap/tidb/mysql"
	"github.com/pingcap/tidb/util/ranger"
	"github.com/pingcap/tidb/util/types"
)

const (
	netWorkFactor      = 1.5
	netWorkStartFactor = 20.0
	scanFactor         = 2.0
	descScanFactor     = 5 * scanFactor
	memoryFactor       = 5.0
	hashAggMemFactor   = 2.0
	selectionFactor    = 0.8
	distinctFactor     = 0.8
	cpuFactor          = 0.9
	aggFactor          = 0.1
	joinFactor         = 0.3
)

// JoinConcurrency means the number of goroutines that participate in joining.
var JoinConcurrency = 5

func (p *DataSource) convert2TableScan(prop *requiredProperty) (*physicalPlanInfo, error) {
	client := p.ctx.GetClient()
	ts := PhysicalTableScan{
		Table:   p.tableInfo,
		Columns: p.Columns,
		DBName:  p.DBName,
		physicalTableSource: physicalTableSource{
			client:          client,
			NeedColHandle:   p.NeedColHandle,
			unionScanSchema: p.unionScanSchema,
		},
	}.init(p.allocator, p.ctx)
	ts.SetSchema(p.schema)
	if p.ctx.Txn() != nil {
		ts.readOnly = p.ctx.Txn().IsReadOnly()
	} else {
		ts.readOnly = true
	}

	var resultPlan PhysicalPlan = ts
	table := p.tableInfo
	sc := p.ctx.GetSessionVars().StmtCtx
	ts.Ranges = []types.IntColumnRange{{LowVal: math.MinInt64, HighVal: math.MaxInt64}}
	if len(p.parents) > 0 {
		if sel, ok := p.parents[0].(*Selection); ok {
			newSel := sel.Copy().(*Selection)
			conds := make([]expression.Expression, 0, len(sel.Conditions))
			for _, cond := range sel.Conditions {
				conds = append(conds, cond.Clone())
			}
			ts.AccessCondition, newSel.Conditions = ranger.DetachColumnConditions(conds, table.GetPkName())
			ts.TableConditionPBExpr, ts.tableFilterConditions, newSel.Conditions =
				expression.ExpressionsToPB(sc, newSel.Conditions, client)
			ranges, err := ranger.BuildTableRange(ts.AccessCondition, sc)
			if err != nil {
				return nil, errors.Trace(err)
			}
			ts.Ranges = ranges
			if len(newSel.Conditions) > 0 {
				newSel.SetChildren(ts)
				newSel.onTable = true
				resultPlan = newSel
			}
		}
	}
	statsTbl := p.statisticTable
	rowCount := float64(statsTbl.Count)
	if table.PKIsHandle {
		for i, colInfo := range ts.Columns {
			if mysql.HasPriKeyFlag(colInfo.Flag) {
				ts.pkCol = p.Schema().Columns[i]
				var err error
				rowCount, err = statsTbl.GetRowCountByIntColumnRanges(sc, ts.pkCol.ID, ts.Ranges)
				if err != nil {
					return nil, errors.Trace(err)
				}
				break
			}
		}
	}
	if ts.TableConditionPBExpr != nil {
		rowCount = rowCount * selectionFactor
	}
	return resultPlan.matchProperty(prop, &physicalPlanInfo{count: rowCount, reliable: !statsTbl.Pseudo}), nil
}

func (p *DataSource) convert2IndexScan(prop *requiredProperty, index *model.IndexInfo) (*physicalPlanInfo, error) {
	client := p.ctx.GetClient()
	is := PhysicalIndexScan{
		Index:      index,
		Table:      p.tableInfo,
		Columns:    p.Columns,
		OutOfOrder: true,
		DBName:     p.DBName,
		physicalTableSource: physicalTableSource{
			client:          client,
			NeedColHandle:   p.NeedColHandle,
			unionScanSchema: p.unionScanSchema,
		},
	}.init(p.allocator, p.ctx)
	is.SetSchema(p.schema)
	if p.ctx.Txn() != nil {
		is.readOnly = p.ctx.Txn().IsReadOnly()
	} else {
		is.readOnly = true
	}

	var resultPlan PhysicalPlan = is
	statsTbl := p.statisticTable
	rowCount := float64(statsTbl.Count)
	sc := p.ctx.GetSessionVars().StmtCtx
	is.Ranges = ranger.FullIndexRange()
	if len(p.parents) > 0 {
		if sel, ok := p.parents[0].(*Selection); ok {
			newSel := sel.Copy().(*Selection)
			conds := make([]expression.Expression, 0, len(sel.Conditions))
			for _, cond := range sel.Conditions {
				conds = append(conds, cond.Clone())
			}
			is.AccessCondition, newSel.Conditions, is.accessEqualCount, is.accessInAndEqCount = ranger.DetachIndexScanConditions(conds, is.Index)
			memDB := infoschema.IsMemoryDB(p.DBName.L)
			isDistReq := !memDB && client != nil && client.IsRequestTypeSupported(kv.ReqTypeIndex, 0)
			if isDistReq {
				idxConds, tblConds := ranger.DetachIndexFilterConditions(newSel.Conditions, is.Index.Columns, is.Table)
				is.IndexConditionPBExpr, is.indexFilterConditions, idxConds = expression.ExpressionsToPB(sc, idxConds, client)
				is.TableConditionPBExpr, is.tableFilterConditions, tblConds = expression.ExpressionsToPB(sc, tblConds, client)
				newSel.Conditions = append(idxConds, tblConds...)
			}
			var err error
			is.Ranges, err = ranger.BuildIndexRange(p.ctx.GetSessionVars().StmtCtx, is.Table, is.Index, is.accessInAndEqCount, is.AccessCondition)
			if err != nil {
				if !types.ErrTruncated.Equal(err) {
					return nil, errors.Trace(err)
				}
				log.Warn("truncate error in buildIndexRange")
			}
			rowCount, err = statsTbl.GetRowCountByIndexRanges(sc, is.Index.ID, is.Ranges)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if len(newSel.Conditions) > 0 {
				newSel.SetChildren(is)
				newSel.onTable = true
				resultPlan = newSel
			}
		}
	}
	is.DoubleRead = !isCoveringIndex(is.Columns, is.Index.Columns, is.Table.PKIsHandle)
	return resultPlan.matchProperty(prop, &physicalPlanInfo{count: rowCount, reliable: !statsTbl.Pseudo}), nil
}

func isCoveringIndex(columns []*model.ColumnInfo, indexColumns []*model.IndexColumn, pkIsHandle bool) bool {
	for _, colInfo := range columns {
		if pkIsHandle && mysql.HasPriKeyFlag(colInfo.Flag) {
			continue
		}
		if colInfo.ID == model.ExtraHandleID {
			continue
		}
		isIndexColumn := false
		for _, indexCol := range indexColumns {
			if colInfo.Name.L == indexCol.Name.L && indexCol.Length == types.UnspecifiedLength {
				isIndexColumn = true
				break
			}
		}
		if !isIndexColumn {
			return false
		}
	}
	return true
}

func (p *DataSource) need2ConsiderIndex(prop *requiredProperty) bool {
	if len(p.parents) == 0 {
		return len(prop.props) > 0
	}
	if _, ok := p.parents[0].(*Selection); ok || len(prop.props) > 0 {
		return true
	}
	return false
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
// If there is no index that matches the required property, the returned physicalPlanInfo
// will be table scan and has the cost of MaxInt64. But this can be ignored because the parent will call
// convert2PhysicalPlan again with an empty *requiredProperty, so the plan with the lowest
// cost will be chosen.
func (p *DataSource) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	info, err = p.tryToConvert2DummyScan(prop)
	if info != nil || err != nil {
		return info, errors.Trace(err)
	}
	client := p.ctx.GetClient()
	memDB := infoschema.IsMemoryDB(p.DBName.L)
	isDistReq := !memDB && client != nil && client.IsRequestTypeSupported(kv.ReqTypeSelect, 0)
	if !isDistReq {
		memTable := PhysicalMemTable{
			DBName:  p.DBName,
			Table:   p.tableInfo,
			Columns: p.Columns,
		}.init(p.allocator, p.ctx)
		memTable.SetSchema(p.schema)
		memTable.Ranges = ranger.FullIntRange()
		info = &physicalPlanInfo{p: memTable}
		info = enforceProperty(prop, info)
		return info, errors.Trace(p.storePlanInfo(prop, info))
	}
	indices, includeTableScan := availableIndices(p.indexHints, p.tableInfo)
	if includeTableScan {
		info, err = p.convert2TableScan(prop)
		if err != nil {
			return nil, errors.Trace(err)
		}
	}
	if !includeTableScan || p.need2ConsiderIndex(prop) {
		for _, index := range indices {
			indexInfo, err := p.convert2IndexScan(prop, index)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if info == nil || indexInfo.cost < info.cost {
				info = indexInfo
			}
		}
	}
	return info, errors.Trace(p.storePlanInfo(prop, info))
}

// tryToConvert2DummyScan is an optimization which checks if its parent is a selection with a constant condition
// that evaluates to false. If it is, there is no need for a real physical scan, a dummy scan will do.
func (p *DataSource) tryToConvert2DummyScan(prop *requiredProperty) (*physicalPlanInfo, error) {
	if len(p.Parents()) == 0 {
		return nil, nil
	}
	sel, isSel := p.parents[0].(*Selection)
	if !isSel {
		return nil, nil
	}

	for _, cond := range sel.Conditions {
		if con, ok := cond.(*expression.Constant); ok {
			result, err := expression.EvalBool([]expression.Expression{con}, nil, p.ctx)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if !result {
				dual := TableDual{}.init(p.allocator, p.ctx)
				dual.SetSchema(p.schema)
				info := &physicalPlanInfo{p: dual}
				return info, errors.Trace(p.storePlanInfo(prop, info))
			}
		}
	}
	return nil, nil
}

// addPlanToResponse creates a *physicalPlanInfo that adds p as the parent of info.
func addPlanToResponse(parent PhysicalPlan, info *physicalPlanInfo) *physicalPlanInfo {
	np := parent.Copy()
	np.SetChildren(info.p)
	ret := &physicalPlanInfo{p: np, cost: info.cost, count: info.count, reliable: info.reliable}
	if _, ok := parent.(*MaxOneRow); ok {
		ret.count = 1
		ret.reliable = true
	}
	return ret
}

// enforceProperty creates a *physicalPlanInfo that satisfies the required property by adding
// sort or limit as the parent of the given physical plan.
func enforceProperty(prop *requiredProperty, info *physicalPlanInfo) *physicalPlanInfo {
	if info.p == nil {
		return info
	}
	if len(prop.props) != 0 {
		items := make([]*ByItems, 0, len(prop.props))
		for _, col := range prop.props {
			items = append(items, &ByItems{Expr: col.col, Desc: col.desc})
		}
		sort := Sort{
			ByItems:   items,
			ExecLimit: prop.limit,
		}.init(info.p.Allocator(), info.p.context())
		sort.SetSchema(info.p.Schema())
		info = addPlanToResponse(sort, info)

		count := info.count
		if prop.limit != nil {
			count = float64(prop.limit.Offset + prop.limit.Count)
			info.reliable = true
		}
		info.cost += sortCost(count)
	} else if prop.limit != nil {
		limit := Limit{Offset: prop.limit.Offset, Count: prop.limit.Count}.init(info.p.Allocator(), info.p.context())
		limit.SetSchema(info.p.Schema())
		info = addPlanToResponse(limit, info)
		info.reliable = true
	}
	if prop.limit != nil && float64(prop.limit.Count) < info.count {
		info.count = float64(prop.limit.Count)
	}
	return info
}

func sortCost(cnt float64) float64 {
	if cnt == 0 {
		// If cnt is 0, the log(cnt) will be NAN.
		return 0.0
	}
	return cnt*math.Log2(cnt)*cpuFactor + memoryFactor*cnt
}

// removeLimit removes the limit from prop.
func removeLimit(prop *requiredProperty) *requiredProperty {
	ret := &requiredProperty{
		props:      prop.props,
		sortKeyLen: prop.sortKeyLen,
	}
	return ret
}

func removeSortOrder(prop *requiredProperty) *requiredProperty {
	ret := &requiredProperty{
		limit: prop.limit,
	}
	return ret
}

// convertLimitOffsetToCount changes the limit(offset, count) in prop to limit(0, offset + count).
func convertLimitOffsetToCount(prop *requiredProperty) *requiredProperty {
	ret := &requiredProperty{
		props:      prop.props,
		sortKeyLen: prop.sortKeyLen,
	}
	if prop.limit != nil {
		ret.limit = &Limit{
			Count: prop.limit.Offset + prop.limit.Count,
		}
	}
	return ret
}

func limitProperty(limit *Limit) *requiredProperty {
	return &requiredProperty{limit: limit}
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *Limit) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	info, err = p.children[0].(LogicalPlan).convert2PhysicalPlan(limitProperty(&Limit{Offset: p.Offset, Count: p.Count}))
	if err != nil {
		return nil, errors.Trace(err)
	}
	info = enforceProperty(prop, info)
	return info, errors.Trace(p.storePlanInfo(prop, info))
}

// convert2PhysicalPlanSemi converts the semi join to *physicalPlanInfo.
func (p *LogicalJoin) convert2PhysicalPlanSemi(prop *requiredProperty) (*physicalPlanInfo, error) {
	lChild := p.children[0].(LogicalPlan)
	rChild := p.children[1].(LogicalPlan)
	allLeft := true
	for _, col := range prop.props {
		if !lChild.Schema().Contains(col.col) {
			allLeft = false
		}
	}
	join := PhysicalHashSemiJoin{
		WithAux:         LeftOuterSemiJoin == p.JoinType,
		EqualConditions: p.EqualConditions,
		LeftConditions:  p.LeftConditions,
		RightConditions: p.RightConditions,
		OtherConditions: p.OtherConditions,
		Anti:            p.anti,
	}.init(p.allocator, p.ctx)
	join.SetSchema(p.schema)
	lProp := prop
	if !allLeft {
		lProp = &requiredProperty{}
	}
	if p.JoinType == SemiJoin {
		lProp = removeLimit(lProp)
	}
	lInfo, err := lChild.convert2PhysicalPlan(lProp)
	if err != nil {
		return nil, errors.Trace(err)
	}
	rInfo, err := rChild.convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	resultInfo := join.matchProperty(prop, lInfo, rInfo)
	if p.JoinType == SemiJoin {
		resultInfo.count = lInfo.count * selectionFactor
	} else {
		resultInfo.count = lInfo.count
	}
	if !allLeft {
		resultInfo = enforceProperty(prop, resultInfo)
	} else if p.JoinType == SemiJoin {
		resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
	}
	return resultInfo, nil
}

// convert2PhysicalPlanLeft converts the left join to *physicalPlanInfo.
func (p *LogicalJoin) convert2PhysicalPlanLeft(prop *requiredProperty, innerJoin bool) (*physicalPlanInfo, error) {
	lChild := p.children[0].(LogicalPlan)
	rChild := p.children[1].(LogicalPlan)
	allLeft := true
	for _, col := range prop.props {
		if !lChild.Schema().Contains(col.col) {
			allLeft = false
		}
	}
	join := PhysicalHashJoin{
		EqualConditions: p.EqualConditions,
		LeftConditions:  p.LeftConditions,
		RightConditions: p.RightConditions,
		OtherConditions: p.OtherConditions,
		SmallTable:      1,
		// TODO: decide concurrency by data size.
		Concurrency:   JoinConcurrency,
		DefaultValues: p.DefaultValues,
	}.init(p.allocator, p.ctx)
	join.SetSchema(p.schema)
	if innerJoin {
		join.JoinType = InnerJoin
	} else {
		join.JoinType = LeftOuterJoin
	}
	lProp := prop
	if !allLeft {
		lProp = &requiredProperty{}
	}
	var lInfo *physicalPlanInfo
	var err error
	if innerJoin {
		lInfo, err = lChild.convert2PhysicalPlan(removeLimit(lProp))
	} else {
		lInfo, err = lChild.convert2PhysicalPlan(convertLimitOffsetToCount(lProp))
	}
	if err != nil {
		return nil, errors.Trace(err)
	}
	rInfo, err := rChild.convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	resultInfo := join.matchProperty(prop, lInfo, rInfo)
	if !allLeft {
		resultInfo = enforceProperty(prop, resultInfo)
	} else {
		resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
	}
	return resultInfo, nil
}

// replaceColsInPropBySchema replaces the columns in original prop with the columns in schema.
func replaceColsInPropBySchema(prop *requiredProperty, schema *expression.Schema) *requiredProperty {
	newProps := make([]*columnProp, 0, len(prop.props))
	for _, p := range prop.props {
		idx := schema.ColumnIndex(p.col)
		if idx == -1 {
			log.Errorf("Can't find column %s in schema", p.col)
		}
		newProps = append(newProps, &columnProp{col: schema.Columns[idx], desc: p.desc})
	}
	return &requiredProperty{
		props:      newProps,
		sortKeyLen: prop.sortKeyLen,
		limit:      prop.limit,
	}
}

// convert2PhysicalPlanRight converts the right join to *physicalPlanInfo.
func (p *LogicalJoin) convert2PhysicalPlanRight(prop *requiredProperty, innerJoin bool) (*physicalPlanInfo, error) {
	lChild := p.children[0].(LogicalPlan)
	rChild := p.children[1].(LogicalPlan)
	allRight := true
	for _, col := range prop.props {
		if !rChild.Schema().Contains(col.col) {
			allRight = false
		}
	}
	join := PhysicalHashJoin{
		EqualConditions: p.EqualConditions,
		LeftConditions:  p.LeftConditions,
		RightConditions: p.RightConditions,
		OtherConditions: p.OtherConditions,
		// TODO: decide concurrency by data size.
		Concurrency:   JoinConcurrency,
		DefaultValues: p.DefaultValues,
	}.init(p.allocator, p.ctx)
	join.SetSchema(p.schema)
	if innerJoin {
		join.JoinType = InnerJoin
	} else {
		join.JoinType = RightOuterJoin
	}
	lInfo, err := lChild.convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	rProp := prop
	if !allRight {
		rProp = &requiredProperty{}
	} else {
		rProp = replaceColsInPropBySchema(rProp, rChild.Schema())
	}
	var rInfo *physicalPlanInfo
	if innerJoin {
		rInfo, err = rChild.convert2PhysicalPlan(removeLimit(rProp))
	} else {
		rInfo, err = rChild.convert2PhysicalPlan(convertLimitOffsetToCount(rProp))
	}
	if err != nil {
		return nil, errors.Trace(err)
	}
	resultInfo := join.matchProperty(prop, lInfo, rInfo)
	if !allRight {
		resultInfo = enforceProperty(prop, resultInfo)
	} else {
		resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
	}
	return resultInfo, nil
}

// buildSelectionWithConds will build a selection use the conditions of join and convert one side's column to correlated column.
// If the inner side is one selection then one data source, the inner child should be the data source other than the selection.
// This is called when build nested loop join.
func (p *LogicalJoin) buildSelectionWithConds(leftAsOuter bool) (*Selection, []*expression.CorrelatedColumn) {
	var (
		outerSchema     *expression.Schema
		innerChild      Plan
		innerConditions []expression.Expression
	)
	if leftAsOuter {
		outerSchema = p.children[0].Schema()
		innerConditions = p.RightConditions
		innerChild = p.children[1]
	} else {
		outerSchema = p.children[1].Schema()
		innerConditions = p.LeftConditions
		innerChild = p.children[0]
	}
	if sel, ok := innerChild.(*Selection); ok {
		innerConditions = append(innerConditions, sel.Conditions...)
		innerChild = sel.children[0]
	}
	corCols := make([]*expression.CorrelatedColumn, 0, outerSchema.Len())
	for _, col := range outerSchema.Columns {
		corCol := &expression.CorrelatedColumn{Column: *col, Data: new(types.Datum)}
		corCol.Column.ResolveIndices(outerSchema)
		corCols = append(corCols, corCol)
	}
	selection := Selection{}.init(p.allocator, p.ctx)
	selection.SetSchema(innerChild.Schema().Clone())
	selection.SetChildren(innerChild)
	conds := make([]expression.Expression, 0, len(p.EqualConditions)+len(innerConditions)+len(p.OtherConditions))
	for _, cond := range p.EqualConditions {
		newCond := expression.ConvertCol2CorCol(cond, corCols, outerSchema)
		conds = append(conds, newCond)
	}
	selection.Conditions = conds
	conds = append(conds, innerConditions...)
	for _, cond := range p.OtherConditions {
		newCond := expression.ConvertCol2CorCol(cond, corCols, outerSchema)
		newCond.ResolveIndices(innerChild.Schema())
		conds = append(conds, newCond)
	}
	selection.Conditions = conds
	return selection, corCols
}

// outerTableCouldINLJ will check the whether is forced to build index nested loop join or outer info is reliable
// and the count satisfies the condition.
func (p *LogicalJoin) outerTableCouldINLJ(outerInfo *physicalPlanInfo, leftAsOuter bool) bool {
	var forced bool
	if leftAsOuter {
		forced = (p.preferINLJ&preferLeftAsOuter) > 0 && p.hasEqualConds()
	} else {
		forced = (p.preferINLJ&preferRightAsOuter) > 0 && p.hasEqualConds()
	}
	return forced || (outerInfo.reliable && outerInfo.count <= float64(p.ctx.GetSessionVars().MaxRowCountForINLJ))
}

func (p *LogicalJoin) convert2IndexNestedLoopJoinLeft(prop *requiredProperty, innerJoin bool) (*physicalPlanInfo, error) {
	lChild := p.children[0].(LogicalPlan)
	switch x := p.children[1].(type) {
	case *DataSource:
	case *Selection:
		if _, ok := x.children[0].(*DataSource); !ok {
			return nil, nil
		}
	default:
		return nil, nil
	}
	allLeft := true
	for _, col := range prop.props {
		if !lChild.Schema().Contains(col.col) {
			allLeft = false
		}
	}
	lProp := prop
	if !allLeft {
		lProp = &requiredProperty{}
	} else {
		lProp = replaceColsInPropBySchema(prop, lChild.Schema())
	}
	var lInfo *physicalPlanInfo
	var err error
	if innerJoin {
		lInfo, err = lChild.convert2PhysicalPlan(removeLimit(lProp))
	} else {
		lInfo, err = lChild.convert2PhysicalPlan(convertLimitOffsetToCount(lProp))
	}
	if err != nil {
		return nil, errors.Trace(err)
	}
	if lInfo.p == nil {
		return nil, nil
	}
	// If the outer table's row count is reliable and don't exceed the MaxRowCountForINLJ or we use hint to force
	// choosing index nested loop join, we will continue building. Otherwise we just break and return nil.
	if !p.outerTableCouldINLJ(lInfo, true) {
		return nil, nil
	}
	selection, corCols := p.buildSelectionWithConds(true)
	if selection == nil {
		return nil, nil
	}
	rInfo := selection.makeScanController()
	join := PhysicalHashJoin{
		LeftConditions: p.LeftConditions,
		// TODO: decide concurrency by data size.
		Concurrency:   JoinConcurrency,
		DefaultValues: p.DefaultValues,
		SmallTable:    1,
	}.init(p.allocator, p.ctx)
	join.SetChildren(lInfo.p, rInfo.p)
	if innerJoin {
		join.JoinType = InnerJoin
	} else {
		join.JoinType = LeftOuterJoin
	}
	join.SetSchema(p.Schema())
	resultInfo := join.matchProperty(prop, lInfo, rInfo)
	ap := PhysicalApply{
		PhysicalJoin: resultInfo.p,
		OuterSchema:  corCols,
	}.init(p.allocator, p.ctx)
	ap.SetChildren(resultInfo.p.Children()...)
	ap.SetSchema(resultInfo.p.Schema())
	resultInfo.p = ap
	if !allLeft {
		resultInfo = enforceProperty(prop, resultInfo)
	} else {
		resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
	}
	return resultInfo, nil
}

func (p *LogicalJoin) convert2IndexNestedLoopJoinRight(prop *requiredProperty, innerJoin bool) (*physicalPlanInfo, error) {
	rChild := p.children[1].(LogicalPlan)
	switch x := p.children[0].(type) {
	case *DataSource:
	case *Selection:
		if _, ok := x.children[0].(*DataSource); !ok {
			return nil, nil
		}
	default:
		return nil, nil
	}
	allRight := true
	for _, col := range prop.props {
		if !rChild.Schema().Contains(col.col) {
			allRight = false
		}
	}
	rProp := prop
	if !allRight {
		rProp = &requiredProperty{}
	} else {
		rProp = replaceColsInPropBySchema(prop, rChild.Schema())
	}
	var rInfo *physicalPlanInfo
	var err error
	if innerJoin {
		rInfo, err = rChild.convert2PhysicalPlan(removeLimit(rProp))
	} else {
		rInfo, err = rChild.convert2PhysicalPlan(convertLimitOffsetToCount(rProp))
	}
	if err != nil {
		return nil, errors.Trace(err)
	}
	if rInfo.p == nil {
		return nil, nil
	}
	// If the outer table's row count is reliable and don't exceed the MaxRowCountForINLJ or we use hint to force
	// choosing index nested loop join, we will continue building. Otherwise we just break and return nil.
	if !p.outerTableCouldINLJ(rInfo, false) {
		return nil, nil
	}
	selection, corCols := p.buildSelectionWithConds(false)
	if selection == nil {
		return nil, nil
	}
	lInfo := selection.makeScanController()
	join := PhysicalHashJoin{
		RightConditions: p.RightConditions,
		// TODO: decide concurrency by data size.
		Concurrency:   JoinConcurrency,
		DefaultValues: p.DefaultValues,
	}.init(p.allocator, p.ctx)
	join.SetChildren(lInfo.p, rInfo.p)
	if innerJoin {
		join.JoinType = InnerJoin
	} else {
		join.JoinType = RightOuterJoin
	}
	join.SetSchema(p.Schema())
	resultInfo := join.matchProperty(prop, lInfo, rInfo)
	ap := PhysicalApply{
		PhysicalJoin: resultInfo.p,
		OuterSchema:  corCols,
	}.init(p.allocator, p.ctx)
	ap.SetChildren(resultInfo.p.Children()...)
	ap.SetSchema(resultInfo.p.Schema())
	resultInfo.p = ap
	if !allRight {
		resultInfo = enforceProperty(prop, resultInfo)
	} else {
		resultInfo = enforceProperty(limitProperty(prop.limit), resultInfo)
	}
	return resultInfo, nil
}

func generateJoinProp(column *expression.Column) *requiredProperty {
	return &requiredProperty{
		props:      []*columnProp{{column, false}},
		sortKeyLen: 1,
	}
}

func compareTypeForOrder(lhs *types.FieldType, rhs *types.FieldType) bool {
	if lhs.Tp != rhs.Tp {
		return false
	}
	if lhs.EvalType().IsStringKind() && (lhs.Charset != rhs.Charset || lhs.Collate != rhs.Collate) {
		return false
	}
	return true
}

// constructPropertyByJoin generates all possible combinations from join conditions for cost evaluation
// It will try all keys in join conditions
func constructPropertyByJoin(join *LogicalJoin) ([][]*requiredProperty, []int, error) {
	var result [][]*requiredProperty
	var condIndex []int

	if join.EqualConditions == nil {
		return nil, nil, nil
	}
	for i, cond := range join.EqualConditions {
		if len(cond.GetArgs()) != 2 {
			return nil, nil, errors.New("unexpected argument count for equal expression")
		}
		lExpr, rExpr := cond.GetArgs()[0], cond.GetArgs()[1]
		// Only consider raw column reference and cowardly ignore calculations
		// since we don't know if the function call preserve order
		lColumn, lOK := lExpr.(*expression.Column)
		rColumn, rOK := rExpr.(*expression.Column)
		if lOK && rOK && compareTypeForOrder(lColumn.RetType, rColumn.RetType) {
			result = append(result, []*requiredProperty{generateJoinProp(lColumn), generateJoinProp(rColumn)})
			condIndex = append(condIndex, i)
		} else {
			continue
		}
	}
	if len(result) == 0 {
		return nil, nil, nil
	}
	return result, condIndex, nil
}

// convert2PhysicalMergeJoin converts the merge join to *physicalPlanInfo.
// TODO: Refactor and merge with hash join
func (p *LogicalJoin) convert2PhysicalMergeJoin(parentProp *requiredProperty, lProp *requiredProperty, rProp *requiredProperty, condIndex int, joinType JoinType) (*physicalPlanInfo, error) {
	lChild := p.children[0].(LogicalPlan)
	rChild := p.children[1].(LogicalPlan)

	newEQConds := make([]*expression.ScalarFunction, 0, len(p.EqualConditions)-1)
	for i, cond := range p.EqualConditions {
		if i == condIndex {
			continue
		}
		// prevent further index contamination
		newCond := cond.Clone()
		newCond.ResolveIndices(p.schema)
		newEQConds = append(newEQConds, newCond.(*expression.ScalarFunction))
	}
	eqCond := p.EqualConditions[condIndex]

	otherFilter := append(expression.ScalarFuncs2Exprs(newEQConds), p.OtherConditions...)

	join := PhysicalMergeJoin{
		EqualConditions: []*expression.ScalarFunction{eqCond},
		LeftConditions:  p.LeftConditions,
		RightConditions: p.RightConditions,
		OtherConditions: otherFilter,
		DefaultValues:   p.DefaultValues,
		// Assume order for both side are the same
		Desc: lProp.props[0].desc,
	}.init(p.allocator, p.ctx)
	join.SetSchema(p.schema)
	join.JoinType = joinType

	var lInfo *physicalPlanInfo
	var rInfo *physicalPlanInfo

	// Try no sort first
	lInfoEnforceSort, err := lChild.convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}

	lInfoEnforceSort = enforceProperty(lProp, lInfoEnforceSort)

	lInfoNoSorted, err := lChild.convert2PhysicalPlan(lProp)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if lInfoNoSorted.cost < lInfoEnforceSort.cost {
		lInfo = lInfoNoSorted
	} else {
		lInfo = lInfoEnforceSort
	}

	rInfoEnforceSort, err := rChild.convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	rInfoEnforceSort = enforceProperty(rProp, rInfoEnforceSort)

	rInfoNoSorted, err := rChild.convert2PhysicalPlan(rProp)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if rInfoEnforceSort.cost < rInfoNoSorted.cost {
		rInfo = rInfoEnforceSort
	} else {
		rInfo = rInfoNoSorted
	}
	parentProp = join.tryConsumeOrder(parentProp, eqCond)

	resultInfo := join.matchProperty(parentProp, lInfo, rInfo)
	// TODO: Considering keeping order in join to remove at least
	// one ordering property
	resultInfo = enforceProperty(parentProp, resultInfo)
	return resultInfo, nil
}

func (p *LogicalJoin) convert2PhysicalMergeJoinOnCost(prop *requiredProperty) (*physicalPlanInfo, error) {
	var info *physicalPlanInfo
	reqPropPairs, condIndex, err := constructPropertyByJoin(p)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if reqPropPairs == nil {
		return nil, nil
	}
	minCost := math.MaxFloat64
	var minInfo *physicalPlanInfo
	for i, reqPropPair := range reqPropPairs {
		info, err = p.convert2PhysicalMergeJoin(prop, reqPropPair[0], reqPropPair[1], condIndex[i], p.JoinType)
		if err != nil {
			return nil, errors.Trace(err)
		}
		// Force to choose first instead of nil if all Inf cost
		// TODO: Consider cost instead of force merge
		if minInfo == nil {
			minInfo = info
			minCost = info.cost
		} else {
			if info.cost <= minCost {
				minInfo = info
				minCost = info.cost
			}
		}
	}
	return minInfo, nil
}

func (p *LogicalJoin) hasEqualConds() bool {
	return len(p.EqualConditions) != 0
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *LogicalJoin) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	switch p.JoinType {
	case SemiJoin, LeftOuterSemiJoin:
		info, err = p.convert2PhysicalPlanSemi(prop)
		if err != nil {
			return nil, errors.Trace(err)
		}
	case LeftOuterJoin:
		if p.preferMergeJoin && p.hasEqualConds() {
			info, err = p.convert2PhysicalMergeJoinOnCost(prop)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if info != nil {
				break
			}
		}

		var nljInfo *physicalPlanInfo
		nljInfo, err = p.convert2IndexNestedLoopJoinLeft(prop, false)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if nljInfo != nil {
			info = nljInfo
			break
		}
		// Otherwise fall into hash join
		info, err = p.convert2PhysicalPlanLeft(prop, false)
		if err != nil {
			return nil, errors.Trace(err)
		}
	case RightOuterJoin:
		if p.preferMergeJoin && p.hasEqualConds() {
			info, err = p.convert2PhysicalMergeJoinOnCost(prop)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if info != nil {
				break
			}
		}
		var nljInfo *physicalPlanInfo
		nljInfo, err = p.convert2IndexNestedLoopJoinRight(prop, false)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if nljInfo != nil {
			info = nljInfo
			break
		}
		info, err = p.convert2PhysicalPlanRight(prop, false)
		if err != nil {
			return nil, errors.Trace(err)
		}
	default:
		// Inner Join
		if p.preferMergeJoin && p.hasEqualConds() {
			info, err = p.convert2PhysicalMergeJoinOnCost(prop)
			if err != nil {
				return nil, errors.Trace(err)
			}
			break
		}
		lNLJInfo, err := p.convert2IndexNestedLoopJoinLeft(prop, true)
		if err != nil {
			return nil, errors.Trace(err)
		}
		rNLJInfo, err := p.convert2IndexNestedLoopJoinRight(prop, true)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if lNLJInfo != nil {
			info = lNLJInfo
		}
		if info == nil || (rNLJInfo != nil && info.cost > rNLJInfo.cost) {
			info = rNLJInfo
		}
		if info != nil {
			break
		}
		// fall back to hash join
		lInfo, err := p.convert2PhysicalPlanLeft(prop, true)
		if err != nil {
			return nil, errors.Trace(err)
		}
		rInfo, err := p.convert2PhysicalPlanRight(prop, true)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if rInfo.cost < lInfo.cost {
			info = rInfo
		} else {
			info = lInfo
		}
	}
	return info, errors.Trace(p.storePlanInfo(prop, info))
}

// convert2PhysicalPlanStream converts the logical aggregation to the stream aggregation *physicalPlanInfo.
func (p *LogicalAggregation) convert2PhysicalPlanStream(prop *requiredProperty) (*physicalPlanInfo, error) {
	for _, aggFunc := range p.AggFuncs {
		if aggFunc.GetMode() == aggregation.FinalMode {
			return &physicalPlanInfo{cost: math.MaxFloat64}, nil
		}
	}
	agg := PhysicalAggregation{
		AggType:      StreamedAgg,
		AggFuncs:     p.AggFuncs,
		GroupByItems: p.GroupByItems,
	}.init(p.allocator, p.ctx)
	agg.HasGby = len(p.GroupByItems) > 0
	agg.SetSchema(p.schema)
	// TODO: Consider distinct key.
	info := &physicalPlanInfo{cost: math.MaxFloat64}
	gbyCols := p.groupByCols
	if len(gbyCols) != len(p.GroupByItems) {
		// group by a + b is not interested in any order.
		return info, nil
	}
	isSortKey := make([]bool, len(gbyCols))
	newProp := &requiredProperty{
		props: make([]*columnProp, 0, len(gbyCols)),
	}
	for _, pro := range prop.props {
		idx := p.getGbyColIndex(pro.col)
		if idx == -1 {
			return info, nil
		}
		isSortKey[idx] = true
		// We should add columns in aggregation in order to keep index right.
		newProp.props = append(newProp.props, &columnProp{col: gbyCols[idx], desc: pro.desc})
	}
	newProp.sortKeyLen = len(newProp.props)
	for i, col := range gbyCols {
		if !isSortKey[i] {
			newProp.props = append(newProp.props, &columnProp{col: col})
		}
	}
	childInfo, err := p.children[0].(LogicalPlan).convert2PhysicalPlan(newProp)
	if err != nil {
		return nil, errors.Trace(err)
	}
	info = addPlanToResponse(agg, childInfo)
	info.cost += info.count * cpuFactor
	info.count = info.count * aggFactor
	return info, nil
}

// convert2PhysicalPlanFinalHash converts the logical aggregation to the final hash aggregation *physicalPlanInfo.
func (p *LogicalAggregation) convert2PhysicalPlanFinalHash(x physicalDistSQLPlan, childInfo *physicalPlanInfo) *physicalPlanInfo {
	agg := PhysicalAggregation{
		AggType:      FinalAgg,
		AggFuncs:     p.AggFuncs,
		GroupByItems: p.GroupByItems,
	}.init(p.allocator, p.ctx)
	agg.SetSchema(p.schema)
	agg.HasGby = len(p.GroupByItems) > 0
	schema := x.addAggregation(p.ctx, agg)
	if schema.Len() == 0 {
		return nil
	}
	x.(PhysicalPlan).SetSchema(schema)
	info := addPlanToResponse(agg, childInfo)
	info.count = info.count * aggFactor
	// if we build the final aggregation, it must be the best plan.
	info.cost = 0
	return info
}

// convert2PhysicalPlanCompleteHash converts the logical aggregation to the complete hash aggregation *physicalPlanInfo.
func (p *LogicalAggregation) convert2PhysicalPlanCompleteHash(childInfo *physicalPlanInfo) *physicalPlanInfo {
	agg := PhysicalAggregation{
		AggType:      CompleteAgg,
		AggFuncs:     p.AggFuncs,
		GroupByItems: p.GroupByItems,
	}.init(p.allocator, p.ctx)
	agg.HasGby = len(p.GroupByItems) > 0
	agg.SetSchema(p.schema)
	info := addPlanToResponse(agg, childInfo)
	info.cost += info.count * memoryFactor
	info.count = info.count * aggFactor
	return info
}

// convert2PhysicalPlanHash converts the logical aggregation to the physical hash aggregation.
func (p *LogicalAggregation) convert2PhysicalPlanHash() (*physicalPlanInfo, error) {
	childInfo, err := p.children[0].(LogicalPlan).convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	distinct := false
	for _, fun := range p.AggFuncs {
		if fun.IsDistinct() {
			distinct = true
			break
		}
	}
	if !distinct {
		if x, ok := childInfo.p.(physicalDistSQLPlan); ok {
			info := p.convert2PhysicalPlanFinalHash(x, childInfo)
			if info != nil {
				return info, nil
			}
		}
	}
	return p.convert2PhysicalPlanCompleteHash(childInfo), nil
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *LogicalAggregation) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	planInfo, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if planInfo != nil {
		return planInfo, nil
	}
	limit := prop.limit
	if len(prop.props) == 0 {
		planInfo, err = p.convert2PhysicalPlanHash()
		if err != nil {
			return nil, errors.Trace(err)
		}
	}
	streamInfo, err := p.convert2PhysicalPlanStream(removeLimit(prop))
	if err != nil {
		return nil, errors.Trace(err)
	}
	if planInfo == nil || streamInfo.cost < planInfo.cost {
		planInfo = streamInfo
	}
	planInfo = enforceProperty(limitProperty(limit), planInfo)
	return planInfo, errors.Trace(p.storePlanInfo(prop, planInfo))
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *Union) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	limit := prop.limit
	childInfos := make([]*physicalPlanInfo, 0, len(p.children))
	for _, child := range p.Children() {
		newProp := &requiredProperty{}
		if limit != nil {
			newProp = convertLimitOffsetToCount(prop)
			newProp.props = make([]*columnProp, 0, len(prop.props))
			for _, c := range prop.props {
				idx := p.Schema().ColumnIndex(c.col)
				newProp.props = append(newProp.props, &columnProp{col: child.Schema().Columns[idx], desc: c.desc})
			}
		}
		childInfo, err := child.(LogicalPlan).convert2PhysicalPlan(newProp)
		if err != nil {
			return nil, errors.Trace(err)
		}
		childInfos = append(childInfos, childInfo)
	}
	info = p.matchProperty(prop, childInfos...)
	info = enforceProperty(prop, info)
	return info, errors.Trace(p.storePlanInfo(prop, info))
}

// makeScanController will try to build a selection that controls the below scan's filter condition,
// and return a physicalPlanInfo. If the onlyCheck is true, it will only check whether this selection
// can become a scan controller without building the physical plan.
func (p *Selection) makeScanController() *physicalPlanInfo {
	var (
		child       PhysicalPlan
		corColConds []expression.Expression
	)
	ds := p.children[0].(*DataSource)
	indices, _ := availableIndices(ds.indexHints, ds.tableInfo)
	for _, expr := range p.Conditions {
		if !expr.IsCorrelated() {
			continue
		}
		cond := expression.PushDownNot(expr, false, nil)
		corCols := extractCorColumns(cond)
		for _, col := range corCols {
			*col.Data = expression.One.Value
		}
		newCond, _ := expression.SubstituteCorCol2Constant(cond)
		corColConds = append(corColConds, newCond)
	}
	if p.controllerStatus == controlTableScan {
		ts := PhysicalTableScan{
			Table:               ds.tableInfo,
			Columns:             ds.Columns,
			DBName:              ds.DBName,
			physicalTableSource: physicalTableSource{client: ds.ctx.GetClient()},
		}.init(p.allocator, p.ctx)
		ts.SetSchema(ds.schema)
		if ds.ctx.Txn() != nil {
			ts.readOnly = p.ctx.Txn().IsReadOnly()
		} else {
			ts.readOnly = true
		}
		child = ts
	} else if p.controllerStatus == controlIndexScan {
		var (
			chosenPlan     *PhysicalIndexScan
			bestEqualCount int
		)
		for _, idx := range indices {
			condsBackUp := make([]expression.Expression, 0, len(corColConds))
			for _, cond := range corColConds {
				condsBackUp = append(condsBackUp, cond.Clone())
			}
			_, _, accessEqualCount, _ := ranger.DetachIndexScanConditions(condsBackUp, idx)
			if chosenPlan == nil || bestEqualCount < accessEqualCount {
				is := PhysicalIndexScan{
					Table:               ds.tableInfo,
					Index:               idx,
					Columns:             ds.Columns,
					OutOfOrder:          true,
					DBName:              ds.DBName,
					physicalTableSource: physicalTableSource{client: ds.ctx.GetClient()},
				}.init(p.allocator, p.ctx)
				is.SetSchema(ds.schema)
				if is.ctx.Txn() != nil {
					is.readOnly = p.ctx.Txn().IsReadOnly()
				} else {
					is.readOnly = true
				}
				is.DoubleRead = !isCoveringIndex(is.Columns, is.Index.Columns, is.Table.PKIsHandle)
				chosenPlan, bestEqualCount = is, accessEqualCount
			}
		}
		child = chosenPlan
	}
	newSel := p.Copy().(*Selection)
	newSel.ScanController = true
	newSel.SetChildren(child)
	info := &physicalPlanInfo{
		p:     newSel,
		count: float64(ds.statisticTable.Count),
	}
	info.cost = info.count * selectionFactor
	return info
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *Selection) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	if p.controllerStatus != notController {
		info = p.makeScanController()
		info = enforceProperty(prop, info)
		return info, errors.Trace(p.storePlanInfo(prop, info))
	}
	// Firstly, we try to push order.
	info, err = p.convert2PhysicalPlanPushOrder(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(prop.props) > 0 {
		// Secondly, we push nothing and enforce this property.
		infoEnforce, err := p.convert2PhysicalPlanEnforce(prop)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if infoEnforce.cost < info.cost {
			info = infoEnforce
		}
	}
	info = p.matchProperty(prop, info)
	return info, errors.Trace(p.storePlanInfo(prop, info))
}

func (p *Selection) appendSelToInfo(info *physicalPlanInfo) *physicalPlanInfo {
	np := p.Copy().(*Selection)
	np.SetChildren(info.p)
	return &physicalPlanInfo{
		p:        np,
		cost:     info.cost,
		count:    info.count * selectionFactor,
		reliable: info.reliable,
	}
}

func (p *Selection) convert2PhysicalPlanPushOrder(prop *requiredProperty) (*physicalPlanInfo, error) {
	child := p.children[0].(LogicalPlan)
	limit := prop.limit
	info, err := child.convert2PhysicalPlan(removeLimit(prop))
	if err != nil {
		return nil, errors.Trace(err)
	}
	if limit != nil && info.p != nil {
		if np, ok := info.p.(physicalDistSQLPlan); ok {
			np.addLimit(limit)
			scanCount := info.count
			info.count = float64(limit.Count)
			info.cost = np.calculateCost(info.count, scanCount)
			if limit.Offset > 0 {
				info = enforceProperty(&requiredProperty{limit: limit}, info)
			}
		} else {
			info = enforceProperty(&requiredProperty{limit: limit}, p.appendSelToInfo(info))
		}
	} else if ds, ok := p.children[0].(*DataSource); !ok {
		// TODO: It's tooooooo tricky here, we will remove all these logic after implementing DAG push down.
		info = p.appendSelToInfo(info)
	} else {
		client := p.ctx.GetClient()
		memDB := infoschema.IsMemoryDB(ds.DBName.L)
		isDistReq := !memDB && client != nil && client.IsRequestTypeSupported(kv.ReqTypeSelect, 0)
		if !isDistReq {
			info = p.appendSelToInfo(info)
		}
	}
	return info, nil
}

// convert2PhysicalPlanEnforce converts a selection to *physicalPlanInfo which does not push the
// required property to the children, but enforce the property instead.
func (p *Selection) convert2PhysicalPlanEnforce(prop *requiredProperty) (*physicalPlanInfo, error) {
	child := p.children[0].(LogicalPlan)
	info, err := child.convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	if prop.limit != nil && len(prop.props) > 0 {
		if t, ok := info.p.(physicalDistSQLPlan); ok {
			t.addTopN(p.ctx, prop)
		} else if _, ok := info.p.(*Selection); !ok {
			info = p.appendSelToInfo(info)
		}
		info = enforceProperty(prop, info)
	} else if len(prop.props) != 0 {
		info = &physicalPlanInfo{cost: math.MaxFloat64}
	}
	return info, nil
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *Projection) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	newProp := &requiredProperty{
		props:      make([]*columnProp, 0, len(prop.props)),
		sortKeyLen: prop.sortKeyLen,
		limit:      prop.limit}
	childSchema := p.children[0].Schema()
	usedCols := make([]bool, childSchema.Len())
	canPassSort := true
loop:
	for _, c := range prop.props {
		idx := p.schema.ColumnIndex(c.col)
		switch v := p.Exprs[idx].(type) {
		case *expression.Column:
			childIdx := childSchema.ColumnIndex(v)
			if !usedCols[childIdx] {
				usedCols[childIdx] = true
				newProp.props = append(newProp.props, &columnProp{col: v, desc: c.desc})
			}
		case *expression.ScalarFunction:
			newProp = nil
			canPassSort = false
			break loop
		default:
			newProp.sortKeyLen--
		}
	}
	if !canPassSort {
		return &physicalPlanInfo{cost: math.MaxFloat64}, nil
	}
	info, err = p.children[0].(LogicalPlan).convert2PhysicalPlan(newProp)
	if err != nil {
		return nil, errors.Trace(err)
	}
	info = addPlanToResponse(p, info)
	return info, errors.Trace(p.storePlanInfo(prop, info))
}

func matchProp(ctx context.Context, target, new *requiredProperty) bool {
	if target.sortKeyLen > len(new.props) {
		return false
	}
	for i := 0; i < target.sortKeyLen; i++ {
		if !target.props[i].equal(new.props[i], ctx) {
			return false
		}
	}
	for i := target.sortKeyLen; i < len(target.props); i++ {
		isMatch := false
		for _, pro := range new.props {
			if pro.col.Equal(target.props[i].col, ctx) {
				isMatch = true
				break
			}
		}
		if !isMatch {
			return false
		}
	}
	return true
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *Sort) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	if len(p.ByItems) == 0 {
		return p.children[0].(LogicalPlan).convert2PhysicalPlan(prop)
	}
	selfProp := &requiredProperty{
		props: make([]*columnProp, 0, len(p.ByItems)),
	}
	for _, by := range p.ByItems {
		if col, ok := by.Expr.(*expression.Column); ok {
			selfProp.props = append(selfProp.props, &columnProp{col: col, desc: by.Desc})
		} else {
			selfProp.props = nil
			break
		}
	}
	selfProp.sortKeyLen = len(selfProp.props)
	if len(selfProp.props) != 0 && len(prop.props) == 0 && prop.limit != nil {
		selfProp.limit = prop.limit
	}
	sortedPlanInfo, err := p.children[0].(LogicalPlan).convert2PhysicalPlan(selfProp)
	if err != nil {
		return nil, errors.Trace(err)
	}
	unSortedPlanInfo, err := p.children[0].(LogicalPlan).convert2PhysicalPlan(&requiredProperty{})
	if err != nil {
		return nil, errors.Trace(err)
	}
	sortCost := sortCost(unSortedPlanInfo.count)
	if len(selfProp.props) == 0 {
		np := p.Copy().(*Sort)
		np.ExecLimit = prop.limit
		sortedPlanInfo = addPlanToResponse(np, sortedPlanInfo)
	} else if sortCost+unSortedPlanInfo.cost < sortedPlanInfo.cost {
		sortedPlanInfo.cost = sortCost + unSortedPlanInfo.cost
		np := p.Copy().(*Sort)
		np.ExecLimit = selfProp.limit
		sortedPlanInfo = addPlanToResponse(np, unSortedPlanInfo)
	}
	if !matchProp(p.ctx, prop, selfProp) {
		sortedPlanInfo.cost = math.MaxFloat64
	}
	return sortedPlanInfo, errors.Trace(p.storePlanInfo(prop, sortedPlanInfo))
}

// convert2PhysicalPlan implements the LogicalPlan convert2PhysicalPlan interface.
func (p *LogicalApply) convert2PhysicalPlan(prop *requiredProperty) (*physicalPlanInfo, error) {
	info, err := p.getPlanInfo(prop)
	if err != nil {
		return info, errors.Trace(err)
	}
	if info != nil {
		return info, nil
	}
	if p.JoinType == InnerJoin || p.JoinType == LeftOuterJoin {
		info, err = p.LogicalJoin.convert2PhysicalPlanLeft(&requiredProperty{}, p.JoinType == InnerJoin)
	} else {
		info, err = p.LogicalJoin.convert2PhysicalPlanSemi(&requiredProperty{})
	}
	if err != nil {
		return info, errors.Trace(err)
	}
	switch info.p.(type) {
	case *PhysicalHashJoin, *PhysicalHashSemiJoin:
		ap := PhysicalApply{
			PhysicalJoin: info.p,
			OuterSchema:  p.corCols,
		}.init(p.allocator, p.ctx)
		ap.SetChildren(info.p.Children()...)
		ap.SetSchema(info.p.Schema())
		info.p = ap
	default:
		info.cost = math.MaxFloat64
		info.p = nil
	}
	info = enforceProperty(prop, info)
	return info, errors.Trace(p.storePlanInfo(prop, info))
}

// addCachePlan will add a Cache plan above the plan whose father's IsCorrelated() is true but its own IsCorrelated() is false.
func addCachePlan(p PhysicalPlan, allocator *idAllocator) []*expression.CorrelatedColumn {
	if len(p.Children()) == 0 {
		return nil
	}
	selfCorCols := p.extractCorrelatedCols()
	newChildren := make([]Plan, 0, len(p.Children()))
	for _, child := range p.Children() {
		childCorCols := addCachePlan(child.(PhysicalPlan), allocator)
		// If p is a Selection and controls the access condition of below scan plan, there shouldn't have a cache plan.
		if sel, ok := p.(*Selection); len(selfCorCols) > 0 && len(childCorCols) == 0 && (!ok || !sel.ScanController) {
			newChild := Cache{}.init(p.Allocator(), p.context())
			newChild.SetSchema(child.Schema())

			addChild(newChild, child)
			newChild.SetParents(p)

			newChildren = append(newChildren, newChild)
		} else {
			newChildren = append(newChildren, child)
		}
	}
	p.SetChildren(newChildren...)
	return selfCorCols
}