text:
<?php

	require dirname(__FILE__)."/j-folder/php/csrf.php";
	$new_token = new CSRF('feedback');

?>
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Feedback form</title>

	<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0" name="viewport">

	<link rel="stylesheet" href="j-folder/css/demo.css">
	<link rel="stylesheet" href="j-folder/css/font-awesome.min.css">
	<link rel="stylesheet" href="j-folder/css/j-forms.css">

					Leave a feedback

						<form action="j-folder/php/action.php" method="post" class="j-forms" id="j-forms" novalidate>

									<?php echo $new_token->get_token();?>

										<input type="text" id="name" name="name" placeholder="name">

										<input type="email" placeholder="email" id="email" name="email">

										<textarea placeholder="feedback message..." spellcheck="false" name="message"></textarea>

								<button type="submit" class="primary-btn">Send</button>

						</form>


text:
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 * @version $Id: Row.php 6400 2012-05-30 09:50:00Z matt $
 *
 * @category Piwik
 * @package Piwik
 */

/**
 * A DataTable is composed of rows.
 *
 * A row is composed of:
 * - columns often at least a 'label' column containing the description
 * 		of the row, and some numeric values ('nb_visits', etc.)
 * - metadata: other information never to be shown as 'columns'
 * - idSubtable: a row can be linked to a SubTable
 *
 * IMPORTANT: Make sure that the column named 'label' contains at least one non-numeric character.
 *            Otherwise the method addDataTable() or sumRow() would fail because they would consider
 *            the 'label' as being a numeric column to sum.
 *
 * PERFORMANCE: Do *not* add new fields except if necessary in this object. New fields will be
 *              serialized and recorded in the DB millions of times. This object size is critical and must be under control.
 *
 * @package Piwik
 * @subpackage Piwik_DataTable
 */
class Piwik_DataTable_Row
{
	/**
	 * This array contains the row information:
	 * - array indexed by self::COLUMNS contains the columns, pairs of (column names, value)
	 * - (optional) array indexed by self::METADATA contains the metadata,  pairs of (metadata name, value)
	 * - (optional) integer indexed by self::DATATABLE_ASSOCIATED contains the ID of the Piwik_DataTable associated to this row.
	 *   This ID can be used to read the DataTable from the DataTable_Manager.
	 *
	 * @var array
	 * @see constructor for more information
	 */
	public $c = array();

	const COLUMNS = 0;
	const METADATA = 1;
	const DATATABLE_ASSOCIATED = 3;

	/**
	 * Efficient load of the Row structure from a well structured php array
	 *
	 * @param array  $row  The row array has the structure
	 *                     array(
	 *                           Piwik_DataTable_Row::COLUMNS => array(
	 *                                                                 'label' => 'Piwik',
	 *                                                                 'column1' => 42,
	 *                                                                 'visits' => 657,
	 *                                                                 'time_spent' => 155744,
	 *                                                                 ),
	 *                            Piwik_DataTable_Row::METADATA => array(
	 *                                                                  'logo' => 'test.png'
	 *                                                                  ),
	 *                            Piwik_DataTable_Row::DATATABLE_ASSOCIATED => #Piwik_DataTable object
	 *                                                                         (but in the row only the ID will be stored)
	 *                           )
	 */
	public function __construct( $row = array() )
	{
		$this->c[self::COLUMNS] = array();
		$this->c[self::METADATA] = array();
		$this->c[self::DATATABLE_ASSOCIATED] = null;

		if(isset($row[self::COLUMNS]))
		{
			$this->c[self::COLUMNS] = $row[self::COLUMNS];
		}
		if(isset($row[self::METADATA]))
		{
			$this->c[self::METADATA] = $row[self::METADATA];
		}
		if(isset($row[self::DATATABLE_ASSOCIATED])
			&& $row[self::DATATABLE_ASSOCIATED] instanceof Piwik_DataTable)
		{
			$this->c[self::DATATABLE_ASSOCIATED] = $row[self::DATATABLE_ASSOCIATED]->getId();
		}
	}

	/**
	 * When destroyed, a row destroys its associated subTable if there is one
	 */
	public function __destruct()
	{
		$idSubtable = $this->c[self::DATATABLE_ASSOCIATED];
		if($idSubtable !== null)
		{
			Piwik_DataTable_Manager::getInstance()->deleteTable($idSubtable);
			$idSubtable = null;
		}
	}

	/**
	 * Applies a basic rendering to the Row and returns the output
	 *
	 * @return string characterizing the row. Example: - 1 ['label' => 'piwik', 'nb_uniq_visitors' => 1685, 'nb_visits' => 1861, 'nb_actions' => 2271, 'max_actions' => 13, 'sum_visit_length' => 920131, 'bounce_count' => 1599] [] [idsubtable = 1375]
	 */
	public function __toString()
	{
		$columns = array();
		foreach($this->getColumns() as $column => $value)
		{
			if(is_string($value)) $value = "'$value'";
			elseif(is_array($value)) $value = var_export($value, true);
			$columns[] = "'$column' => $value";
		}
		$columns = implode(", ", $columns);
		$metadata = array();
		foreach($this->getMetadata() as $name => $value)
		{
			if(is_string($value)) $value = "'$value'";
			elseif(is_array($value)) $value = var_export($value, true);
			$metadata[] = "'$name' => $value";
		}
		$metadata = implode(", ", $metadata);
		$output = "# [".$columns."] [".$metadata."] [idsubtable = " . $this->getIdSubDataTable()."]<br />\n";
		return $output;
	}

	/**
	 * Deletes the given column
	 *
	 * @param string  $name  Column name
	 * @return bool  True on success, false if the column didn't exist
	 */
	public function deleteColumn( $name )
	{
		if(!isset($this->c[self::COLUMNS][$name]))
		{
			return false;
		}
		unset($this->c[self::COLUMNS][$name]);
		return true;
	}

	/**
	 * Renames the given column
	 *
	 * @param string  $oldName
	 * @param string  $newName
	 */
	public function renameColumn($oldName, $newName)
	{
		if(isset($this->c[self::COLUMNS][$oldName]))
		{
			$this->c[self::COLUMNS][$newName] = $this->c[self::COLUMNS][$oldName];
		}
		// outside the if() since we want to delete nulled columns
		unset($this->c[self::COLUMNS][$oldName]);
	}

	/**
	 * Returns the given column
	 *
	 * @param string  $name  Column name
	 * @return mixed|false  The column value
	 */
	public function getColumn( $name )
	{
		if(!isset($this->c[self::COLUMNS][$name]))
		{
			return false;
		}
		return $this->c[self::COLUMNS][$name];
	}

	/**
	 * Returns the array of all metadata,
	 * or the specified metadata
	 *
	 * @param string  $name  Metadata name
	 * @return mixed|array|false
	 */
	public function getMetadata( $name = null )
	{
		if(is_null($name))
		{
			return $this->c[self::METADATA];
		}
		if(!isset($this->c[self::METADATA][$name]))
		{
			return false;
		}
		return $this->c[self::METADATA][$name];
	}

	/**
	 * Returns the array containing all the columns
	 *
	 * @return array  Example: array(
	 *                              'column1'   => VALUE,
	 *                              'label'     => 'www.php.net'
	 *                              'nb_visits' => 15894,
	 *                              )
	 */
	public function getColumns()
	{
		return $this->c[self::COLUMNS];
	}

	/**
	 * Returns the ID of the subDataTable.
	 * If there is no such a table, returns null.
	 *
	 * @return int|null
	 */
	public function getIdSubDataTable()
	{
		return $this->c[self::DATATABLE_ASSOCIATED];
	}

	/**
	 * Sums a DataTable to this row subDataTable.
	 * If this row doesn't have a SubDataTable yet, we create a new one.
	 * Then we add the values of the given DataTable to this row's DataTable.
	 *
	 * @param Piwik_DataTable  $subTable  Table to sum to this row's subDatatable
	 * @see Piwik_DataTable::addDataTable() for the algorithm used for the sum
	 */
	public function sumSubtable(Piwik_DataTable $subTable)
	{
		$thisSubtableID = $this->getIdSubDataTable();
		if($thisSubtableID === null)
		{
			$thisSubTable = new Piwik_DataTable();
			$this->addSubtable($thisSubTable);
		}
		else
		{
			$thisSubTable = Piwik_DataTable_Manager::getInstance()->getTable( $thisSubtableID );
		}

		$thisSubTable->addDataTable($subTable);
	}

	/**
	 * Set a DataTable to be associated to this row.
	 * If the row already has a DataTable associated to it, throws an Exception.
	 *
	 * @param Piwik_DataTable  $subTable  DataTable to associate to this row
	 * @throws Exception
	 *
	 */
	public function addSubtable(Piwik_DataTable $subTable)
	{
		if(!is_null($this->c[self::DATATABLE_ASSOCIATED]))
		{
			throw new Exception("Adding a subtable to the row, but it already has a subtable associated.");
		}
		$this->c[self::DATATABLE_ASSOCIATED] = $subTable->getId();
	}

	/**
	 * Set a DataTable to this row. If there is already
	 * a DataTable associated, it is simply overwritten.
	 *
	 * @param Piwik_DataTable  $subTable  DataTable to associate to this row
	 */
	public function setSubtable(Piwik_DataTable $subTable)
	{
		$this->c[self::DATATABLE_ASSOCIATED] = $subTable->getId();
	}

	/**
	 * Remove the sub table reference
	 */
	public function removeSubtable()
	{
		$this->c[self::DATATABLE_ASSOCIATED] = null;
	}

	/**
	 * Set all the columns at once. Overwrites previously set columns.
	 *
	 * @param array  array(
	 *                    'label'       => 'www.php.net'
	 *                    'nb_visits'   => 15894,
	 *                    )
	 */
	public function setColumns( $columns )
	{
		$this->c[self::COLUMNS] = $columns;
	}

	/**
	 * Set the value $value to the column called $name.
	 *
	 * @param string  $name   name of the column to set
	 * @param mixed   $value  value of the column to set
	 */
	public function setColumn($name, $value)
	{
		$this->c[self::COLUMNS][$name] = $value;
	}

	/**
	 * Set the value $value to the metadata called $name.
	 *
	 * @param string  $name   name of the metadata to set
	 * @param mixed   $value  value of the metadata to set
	 */
	public function setMetadata($name, $value)
	{
		$this->c[self::METADATA][$name] = $value;
	}

	/**
	 * Deletes the given metadata
	 *
	 * @param bool|string  $name  Meta column name (omit to delete entire metadata)
	 * @return bool  True on success, false if the column didn't exist
	 */
	public function deleteMetadata($name = false)
	{
		if($name === false)
		{
			$this->c[self::METADATA] = array();
			return true;
		}
		if(!isset($this->c[self::METADATA][$name]))
		{
			return false;
		}
		unset($this->c[self::METADATA][$name]);
		return true;
	}

	/**
	 * Add a new column to the row. If the column already exists, throws an exception
	 *
	 * @param string  $name   name of the column to add
	 * @param mixed   $value  value of the column to set
	 * @throws Exception
	 */
	public function addColumn($name, $value)
	{
		if(isset($this->c[self::COLUMNS][$name]))
		{
//			debug_print_backtrace();
			throw new Exception("Column $name already in the array!");
		}
		$this->c[self::COLUMNS][$name] = $value;
	}

	/**
	 * Add columns to the row
	 *
	 * @param array  $columns  Name/Value pairs, e.g., array( name => value , ...)
	 * @return void
	 */
	public function addColumns($columns)
	{
		foreach($columns as $name => $value)
		{
			try {
				$this->addColumn($name, $value);
			} catch(Exception $e) {
			}
		}

		if(!empty($e)) {
			throw $e;
		}
	}

	/**
	 * Add a new metadata to the row. If the column already exists, throws an exception.
	 *
	 * @param string  $name   name of the metadata to add
	 * @param mixed   $value  value of the metadata to set
	 * @throws Exception
	 */
	public function addMetadata($name, $value)
	{
		if(isset($this->c[self::METADATA][$name]))
		{
			throw new Exception("Metadata $name already in the array!");
		}
		$this->c[self::METADATA][$name] = $value;
	}

	/**
	 * Sums the given $row columns values to the existing row' columns values.
	 * It will sum only the int or float values of $row.
	 * It will not sum the column 'label' even if it has a numeric value.
	 *
	 * If a given column doesn't exist in $this then it is added with the value of $row.
	 * If the column already exists in $this then we have
	 *         this.columns[idThisCol] += $row.columns[idThisCol]
	 *
	 * @param Piwik_DataTable_Row  $rowToSum
	 */
	public function sumRow( Piwik_DataTable_Row $rowToSum )
	{
		foreach($rowToSum->getColumns() as $columnToSumName => $columnToSumValue)
		{
			if($columnToSumName != 'label')
			{
				$thisColumnValue = $this->getColumn($columnToSumName);

				// Max operation
				if($columnToSumName == Piwik_Archive::INDEX_MAX_ACTIONS )
				{
					$newValue = max($thisColumnValue, $columnToSumValue);
				}
				else
				{
					$newValue = $this->sumRowArray($thisColumnValue, $columnToSumValue);
				}
				$this->setColumn( $columnToSumName, $newValue);
			}
		}
	}

	/**
	 *
	 * @param number|bool   $thisColumnValue
	 * @param number|array  $columnToSumValue
	 * @return array|int
	 */
	protected function sumRowArray( $thisColumnValue, $columnToSumValue )
	{
		if(is_numeric($columnToSumValue))
		{
			if($thisColumnValue === false)
			{
				$thisColumnValue = 0;
			}
			return $thisColumnValue + $columnToSumValue;
		}

		if(is_array($columnToSumValue))
		{
			if($thisColumnValue == false)
			{
				return $columnToSumValue;
			}
			$newValue = $thisColumnValue;
			foreach($columnToSumValue as $arrayIndex => $arrayValue)
			{
				if(!isset($newValue[$arrayIndex]))
				{
					$newValue[$arrayIndex] = false;
				}
				$newValue[$arrayIndex] = $this->sumRowArray($newValue[$arrayIndex], $arrayValue);
			}
			return $newValue;
		}
		return 0;
	}

	/**
	 * Helper function to compare array elements
	 *
	 * @param mixed  $elem1
	 * @param mixed  $elem2
	 * @return bool
	 */
	static public function compareElements($elem1, $elem2)
	{
		if (is_array($elem1)) {
			if (is_array($elem2))
			{
				return strcmp(serialize($elem1), serialize($elem2));
			}
			return 1;
		}
		if (is_array($elem2))
			return -1;

		if ((string)$elem1 === (string)$elem2)
			return 0;

		return ((string)$elem1 > (string)$elem2) ? 1 : -1;
	}

	/**
	 * Helper function to test if two rows are equal.
	 *
	 * Two rows are equal
	 * - if they have exactly the same columns / metadata
	 * - if they have a subDataTable associated, then we check that both of them are the same.
	 *
	 * @param Piwik_DataTable_Row  $row1  first to compare
	 * @param Piwik_DataTable_Row  $row2  second to compare
	 * @return bool
	 */
	static public function isEqual( Piwik_DataTable_Row $row1, Piwik_DataTable_Row $row2 )
	{
		//same columns
		$cols1 = $row1->getColumns();
		$cols2 = $row2->getColumns();

		$diff1 = array_udiff($cols1, $cols2, array(__CLASS__, 'compareElements'));
		$diff2 = array_udiff($cols2, $cols1, array(__CLASS__, 'compareElements'));

		if($diff1 != $diff2)
		{
			return false;
		}

		$dets1 = $row1->getMetadata();
		$dets2 = $row2->getMetadata();

		ksort($dets1);
		ksort($dets2);

		if($dets1 != $dets2)
		{
			return false;
		}

		// either both are null
		// or both have a value
		if( !(is_null($row1->getIdSubDataTable())
				&& is_null($row2->getIdSubDataTable())
			)
		)
		{
			$subtable1 = Piwik_DataTable_Manager::getInstance()->getTable($row1->getIdSubDataTable());
			$subtable2 = Piwik_DataTable_Manager::getInstance()->getTable($row2->getIdSubDataTable());
			if(!Piwik_DataTable::isEqual($subtable1, $subtable2))
			{
				return false;
			}
		}
		return true;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.dremio.exec.store.dfs;

import java.util.concurrent.ExecutorService;

import javax.inject.Provider;

import org.apache.arrow.memory.BufferAllocator;

import com.dremio.exec.proto.CoordinationProtos.NodeEndpoint;
import com.dremio.services.fabric.api.FabricRunnerFactory;

/**
 * Class used to pass configuration to file system instances.
 */
class PDFSConfig {

  private final ExecutorService executor;
  private final FabricRunnerFactory runnerFactory;
  private final BufferAllocator allocator;
  private final Provider<Iterable<NodeEndpoint>> endpointProvider;
  private final NodeEndpoint localIdentity;
  private final boolean localAccessAllowed;

  public PDFSConfig(ExecutorService executor, FabricRunnerFactory runnerFactory, BufferAllocator allocator,
      Provider<Iterable<NodeEndpoint>> endpointProvider, NodeEndpoint localIdentity, boolean localAccessAllowed) {
    super();
    this.executor = executor;
    this.runnerFactory = runnerFactory;
    this.allocator = allocator;
    this.endpointProvider = endpointProvider;
    this.localIdentity = localIdentity;
    this.localAccessAllowed = localAccessAllowed;
  }

  public ExecutorService getExecutor() {
    return executor;
  }

  public FabricRunnerFactory getRunnerFactory() {
    return runnerFactory;
  }

  public BufferAllocator getAllocator() {
    return allocator;
  }

  public Provider<Iterable<NodeEndpoint>> getEndpointProvider() {
    return endpointProvider;
  }

  public NodeEndpoint getLocalIdentity() {
    return localIdentity;
  }

  public boolean isLocalAccessAllowed() {
    return localAccessAllowed;
  }

}


text:
from __future__ import division

import numpy as np
import pandas as pd
import scipy as sp
from scipy import stats
import seaborn as sns

import matplotlib.pyplot as plt

import pymc3 as pm

from .timeseries import cum_returns

def model_returns_t_alpha_beta(data, bmark, samples=2000):
    """Run Bayesian alpha-beta-model with T distributed returns.

    This model estimates intercept (alpha) and slope (beta) of two
    return sets. Usually, these will be algorithm returns and
    benchmark returns (e.g. S&P500). The data is assumed to be T
    distributed and thus is robust to outliers and takes tail events
    into account.

    Parameters
    ----------
    returns : pandas.Series
        Series of simple returns of an algorithm or stock.
    bmark : pandas.Series
        Series of simple returns of a benchmark like the S&P500.
        If bmark has more recent returns than returns_train, these dates
        will be treated as missing values and predictions will be
        generated for them taking market correlations into account.
    samples : int (optional)
        Number of posterior samples to draw.

    Returns
    -------
    pymc3.sampling.BaseTrace object
        A PyMC3 trace object that contains samples for each parameter
        of the posterior.
    """

    if len(data) != len(bmark):
        # pad missing data
        data = pd.Series(data, index=bmark.index)

    data_no_missing = data.dropna()

    with pm.Model():
        sigma = pm.HalfCauchy(
            'sigma',
            beta=1,
            testval=data_no_missing.values.std())
        nu = pm.Exponential('nu_minus_two', 1. / 10., testval=.3)

        # alpha and beta
        beta_init, alpha_init = sp.stats.linregress(
            bmark.loc[data_no_missing.index],
            data_no_missing)[:2]

        alpha_reg = pm.Normal('alpha', mu=0, sd=.1, testval=alpha_init)
        beta_reg = pm.Normal('beta', mu=0, sd=1, testval=beta_init)

        pm.T('returns',
             nu=nu + 2,
             mu=alpha_reg + beta_reg * bmark,
             sd=sigma,
             observed=data)
        start = pm.find_MAP(fmin=sp.optimize.fmin_powell)
        step = pm.NUTS(scaling=start)
        trace = pm.sample(samples, step, start=start)

    return trace

def model_returns_normal(data, samples=500):
    """Run Bayesian model assuming returns are Student-T distributed.

    Compared with the normal model, this model assumes returns be
    T-distributed and thus has a 3rd parameter (nu) that controls the
    mass in the tails.

    Parameters
    ----------
    returns : pandas.Series
        Series of simple returns of an algorithm or stock.
    samples : int (optional)
        Number of posterior samples to draw.

    Returns
    -------
    pymc3.sampling.BaseTrace object
        A PyMC3 trace object that contains samples for each parameter
        of the posterior.

    """
    with pm.Model():
        mu = pm.Normal('mean returns', mu=0, sd=.01, testval=data.mean())
        sigma = pm.HalfCauchy('volatility', beta=1, testval=data.std())
        returns = pm.Normal('returns', mu=mu, sd=sigma, observed=data)
        pm.Deterministic(
            'annual volatility',
            returns.distribution.variance**.5 *
            np.sqrt(252))
        pm.Deterministic(
            'sharpe',
            returns.distribution.mean /
            returns.distribution.variance**.5 *
            np.sqrt(252))

        start = pm.find_MAP(fmin=sp.optimize.fmin_powell)
        step = pm.NUTS(scaling=start)
        trace = pm.sample(samples, step, start=start)
    return trace

def model_returns_t(data, samples=500):
    """Run Bayesian model assuming returns are normally distributed.

    Parameters
    ----------
    returns : pandas.Series
        Series of simple returns of an algorithm or stock.
    samples : int, optional
        Number of posterior samples to draw.

    Returns
    -------
    pymc3.sampling.BaseTrace object
        A PyMC3 trace object that contains samples for each parameter
        of the posterior.

    """

    with pm.Model():
        mu = pm.Normal('mean returns', mu=0, sd=.01, testval=data.mean())
        sigma = pm.HalfCauchy('volatility', beta=1, testval=data.std())
        nu = pm.Exponential('nu_minus_two', 1. / 10., testval=3.)

        returns = pm.T('returns', nu=nu + 2, mu=mu, sd=sigma, observed=data)
        pm.Deterministic('annual volatility',
                         returns.distribution.variance**.5 * np.sqrt(252))

        pm.Deterministic('sharpe', returns.distribution.mean /
                         returns.distribution.variance**.5 *
                         np.sqrt(252))

        start = pm.find_MAP(fmin=sp.optimize.fmin_powell)
        step = pm.NUTS(scaling=start)
        trace = pm.sample(samples, step, start=start)
    return trace

def model_best(y1, y2, samples=1000):
    """Bayesian Estimation Supersedes the T-Test

    This model runs a Bayesian hypothesis comparing if y1 and y2 come
    from the same distribution. Returns are assumed to be T-distributed.

    In addition, computes annual volatility and Sharpe of in and
    out-of-sample periods.

    This model replicates the example used in:
    Kruschke, John. (2012) Bayesian estimation supersedes the t
    test. Journal of Experimental Psychology: General.

    Parameters
    ----------
    y1 : array-like
        Array of returns (e.g. in-sample)
    y2 : array-like
        Array of returns (e.g. out-of-sample)
    samples : int, optional
        Number of posterior samples to draw.

    Returns
    -------
    pymc3.sampling.BaseTrace object
        A PyMC3 trace object that contains samples for each parameter
        of the posterior.

    See Also
    --------
    plot_stoch_vol : plotting of tochastic volatility model
    """

    y = np.concatenate((y1, y2))

    mu_m = np.mean(y)
    mu_p = 0.000001 * 1 / np.std(y)**2

    sigma_low = np.std(y) / 1000
    sigma_high = np.std(y) * 1000
    with pm.Model():
        group1_mean = pm.Normal('group1_mean', mu=mu_m, tau=mu_p,
                                testval=y1.mean())
        group2_mean = pm.Normal('group2_mean', mu=mu_m, tau=mu_p,
                                testval=y2.mean())
        group1_std = pm.Uniform('group1_std', lower=sigma_low,
                                upper=sigma_high, testval=y1.std())
        group2_std = pm.Uniform('group2_std', lower=sigma_low,
                                upper=sigma_high, testval=y2.std())
        nu = pm.Exponential('nu_minus_two', 1 / 29., testval=4.) + 2.

        returns_group1 = pm.T('group1', nu=nu, mu=group1_mean,
                              lam=group1_std**-2, observed=y1)
        returns_group2 = pm.T('group2', nu=nu, mu=group2_mean,
                              lam=group2_std**-2, observed=y2)

        diff_of_means = pm.Deterministic('difference of means',
                                         group2_mean - group1_mean)
        pm.Deterministic('difference of stds',
                         group2_std - group1_std)
        pm.Deterministic('effect size', diff_of_means /
                         pm.sqrt((group1_std**2 +
                                  group2_std**2) / 2))

        pm.Deterministic('group1_annual_volatility',
                         returns_group1.distribution.variance**.5 *
                         np.sqrt(252))
        pm.Deterministic('group2_annual_volatility',
                         returns_group2.distribution.variance**.5 *
                         np.sqrt(252))

        pm.Deterministic('group1_sharpe', returns_group1.distribution.mean /
                         returns_group1.distribution.variance**.5 *
                         np.sqrt(252))
        pm.Deterministic('group2_sharpe', returns_group2.distribution.mean /
                         returns_group2.distribution.variance**.5 *
                         np.sqrt(252))

        step = pm.NUTS()

        trace = pm.sample(samples, step)
    return trace

def plot_best(trace=None, data_train=None, data_test=None,
              samples=1000, burn=200, axs=None):
    """Plot BEST significance analysis.

    Parameters
    ----------
    trace : pymc3.sampling.BaseTrace, optional
        trace object as returned by model_best()
        If not passed, will run model_best(), for which
        data_train and data_test are required.
    data_train : pandas.Series, optional
        Returns of in-sample period.
        Required if trace=None.
    data_test : pandas.Series, optional
        Returns of out-of-sample period.
        Required if trace=None.
    samples : int, optional
        Posterior samples to draw.
    burn : int
        Posterior sampels to discard as burn-in.
    axs : array of matplotlib.axes objects, optional
        Plot into passed axes objects. Needs 6 axes.

    Returns
    -------
    None

    See Also
    --------
    model_best : Estimation of BEST model.
    """
    if trace is None:
        if (data_train is not None) or (data_test is not None):
            raise ValueError('Either pass trace or data_train and data_test')
        trace = model_best(data_train, data_test, samples=samples)

    trace = trace[burn:]
    if axs is None:
        fig, axs = plt.subplots(ncols=2, nrows=3, figsize=(16, 4))

    def distplot_w_perc(trace, ax):
        sns.distplot(trace, ax=ax)
        ax.axvline(
            stats.scoreatpercentile(trace, 2.5),
            color='0.5', label='2.5 and 97.5 percentiles')
        ax.axvline(
            stats.scoreatpercentile(trace, 97.5),
            color='0.5')

    sns.distplot(trace['group1_mean'], ax=axs[0], label='backtest')
    sns.distplot(trace['group2_mean'], ax=axs[0], label='forward')
    axs[0].legend(loc=0)
    axs[1].legend(loc=0)

    distplot_w_perc(trace['difference of means'], axs[1])

    axs[0].set(xlabel='mean', ylabel='belief', yticklabels=[])
    axs[1].set(xlabel='difference of means', yticklabels=[])

    sns.distplot(trace['group1_annual_volatility'], ax=axs[2],
                 label='backtest')
    sns.distplot(trace['group2_annual_volatility'], ax=axs[2],
                 label='forward')
    distplot_w_perc(trace['group2_annual_volatility'] -
                    trace['group1_annual_volatility'], axs[3])
    axs[2].set(xlabel='Annual volatility', ylabel='belief',
               yticklabels=[])
    axs[2].legend(loc=0)
    axs[3].set(xlabel='difference of volatility', yticklabels=[])

    sns.distplot(trace['group1_sharpe'], ax=axs[4], label='backtest')
    sns.distplot(trace['group2_sharpe'], ax=axs[4], label='forward')
    distplot_w_perc(trace['group2_sharpe'] - trace['group1_sharpe'],
                    axs[5])
    axs[4].set(xlabel='Sharpe', ylabel='belief', yticklabels=[])
    axs[4].legend(loc=0)
    axs[5].set(xlabel='difference of Sharpes', yticklabels=[])

    sns.distplot(trace['effect size'], ax=axs[6])
    axs[6].axvline(
        stats.scoreatpercentile(trace['effect size'], 2.5),
        color='0.5')
    axs[6].axvline(
        stats.scoreatpercentile(trace['effect size'], 97.5),
        color='0.5')
    axs[6].set(xlabel='difference of means normalized by volatility',
               ylabel='belief', yticklabels=[])

def model_stoch_vol(data, samples=2000):
    """Run stochastic volatility model.

    This model estimates the volatility of a returns series over time.
    Returns are assumed to be T-distributed. lambda (width of
    T-distributed) is assumed to follow a random-walk.

    Parameters
    ----------
    data : pandas.Series
        Return series to model.
    samples : int, optional
        Posterior samples to draw.

    Returns
    -------
    pymc3.sampling.BaseTrace object
        A PyMC3 trace object that contains samples for each parameter
        of the posterior.

    See Also
    --------
    plot_stoch_vol : plotting of tochastic volatility model
    """
    from pymc3.distributions.timeseries import GaussianRandomWalk

    with pm.Model():
        nu = pm.Exponential('nu', 1. / 10, testval=5.)
        sigma = pm.Exponential('sigma', 1. / .02, testval=.1)
        s = GaussianRandomWalk('s', sigma**-2, shape=len(data))
        volatility_process = pm.Deterministic('volatility_process',
                                              pm.exp(-2 * s))
        pm.T('r', nu, lam=volatility_process, observed=data)
        start = pm.find_MAP(vars=[s], fmin=sp.optimize.fmin_l_bfgs_b)

        step = pm.NUTS(scaling=start)
        trace = pm.sample(100, step, progressbar=False)

        # Start next run at the last sampled position.
        step = pm.NUTS(scaling=trace[-1], gamma=.25)
        trace = pm.sample(samples, step, start=trace[-1],
                          progressbar=False, njobs=2)

    return trace

def plot_stoch_vol(data, trace=None, ax=None):
    """Generate plot for stochastic volatility model.

    Parameters
    ----------
    data : pandas.Series
        Returns to model.
    trace : pymc3.sampling.BaseTrace object, optional
        trace as returned by model_stoch_vol
        If not passed, sample from model.
    ax : matplotlib.axes object, optional
        Plot into axes object

    Returns
    -------
    ax object

    See Also
    --------
    model_stoch_vol : run stochastic volatility model
    """
    if trace is None:
        trace = model_stoch_vol(data)

    if ax is None:
        fig, ax = plt.subplots(figsize=(15, 8))

    data.abs().plot(ax=ax)
    ax.plot(data.index, np.exp(trace['s', ::30].T), 'r', alpha=.03)
    ax.set(title='Stochastic Volatility', xlabel='time', ylabel='volatility')
    ax.legend(['abs returns', 'stochastic volatility process'])

    return ax

def compute_bayes_cone(preds, starting_value=1.):
    """Compute 5, 25, 75 and 95 percentiles of cumulative returns, used
    for the Bayesian cone.

    Parameters
    ----------
    preds : numpy.array
        Multiple (simulated) cumulative returns.
    starting_value : int (optional)
        Have cumulative returns start around this value.
        Default = 1.

    Returns
    -------
    dict of percentiles over time
        Dictionary mapping percentiles (5, 25, 75, 95) to a
        timeseries.

    """

    def scoreatpercentile(cum_preds, p):
        return [stats.scoreatpercentile(
            c, p) for c in cum_preds.T]

    cum_preds = np.cumprod(preds + 1, 1) * starting_value
    perc = {p: scoreatpercentile(cum_preds, p) for p in (5, 25, 75, 95)}

    return perc

def compute_consistency_score(returns_test, preds):
    """Compute Bayesian consistency score.

    Parameters
    ----------
    returns_test : pd.Series
        Observed cumulative returns.
    preds : numpy.array
        Multiple (simulated) cumulative returns.

    Returns
    -------
    Consistency score
        Score from 100 (returns_test perfectly on the median line of the
        Bayesian cone spanned by preds) to 0 (returns_test completely
        outside of Bayesian cone.)
    """
    returns_test_cum = cum_returns(returns_test, starting_value=1.)
    cum_preds = np.cumprod(preds + 1, 1)

    q = [sp.stats.percentileofscore(cum_preds[:, i],
                                    returns_test_cum.iloc[i],
                                    kind='weak')
         for i in range(len(returns_test_cum))]
    # normalize to be from 100 (perfect median line) to 0 (completely outside
    # of cone)
    return 100 - np.abs(50 - np.mean(q)) / .5

def _plot_bayes_cone(returns_train, returns_test,
                     preds, plot_train_len=None, ax=None):
    if ax is None:
        ax = plt.gca()

    returns_train_cum = cum_returns(returns_train, starting_value=1.)
    returns_test_cum = cum_returns(returns_test,
                                   starting_value=returns_train_cum.iloc[-1])

    perc = compute_bayes_cone(preds, starting_value=returns_train_cum.iloc[-1])
    # Add indices
    perc = {k: pd.Series(v, index=returns_test.index) for k, v in perc.items()}

    returns_test_cum_rel = returns_test_cum
    # Stitch together train and test
    returns_train_cum.loc[returns_test_cum_rel.index[0]] = \
        returns_test_cum_rel.iloc[0]

    # Plotting
    if plot_train_len is not None:
        returns_train_cum = returns_train_cum.iloc[-plot_train_len:]

    returns_train_cum.plot(ax=ax, color='g', label='in-sample')
    returns_test_cum_rel.plot(ax=ax, color='r', label='out-of-sample')

    ax.fill_between(returns_test.index, perc[5], perc[95], alpha=.3)
    ax.fill_between(returns_test.index, perc[25], perc[75], alpha=.6)
    ax.legend(loc='best')
    ax.set_title('Bayesian Cone')
    ax.set_xlabel('')
    ax.set_ylabel('Cumulative Returns')

    return ax

def run_model(model, returns_train, returns_test=None,
              bmark=None, samples=500):
    """Run one of the Bayesian models.

    Parameters
    ----------
    model : {'alpha_beta', 't', 'normal', 'best'}
        Which model to run
    returns_train : pd.Series
        Timeseries of simple returns
    returns_test : pd.Series (optional)
        Out-of-sample returns. Datetimes in returns_test will be added to
        returns_train as missing values and predictions will be generated
        for them.
    bmark : pd.Series (optional)
        Only used for alpha_beta to estimate regression coefficients.
        If bmark has more recent returns than returns_train, these dates
        will be treated as missing values and predictions will be
        generated for them taking market correlations into account.

    Returns
    -------
    pymc3.sampling.BaseTrace object
        A PyMC3 trace object that contains samples for each parameter
        of the posterior.
    """
    if returns_test is not None:
        period = returns_train.index.append(returns_test.index)
        rets = pd.Series(returns_train, period)
    else:
        rets = returns_train

    if model == 'alpha_beta':
        trace = model_returns_t_alpha_beta(returns_train, bmark, samples)
    elif model == 't':
        trace = model_returns_t(rets, samples)
    elif model == 'normal':
        trace = model_returns_normal(rets, samples)
    elif model == 'best':
        trace = model_best(returns_train, returns_test, samples=samples)
    else:
        raise NotImplementedError(
            'Model {} not found.'
            'Use alpha_beta, t, normal, or best.'.format(model))

    return trace

def plot_bayes_cone(returns_train, returns_test, bmark=None, model='t',
                    trace=None, plot_train_len=50, ax=None,
                    samples=500):
    """Generate cumulative returns plot with Bayesian cone.

    Parameters
    ----------
    returns_train : pd.Series
        Timeseries of simple returns
    returns_test : pd.Series
        Out-of-sample returns. Datetimes in returns_test will be added to
        returns_train as missing values and predictions will be generated
        for them.
    bmark : pd.Series (optional)
        Only used for alpha_beta to estimate regression coefficients.
        If bmark has more recent returns than returns_train, these dates
        will be treated as missing values and predictions will be
        generated for them taking market correlations into account.
    model : {None, 'alpha_beta', 't', 'normal'} (optional)
        Which model to run. If none, assume trace is being passed in.
    trace : pymc3.sampling.BaseTrace (optional)
        Trace of a previously run model.
    plot_train_len : int (optional)
        How many data points to plot of returns_train. Useful to zoom in on
        the prediction if there is a long backtest period.
    ax : matplotlib.Axis (optional)
        Axes upon which to plot.
    samples : int (optional)
        Number of posterior samples to draw.

    Returns
    -------
    score : float
        Consistency score (see compute_consistency_score)
    trace : pymc3.sampling.BaseTrace
        A PyMC3 trace object that contains samples for each parameter
        of the posterior.
    """

    # generate cone
    if trace is None:
        trace = run_model(model, returns_train, returns_test=returns_test,
                          bmark=bmark, samples=samples)

    score = compute_consistency_score(returns_test, trace['returns_missing'])

    ax = _plot_bayes_cone(
        returns_train,
        returns_test,
        trace['returns_missing'],
        plot_train_len=plot_train_len,
        ax=ax)
    ax.text(
        0.40,
        0.90,
        'Consistency score: %.1f' %
        score,
        verticalalignment='bottom',
        horizontalalignment='right',
        transform=ax.transAxes,
    )

    ax.set_ylabel('Cumulative returns', fontsize=14)
    return score, trace


text:
'''Simple RNN for Language Model
'''
from __future__ import print_function
import os

from keras.models import Model
from keras.layers import Input, Embedding, Dense, TimeDistributed
from keras.optimizers import *

from ternary_layers import *
from imdb_generator import IMDBLM

def LM(batch_size, window_size=3, vocsize=20000, embed_dim=20, hidden_dim=30, nb_layers=1):
    x = Input(batch_shape=(batch_size, None))
    # mebedding
    y = Embedding(vocsize+2, embed_dim, mask_zero=False)(x)
    for i in range(nb_layers-1):
        y = TernaryRNN(hidden_dim, return_sequences=True, name='trnn{}'.format(i + 1))(y)
    y = TernaryRNN(hidden_dim, return_sequences=True, name='trnn{}'.format(nb_layers))(y)
    y = TimeDistributed(Dense(vocsize+2, activation='softmax', name='dense{}'.format(nb_layers)))(y)

    model = Model(input=x, output=y)

    return model

def train_model():
    batch_size = 32
    epochs = 100

    vocsize = 2000 # top 2k
    max_len = 30
    train_ratio = 0.99

    # Build model
    model = LM(batch_size, vocsize=vocsize, nb_layers=1)
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy')

    # Prepare data
    path = './data/imdb-full.pkl'
    # Train
    train_gen = IMDBLM(path=path, max_len=max_len, vocab_size=vocsize, shuffle=True,
                       which_set='train', train_ratio=train_ratio, batch_size=batch_size)
    # Validation
    val_gen = IMDBLM(path=path, max_len=max_len, vocab_size=vocsize,
                     which_set='validation', train_ratio=train_ratio, batch_size=batch_size)

    train_steps = 2000
    val_steps = 200

    # Start training
    model.summary()
    model.fit_generator(train_gen(), steps_per_epoch=train_steps,
                        validation_data=val_gen(), validation_steps=val_steps,
                        epochs=epochs, verbose=1)

def run_demo():
    train_model()

if __name__ == '__main__':
    run_demo()


text:
//          Copyright Daniel Goertzen 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

//
// nifpp is a C++11 Wrapper for the Erlang NIF API
//

//
// Boost license was chosen for nifpp because resource_ptr is derived
// from boost::intrusive_ptr.  License header from intrusive_ptr.hpp is...
//
//  intrusive_ptr.hpp
//
//  Copyright (c) 2001, 2002 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//  See http://www.boost.org/libs/smart_ptr/intrusive_ptr.html for documentation.
//

#ifndef NIFPP_H
#define NIFPP_H

#include <erl_nif.h>

// Only define map functions if they are available
#define NIFPP_HAS_MAPS ((ERL_NIF_MAJOR_VERSION > 2) || (ERL_NIF_MAJOR_VERSION==2 && ERL_NIF_MINOR_VERSION >= 6))

#include <string>
#include <tuple>
#include <array>
#include <vector>
#include <list>
#include <deque>
#include <set>
#include <unordered_set>
#if NIFPP_HAS_MAPS
#include <map>
#include <unordered_map>
#endif
#include <cassert>
#include <cstring>

namespace nifpp
{

struct TERM
{
    ERL_NIF_TERM v;

    TERM(){}
    explicit TERM(ERL_NIF_TERM x):v(x){}

    inline operator ERL_NIF_TERM(){return v;}

    bool operator<(const TERM rhs) const
    {return v<rhs.v;}

    bool operator==(const TERM rhs) const
    {return v==rhs.v;}
};

static_assert(sizeof(TERM)==sizeof(ERL_NIF_TERM), "TERM size does not match ERL_NIF_TERM");

class str_atom: public std::string
{
public:
    template<class ... Args>
    str_atom(Args&& ... args) : std::string(args...) { }
};

} //namespace nifpp

// Add std::hash specializations.
// This allows nifpp types to be used in unordered_xxx containers.
namespace std {

template<> struct hash<nifpp::TERM>
{
  std::size_t operator()(const nifpp::TERM& k) const
  {
      return hash<ERL_NIF_TERM>()(k.v);
  }
};

template<> struct hash<nifpp::str_atom>
{
  std::size_t operator()(const nifpp::str_atom& k) const
  {
      return hash<std::string>()(k);
  }
};

} //namespace std

namespace nifpp
{

struct binary;
TERM make(ErlNifEnv *env, binary &var);
struct binary: public ErlNifBinary
{
public:
    //binary(): needs_release(false) {}
    binary(size_t _size)
    {
        if(enif_alloc_binary(_size, this))
        {
            needs_release=true;
        }
        else
        {
            needs_release=false;
        }
    }

#ifdef NIFPP_INTRUSIVE_UNIT_TEST
    static int release_counter;
#endif
    ~binary()
    {
        if(needs_release)
        {
#ifdef NIFPP_INTRUSIVE_UNIT_TEST
            release_counter++;
#endif
            enif_release_binary(this);
        }
    }

    friend TERM make(ErlNifEnv *env, binary &var); // make can set owns_data to false

protected:
    bool needs_release;

private:
    // there's no nice way to keep track of owns_data in copies, so just prevent copying
    binary(const binary &src){}
};

#ifdef NIFPP_INTRUSIVE_UNIT_TEST
int binary::release_counter=0;
#endif

class badarg{};

//
// get()/make() functions
//

// forward declare all container overloads so they can be used recursively
template<typename ...Ts> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::tuple<Ts...> &var);
template<typename ...Ts> TERM make(ErlNifEnv *env, const std::tuple<Ts...> &var);

template<typename T> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::vector<T> &var);
template<typename T> TERM make(ErlNifEnv *env, const std::vector<T> &var);
TERM make(ErlNifEnv *env, const std::vector<TERM> &var);

template<typename T, size_t N> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::array<T, N> &var);
template<typename T, size_t N> TERM make(ErlNifEnv *env, const std::array<T, N> &var);
template<size_t N>TERM make(ErlNifEnv *env, const std::array<TERM, N> &var);

template<typename T> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::list<T> &var);
template<typename T> TERM make(ErlNifEnv *env, const std::list<T> &var);

template<typename T> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::deque<T> &var);
template<typename T> TERM make(ErlNifEnv *env, const std::deque<T> &var);

template<typename T> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::set<T> &var);
template<typename T> TERM make(ErlNifEnv *env, const std::set<T> &var);

template<typename T> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::unordered_set<T> &var);
template<typename T> TERM make(ErlNifEnv *env, const std::unordered_set<T> &var);

template<typename T> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::multiset<T> &var);
template<typename T> TERM make(ErlNifEnv *env, const std::multiset<T> &var);

#if NIFPP_HAS_MAPS
template<typename TK, typename TV> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::map<TK,TV> &var);
template<typename TK, typename TV> TERM make(ErlNifEnv *env, const std::map<TK,TV> &var);

template<typename TK, typename TV> int get(ErlNifEnv *env, ERL_NIF_TERM term, std::unordered_map<TK,TV> &var);
template<typename TK, typename TV> TERM make(ErlNifEnv *env, const std::unordered_map<TK,TV> &var);
#endif

// ERL_NIF_TERM
inline int get(ErlNifEnv *env, ERL_NIF_TERM term, TERM &var)
{
    var = TERM(term);
    return 1;
}
inline TERM make(ErlNifEnv *env, const TERM term)
{
    return TERM(term);
}

// str_atom
inline int get(ErlNifEnv *env, ERL_NIF_TERM term, str_atom &var)
{
    unsigned len;
    int ret = enif_get_atom_length(env, term, &len, ERL_NIF_LATIN1);
    if(!ret) return 0;
    var.resize(len+1); // +1 for terminating null
    ret =  enif_get_atom(env, term,
                         &(*(var.begin())), var.size(), ERL_NIF_LATIN1);
    if(!ret) return 0;
    var.resize(len); // trim terminating null
    return 1;
}
inline TERM make(ErlNifEnv *env, const str_atom &var)
{
    return TERM(enif_make_atom(env, var.c_str()));
}

// std::string
inline int get(ErlNifEnv *env, ERL_NIF_TERM term, std::string &var)
{
    // The implementation below iterates through the list twice.  It may
    // be faster to iterate through the list and append bytes one at a time.

    unsigned len;
    int ret = enif_get_list_length(env, term, &len); // full list iteration
    if(!ret)
    {
        // not a list, try as binary
        ErlNifBinary bin;
        ret = enif_inspect_binary(env, term, &bin);
        if(!ret)
        {
            // not a binary either, so fail.
            return 0;
        }
        var = std::string((const char*)bin.data, bin.size);
        return ret;
    }
    var.resize(len+1); // +1 for terminating null
    ret =  enif_get_string(env, term, &*(var.begin()), var.size(), ERL_NIF_LATIN1); // full list iteration
    if(ret > 0)
    {
        var.resize(ret-1); // trim terminating null
    }
    else if(ret==0)
    {
        var.resize(0);
    }
    else
    {
        // oops string somehow got truncated
        // var is correct size so do nothing
    }
    return ret;
}
inline TERM make(ErlNifEnv *env, const std::string &var)
{
    return TERM(enif_make_string_len(env, &(*(var.begin())), var.size(), ERL_NIF_LATIN1));
}

// bool
inline int get(ErlNifEnv *env, ERL_NIF_TERM term, bool &var)
{
    char buf[6]; // max( len("true"), len("false")) + 1

    if(!enif_get_atom(env, term, buf, sizeof(buf), ERL_NIF_LATIN1))
        return 0;

    if(strcmp(buf, "true")==0)
    {
        var = true;
        return 1;
    }
    else if(strcmp(buf, "false")==0)
    {
        var = false;
        return 1;
    }

    return 0; // some other atom, return error
}
inline TERM make(ErlNifEnv *env, const bool var)
{
    return TERM(enif_make_atom(env, var?"true":"false"));
}

// Number conversions

inline int get(ErlNifEnv *env, ERL_NIF_TERM term, double &var)
{
    return enif_get_double(env, term, &var);
}
inline TERM make(ErlNifEnv *env, const double var)
{
    return TERM(enif_make_double(env, var));
}

inline int get(ErlNifEnv *env, ERL_NIF_TERM term, int &var)
{
    return enif_get_int(env, term, &var);
}
inline TERM make(ErlNifEnv *env, const int var)
{
    return TERM(enif_make_int(env, var));
}

inline int get(ErlNifEnv *env, ERL_NIF_TERM term, unsigned int &var)
{
    return enif_get_uint(env, term, &var);
}
inline TERM make(ErlNifEnv *env, const unsigned int var)
{
    return TERM(enif_make_uint(env, var));
}

#if SIZEOF_LONG != 8
inline int get(ErlNifEnv *env, ERL_NIF_TERM term, ErlNifSInt64 &var)
{
    return enif_get_int64(env, term, &var);
}
inline TERM make(ErlNifEnv *env, const ErlNifSInt64 var)
{
    return TERM(enif_make_int64(env, var));
}

inline int get(ErlNifEnv *env, ERL_NIF_TERM term, ErlNifUInt64 &var)
{
    return enif_get_uint64(env, term, &var);
}
inline TERM make(ErlNifEnv *env, const ErlNifUInt64 var)
{
    return TERM(enif_make_uint64(env, var));
}
#endif

inline int get(ErlNifEnv *env, ERL_NIF_TERM term, long &var)
{
    return enif_get_long(env, term, &var);
}
inline TERM make(ErlNifEnv *env, const long var)
{
    return TERM(enif_make_long(env, var));
}

inline int get(ErlNifEnv *env, ERL_NIF_TERM term, unsigned long &var)
{
    return enif_get_ulong(env, term, &var);
}
inline TERM make(ErlNifEnv *env, const unsigned long var)
{
    return TERM(enif_make_ulong(env, var));
}

// binary and ErlNifBinary

inline int get(ErlNifEnv *env, ERL_NIF_TERM term, ErlNifBinary &var)
{
    return enif_inspect_binary(env, term, &var);
}
inline TERM make(ErlNifEnv *env, ErlNifBinary &var)
{
    return TERM(enif_make_binary(env, &var));
}
inline TERM make(ErlNifEnv *env, binary &var)
{
    var.needs_release = false;
    return TERM(enif_make_binary(env, &var));
}

// ErlNifPid

inline int get(ErlNifEnv *env, ERL_NIF_TERM term, ErlNifPid &var)
{
    return TERM(enif_get_local_pid(env, term, &var));
}

inline TERM make(ErlNifEnv *env, const ErlNifPid &var)
{
    return TERM(enif_make_pid(env, &var));
}

//
// resource wrappers
//

// forward declarations for friend statements
template<class T> class resource_ptr;
template<typename T> int get(ErlNifEnv *env, ERL_NIF_TERM term, resource_ptr<T> &var);
template<typename T, typename ...Args> resource_ptr<T> construct_resource(Args&&... args);

template<class T> class resource_ptr
{
private:

    typedef resource_ptr this_type;

public:

    typedef T element_type;

    resource_ptr(): px( 0 )
    {
    }

private:
    resource_ptr( T * p, bool add_ref ): px( p )
    {
        if( px != 0 && add_ref ) enif_keep_resource((void*)px);
    }

    // construction only permitted from these functions:
    template<typename U, typename ...Args>
    friend resource_ptr<U> construct_resource(Args&&... args);
    template<typename U>
    friend int get(ErlNifEnv *env, ERL_NIF_TERM term, resource_ptr<U> &var);
    // I would have liked to specialize these to T instead of granting access
    // to all U, but this is just simpler.

public:

    resource_ptr(resource_ptr const & rhs): px( rhs.px )
    {
        if( px != 0 ) enif_keep_resource((void*)px);
    }

    ~resource_ptr()
    {
        if( px != 0 ) enif_release_resource((void*)px);
    }

    resource_ptr(resource_ptr && rhs): px( rhs.px )
    {
        rhs.px = 0;
    }

    resource_ptr & operator=(resource_ptr && rhs)
    {
        this_type( static_cast< resource_ptr && >( rhs ) ).swap(*this);
        return *this;
    }

    resource_ptr & operator=(resource_ptr const & rhs)
    {
        this_type(rhs).swap(*this);
        return *this;
    }

    resource_ptr & operator=(T * rhs)
    {
        this_type(rhs).swap(*this);
        return *this;
    }

    void reset()
    {
        this_type().swap( *this );
    }

    void reset( T * rhs )
    {
        this_type( rhs ).swap( *this );
    }

    T * get() const
    {
        return px;
    }

    T & operator*() const
    {
        assert( px != 0 );
        return *px;
    }

    T * operator->() const
    {
        assert( px != 0 );
        return px;
    }

    operator bool () const
    {
        return px != 0;
    }

    void swap(resource_ptr & rhs)
    {
        T * tmp = px;
        px = rhs.px;
        rhs.px = tmp;
    }

private:

    T * px;
};

template<class T, class U> inline bool operator==(resource_ptr<T> const & a, resource_ptr<U> const & b)
{
    return a.get() == b.get();
}

template<class T, class U> inline bool operator!=(resource_ptr<T> const & a, resource_ptr<U> const & b)
{
    return a.get() != b.get();
}

template<class T, class U> inline bool operator==(resource_ptr<T> const & a, U * b)
{
    return a.get() == b;
}

template<class T, class U> inline bool operator!=(resource_ptr<T> const & a, U * b)
{
    return a.get() != b;
}

template<class T, class U> inline bool operator==(T * a, resource_ptr<U> const & b)
{
    return a == b.get();
}

template<class T, class U> inline bool operator!=(T * a, resource_ptr<U> const & b)
{
    return a != b.get();
}

template<class T> inline bool operator<(resource_ptr<T> const & a, resource_ptr<T> const & b)
{
    return std::less<T *>()(a.get(), b.get());
}

template<class T> void swap(resource_ptr<T> & lhs, resource_ptr<T> & rhs)
{
    lhs.swap(rhs);
}

// mem_fn support

template<class T> T * get_pointer(resource_ptr<T> const & p)
{
    return p.get();
}

template<class T, class U> resource_ptr<T> static_pointer_cast(resource_ptr<U> const & p)
{
    return static_cast<T *>(p.get());
}

template<class T, class U> resource_ptr<T> const_pointer_cast(resource_ptr<U> const & p)
{
    return const_cast<T *>(p.get());
}

template<class T, class U> resource_ptr<T> dynamic_pointer_cast(resource_ptr<U> const & p)
{
    return dynamic_cast<T *>(p.get());
}

namespace detail //(resource detail)
{

template<typename T>
struct dtor_wrapper
{
    T obj;
    bool constructed;
};

template<typename T>
void resource_dtor(ErlNifEnv*, void* obj)
{
    // invoke destructor only if object was successfully constructed
    if(reinterpret_cast<dtor_wrapper<T>*>(obj)->constructed)
    {
        reinterpret_cast<T*>(obj)->~T();
    }
}

template<typename T>
struct resource_data
{
    static ErlNifResourceType* type;
};

template<typename T> ErlNifResourceType* resource_data<T>::type=0;
/*
The above definition deserves some explanation:

As the compiler sees usages of register_resource<T>() and get(..., resource_ptr<T>),
instances of the above variable will pop into existance to hold the Erlang
resource type (ErlNifResourceType*).  register_resource<T>() initializes the
value, and get(..., resource_ptr<T>) uses it.

Definitions of static data members have external linkage, so if you are using
the same resource type in multiple source files, each compiled object will
have a duplicate instance of resource_data<T>::type.  For non-template static
data members you will get duplicate symbol errors at link-time.  For *template*
static data members, the consensus seems to be that the linker should eliminate
all duplicates (which is what we want).  The C++ standard isn't very explicit
about this (at least to me), so if you do run into duplicate symbol issues with
the above definition, simply move the above def into your source file where all
your register_resource<T>() calls are.  This will ensure that the above
definition appears only once in the final binary.

References:
http://stackoverflow.com/questions/19366615/static-member-variable-in-class-template

*/

} // namespace detail (resource detail)

template<typename T>
int get(ErlNifEnv *env, ERL_NIF_TERM term, resource_ptr<T> &var)
{
    void *rawptr;
    if(!enif_get_resource(env, term, detail::resource_data<T>::type, &rawptr))
        return 0;
    var=resource_ptr<T>((T*)rawptr, true);
    return 1;
}
template<typename T>
int get(ErlNifEnv *env, ERL_NIF_TERM term, T* &var)
{
    return enif_get_resource(env, term, detail::resource_data<T>::type, (void**)&var);
}
template<typename T>
TERM make(ErlNifEnv *env, const resource_ptr<T> &var)
{
    return TERM(enif_make_resource(env, (void*)var.get()));
}
template<typename T>
TERM make_resource_binary(ErlNifEnv *env, const resource_ptr<T> &var, const void* data, size_t size)
{
    return TERM(enif_make_resource_binary(env, (void*)var.get(), data, size));
}

template<typename T>
int register_resource(ErlNifEnv* env,
                      const char* module_str,
                      const char* name,
                      ErlNifResourceFlags flags = ErlNifResourceFlags(ERL_NIF_RT_CREATE|ERL_NIF_RT_TAKEOVER),
                      ErlNifResourceFlags* tried = nullptr)
{
    ErlNifResourceType* type = enif_open_resource_type(env,
                                                       module_str,
                                                       name,
                                                       &detail::resource_dtor<T>,
                                                       flags,
                                                       tried);

    if(!type)
    {
        detail::resource_data<T>::type = 0;
        return 0;
    }
    else
    {
        detail::resource_data<T>::type = type;
        return 1;
    }
}

template<typename T, typename ...Args>
resource_ptr<T> construct_resource(Args&&... args)
{
    ErlNifResourceType* type = detail::resource_data<T>::type;
    assert(type!=0);
    if(type)
    {
        void *mem = enif_alloc_resource(type, sizeof(detail::dtor_wrapper<T>));

        // immediately assign to resource pointer so that release will be called if construction fails
        resource_ptr<T> rptr(reinterpret_cast<T*>(mem), false); //note: private ctor
        // inhibit destructor in case ctor fails
        reinterpret_cast<detail::dtor_wrapper<T>*>(mem)->constructed = false;

        //  invoke constructor with "placement new"
        new(mem) T(std::forward<Args>(args)...);

        // ctor succeeded, enable dtor
        reinterpret_cast<detail::dtor_wrapper<T>*>(mem)->constructed = true;
        return std::move(rptr);
    }
    else
    {
        return resource_ptr<T>();
    }
}

//
// container get()/make()
//

// tuple

namespace detail
{

//    I would have liked to implement the template below as only a function,
//    but partial specialization of template functions is not permitted. Hence
//    the weird stuct/function composite.

    template<int I>
    struct array_to_tupler
    {
        template<typename ...Ts>
        static int go(ErlNifEnv *env, std::tuple<Ts...> &t, const ERL_NIF_TERM *end)
        {
            end--;
            if(!array_to_tupler<I-1>::go(env, t, end))
                return 0;
            return get(env, *end, std::get<I-1>(t));
        }
    };

    template<>
    struct array_to_tupler<0>
    {
        template<typename ...Ts>
        static int go(ErlNifEnv *env, std::tuple<Ts...> &t, const ERL_NIF_TERM *end)
        {
            return 1;
        }
    };
} // namespace detail

template<typename ...Ts>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::tuple<Ts...> &var)
{
    int arity;
    const ERL_NIF_TERM *array;
    int ret = enif_get_tuple(env, term, &arity, &array);

    // check if tuple
    if(!ret)
        return ret;

    // check for matching arity
    if(size_t(arity) != std::tuple_size<std::tuple<Ts...>>::value)
        return 0;

    // invoke recursive template to convert all items of tuple
    return detail::array_to_tupler<std::tuple_size<std::tuple<Ts...>>::value>::go(env, var, array+arity);
}

namespace detail
{
    template<int I>
    struct tuple_to_arrayer
    {
        template<typename ...Ts>
        static void go(ErlNifEnv *env, const std::tuple<Ts...> &t, ERL_NIF_TERM *end)
        {
            tuple_to_arrayer<I-1>::go(env, t, --end);
            *end = make(env, std::get<I-1>(t));
        }
    };

    template<>
    struct tuple_to_arrayer<0>
    {
        template<typename ...Ts>
        static void go(ErlNifEnv *env, const std::tuple<Ts...> &t, ERL_NIF_TERM *end)
        {}
    };
} // namespace detail

template<typename ...Ts>
TERM make(ErlNifEnv *env, const std::tuple<Ts...> &var)
{
    std::array<ERL_NIF_TERM, std::tuple_size<std::tuple<Ts...>>::value> array;
    detail::tuple_to_arrayer<std::tuple_size<std::tuple<Ts&...>>::value>::go(env, var, array.end());
    return TERM(enif_make_tuple_from_array(env, array.begin(), array.size()));
}

/*
  Disabling for now.  These feel too "loose".  Just use an explicit tuple
template<typename T0, typename T1, typename ...Ts>
int get(ErlNifEnv *env, ERL_NIF_TERM term, T0 &t0, T1 &t1, Ts&... ts)
{
    auto tup = std::tie(t0, t1, ts...);
    return get(env, term, tup);
}

template<typename T0, typename T1, typename ...Ts>
ERL_NIF_TERM make(ErlNifEnv *env, const T0 &t0, const T1 &t1, const Ts&... ts)
{
    return make(env, std::make_tuple(t0, t1, ts...));
}
*/

/*
template<typename T=ERL_NIF_TERM, typename F>
int niftuple_for_each(ErlNifEnv *env, ERL_NIF_TERM term, const F &f)
{
    int arity;
    ERL_NIF_TERM *array;
    if(!enif_get_tuple(env, term, &arity, &array)) return 0;
    for(int i=0; i<arity; i++)
    {
        T var;
        if(!get(env, array[i], var)) return 0; // conversion failure
        f(std::move(var));
    }
    return 1;
}
*/

// list

template<typename T=ERL_NIF_TERM, typename F>
int list_for_each(ErlNifEnv *env, ERL_NIF_TERM term, const F &f)
{
    if(!enif_is_list(env, term)) return 0;
    ERL_NIF_TERM head, tail;
    tail = term;
    while(enif_get_list_cell(env, tail, &head, &tail))
    {
        T var;
        if(!get(env, head, var)) return 0; // conversion failure
        f(std::move(var));
    }
    return 1;
}

template<typename T>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::vector<T> &var)
{
    unsigned len;
    int ret = enif_get_list_length(env, term, &len);
    if(!ret) return 0;
    var.clear();
    return list_for_each<T>(env, term, [&var](T item){var.push_back(item);});
}
template<typename T>
TERM make(ErlNifEnv *env, const std::vector<T> &var)
{
    ERL_NIF_TERM tail;
    tail = enif_make_list(env, 0);
    for(auto i=var.rbegin(); i!=var.rend(); i++)
    {
        tail = enif_make_list_cell(env, make(env,*i), tail);
    }
    return TERM(tail);
}
inline TERM make(ErlNifEnv *env, const std::vector<TERM> &var)
{
    return TERM(enif_make_list_from_array(env, (ERL_NIF_TERM*)&var[0], var.size()));
}

template<typename T, size_t N>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::array<T, N> &var)
{
    unsigned len;
    int ret = enif_get_list_length(env, term, &len);
    if(!ret) return 0;

    // arrays are statically sized so size must match.
    if(size_t(len) != var.size()) return 0;

    int i=0;
    return list_for_each<T>(env, term, [&var, &i](T item){var[i++] = item;});
}
template<typename T, size_t N>
TERM make(ErlNifEnv *env, const std::array<T, N> &var)
{
    ERL_NIF_TERM tail;
    tail = enif_make_list(env, 0);
    for(auto i=var.rbegin(); i!=var.rend(); i++)
    {
        tail = enif_make_list_cell(env, make(env,*i), tail);
    }
    return TERM(tail);
}
template<size_t N>
TERM make(ErlNifEnv *env, const std::array<TERM, N> &var)
{
    return TERM(enif_make_list_from_array(env, (ERL_NIF_TERM*)&var[0], var.size()));
}

template<typename T>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::list<T> &var)
{
    var.clear();
    return list_for_each<T>(env, term, [&var](T item){var.push_back(item);});
}
template<typename T>
TERM make(ErlNifEnv *env, const std::list<T> &var)
{
    ERL_NIF_TERM tail;
    tail = enif_make_list(env, 0);
    for(auto i=var.rbegin(); i!=var.rend(); i++)
    {
        tail = enif_make_list_cell(env, make(env,*i), tail);
    }
    return TERM(tail);
}

template<typename T>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::deque<T> &var)
{
    var.clear();
    return list_for_each<T>(env, term, [&var](T item){var.push_back(item);});
}
template<typename T>
TERM make(ErlNifEnv *env, const std::deque<T> &var)
{
    ERL_NIF_TERM tail;
    tail = enif_make_list(env, 0);
    for(auto i=var.rbegin(); i!=var.rend(); i++)
    {
        tail = enif_make_list_cell(env, make(env,*i), tail);
    }
    return TERM(tail);
}

template<typename T>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::set<T> &var)
{
    var.clear();
    return list_for_each<T>(env, term, [&var](T item){var.insert(item);});
}
template<typename T>
TERM make(ErlNifEnv *env, const std::set<T> &var)
{
    ERL_NIF_TERM tail;
    tail = enif_make_list(env, 0);
    for(auto i=var.rbegin(); i!=var.rend(); i++)
    {
        tail = enif_make_list_cell(env, make(env,*i), tail);
    }
    return TERM(tail);
}

template<typename T>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::unordered_set<T> &var)
{
    var.clear();
    return list_for_each<T>(env, term, [&var](T item){var.insert(item);});
}
template<typename T>
TERM make(ErlNifEnv *env, const std::unordered_set<T> &var)
{
    ERL_NIF_TERM tail;
    tail = enif_make_list(env, 0);
    for(auto i=var.begin(); i!=var.end(); i++)
    {
        tail = enif_make_list_cell(env, make(env,*i), tail);
    }
    return TERM(tail);
}

template<typename T>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::multiset<T> &var)
{
    var.clear();
    return list_for_each<T>(env, term, [&var](T item){var.insert(item);});
}
template<typename T>
TERM make(ErlNifEnv *env, const std::multiset<T> &var)
{
    ERL_NIF_TERM tail;
    tail = enif_make_list(env, 0);
    for(auto i=var.rbegin(); i!=var.rend(); i++)
    {
        tail = enif_make_list_cell(env, make(env,*i), tail);
    }
    return TERM(tail);
}

#if NIFPP_HAS_MAPS
template<typename TK, typename TV, typename F>
int map_for_each(ErlNifEnv *env, ERL_NIF_TERM term, const F &f)
{
    ErlNifMapIterator iter;

    if(!enif_map_iterator_create(env, term, &iter, ERL_NIF_MAP_ITERATOR_HEAD)) return 0;

    TERM key_term, value_term;
    TK key;
    TV value;
    while(enif_map_iterator_get_pair(env, &iter, (ERL_NIF_TERM *)&key_term, (ERL_NIF_TERM *)&value_term))
    {
        if(!get(env, key_term, key)) goto error; // conversion failure
        if(!get(env, value_term, value)) goto error; // conversion failure
        f(std::move(key), std::move(value));

        enif_map_iterator_next(env, &iter);
    }
    enif_map_iterator_destroy(env, &iter);
    return 1;

    error:
    enif_map_iterator_destroy(env, &iter);
    return 0;
}

template<typename TK, typename TV>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::map<TK,TV> &var)
{
    var.clear();
    return map_for_each<TK,TV>(env, term, [&var](TK key, TV value){var[key]=value;});
}

template<typename TK, typename TV>
TERM make(ErlNifEnv *env, const std::map<TK,TV> &var)
{
    TERM map(enif_make_new_map(env));
    for(auto i=var.begin(); i!=var.end(); i++)
    {
        enif_make_map_put(env, map, make(env, i->first), make(env, i->second), (ERL_NIF_TERM *)&map);
    }
    return map;
}

template<typename TK, typename TV>
int get(ErlNifEnv *env, ERL_NIF_TERM term, std::unordered_map<TK,TV> &var)
{
    var.clear();
    return map_for_each<TK,TV>(env, term, [&var](TK key, TV value){var[key]=value;});
}

template<typename TK, typename TV>
TERM make(ErlNifEnv *env, const std::unordered_map<TK,TV> &var)
{
    TERM map(enif_make_new_map(env));
    for(auto i=var.begin(); i!=var.end(); i++)
    {
        enif_make_map_put(env, map, make(env, i->first), make(env, i->second), (ERL_NIF_TERM *)&map);
    }
    return map;
}
#endif //NIFPP_HAS_MAPS

// convenience wrappers for get()

template<typename T>
T get(ErlNifEnv *env, ERL_NIF_TERM term)
{
    T temp;
    if(get(env, term, temp))
    {
        return std::move(temp);
    }
    throw badarg();
}

template<typename T>
void get_throws(ErlNifEnv *env, ERL_NIF_TERM term, T &t)
{
    if(!get(env, term, t))
    {
        throw badarg();
    }
}

} // namespace nifpp

#endif // NIFPP_H


text:
using System;
using System.Data.SqlTypes;
using System.Collections.Generic;
using Chutzpah.Models;

namespace Chutzpah.FrameworkDefinitions
{

    /// <summary>
    /// Interface that describes a test framework.
    /// </summary>
    public interface IFrameworkDefinition
    {
        /// <summary>
        /// Gets a list of file dependencies to bundle with the framework test harness.
        /// </summary>
        /// <param name="chutzpahTestSettings"></param>
        IEnumerable<string> GetFileDependencies(ChutzpahTestSettingsFile chutzpahTestSettings);

        /// <summary>
        /// Gets the file name of the HTML test harness to use with the framework.
        /// </summary>
        /// <param name="chutzpahTestSettings"></param>
        string GetTestHarness(ChutzpahTestSettingsFile chutzpahTestSettings);

        /// <summary>
        /// Gets the file name of the JavaScript test runner to use with the framework.
        /// </summary>
        /// <param name="chutzpahTestSettings"></param>
        string GetTestRunner(ChutzpahTestSettingsFile chutzpahTestSettings);

        /// <summary>
        /// Gets the name of the blanket script to use for code coverage
        /// </summary>
        /// <param name="chutzpahTestSettings"></param>
        /// <returns></returns>
        string GetBlanketScriptName(ChutzpahTestSettingsFile chutzpahTestSettings);

        /// <summary>
        /// Gets a short, file system friendly key for the framework library.
        /// </summary>
        string FrameworkKey { get; }

        /// <summary>
        /// Tests whether the given file contents uses the framework.
        /// </summary>
        /// <param name="fileContents">Contents of the file as a string to test.</param>
        /// <param name="bestGuess">True if the method should fall back to best guess detection.</param>
        /// <param name="pathType">The type of the file being tests</param>
        /// <returns>True if the file uses the framework, otherwise false.</returns>
        bool FileUsesFramework(string fileContents, bool bestGuess, PathType pathType);

        /// <summary>
        /// Tests whether the given file is the framework itself or one of its core dependencies.
        /// </summary>
        /// <param name="referenceFileName">File name of a reference to test.</param>
        /// <param name="testSettingsFile"></param>
        /// <returns>True if the file is a framework dependency, otherwise false.</returns>
        bool ReferenceIsDependency(string referenceFileName, ChutzpahTestSettingsFile testSettingsFile);

        /// <summary>
        /// Processes a referenced file according to the framework's needs.
        /// </summary>
        /// <param name="referencedFile">A referenced file to process.</param>
        /// <param name="testFileText"></param>
        /// <param name="settings"></param>
        void Process(ReferencedFile referencedFile, string testFileText, ChutzpahTestSettingsFile settings);

        Dictionary<string, string> GetFrameworkReplacements(ChutzpahTestSettingsFile chutzpahTestSettings, string testFilePath, string testFileText);
    }
}


text:
%% Machine Learning Online Class
%  Exercise 5 | Regularized Linear Regression and Bias-Variance
%
%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the
%  exercise. You will need to complete the following functions:
%
%     linearRegCostFunction.m
%     learningCurve.m
%     validationCurve.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%

%% Initialization
clear ; close all; clc

%% =========== Part 1: Loading and Visualizing Data =============
%  We start the exercise by first loading and visualizing the dataset.
%  The following code will load the dataset into your environment and plot
%  the data.
%

% Load Training Data
fprintf('Loading and Visualizing Data ...\n')

% Load from ex5data1:
% You will have X, y, Xval, yval, Xtest, ytest in your environment
load ('ex5data1.mat');

% m = Number of examples
m = size(X, 1);

% Plot training data
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 2: Regularized Linear Regression Cost =============
%  You should now implement the cost function for regularized linear
%  regression.
%

theta = [1 ; 1];
J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);

fprintf(['Cost at theta = [1 ; 1]: %f '...
         '\n(this value should be about 303.993192)\n'], J);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 3: Regularized Linear Regression Gradient =============
%  You should now implement the gradient for regularized linear
%  regression.
%

theta = [1 ; 1];
[J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);

fprintf(['Gradient at theta = [1 ; 1]:  [%f; %f] '...
         '\n(this value should be about [-15.303016; 598.250744])\n'], ...
         grad(1), grad(2));

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 4: Train Linear Regression =============
%  Once you have implemented the cost and gradient correctly, the
%  trainLinearReg function will use your cost function to train
%  regularized linear regression.
%
%  Write Up Note: The data is non-linear, so this will not give a great
%                 fit.
%

%  Train linear regression with lambda = 0
lambda = 0;
[theta] = trainLinearReg([ones(m, 1) X], y, lambda);

%  Plot fit over the data
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');
hold on;
plot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2)
hold off;

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 5: Learning Curve for Linear Regression =============
%  Next, you should implement the learningCurve function.
%
%  Write Up Note: Since the model is underfitting the data, we expect to
%                 see a graph with "high bias" -- slide 8 in ML-advice.pdf
%

lambda = 0;
[error_train, error_val] = ...
    learningCurve([ones(m, 1) X], y, ...
                  [ones(size(Xval, 1), 1) Xval], yval, ...
                  lambda);

plot(1:m, error_train, 1:m, error_val);
title('Learning curve for linear regression')
legend('Train', 'Cross Validation')
xlabel('Number of training examples')
ylabel('Error')
axis([0 13 0 150])

fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
for i = 1:m
    fprintf('  \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
end

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 6: Feature Mapping for Polynomial Regression =============
%  One solution to this is to use polynomial regression. You should now
%  complete polyFeatures to map each example into its powers
%

p = 8;

% Map X onto Polynomial Features and Normalize
X_poly = polyFeatures(X, p);
[X_poly, mu, sigma] = featureNormalize(X_poly);  % Normalize
X_poly = [ones(m, 1), X_poly];                   % Add Ones

% Map X_poly_test and normalize (using mu and sigma)
X_poly_test = polyFeatures(Xtest, p);
X_poly_test = bsxfun(@minus, X_poly_test, mu);
X_poly_test = bsxfun(@rdivide, X_poly_test, sigma);
X_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test];         % Add Ones

% Map X_poly_val and normalize (using mu and sigma)
X_poly_val = polyFeatures(Xval, p);
X_poly_val = bsxfun(@minus, X_poly_val, mu);
X_poly_val = bsxfun(@rdivide, X_poly_val, sigma);
X_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val];           % Add Ones

fprintf('Normalized Training Example 1:\n');
fprintf('  %f  \n', X_poly(1, :));

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% =========== Part 7: Learning Curve for Polynomial Regression =============
%  Now, you will get to experiment with polynomial regression with multiple
%  values of lambda. The code below runs polynomial regression with
%  lambda = 0. You should try running the code with different values of
%  lambda to see how the fit and learning curve change.
%

lambda = 1;
[theta] = trainLinearReg(X_poly, y, lambda);

% Plot training data and fit
figure(1);
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
plotFit(min(X), max(X), mu, sigma, theta, p);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');
title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));

figure(2);
[error_train, error_val] = ...
    learningCurve(X_poly, y, X_poly_val, yval, lambda);
plot(1:m, error_train, 1:m, error_val);

title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
xlabel('Number of training examples')
ylabel('Error')
axis([0 13 0 100])
legend('Train', 'Cross Validation')

fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
for i = 1:m
    fprintf('  \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
end

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 8: Validation for Selecting Lambda =============
%  You will now implement validationCurve to test various values of
%  lambda on a validation set. You will then use this to select the
%  "best" lambda value.
%

[lambda_vec, error_train, error_val] = ...
    validationCurve(X_poly, y, X_poly_val, yval);

close all;
plot(lambda_vec, error_train, lambda_vec, error_val);
legend('Train', 'Cross Validation');
xlabel('lambda');
ylabel('Error');

fprintf('lambda\t\tTrain Error\tValidation Error\n');
for i = 1:length(lambda_vec)
	fprintf(' %f\t%f\t%f\n', ...
            lambda_vec(i), error_train(i), error_val(i));
end

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 9: Computing test set error ===================
%  Compute the test error using the best value of lambda you found.
%  In our cross validation, we obtained a test error of 3.8599 for lambda = 3.
%

lambda = 3;

theta = trainLinearReg(X_poly, y, lambda);
error_test = linearRegCostFunction(X_poly_test, ytest, theta, 0);

%fprintf(['Error with test set: %f\n'], error_test);
fprintf(['Test error (lambda = %f): %f'...
         '\n(this value should be about 3.8599)\n'], lambda, error_test);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 10: Learning curves with randomly selected examples =======
%  To determine the training error and cross validation error for i examples,
%  you should first randomly select i examples from the training set and
%  i examples from the cross validation set. You will then learn the parameters
%  theta using the randomly chosen training set and evaluate the parameters
%  theta on the randomly chosen training set and cross validation set.
%  The above steps should then be repeated multiple times (say 50) and
%  the averaged error should be used to determine the training error and
%  cross validation error for i examples.
%

steps = 50;
lambda = 0.01;
[theta] = trainLinearReg(X_poly, y, lambda);

[error_train, error_val] = ...
    learningCurveWithRandomExamples(X_poly, y, X_poly_val, yval, lambda, steps);
plot(1:m, error_train, 1:m, error_val);

title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
xlabel('Number of training examples')
ylabel('Error')
axis([0 13 0 100])
legend('Train', 'Cross Validation')

fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
for i = 1:m
    fprintf('  \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
end

fprintf('Program paused. Press enter to continue.\n');
pause;


text:
@interface GWDSubTagTableVC : UITableViewController

@end


text:
$UrlRouterProvider.$inject = ['$urlMatcherFactoryProvider'];
function $UrlRouterProvider(  $urlMatcherFactory) {
  var rules = [],
      otherwise = null;

  // Returns a string that is a prefix of all strings matching the RegExp
  function regExpPrefix(re) {
    var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
    return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
  }

  // Interpolates matched values into a String.replace()-style pattern
  function interpolate(pattern, match) {
    return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
      return match[what === '$' ? 0 : Number(what)];
    });
  }

  this.rule =
    function (rule) {
      if (!isFunction(rule)) throw new Error("'rule' must be a function");
      rules.push(rule);
      return this;
    };

  this.otherwise =
    function (rule) {
      if (isString(rule)) {
        var redirect = rule;
        rule = function () { return redirect; };
      }
      else if (!isFunction(rule)) throw new Error("'rule' must be a function");
      otherwise = rule;
      return this;
    };

  function handleIfMatch($injector, handler, match) {
    if (!match) return false;
    var result = $injector.invoke(handler, handler, { $match: match });
    return isDefined(result) ? result : true;
  }

  this.when =
    function (what, handler) {
      var redirect, handlerIsString = isString(handler);
      if (isString(what)) what = $urlMatcherFactory.compile(what);

      if (!handlerIsString && !isFunction(handler) && !isArray(handler))
        throw new Error("invalid 'handler' in when()");

      var strategies = {
        matcher: function (what, handler) {
          if (handlerIsString) {
            redirect = $urlMatcherFactory.compile(handler);
            handler = ['$match', function ($match) { return redirect.format($match); }];
          }
          return extend(function ($injector, $location) {
            return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
          }, {
            prefix: isString(what.prefix) ? what.prefix : ''
          });
        },
        regex: function (what, handler) {
          if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");

          if (handlerIsString) {
            redirect = handler;
            handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
          }
          return extend(function ($injector, $location) {
            return handleIfMatch($injector, handler, what.exec($location.path()));
          }, {
            prefix: regExpPrefix(what)
          });
        }
      };

      var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };

      for (var n in check) {
        if (check[n]) {
          return this.rule(strategies[n](what, handler));
        }
      }

      throw new Error("invalid 'what' in when()");
    };

  this.$get =
    [        '$location', '$rootScope', '$injector',
    function ($location,   $rootScope,   $injector) {
      // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
      function update() {
        function check(rule) {
          var handled = rule($injector, $location);
          if (handled) {
            if (isString(handled)) $location.replace().url(handled);
            return true;
          }
          return false;
        }
        var n=rules.length, i;
        for (i=0; i<n; i++) {
          if (check(rules[i])) return;
        }
        // always check otherwise last to allow dynamic updates to the set of rules
        if (otherwise) check(otherwise);
      }

      $rootScope.$on('$locationChangeSuccess', update);
      return {};
    }];
}

angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);


text:
System.register(['./first.js'], function (exports, module) {
	'use strict';
	return {
		setters: [function (module) {
			exports('default', module.default);
		}],
		execute: function () {

		}
	};
});


text:
{% capture imagePath %}/files/{{ page.date | date: "%Y-%m-%d" }}/{{ include.name }}{% endcapture %}
{% if include.nameSmall %}
  {% capture smallImagePath %}/files/{{ page.date | date: "%Y-%m-%d" }}/{{ include.nameSmall }}{% endcapture %}
{% endif %}

{% if include.alt %}
  {% capture alt %}{{ include.alt }}{% endcapture %}
{% else %}
  {% capture alt %}{{ include.caption }}{% endcapture %}
{% endif %}

{% capture extension %}{{ imagePath | split: '.' | last }}{% endcapture %}
{% capture imgWidthStyle %}style="width: {{ include.width | default: '100%' }}"{% endcapture %}

  {% if extension == 'svg' %}
  <object data="{{ imagePath }}" type="image/svg+xml" {{ imgWidthStyle> }}></object>
  {% else %}
    {% if include.nameSmall %}

         }}>

    {% else %}
       }}>
    {% endif %}
  {% endif %}

  {% if include.caption %}
    {% if include.captionWidth %}
      {% assign captionWidth = include.captionWidth %}
    {% else %}
      {% assign captionWidth = include.width %}
    {% endif %}

{{ include.caption }}

  {% endif %}


text:
interface I {
    (x: string): string;
}

interface I2<T> {
    (x: T): T;
}

var a: { (x: string): string }

function foo2(x: I);
function foo2(x: I); // error
function foo2(x: any) { }

function foo3(x: typeof a);
function foo3(x: typeof a); // error
function foo3(x: any) { }

function foo4(x: typeof b);
function foo4(x: typeof b); // error
function foo4(x: any) { }

function foo13(x: I);
function foo13(x: typeof a); // error
function foo13(x: any) { }

function foo14(x: I);
function foo14(x: I2<string>); // error
function foo14(x: any) { }

function foo14b(x: typeof a);
function foo14b(x: I2<string>); // error
function foo14b(x: any) { }

function foo15(x: I);
function foo15(x: I2<number>); // ok
function foo15(x: any) { }

//// [objectTypesIdentityWithCallSignatures3.js]
// object types are identical structurally
var a;
function foo2(x) { }
function foo3(x) { }
function foo4(x) { }
function foo13(x) { }
function foo14(x) { }
function foo14b(x) { }
function foo15(x) { }


text:
app.core.router = function() {
	'use strict';

	var hooks = {};
	var self = this;
	var errorHandler = false;

	this.active = false;

	/**
	 * Click listener for links
	 * @param Event event
	 */
	var handleClick = function(event) {
		// Get the URL
		var link = $(this).attr('href');

		if (link && link !== 'javascript:void(0)') {
			// Load the page
			self.routeTo(link);

			// Send it to the browser history
			history.pushState(null, null, link);

			// Prevent site from refreshing
			event.preventDefault();
		}
	};

	/**
	 * Assign click listeners to all internal links
	 * @param String parentSelector
	 */
	this.assignEvents = function(parentSelector) {
		if (!history.pushState) return;

		var selector = 'a';

		if (parentSelector) {
			selector = parentSelector + ' ' + selector;
		}

		// Assign AJAX loading behavior
		$(selector).each(function() {
			var $element = $(this);

			// Make sure it has not been assigned already and is not an external link
			if ($element.attr('data-hasevents') != '1'
			&& $element.attr('target') != '_blank'
			&& !/http(s)?:\/\//.test($element.attr('href'))
			&& $element.attr('data-direct') != '1') {
				$element.attr('data-hasevents', '1');
				$element.on('click', handleClick);
			}
		});
	};

	/**
	 * Listen for 404 errors
	 * @param Function callback
	 */
	this.error = function(callback) {
		errorHandler = callback;
	};

	/**
	 * Attach a controller to an URL
	 * @param String call
	 * @param Function object
	 */
	this.get = function(call, object) {
		hooks[call] = object;
	};

	/**
	 * Load an URL from the hooked controllers
	 * @param String url
	 */
	this.routeTo = function(url) {
		// Remove the base path from the URL
		url = url.replace(app.config.path, '');

		// Rewrite ./ to /
		if (/^\.\/$/.test(url)) {
			url = '/';
		}

		// Force / in the beginning of URL
		if (!/^\//.test(url)) {
			url = '/' + url;
		}

		// Remove / from the end
		if (url != '/' && /\/$/.test(url)) {
			url = url.substr(0, url.length - 1);
		}

		self.active = url;

		app.core.hooks.trigger('route', { path: self.active }, function() {
			// Try to find a controller in the hooks
			if (typeof hooks[url] != 'undefined') {
				app.core.log.debug('Routed to controller [' + url + ']', 'Zeus/Router');
				window.app.controller = new hooks[url]();
			} else {
				app.core.log.warning('Controller [' + url + '] not found', 'Zeus/Router');

				if (errorHandler) {
					window.app.controller = new errorHandler();
				}
			}
		});
	};

	/**
	 * Load the default controller
	 */
	app.core.hooks.on('ready', function(data, next) {
		// Check for HTML5 pushState support
		if (history.pushState) {
			app.core.log.debug('Initialized router', 'Zeus/Router');

			$(window).bind('popstate', function() {
				self.routeTo(window.location.pathname);
			});

			self.assignEvents();
			self.routeTo(window.location.pathname);
			next();
		}
	});
};


text:
package de.lgblaumeiser.anpfiff;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;

import de.lgblaumeiser.anpfiff.simulation.SimulationManager;
import de.lgblaumeiser.anpfiff.simulation.model.Game;
import de.lgblaumeiser.anpfiff.simulation.model.GameResult;
import de.lgblaumeiser.anpfiff.simulation.model.SeasonConstants;
import de.lgblaumeiser.anpfiff.simulation.model.TableEntry;
import de.lgblaumeiser.anpfiff.simulation.services.season.SeasonManager;

public class AnpfiffRankingPage extends ActionBarActivity {
    private SeasonManager seasonManager;
    private PageState currentDisplay = PageState.Table;

    private static String makeNamesHTMLReady(String input) {
        return input.replaceAll("ü", "ü")
                    .replaceAll("ö", "ö")
                    .replaceAll("ä", "ä")
                    .replaceAll("ß", "ß")
                    .replaceAll("Ü", "Ü")
                    .replaceAll("Ö", "Ö")
                    .replaceAll("Ä", "Ä");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_anpfiff_ranking_page);
        seasonManager = new SimulationManager().simulation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SeasonManager season = seasonManager.newSeason();
        findViewById(R.id.left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leftClicked();
            }
        });
        findViewById(R.id.right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rightClicked();
            }
        });
        redraw();
    }

    private void redraw() {
        switch(currentDisplay) {
            case Table:
                drawTable();
                break;
            case NextGameDay:
                drawGameDay();
                break;
            case LastGameDay:
                drawResults();
                break;
            case PlayGameDay:
                playGameDay();
                break;
        }
    }

    private void drawTable() {
        StringBuilder htmlTableResult = new StringBuilder(2000);
        htmlTableResult.append("<title>Anpfiff Table View</title>");
        htmlTableResult.append("
Table for game day ");
        htmlTableResult.append(seasonManager.getCurrentGameDay());
        htmlTableResult.append("
");
        htmlTableResult.append("

Team	Points	Diff

");
        for (final TableEntry entry : seasonManager.getTableForLastGameDay()) {
            htmlTableResult.append("
");
            htmlTableResult.append(makeNamesHTMLReady(entry.getTeam().getName()));
            htmlTableResult.append("	");
            htmlTableResult.append(entry.getPoints());
            htmlTableResult.append("	");
            htmlTableResult.append(entry.getGoalDifference());
            htmlTableResult.append("
");
        }
        htmlTableResult.append("
");

        WebView browser = (WebView)findViewById(R.id.rankingsView);
        browser.loadData(htmlTableResult.toString(), "text/html", "UTF-8");

        Button leftButton = (Button) findViewById(R.id.left);
        leftButton.setText("Last Game Day");
        leftButton.setActivated(seasonManager.getCurrentGameDay() > 0);
        Button rightButton = (Button) findViewById(R.id.right);
        rightButton.setText("Next Game Day");
        rightButton.setActivated(seasonManager.getCurrentGameDay() < SeasonConstants.NUMBER_OF_GAME_DAYS);
    }

    private void drawGameDay() {
        StringBuilder htmlTableResult = new StringBuilder(2000);
        htmlTableResult.append("<title>Anpfiff Game Day View</title>");
        htmlTableResult.append("
Games for game day ");
        htmlTableResult.append(seasonManager.getCurrentGameDay() + 1);
        htmlTableResult.append("
");
        htmlTableResult.append("

Home Team		Guest Team

");
        for (final Game entry : seasonManager.getNextGameDay()) {
            htmlTableResult.append("
");
            htmlTableResult.append(makeNamesHTMLReady(entry.getHometeam().getName()));
            htmlTableResult.append("	vs.	");
            htmlTableResult.append(makeNamesHTMLReady(entry.getGuestteam().getName()));
            htmlTableResult.append("

");
        }
        htmlTableResult.append("");

        WebView browser = (WebView) findViewById(R.id.rankingsView);
        browser.loadData(htmlTableResult.toString(), "text/html", "UTF-8");

        Button leftButton = (Button) findViewById(R.id.left);
        leftButton.setText("Current Table");
        leftButton.setActivated(true);
        Button rightButton = (Button) findViewById(R.id.right);
        rightButton.setText("Play Game Day");
        rightButton.setActivated(true);
    }

    private void drawResults() {
        StringBuilder htmlTableResult = new StringBuilder(2000);
        htmlTableResult.append("<title>Anpfiff Game Day View</title>");
        htmlTableResult.append("
Results for game day ");
        htmlTableResult.append(seasonManager.getCurrentGameDay());
        htmlTableResult.append("
");
        htmlTableResult.append("

Home Team		Guest Team	Result

");
        for (final GameResult entry : seasonManager.getResultsForLastGameDay()) {
            htmlTableResult.append("
");
            htmlTableResult.append(makeNamesHTMLReady(entry.getHometeam().getName()));
            htmlTableResult.append("	vs.	");
            htmlTableResult.append(makeNamesHTMLReady(entry.getGuestteam().getName()));
            htmlTableResult.append("	");
            htmlTableResult.append(entry.getHometeamgoals());
            htmlTableResult.append(" : ");
            htmlTableResult.append(entry.getGuestteamgoals());
            htmlTableResult.append("

");
        }
        htmlTableResult.append("");

        WebView browser = (WebView) findViewById(R.id.rankingsView);
        browser.loadData(htmlTableResult.toString(), "text/html", "UTF-8");

        Button leftButton = (Button) findViewById(R.id.left);
        leftButton.setText("No Way");
        leftButton.setActivated(false);
        Button rightButton = (Button) findViewById(R.id.right);
        rightButton.setText("Show New Table");
        rightButton.setActivated(true);
    }

    private void playGameDay() {
        if (seasonManager.getCurrentGameDay() < SeasonConstants.NUMBER_OF_GAME_DAYS) {
            seasonManager.playNextGameDay();
        }
        currentDisplay = PageState.LastGameDay;
        redraw();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_anpfiff_ranking_page, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void rightClicked() {
        switch (currentDisplay) {
        case Table:
            currentDisplay = PageState.NextGameDay;
            break;
        case NextGameDay:
            currentDisplay = PageState.PlayGameDay;
            break;
        case LastGameDay:
            currentDisplay = PageState.Table;
            break;
        case PlayGameDay:
            currentDisplay = PageState.PlayGameDay;
            break;
        }
        redraw();
    }

    private void leftClicked() {
        switch (currentDisplay) {
        case Table:
            currentDisplay = PageState.LastGameDay;
            break;
        case NextGameDay:
            currentDisplay = PageState.Table;
            break;
        case LastGameDay:
            currentDisplay = PageState.LastGameDay;
            break;
        case PlayGameDay:
            currentDisplay = PageState.PlayGameDay;
            break;
        }
        redraw();
    }

}


text: <!DOCTYPE html>


text:
//---------------------------------------------------------------------
// <copyright file="IProtocolFormatStrategySelector.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Astoria.Contracts.OData
{
    using Microsoft.Test.Taupo.Common;

    /// <summary>
    /// Provides a mechanism for getting wire format representations for a given mime type
    /// </summary>
    [ImplementationSelector("ProtocolFormatStrategySelector",
        DefaultImplementation = "Default",
        HelpText = "The selector used when finding the wire format for a given content type")]
    public interface IProtocolFormatStrategySelector
    {
        /// <summary>
        /// Gets the serialization strategy for the given content type and uri
        /// </summary>
        /// <param name="contentType">The content type</param>
        /// <param name="uri">The request uri</param>
        /// <returns>A serialization strategy</returns>
        IProtocolFormatStrategy GetStrategy(string contentType, ODataUri uri);
    }
}


text:
<?php

namespace CoreSphere\ConsoleBundle\Tests\Source;

use Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle;
use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;

final class KernelWithBundlesWithCommands extends Kernel
{
    /**
     * {@inheritdoc}
     */
    public function registerBundles()
    {
        $bundles = [];

        if (in_array($this->getEnvironment(), ['prod'])) {
            $bundles[] = new DoctrineMigrationsBundle();
        }

        if (in_array($this->getEnvironment(), ['dev'])) {
            $bundles[] = new DoctrineFixturesBundle();
        }

        return $bundles;
    }

    /**
     * {@inheritdoc}
     */
    public function registerContainerConfiguration(LoaderInterface $loader)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function getCacheDir()
    {
        return sys_get_temp_dir().'/_console_tests/temp';
    }

    /**
     * {@inheritdoc}
     */
    public function getLogDir()
    {
        return sys_get_temp_dir().'/_console_tests/log';
    }
}


text:
<?php

// Sidebar
if (gp_option('gp_contact_sidebar')) {

    $sidebar = gp_option('gp_contact_sidebar');

} else {

    $sidebar = 'right';

}
?>

<div class="sidebar-contact sidebar-<?php echo $sidebar; ?> sidebar" role="complementary">

    <?php dynamic_sidebar('widget-area-contact'); ?>

</div><!-- END // sidebar -->


text:
class DevelopmentInterceptor
  def self.delivering_email(message)
    message.to = ["development@onepx.co"]
  end
end