text:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Seminar</title>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

Department of Mathematics

Indian Institute of Science

Bangalore 560 012

SEMINAR

    Speaker

    :

 Prof. Anjishnu Banerjee

    Affiliation

    :

     Duke University, USA

    Subject Area

    :

    Mathematics

    Venue

    :

     Lecture Hall III, Department of Mathematic

    Time

    :

11.30 am-12.30 p.m.

    Date

    :

October20, 2011 (Thursday)

    Title

    :

"Challenges in high dimensional Bayesian nonparametrics and some possible solutions"

    Abstract

    :

 Large dimensional data presents many challenges for statistical modeling via Bayesian nonparametrics, both with respect to theroetical
 issues and computational aspects. We discuss some models that can accomodate large dimensional data and have attractive theoretical properties, specially
 focussing on kernel partition processes, which are a generalization of the well known Dirichlet Processes. We discuss issues of consistency. We then move
 onto some typical computational problems in Bayesian nonparametrics, focussing initially on Gaussian processes (GPs). GPs are widely used in nonparametric
 regression, classification and spatio-temporal modeling, motivated in part by a rich literature on theoretical properties.  However, a well known drawback
 of GPs that limits their use is the expensive computation, typically O($n^3$) in performing the necessary matrix inversions with $n$ denoting the number of
 data points.  In large data sets, data storage and processing also lead to computational bottlenecks and numerical stability of the estimates and predicted
 values degrades with $n$.  To address these problems, a rich variety of methods have been proposed, with recent options including predictive processes in
 spatial data analysis and subset of regressors in machine learning.  The underlying idea in these approaches is to use a subset of the data, leading to ques-
 tions of sensitivity to the subset and limitations in estimating fine scale structure in regions that are not well covered by the subset. Partially motivated
 by the literature on compressive sensing, we propose an alternative random projection of all the data points onto a lower-dimensional subspace, which also
 allows for easy parallelizability for further speeding computation.  We connect this with a wide class of matrix approximation techniques. We demonstrate the
 superiority of this approach from a theoretical perspective and through the use of simulated and real data examples. We finally consider extensions of these
 approaches for dimension reduction in other non parametric models.

redpajama_set_name: RedPajamaGithub


text:
package postgres

import (
	"context"

	"github.com/jmoiron/sqlx"
)

// Link is used to insert and update in mysql
type Link struct{}

// MigrateUp creates the needed tables
func (link *Link) MigrateUp(ctx context.Context, exec sqlx.ExecerContext) (errExec error) {
	_, errExec = exec.ExecContext(
		ctx,
		`
            CREATE TABLE IF NOT EXISTS entityone (
                entityone_id BIGSERIAL NOT NULL,
                status_id INT NOT NULL DEFAULT 1,
                action_id INT NOT NULL DEFAULT 1,
                time_created DATE NOT NULL DEFAULT CURRENT_DATE,
                time_updated DATE NOT NULL DEFAULT CURRENT_DATE,
                PRIMARY KEY (entityone_id)
            );

            CREATE TABLE IF NOT EXISTS entityone_history (
                entityone_id BIGINT NOT NULL,
                action_id INT NOT NULL DEFAULT 1,
                status_id INT NOT NULL DEFAULT 1,
                time_created DATE NOT NULL DEFAULT CURRENT_DATE,
                CONSTRAINT es_fk_e_eid
                    FOREIGN KEY (entityone_id)
                    REFERENCES entityone (entityone_id)
            );

			CREATE INDEX es_idx_eid ON entityone_history(entityone_id);

			CREATE INDEX e_idx_sid ON entityone(status_id);

			CREATE INDEX es_idx_sid ON entityone_history(status_id);

			CREATE INDEX es_idx_aid ON entityone_history(action_id);
	`)
	return errExec
}

// MigrateDown destroys the needed tables
func (link *Link) MigrateDown(ctx context.Context, exec sqlx.ExecerContext) (errExec error) {
	_, errExec = exec.ExecContext(ctx, `
		DROP TABLE IF EXISTS entityone_history;
		DROP TABLE IF EXISTS entityone;
	`)

	return errExec
}


text:
package org.apache.river.landlord;

import net.jini.core.lease.Lease;
import net.jini.core.lease.LeaseDeniedException;

/**
 * Simple implementation of LeasePeriodPolicy that grants
 * lease times based on a fixed default and maximum lease. Will grant
 * renewals longer than the maximum if the current lease and the
 * request are both longer than the maximum.
 *
 * @author Sun Microsystems, Inc.
 * @since 2.0
 */
public class FixedLeasePeriodPolicy implements LeasePeriodPolicy {
    /** Under normal circumstances, the maximum lease or renewal to grant */
    final private long maximum;

    /** The default lease length */
    final private long defaultLength;

    /**
     * Create a new FixedLeasePeriodPolicy with
     * the specified values for the maxium and default lease
     * lengths.
     * @param maximum the length in milliseconds of the longest lease
     *                this object should normally grant
     * @param defaultLength the length in milliseconds of the
     *                default lease grants
     * @throws IllegalArgumentException if either argument
     *         is not positive.
     */
    public FixedLeasePeriodPolicy(long maximum, long defaultLength) {
	if (maximum <= 0)
	    throw new IllegalArgumentException("FixedLeasePeriodPolicy:" +
	        "maximum lease time must be larger than 0, " +
		 "passed:" + maximum);

	if (defaultLength <= 0)
	    throw new IllegalArgumentException("FixedLeasePeriodPolicy:" +
	        "default lease time must be larger than 0, " +
		 "passed:" + defaultLength);

	this.maximum = maximum;
	this.defaultLength = defaultLength;
    }

    /**
     * Returns the duration this policy is willing to grant for the
     * passed resource at this time.  The duration actually granted
     * will be shorter if the duration extends pass the end of the
     * epoch.  Must return a positive number.
     *

     * Note the duration returned by this method will be shorter than
     * the final duration granted if the requested duration extends
     * past the current expiration, and duration return by this
     * method is before the current expiration.
     *
     * @param resource          the resource having a lease granted
     *                          or renewed
     * @param requestedDuration the duration the client wants
     * @return  duration in milliseconds.
     * @exception IllegalArgumentException thrown if requestedDuration
     *            is less than 0 and not equal to
     *            Lease.ANYLENGTH or
     *            Lease.FOREVER.
     */
    protected long calculateDuration(LeasedResource resource,
        long requestedDuration)
    {
	if (requestedDuration == Lease.FOREVER)
	    requestedDuration = Long.MAX_VALUE;
	else if (requestedDuration == Lease.ANY)
	    requestedDuration = defaultLength;
	else if (requestedDuration < 0)
	    throw new
		IllegalArgumentException("Negative lease duration " +
		    "requested");

	return Math.min(requestedDuration, maximum);
    }

    /**
     * Method that provides some notion of the current time in milliseconds
     * since the beginning of the epoch. Default implementation
     * calls System.currentTimeMillis()
     * @return current time in milliseconds.
     */
    protected long currentTime() {
	return System.currentTimeMillis();
    }

    /**
     * Calculates an expiration based on the passed time and a requested
     * duration. Will clip the expiration to the end of the epoch
     * @param preferredDuration the duration the policy wants to grant
     * @param now               the current time in milliseconds since
     *                          the beginning of the epoch
     * @return the new expiration time for the lease in milliseconds since
     *         the beginning of the epoch
     */
    private long calcExpiration(long preferredDuration, long now) {
	long expiration = now + preferredDuration;
	// Any addition of two positive longs is guaranteed to be
	// negative if it overflowed
	if (expiration < 0) {
	    // Not enough time for the duration we want, set to end of
	    // epoch
	    return Long.MAX_VALUE;
	}

	return expiration;
    }

    public Result grant(LeasedResource resource, long requestedDuration)
        throws LeaseDeniedException
    {
	final long now = currentTime();
	final long expiration =
	    calcExpiration(calculateDuration(resource, requestedDuration),
			   now);
	final long duration = expiration - now;
	return new Result(expiration, duration);
    }

    public Result renew(LeasedResource resource, long requestedDuration)
        throws LeaseDeniedException
    {
	final long now = currentTime();

	// The new expiration we would grant independent of the
	// current expiration time
	long newExpiration =
	    calcExpiration(calculateDuration(resource, requestedDuration),
			   now);

	// Do not change the expiration time to be sooner that it is
	// now unless the client explicitly asked for it.  If they did
	// ask for a sooner expiration give them exactly what they
	// asked for.

	// The current expiration of the lease
	final long oldExpiration = resource.getExpiration();

	if (oldExpiration > newExpiration) {
	    // need to make sure they asked for it

	    if (requestedDuration == Lease.ANY) {
		// they did not explicitly ask for a sooner
		// expiration, give them at least what they had
		newExpiration = oldExpiration;
	    } else {
		// The new expiration time they are requesting
		// (possibly clipped to the end of the epoch) this is
		// not affected by what we are willing to grant.
		// [Note we know at this point that requestedDuration
		// is >= 0]
		final long requestedExpiration = calcExpiration(
		    requestedDuration, now);

		if (requestedExpiration > oldExpiration) {
		    // they made a request for something longer, give
		    // them at least what they had
		    newExpiration = oldExpiration;
		} else {
		    // They made a request for something shorter,
		    // give them what they at least what they want
		    newExpiration = requestedExpiration;
		}
	    }
	}

	// Now that we finally have decided on a new expiration,
	// get the real duration and return the result.
	return new Result(newExpiration, newExpiration - now);
    }
}


text:
{% extends "main.html" %}
{% block content %}
{% include "header.html" %}

Edit Menu Item

			<form action="#" method = "post">

					Name:
					<input type ="text" maxlength="100" class="form-control" name="name" value="{{item.name }}">

					Description:
					<textarea class="form-control" maxlength="250" rows="3" name="description">{{item.description}}</textarea>

					Price:

$

						<input type ="text" maxlength="10" class="form-control" name="price" value="{{item.price}}">

					Course:

					    <input type="radio" name="course" id="course1" value="Appetizer" {% if item.course == 'Appetizer'%}checked{%endif%}>Appetizer

					    <input type="radio" name="course" id="course2" value="Entree" {% if item.course == 'Entree' %}checked{%endif%}>Entree

					    <input type="radio" name="course" id="course3" value="Dessert" {% if item.course == 'Dessert'%}checked{%endif%}>Dessert

					    <input type="radio" name="course" id="course4" value="Beverage" {%if item.course =='Beverage'%}checked{%endif%}>Beverage

					<button type="submit" class="btn btn-default" id="submit" type="submit">
					Save</button>

						<button class="btn btn-default delete">
						 Cancel</button>

			</form>

{% endblock %}


text:
<?php

/**
 * Base class for style generators.
 *
 * Style generators used in {@link ezcDocumentOdtStyler} must extend this
 * abstract class.
 *
 * @package Document
 * @access private
 * @version //autogen//
 */
abstract class ezcDocumentOdtStyleGenerator
{
    /**
     * Style converters.
     *
     * @var ezcDocumentOdtPcssConverterManager
     */
    protected $styleConverters;

    /**
     * Counters for style prefixes.
     *
     * @var array(string=>int)
     */
    protected $prefixCounters = array();

    /**
     * Creates a new style genertaor.
     *
     * @param ezcDocumentOdtPcssConverterManager $styleConverters
     */
    public function __construct( ezcDocumentOdtPcssConverterManager $styleConverters )
    {
        $this->styleConverters = $styleConverters;
    }

    /**
     * Returns if a style generator handles style generation for $odtElement.
     *
     * @param DOMElement $odtElement
     * @return bool
     */
    public abstract function handles( DOMElement $odtElement );

    /**
     * Creates the necessary styles to apply $styleAttributes to $odtElement.
     *
     * This method should create the necessary styles to apply $styleAttributes
     * to the given $odtElement. In addition, it must set the correct
     * attributes on $odtElement to source this style.
     *
     * @param ezcDocumentOdtStyleInformation $styleInfo
     * @param DOMElement $odtElement
     * @param array $styleAttributes
     */
    public abstract function createStyle( ezcDocumentOdtStyleInformation $styleInfo, DOMElement $odtElement, array $styleAttributes );

    /**
     * Returns a unique style name with the given $prefix.
     *
     * Note that generated name is only unique within this style generator,
     * which is no problem, if only a single style generator takes care for a
     * certain style family.
     *
     * @param string $prefix
     * @return string
     */
    protected function getUniqueStyleName( $prefix = 'style' )
    {
        if ( !isset( $this->prefixCounters[$prefix] ) )
        {
            $this->prefixCounters[$prefix] = 0;
        }
        return $prefix . ++$this->prefixCounters[$prefix];
    }
}

?>


text:
/* font-face */
@font-face {
  font-family: "SocialFoundicons";
  src: url("../fonts/social_foundicons.eot");
  src: url("../fonts/social_foundicons.eot?#iefix") format("embedded-opentype"), url("../fonts/social_foundicons.woff") format("woff"), url("../fonts/social_foundicons.ttf") format("truetype"), url("../fonts/social_foundicons.svg#SocialFoundicons") format("svg");
  font-weight: normal;
  font-style: normal;
}

/* global foundicon styles */
/* line 7, ../sass/social_foundicons.scss */
[class*="socialfoundicon-"] {
  display: inline;
  width: auto;
  height: auto;
  line-height: inherit;
  vertical-align: baseline;
  background-image: none;
  background-position: 0 0;
  background-repeat: repeat;
}

/* line 17, ../sass/social_foundicons.scss */
[class*="socialfoundicon-"]:before {
  font-family: "SocialFoundicons";
  font-weight: normal;
  font-style: normal;
  text-decoration: inherit;
}

/* icons */
/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-thumb-up:before {
  content: "\f000";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-thumb-down:before {
  content: "\f001";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-rss:before {
  content: "\f002";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-facebook:before {
  content: "\f003";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-twitter:before {
  content: "\f004";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-pinterest:before {
  content: "\f005";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-github:before {
  content: "\f006";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-path:before {
  content: "\f007";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-linkedin:before {
  content: "\f008";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-dribbble:before {
  content: "\f009";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-stumble-upon:before {
  content: "\f00a";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-behance:before {
  content: "\f00b";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-reddit:before {
  content: "\f00c";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-google-plus:before {
  content: "\f00d";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-youtube:before {
  content: "\f00e";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-vimeo:before {
  content: "\f00f";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-flickr:before {
  content: "\f010";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-slideshare:before {
  content: "\f011";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-picassa:before {
  content: "\f012";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-skype:before {
  content: "\f013";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-steam:before {
  content: "\f014";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-instagram:before {
  content: "\f015";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-foursquare:before {
  content: "\f016";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-delicious:before {
  content: "\f017";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-chat:before {
  content: "\f018";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-torso:before {
  content: "\f019";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-tumblr:before {
  content: "\f01a";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-video-chat:before {
  content: "\f01b";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-digg:before {
  content: "\f01c";
}

/* line 6, ../sass/social_foundicons_settings.scss */
.socialfoundicon-wordpress:before {
  content: "\f01d";
}

/* font-face */
@font-face {
  font-family: "GeneralFoundicons";
  src: url("../fonts/general_foundicons.eot");
  src: url("../fonts/general_foundicons.eot?#iefix") format("embedded-opentype"), url("../fonts/general_foundicons.woff") format("woff"), url("../fonts/general_foundicons.ttf") format("truetype"), url("../fonts/general_foundicons.svg#GeneralFoundicons") format("svg");
  font-weight: normal;
  font-style: normal;
}

/* global foundicon styles */
/* line 7, ../sass/general_foundicons.scss */
[class*="generalfoundicon-"] {
  display: inline;
  width: auto;
  height: auto;
  line-height: inherit;
  vertical-align: baseline;
  background-image: none;
  background-position: 0 0;
  background-repeat: repeat;
}

/* line 17, ../sass/general_foundicons.scss */
[class*="generalfoundicon-"]:before {
  font-family: "GeneralFoundicons";
  font-weight: normal;
  font-style: normal;
  text-decoration: inherit;
}

/* icons */
/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-settings:before {
  content: "\f000";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-heart:before {
  content: "\f001";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-star:before {
  content: "\f002";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-plus:before {
  content: "\f003";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-minus:before {
  content: "\f004";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-checkmark:before {
  content: "\f005";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-remove:before {
  content: "\f006";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-mail:before {
  content: "\f007";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-calendar:before {
  content: "\f008";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-page:before {
  content: "\f009";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-tools:before {
  content: "\f00a";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-globe:before {
  content: "\f00b";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-home:before {
  content: "\f00c";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-quote:before {
  content: "\f00d";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-people:before {
  content: "\f00e";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-monitor:before {
  content: "\f00f";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-laptop:before {
  content: "\f010";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-phone:before {
  content: "\f011";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-cloud:before {
  content: "\f012";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-error:before {
  content: "\f013";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-right-arrow:before {
  content: "\f014";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-left-arrow:before {
  content: "\f015";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-up-arrow:before {
  content: "\f016";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-down-arrow:before {
  content: "\f017";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-trash:before {
  content: "\f018";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-add-doc:before {
  content: "\f019";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-edit:before {
  content: "\f01a";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-lock:before {
  content: "\f01b";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-unlock:before {
  content: "\f01c";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-refresh:before {
  content: "\f01d";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-paper-clip:before {
  content: "\f01e";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-video:before {
  content: "\f01f";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-photo:before {
  content: "\f020";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-graph:before {
  content: "\f021";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-idea:before {
  content: "\f022";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-mic:before {
  content: "\f023";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-cart:before {
  content: "\f024";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-address-book:before {
  content: "\f025";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-compass:before {
  content: "\f026";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-flag:before {
  content: "\f027";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-location:before {
  content: "\f028";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-clock:before {
  content: "\f029";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-folder:before {
  content: "\f02a";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-inbox:before {
  content: "\f02b";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-website:before {
  content: "\f02c";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-smiley:before {
  content: "\f02d";
}

/* line 6, ../sass/general_foundicons_settings.scss */
.generalfoundicon-search:before {
  content: "\f02e";
}

/*colors*/
/* line 13, ../sass/about_us.scss */
.center {
  text-align: center;
}

/* line 16, ../sass/about_us.scss */
.asterisk {
  color: red;
}

/* line 20, ../sass/about_us.scss */
.about_font {
  font-size: 1.2em;
}

/* line 24, ../sass/about_us.scss */
div.large-6 article h5 {
  margin-top: 35px;
  text-align: center;
}

/* line 29, ../sass/about_us.scss */
div.large-6 img.show-for-small {
  margin-bottom: 15px;
}

/* line 33, ../sass/about_us.scss */
html.js body div.container div.row div.large-12 div.large-9 div#about_help.get-help {
  margin-top: -20px;
  margin-bottom: 35px;
}

@media only screen and (min-width: 640px) {
  /* line 40, ../sass/about_us.scss */
  div.large-6 img.show-for-small {
    margin: 0 auto;
    margin-bottom: 15px;
  }
}
@media only screen and (min-width: 768px) {
  /* line 47, ../sass/about_us.scss */
  div.large-6 img.hide-for-small {
    margin-top: 175px;
  }
}
@media only screen and (min-width: 800px) {
  /* line 53, ../sass/about_us.scss */
  div.large-6 img.hide-for-small {
    margin-top: 155px;
  }
}
@media only screen and (min-width: 980px) {
  /* line 59, ../sass/about_us.scss */
  div.large-6 img.hide-for-small {
    margin-top: 112px;
  }
}
@media only screen and (min-width: 1024px) {
  /* line 65, ../sass/about_us.scss */
  div.large-6 img.hide-for-small {
    margin-top: 112px;
  }

  /* line 69, ../sass/about_us.scss */
  div.row div.push {
    margin-left: 20px;
  }
}
@media only screen and (min-width: 1280px) {
  /* line 77, ../sass/about_us.scss */
  div.large-6 img.hide-for-small {
    margin-top: 65px;
  }

  /* line 81, ../sass/about_us.scss */
  div.row div.push {
    margin-left: 80px;
    margin-bottom: 25px;
  }
}


text:
#ifndef _EGF_UI_MENUBUILDER_HPP
#define _EGF_UI_MENUBUILDER_HPP

#include <fstream>
#include <stdexcept>
#include <string>

#include <tinyxml.h>

#include <ResourceManager.hpp>
#include <SingletonPointer.hpp>

#include <UI/ComponentBuilder.hpp>
#include <UI/Menu.hpp>

namespace EGF {

    namespace UI {

        /** Класс для создания меню.
          * @author Elijah Vlasov
        */

        class MenuBuilder: public Singleton<MenuBuilder> {

            SINGLETON(MenuBuilder)

            public:

                /** Создать меню из XML.
                  * @param xmlMenu XML-меню
                  * @throw Генерирует std::invalid_argument, если
                  *        xmlMenu == NULL или xmlMenu - пустая строка.
                  *        Генерирует std::runtime_error, если произошла ошибка парсинга.
                */

                Menu* createMenu(const char* xmlMenu)
                                    throw(std::invalid_argument, std::runtime_error);

                /** Создать меню из XML.
                  * @param xmlMenu XML-меню
                  * @throw Генерирует std::invalid_argument, если xmlMenu - пустая
                  *        строка. Генерирует std::runtime_error, если произошла ошибка парсинга.
                */

                Menu* createMenu(const std::string& xmlMenu)
                                    throw(std::invalid_argument, std::runtime_error);

            protected:

                MenuBuilder() throw(std::runtime_error);

            private:

                SingletonPointer<ResourceManager>    resourceManager_;

                SingletonPointer<ComponentBuilder>   componentBuilder_;

                static const std::string MENU_ROOT_NODE_VALUE;

                // Загрузить menu из TiXml document
                void loadComponents(TiXmlDocument& document, UI::Menu* menu) throw(std::runtime_error);

        };

    }

}

#endif


text:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11792865-44']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

// Outbound Link Tracking with Google Analytics
// Wallace Sidhrée - http://dreamyguy.com/
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$(function() {
    $("a").on('click',function(e){
        var url = $(this).attr("href");
        if (e.currentTarget.host != window.location.host) {
            _gat._getTrackerByName()._trackEvent("Outbound Links", e.currentTarget.host.replace(':80',''), url, 0);
            if (e.metaKey || e.ctrlKey || this.target == "_blank" || e.which == 2) {
                var newtab = true;
            }
            if (!newtab) {
                e.preventDefault();
                setTimeout('document.location = "' + url + '"', 100);
            }
        }
    });
});


text:
(function() {
  var app = angular.module("githubViewer");

  var MainController = function(
      $scope, $interval, $location) {

    var decrementCounter = function() {
      $scope.countdown += -1;
      if ($scope.countdown < 1) {
        $scope.search($scope.username);
      }
    };

    var countdownInterval = null;
    var startCountDown = function() {
      countdownInterval = $interval(decrementCounter, 1000, $scope.countdown);
    };

    $scope.search = function(username) {
      if (countdownInterval) {
        $interval.cancel(countdownInterval);
        $scope.countdown = null;
      }
      $location.path("/user/" + username);
    }

    $scope.username = "angular";
    $scope.countdown = 5;
    startCountDown();
  };

  app.controller("MainController", ['$scope', '$interval', '$location', MainController]);
}());


text:
package org.apache.flink.table.planner.plan.nodes.exec.serde;

import org.apache.flink.table.api.TableException;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonGenerator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ser.std.StdSerializer;

import org.apache.calcite.rex.RexWindowBound;

import java.io.IOException;

/**
 * JSON serializer for {@link RexWindowBound}. refer to {@link RexWindowBoundJsonDeserializer} for
 * deserializer.
 *
 * <p>Supports serialize CURRENT_ROW, UNBOUNDED_PRECEDING, UNBOUNDED_FOLLOWING, Preceding Bounded
 * Window and Following Bounded Window.
 */
public class RexWindowBoundJsonSerializer extends StdSerializer<RexWindowBound> {

    public static final String FIELD_NAME_KIND = "kind";
    public static final String KIND_CURRENT_ROW = "CURRENT_ROW";
    public static final String KIND_UNBOUNDED_PRECEDING = "UNBOUNDED_PRECEDING";
    public static final String KIND_UNBOUNDED_FOLLOWING = "UNBOUNDED_FOLLOWING";
    public static final String KIND_BOUNDED_WINDOW = "BOUNDED_WINDOW";

    public static final String FIELD_NAME_IS_PRECEDING = "isPreceding";
    public static final String FIELD_NAME_IS_FOLLOWING = "isFollowing";
    public static final String FIELD_NAME_OFFSET = "offset";

    public RexWindowBoundJsonSerializer() {
        super(RexWindowBound.class);
    }

    @Override
    public void serialize(
            RexWindowBound rexWindowBound, JsonGenerator gen, SerializerProvider serializerProvider)
            throws IOException {
        gen.writeStartObject();
        if (rexWindowBound.isCurrentRow()) {
            gen.writeStringField(FIELD_NAME_KIND, KIND_CURRENT_ROW);
        } else if (rexWindowBound.isUnbounded()) {
            if (rexWindowBound.isPreceding()) {
                gen.writeStringField(FIELD_NAME_KIND, KIND_UNBOUNDED_PRECEDING);
            } else if (rexWindowBound.isFollowing()) {
                gen.writeStringField(FIELD_NAME_KIND, KIND_UNBOUNDED_FOLLOWING);
            } else {
                throw new TableException("Unknown RexWindowBound: " + rexWindowBound);
            }
        } else {
            gen.writeStringField(FIELD_NAME_KIND, KIND_BOUNDED_WINDOW);
            if (rexWindowBound.isPreceding()) {
                gen.writeBooleanField(FIELD_NAME_IS_PRECEDING, true);
            } else if (rexWindowBound.isFollowing()) {
                gen.writeBooleanField(FIELD_NAME_IS_FOLLOWING, true);
            } else {
                throw new TableException("Unknown RexWindowBound: " + rexWindowBound);
            }
            gen.writeObjectField(FIELD_NAME_OFFSET, rexWindowBound.getOffset());
        }
        gen.writeEndObject();
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>University Health Services</title>
        <link rel="shortcut icon" href="/img/abulogo.png"/>

        <link href="/css/bootstrap.min.css" rel="stylesheet">

        <link href="/css/modern-business.css" rel="stylesheet">
        <link href="/style/uhs-style.css" rel="stylesheet">

        <link href="/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

University Health Services

Ahmadu Bello University, Zaria

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>

                            Home

                            Units

Curative

Medical Unit

Pharmacy Unit

Laboratory Unit

Dental Unit

Nursing Unit

Preventive

Preventive & Sanitation Unit

Parks & Afforestation Unit

Forest Guard Unit

Administrative

Account Unit

Store Unit

Medical Record Unit

NHIS Unit

                            Organization

Directors

                            People

                            Services

                            About

                            Contact

People
                        Our Admin Staff

Home

Staff

Back to top

© 2017 All Rights Reseverd | University Health Services | Ahmadu Bello University, Zaria


text:
local base_dir = ((debug.getinfo(1).source):match('^@?(.-)index.lua$') or '')

package.path =  base_dir..'../../src/?.lua;'..package.path

local sailor = require "sailor"
sailor.launch()


text:
package com.microsoft.build;

import com.google.testing.compile.CompilationRule;
import com.microsoft.lookup.ClassItemsLookup;
import com.microsoft.lookup.ClassLookup;
import com.microsoft.model.MetadataFile;
import com.microsoft.model.MetadataFileItem;
import com.microsoft.util.ElementUtil;
import com.sun.source.util.DocTrees;
import jdk.javadoc.doclet.DocletEnvironment;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;

import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import java.io.File;
import java.util.Collection;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

public class ClassBuilderTest {
    @Rule
    public CompilationRule rule = new CompilationRule();
    private Elements elements;
    private ClassBuilder classBuilder;
    private DocletEnvironment environment;
    private DocTrees docTrees;

    @Before
    public void setup() {
        elements = rule.getElements();
        environment = Mockito.mock(DocletEnvironment.class);
        docTrees = Mockito.mock(DocTrees.class);
        ElementUtil elementUtil = new ElementUtil(new String[0], new String[0]);
        ClassLookup classLookup = new ClassLookup(environment, elementUtil);
        classBuilder = new ClassBuilder(
            elementUtil,
            classLookup,
            new ClassItemsLookup(environment, elementUtil),
            "./target",
            new ReferenceBuilder(environment, classLookup, elementUtil));
    }
    @Test
    public void addConstructorsInfoWhenOnlyDefaultConstructor() {
        TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person");
        MetadataFile container = new MetadataFile("output", "name");
        when(environment.getElementUtils()).thenReturn(elements);
        when(environment.getDocTrees()).thenReturn(docTrees);

        classBuilder.addConstructorsInfo(element, container);

        assertEquals("Wrong file name", container.getFileNameWithPath(), "output" + File.separator + "name");
        assertEquals("Container should contain constructor item", container.getItems().size(), 1);
    }

    @Test
    public void addConstructorsInfo() {
        TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero");
        MetadataFile container = new MetadataFile("output", "name");
        when(environment.getElementUtils()).thenReturn(elements);
        when(environment.getDocTrees()).thenReturn(docTrees);

        classBuilder.addConstructorsInfo(element, container);

        assertEquals("Wrong file name", container.getFileNameWithPath(), "output" + File.separator + "name");
        Collection<MetadataFileItem> constructorItems = container.getItems();
        assertEquals("Container should contain 2 constructor items", constructorItems.size(), 2);
    }
}


text:
process.env.DEBUG = 'service,service:*,prop,prop:connect'; // activate debug messages

var jService = require('../index.js');
var colorToggle = true;

jService.scan({ seconds: 3 })
.catch(function(error) {
  console.log('ERROR: ' + error);
});

jService.on('found', function(peripheral) {
  return jService.connect({ peripheral: peripheral });
});

jService.on('connected', function(prop) {
    setTimeout(function() {
      prop.shutdown();
    }, 2000);
});


text:
import asyncio
import os
import sys

root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root + '/python')

import ccxt.async_support as ccxt  # noqa: E402

async def run_all_exchanges(exchange_ids):
    results = {}

    for exchange_id in exchange_ids:

        exchange = getattr(ccxt, exchange_id)({
            'options': {
                'useWebapiForFetchingFees': False,
            }
        })

        symbol = 'ETH/BTC'
        print('Exchange:', exchange_id)

        print(exchange_id, 'symbols:')
        markets = await load_markets(exchange, symbol)  # ←----------- STEP 1
        print(list(markets.keys()))

        print(symbol, 'ticker:')
        ticker = await fetch_ticker(exchange, symbol)  # ←------------ STEP 2
        print(ticker)

        print(symbol, 'orderbook:')
        orderbook = await fetch_orderbook(exchange, symbol)  # ←------ STEP 3
        print(orderbook)

        await exchange.close()  # ←----------- LAST STEP GOES AFTER ALL CALLS

        results[exchange_id] = ticker

    return results

async def load_markets(exchange, symbol):
    try:
        result = await exchange.load_markets()
        return result
    except ccxt.BaseError as e:
        print(type(e).__name__, str(e), str(e.args))
        raise e

async def fetch_ticker(exchange, symbol):
    try:
        result = await exchange.fetch_ticker(symbol)
        return result
    except ccxt.BaseError as e:
        print(type(e).__name__, str(e), str(e.args))
        raise e

async def fetch_orderbook(exchange, symbol):
    try:
        result = await exchange.fetch_order_book(symbol)
        return result
    except ccxt.BaseError as e:
        print(type(e).__name__, str(e), str(e.args))
        raise e

if __name__ == '__main__':
    exchange_ids = ['bitfinex', 'okex', 'exmo']
    exchanges = []
    results = asyncio.run(run_all_exchanges(exchange_ids))
    print([(exchange_id, ticker) for exchange_id, ticker in results.items()])


text:
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type helloWorldResponse struct {
	Message string `json:"message"`
}

type helloWorldRequest struct {
	Name string `json:"name"`
}

const port = 8080

func main() {
	server()
}

func server() {
	http.HandleFunc("/helloworld", helloWorldHandler)

	log.Printf("Server starting on port %v\n", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}

func helloWorldHandler(w http.ResponseWriter, r *http.Request) {

	var request helloWorldRequest
	decoder := json.NewDecoder(r.Body)

	err := decoder.Decode(&request)
	if err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}

	response := helloWorldResponse{Message: "Hello " + request.Name}

	encoder := json.NewEncoder(w)
	encoder.Encode(response)
}


text:
#ifndef __rtkRayQuadricIntersectionImageFilter_h
#define __rtkRayQuadricIntersectionImageFilter_h

#include <itkInPlaceImageFilter.h>
#include "rtkConfiguration.h"
#include "rtkThreeDCircularProjectionGeometry.h"
#include "rtkRayQuadricIntersectionFunction.h"

namespace rtk
{

/** \class RayQuadricIntersectionImageFilter
 * \brief Computes intersection of projection rays with quadric objects.
 *
 * Quadrics are ellipsoid, cone, cylinder... See
 * http://www.siggraph.org/education/materials/HyperGraph/raytrace/rtinter4.htm
 * for more information.
 *
 * \author Simon Rit
 *
 * \ingroup InPlaceImageFilter
 */
template <class TInputImage, class TOutputImage>
class ITK_EXPORT RayQuadricIntersectionImageFilter :
  public itk::InPlaceImageFilter<TInputImage,TOutputImage>
{
public:
  /** Standard class typedefs. */
  typedef RayQuadricIntersectionImageFilter                 Self;
  typedef itk::InPlaceImageFilter<TInputImage,TOutputImage> Superclass;
  typedef itk::SmartPointer<Self>                           Pointer;
  typedef itk::SmartPointer<const Self>                     ConstPointer;

  typedef typename TOutputImage::RegionType               OutputImageRegionType;
  typedef typename TOutputImage::Superclass::ConstPointer OutputImageBaseConstPointer;
  typedef rtk::ThreeDCircularProjectionGeometry           GeometryType;
  typedef typename GeometryType::Pointer                  GeometryPointer;
  typedef RayQuadricIntersectionFunction<double, 3>       RQIFunctionType;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(RayQuadricIntersectionImageFilter, itk::ImageToImageFilter);

  /** Get / Set the object pointer to projection geometry */
  itkGetMacro(Geometry, GeometryPointer);
  itkSetMacro(Geometry, GeometryPointer);

  /** Get / Set the multiplicative constant of the volume */
  itkGetMacro(Density, double);
  itkSetMacro(Density, double);

  /** Get the RayQuadricIntersectionFunction to set its parameters.
    * A call to this function will assume modification of the function.*/
  RQIFunctionType::Pointer GetRQIFunctor();

protected:
  RayQuadricIntersectionImageFilter();
  virtual ~RayQuadricIntersectionImageFilter() {};

  virtual void BeforeThreadedGenerateData();

  /** Apply changes to the input image requested region. */
  virtual void ThreadedGenerateData( const OutputImageRegionType& outputRegionForThread,
                                     ThreadIdType threadId );

  /** The two inputs should not be in the same space so there is nothing
   * to verify. */
  virtual void VerifyInputInformation() {}

private:
  RayQuadricIntersectionImageFilter(const Self&); //purposely not implemented
  void operator=(const Self&);            //purposely not implemented

  /** Functor object to compute the intersection */
  RQIFunctionType::Pointer m_RQIFunctor;

  /** RTK geometry object */
  GeometryPointer m_Geometry;

  /** Multiplicative factor of intersection length */
  double m_Density;
};

} // end namespace rtk

#ifndef ITK_MANUAL_INSTANTIATION
#include "rtkRayQuadricIntersectionImageFilter.txx"
#endif

#endif


text:
import { expect } from 'chai';

describe('createDefaultDuration', () => {

});


text:
<?php

namespace Hubzero\Message;

use Hubzero\Database\Relational;

/**
 * Model class for message actions
 */
class Action extends Relational
{
	/**
	 * The table namespace
	 *
	 * @var  string
	 */
	protected $namespace = 'xmessage';

	/**
	 * The table to which the class pertains
	 *
	 * This will default to #__{namespace}_{modelName} unless otherwise
	 * overwritten by a given subclass. Definition of this property likely
	 * indicates some derivation from standard naming conventions.
	 *
	 * @var  string
	 **/
	protected $table = '#__xmessage_action';

	/**
	 * Default order by for model
	 *
	 * @var  string
	 */
	public $orderBy = 'id';

	/**
	 * Default order direction for select queries
	 *
	 * @var  string
	 */
	public $orderDir = 'asc';

	/**
	 * Fields and their validation criteria
	 *
	 * @var  array
	 */
	protected $rules = array(
		'element' => 'notempty'
	);

	/**
	 * Get records for specific type, element, component, and user
	 *
	 * @param   string   $type       Action type
	 * @param   string   $component  Component name
	 * @param   integer  $element    ID of element that needs action
	 * @param   integer  $uid        User ID
	 * @return  object
	 */
	public static function getActionItems($type, $component, $element, $uid)
	{
		$entries = self::all();

		$a = $entries->getTableName();
		$m = Message::blank()->getTableName();
		$r = Recipient::blank()->getTableName();

		return $entries
			->select($m . '.id')
			->join($r, $r . '.actionid', $a . '.id', 'inner')
			->join($m, $m . '.id', $r . '.mid', 'inner')
			->whereEquals($m . '.type', $type)
			->whereEquals($r . '.uid', $uid)
			->whereEquals($a . '.class', $component)
			->whereEquals($a . '.element', $element)
			->rows();
	}
}


text:
"""Library to upload benchmark generated by BenchmarkLogger to remote repo.

This library require google cloud bigquery lib as dependency, which can be
installed with:
  > pip install --upgrade google-cloud-bigquery
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json

from google.cloud import bigquery
from google.cloud import exceptions

import REDACTED
import tensorflow as tf

class BigQueryUploader(object):
  """Upload the benchmark and metric info from JSON input to BigQuery. """

  def __init__(self, gcp_project=None, credentials=None):
    """Initialized BigQueryUploader with proper setting.

    Args:
      gcp_project: string, the name of the GCP project that the log will be
        uploaded to. The default project name will be detected from local
        environment if no value is provided.
      credentials: google.auth.credentials. The credential to access the
        BigQuery service. The default service account credential will be
        detected from local environment if no value is provided. Please use
        google.oauth2.service_account.Credentials to load credential from local
        file for the case that the test is run out side of GCP.
    """
    self._bq_client = bigquery.Client(
        project=gcp_project, credentials=credentials)

  def upload_benchmark_run_json(
      self, dataset_name, table_name, run_id, run_json):
    """Upload benchmark run information to Bigquery.

    Args:
      dataset_name: string, the name of bigquery dataset where the data will be
        uploaded.
      table_name: string, the name of bigquery table under the dataset where
        the data will be uploaded.
      run_id: string, a unique ID that will be attached to the data, usually
        this is a UUID4 format.
      run_json: dict, the JSON data that contains the benchmark run info.
    """
    run_json["model_id"] = run_id
    self._upload_json(dataset_name, table_name, [run_json])

  def upload_benchmark_metric_json(
      self, dataset_name, table_name, run_id, metric_json_list):
    """Upload metric information to Bigquery.

    Args:
      dataset_name: string, the name of bigquery dataset where the data will be
        uploaded.
      table_name: string, the name of bigquery table under the dataset where
        the metric data will be uploaded. This is different from the
        benchmark_run table.
      run_id: string, a unique ID that will be attached to the data, usually
        this is a UUID4 format. This should be the same as the benchmark run_id.
      metric_json_list: list, a list of JSON object that record the metric info.
    """
    for m in metric_json_list:
      m["run_id"] = run_id
    self._upload_json(dataset_name, table_name, metric_json_list)

  def upload_benchmark_run_file(
      self, dataset_name, table_name, run_id, run_json_file):
    """Upload benchmark run information to Bigquery from input json file.

    Args:
      dataset_name: string, the name of bigquery dataset where the data will be
        uploaded.
      table_name: string, the name of bigquery table under the dataset where
        the data will be uploaded.
      run_id: string, a unique ID that will be attached to the data, usually
        this is a UUID4 format.
      run_json_file: string, the file path that contains the run JSON data.
    """
    with tf.io.gfile.GFile(run_json_file) as f:
      benchmark_json = json.load(f)
      self.upload_benchmark_run_json(
          dataset_name, table_name, run_id, benchmark_json)

  def upload_metric_file(
      self, dataset_name, table_name, run_id, metric_json_file):
    """Upload metric information to Bigquery from input json file.

    Args:
      dataset_name: string, the name of bigquery dataset where the data will be
        uploaded.
      table_name: string, the name of bigquery table under the dataset where
        the metric data will be uploaded. This is different from the
        benchmark_run table.
      run_id: string, a unique ID that will be attached to the data, usually
        this is a UUID4 format. This should be the same as the benchmark run_id.
      metric_json_file: string, the file path that contains the metric JSON
        data.
    """
    with tf.io.gfile.GFile(metric_json_file) as f:
      metrics = []
      for line in f:
        metrics.append(json.loads(line.strip()))
      self.upload_benchmark_metric_json(
          dataset_name, table_name, run_id, metrics)

  def _upload_json(self, dataset_name, table_name, json_list):
    # Find the unique table reference based on dataset and table name, so that
    # the data can be inserted to it.
    table_ref = self._bq_client.dataset(dataset_name).table(table_name)
    errors = self._bq_client.insert_rows_json(table_ref, json_list)
    if errors:
      tf.logging.error(
          "Failed to upload benchmark info to bigquery: {}".format(errors))

  def insert_run_status(self, dataset_name, table_name, run_id, run_status):
    """Insert the run status in to Bigquery run status table."""
    query = ("INSERT {ds}.{tb} "
             "(run_id, status) "
             "VALUES('{rid}', '{status}')").format(
                 ds=dataset_name, tb=table_name, rid=run_id, status=run_status)
    try:
      self._bq_client.query(query=query).result()
    except exceptions.GoogleCloudError as e:
      tf.logging.error("Failed to insert run status: %s", e)

  def update_run_status(self, dataset_name, table_name, run_id, run_status):
    """Update the run status in in Bigquery run status table."""
    query = ("UPDATE {ds}.{tb} "
             "SET status = '{status}' "
             "WHERE run_id = '{rid}'").format(
                 ds=dataset_name, tb=table_name, status=run_status, rid=run_id)
    try:
      self._bq_client.query(query=query).result()
    except exceptions.GoogleCloudError as e:
      tf.logging.error("Failed to update run status: %s", e)


text:
package org.bbop.apollo.web.user;

public class UserAuthenticationException extends Exception {

	private static final long serialVersionUID = 1L;

	public UserAuthenticationException(String message) {
		super(message);
	}

	public UserAuthenticationException(Throwable e) {
		super(e);
	}

}


text:
namespace Leo.CleanUpTasks.Contracts
{
    using System;
    using System.Diagnostics.Contracts;
    using Utilities;

    [ContractClassFor(typeof(IXmlReportGenerator))]
    internal abstract class IXmlReportGeneratorContract : IXmlReportGenerator
    {
        public void AddConversionItem(string segmentNumber, string before, string after, string searchText, string replaceText)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(segmentNumber));
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(before));
            // After text maybe empty
            Contract.Requires<ArgumentNullException>(after != null);
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(searchText));
            // Replacement text maybe empty
            Contract.Requires<ArgumentNullException>(replaceText != null);
        }

        public void AddFile(string fileName)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(fileName));
        }

        public void AddLockItem(string segmentNumber, string lockedContent, string lockReason)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(segmentNumber));
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(lockedContent));
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(lockReason));
        }

        public void AddTagItem(string segmentNumber, string removedTag)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(segmentNumber));
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(removedTag));
        }
    }
}


text:
echo 'make sure to add:
# update settings for running in docker. Keep the lines last. It should contain ONLY docker conf.
if os.getenv("DOCKER_DEVEL"):
    try:
        from PROJECT.docker_local_settings import *  # noqa: F403
    except ImportError:
        print()
        print("Looks like you are trying to run project in docker but missinig docker_local_settings.py file.")
        print("Please run: sh aa-docker-tools/scripts/dockerize-django.sh")
        print()
        raise

at the very bottom of your settins.py file if it is not already there (and replace PROJECT with dir name).
Please choose your python version:'

PS3='Please enter your choice: '
options=("Python 3.6" "Python 2.7" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "Python 3.6")
            ln -s ./aa-docker-tools/devel/py36/Dockerfile
            break
            ;;
        "Python 2.7")
            ln -s ./aa-docker-tools/devel/py27/Dockerfile
            break
            ;;
        "Quit")
            echo "Goodbye"
            exit 1
            ;;
        *) echo Invalid option;;
    esac
done

cp ./aa-docker-tools/devel/pycommon/docker-compose.yml .
ln -s ./aa-docker-tools/devel/pycommon/docker-celery-entrypoint.sh
ln -s ./aa-docker-tools/devel/pycommon/docker-entrypoint.sh
# yes, this can be done better
MOD="$(egrep -o '(DJANGO_SETTINGS_MODULE)(.*)(\.)' manage.py)"
IFS='"' list=($MOD)
MOD=${list[2]}
IFS='.' list=($MOD)
MOD=${list[0]}
cd $MOD && cp ../aa-docker-tools/devel/pycommon/docker_local_settings.py .


text:
package com.opengamma.analytics.financial.model.option.pricing.tree;

import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertTrue;

import org.testng.annotations.Test;

import com.opengamma.analytics.financial.greeks.Greek;
import com.opengamma.analytics.financial.greeks.GreekResultCollection;
import com.opengamma.analytics.math.statistics.distribution.NormalDistribution;
import com.opengamma.analytics.math.statistics.distribution.ProbabilityDistribution;
import com.opengamma.util.test.TestGroup;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class CappedPowerOptionFunctionProviderTest {

  private static final ProbabilityDistribution<Double> NORMAL = new NormalDistribution(0, 1);

  private static final BinomialTreeOptionPricingModel MODEL = new BinomialTreeOptionPricingModel();
  private static final TrinomialTreeOptionPricingModel TRINOMIAL = new TrinomialTreeOptionPricingModel();
  private static final double SPOT = 10.;
  private static final double POWER = 2.;
  private static final double[] STRIKES = new double[] {97., 105., 105.1, 114. };
  private static final double TIME = 4.2;
  private static final double[] INTERESTS = new double[] {-0.01, 0.017, 0.05 };
  private static final double[] VOLS = new double[] {0.05, 0.1, 0.5 };
  private static final double[] DIVIDENDS = new double[] {0.005, 0.014 };

  /**
   *
   */
  @Test
  public void priceLatticeTrinomialTest() {
    final LatticeSpecification[] lattices = new LatticeSpecification[] {new CoxRossRubinsteinLatticeSpecification(), new JarrowRuddLatticeSpecification(),
        new TrigeorgisLatticeSpecification(), new TianLatticeSpecification() };

    final boolean[] tfSet = new boolean[] {true, false };
    for (final LatticeSpecification lattice : lattices) {
      for (final boolean isCall : tfSet) {
        for (final double strike : STRIKES) {
          final double[] caps = new double[] {strike * 0.2, strike * 0.4 };
          for (final double cap : caps) {
            for (final double interest : INTERESTS) {
              for (final double vol : VOLS) {
                final int nSteps = 381;
                for (final double dividend : DIVIDENDS) {
                  final OptionFunctionProvider1D function = new CappedPowerOptionFunctionProvider(strike, TIME, nSteps, isCall, POWER, cap);
                  final double exactDiv = price(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double resDiv = TRINOMIAL.getPrice(lattice, function, SPOT, vol, interest, dividend);
                  final double refDiv = Math.max(exactDiv, 1.) * 1.e-2;
                  assertEquals(resDiv, exactDiv, refDiv);
                }
              }
            }
          }
        }
      }
    }
  }

  /**
   *
   */
  @Test
  public void greekTrinomialTest() {
    final LatticeSpecification[] lattices = new LatticeSpecification[] {new CoxRossRubinsteinLatticeSpecification(), new JarrowRuddLatticeSpecification(),
        new TrigeorgisLatticeSpecification(), new TianLatticeSpecification() };
    final boolean[] tfSet = new boolean[] {true, false };
    for (final LatticeSpecification lattice : lattices) {
      for (final boolean isCall : tfSet) {
        for (final double strike : STRIKES) {
          final double[] caps = new double[] {strike * 0.2, strike * 0.4 };
          for (final double cap : caps) {
            for (final double interest : INTERESTS) {
              for (final double vol : VOLS) {
                final int nSteps = 391;
                for (final double dividend : DIVIDENDS) {
                  final OptionFunctionProvider1D function = new CappedPowerOptionFunctionProvider(strike, TIME, nSteps, isCall, POWER, cap);
                  final GreekResultCollection resDiv = TRINOMIAL.getGreeks(lattice, function, SPOT, vol, interest, dividend);
                  final double priceDiv = price(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double refPriceDiv = Math.max(Math.abs(priceDiv), 1.) * 1.e-2;
                  assertEquals(resDiv.get(Greek.FAIR_PRICE), priceDiv, refPriceDiv);
                  final double deltaDiv = delta(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double refDeltaDiv = Math.max(Math.abs(deltaDiv), 1.) * 1.e-2;
                  assertEquals(resDiv.get(Greek.DELTA), deltaDiv, refDeltaDiv);
                  final double gammaDiv = gamma(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double refGammaDiv = Math.max(Math.abs(gammaDiv), 1.) * 1.e-1;
                  assertEquals(resDiv.get(Greek.GAMMA), gammaDiv, refGammaDiv);
                  final double thetaDiv = theta(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double refThetaDiv = Math.max(Math.abs(thetaDiv), 1.) * 1.e-1;
                  assertEquals(resDiv.get(Greek.THETA), thetaDiv, refThetaDiv);
                }
              }
            }
          }
        }
      }
    }
  }

  /**
   *
   */
  @Test
  public void priceLatticeTest() {
    final LatticeSpecification[] lattices = new LatticeSpecification[] {new CoxRossRubinsteinLatticeSpecification(), new JarrowRuddLatticeSpecification(), new TrigeorgisLatticeSpecification(),
        new JabbourKraminYoungLatticeSpecification(), new TianLatticeSpecification() };

    /**
     * Since d1, d2 in Black-Scholes formula are not relevant in the case of power option, Leisen-Reimer is poor approximation
     */
    //    final LatticeSpecification[] lattices = new LatticeSpecification[] {new LeisenReimerLatticeSpecification() };

    final boolean[] tfSet = new boolean[] {true, false };
    for (final LatticeSpecification lattice : lattices) {
      for (final boolean isCall : tfSet) {
        for (final double strike : STRIKES) {
          final double[] caps = new double[] {strike * 0.2, strike * 0.4 };
          for (final double cap : caps) {
            for (final double interest : INTERESTS) {
              for (final double vol : VOLS) {
                final int nSteps = 369;
                for (final double dividend : DIVIDENDS) {
                  final OptionFunctionProvider1D function = new CappedPowerOptionFunctionProvider(strike, TIME, nSteps, isCall, POWER, cap);
                  final double exactDiv = price(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double resDiv = MODEL.getPrice(lattice, function, SPOT, vol, interest, dividend);
                  final double refDiv = Math.max(Math.abs(exactDiv), 1.) * 1.e-2;
                  assertEquals(resDiv, exactDiv, refDiv);
                }
              }
            }
          }
        }
      }
    }
  }

  /**
   * The dividend is cash or proportional to asset price
   */
  @Test
  public void priceDiscreteDividendTest() {
    final LatticeSpecification[] lattices = new LatticeSpecification[] {new CoxRossRubinsteinLatticeSpecification(), new JarrowRuddLatticeSpecification(), new TrigeorgisLatticeSpecification(),
        new JabbourKraminYoungLatticeSpecification(), new TianLatticeSpecification() };
    //    final LatticeSpecification[] lattices = new LatticeSpecification[] {new LeisenReimerLatticeSpecification() };

    final double[] propDividends = new double[] {0.01, 0.01, 0.01 };
    final double[] cashDividends = new double[] {0.5, 1., 0.8 };
    final double[] dividendTimes = new double[] {TIME / 6., TIME / 3., TIME / 2. };

    final boolean[] tfSet = new boolean[] {true, false };
    for (final LatticeSpecification lattice : lattices) {
      for (final boolean isCall : tfSet) {
        for (final double strike : STRIKES) {
          final double[] caps = new double[] {strike * 0.2, strike * 0.4 };
          for (final double cap : caps) {
            for (final double interest : INTERESTS) {
              for (final double vol : VOLS) {
                final int nSteps = 521;
                final int nStepsTri = 71;
                final OptionFunctionProvider1D function = new CappedPowerOptionFunctionProvider(strike, TIME, nSteps, isCall, POWER, cap);
                final DividendFunctionProvider cashDividend = new CashDividendFunctionProvider(dividendTimes, cashDividends);
                final DividendFunctionProvider propDividend = new ProportionalDividendFunctionProvider(dividendTimes, propDividends);
                final double resSpot = SPOT * (1. - propDividends[0]) * (1. - propDividends[1]) * (1. - propDividends[2]);
                final double modSpot = SPOT - cashDividends[0] * Math.exp(-interest * dividendTimes[0]) - cashDividends[1] * Math.exp(-interest * dividendTimes[1]) - cashDividends[2] *
                    Math.exp(-interest * dividendTimes[2]);
                final double exactProp = price(resSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);
                final double appCash = price(modSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);
                final double resProp = MODEL.getPrice(lattice, function, SPOT, vol, interest, propDividend);
                final double refProp = Math.max(Math.abs(exactProp), 1.) * 1.e-2;
                assertEquals(resProp, exactProp, refProp);
                final double resCash = MODEL.getPrice(lattice, function, SPOT, vol, interest, cashDividend);
                final double refCash = Math.max(Math.abs(appCash), 1.) * 1.e-1;
                assertEquals(resCash, appCash, refCash);

                if (lattice instanceof CoxRossRubinsteinLatticeSpecification || lattice instanceof JarrowRuddLatticeSpecification || lattice instanceof TrigeorgisLatticeSpecification ||
                    lattice instanceof TianLatticeSpecification) {
                  final OptionFunctionProvider1D functionTri = new CappedPowerOptionFunctionProvider(strike, TIME, nStepsTri, isCall, POWER, cap);
                  final double resPropTrinomial = TRINOMIAL.getPrice(lattice, functionTri, SPOT, vol, interest, propDividend);
                  final double resCashTrinomial = TRINOMIAL.getPrice(lattice, functionTri, SPOT, vol, interest, cashDividend);
                  assertEquals(resPropTrinomial, exactProp, Math.max(exactProp, 1.) * 1.e-1);
                  assertEquals(resCashTrinomial, appCash, Math.max(appCash, 1.) * 1.e-1);
                }
              }
            }
          }
        }
      }
    }
  }

  /**
   *
   */
  @Test
  public void greekTest() {
    final LatticeSpecification[] lattices = new LatticeSpecification[] {new CoxRossRubinsteinLatticeSpecification(), new JarrowRuddLatticeSpecification(), new TrigeorgisLatticeSpecification(),
        new JabbourKraminYoungLatticeSpecification(), new TianLatticeSpecification() };
    //    final LatticeSpecification[] lattices = new LatticeSpecification[] {new LeisenReimerLatticeSpecification() };

    final boolean[] tfSet = new boolean[] {true, false };
    for (final LatticeSpecification lattice : lattices) {
      for (final boolean isCall : tfSet) {
        for (final double strike : STRIKES) {
          final double[] caps = new double[] {strike * 0.2, strike * 0.4 };
          for (final double cap : caps) {
            for (final double interest : INTERESTS) {
              for (final double vol : VOLS) {
                final int nSteps = 429;
                for (final double dividend : DIVIDENDS) {
                  final OptionFunctionProvider1D function = new CappedPowerOptionFunctionProvider(strike, TIME, nSteps, isCall, POWER, cap);
                  final GreekResultCollection resDiv = MODEL.getGreeks(lattice, function, SPOT, vol, interest, dividend);
                  final double priceDiv = price(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double refPriceDiv = Math.max(Math.abs(priceDiv), 1.) * 1.e-2;
                  assertEquals(resDiv.get(Greek.FAIR_PRICE), priceDiv, refPriceDiv);
                  final double deltaDiv = delta(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double refDeltaDiv = Math.max(Math.abs(deltaDiv), 1.) * 1.e-2;
                  assertEquals(resDiv.get(Greek.DELTA), deltaDiv, refDeltaDiv);
                  final double gammaDiv = gamma(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double refGammaDiv = Math.max(Math.abs(gammaDiv), 1.) * 1.e-1;
                  assertEquals(resDiv.get(Greek.GAMMA), gammaDiv, refGammaDiv);
                  final double thetaDiv = theta(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                  final double refThetaDiv = Math.max(Math.abs(thetaDiv), 1.) * 1.e-1;
                  assertEquals(resDiv.get(Greek.THETA), thetaDiv, refThetaDiv);
                }
              }
            }
          }
        }
      }
    }
  }

  /**
   * The dividend is cash or proportional to asset price
   */
  @Test
  public void greeksDiscreteDividendLatticeTest() {
    final LatticeSpecification[] lattices = new LatticeSpecification[] {new JarrowRuddLatticeSpecification(),
        new JabbourKraminYoungLatticeSpecification(), new TianLatticeSpecification() };
    //    new CoxRossRubinsteinLatticeSpecification(),new TrigeorgisLatticeSpecification(), //Omitted due to slow convergence
    //    final LatticeSpecification[] lattices = new LatticeSpecification[] {new LeisenReimerLatticeSpecification() };

    final double[] propDividends = new double[] {0.01, 0.02, 0.02 };
    final double[] cashDividends = new double[] {0.1, 0.4, 0.1 };
    final double[] dividendTimes = new double[] {TIME / 6., TIME / 3., TIME / 2. };

    final boolean[] tfSet = new boolean[] {true, false };
    for (final LatticeSpecification lattice : lattices) {
      for (final boolean isCall : tfSet) {
        for (final double strike : STRIKES) {
          final double[] caps = new double[] {strike * 0.2, strike * 0.4 };
          for (final double cap : caps) {
            for (final double interest : INTERESTS) {
              for (final double vol : VOLS) {
                final int nSteps = 781;
                final int nStepsTri = 481;
                //              final int nSteps = 8637;
                final double resSpot = SPOT * (1. - propDividends[0]) * (1. - propDividends[1]) * (1. - propDividends[2]);
                final double modSpot = SPOT - cashDividends[0] * Math.exp(-interest * dividendTimes[0]) - cashDividends[1] * Math.exp(-interest * dividendTimes[1]) - cashDividends[2] *
                    Math.exp(-interest * dividendTimes[2]);
                final double exactPriceProp = price(resSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);
                final double exactDeltaProp = delta(resSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);
                final double exactGammaProp = gamma(resSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);
                final double exactThetaProp = theta(resSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);

                final double appPriceCash = price(modSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);
                final double appDeltaCash = delta(modSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);
                final double appGammaCash = gamma(modSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);
                final double appThetaCash = theta(modSpot, strike, TIME, vol, interest, interest, isCall, POWER, cap);

                final OptionFunctionProvider1D function = new CappedPowerOptionFunctionProvider(strike, TIME, nSteps, isCall, POWER, cap);
                final DividendFunctionProvider cashDividend = new CashDividendFunctionProvider(dividendTimes, cashDividends);
                final DividendFunctionProvider propDividend = new ProportionalDividendFunctionProvider(dividendTimes, propDividends);
                final GreekResultCollection resProp = MODEL.getGreeks(lattice, function, SPOT, vol, interest, propDividend);
                final GreekResultCollection resCash = MODEL.getGreeks(lattice, function, SPOT, vol, interest, cashDividend);

                assertEquals(resProp.get(Greek.FAIR_PRICE), exactPriceProp, Math.max(1., Math.abs(exactPriceProp)) * 1.e-2);
                assertEquals(resProp.get(Greek.DELTA), exactDeltaProp, Math.max(1., Math.abs(exactDeltaProp)) * 1.e-1);
                assertEquals(resProp.get(Greek.GAMMA), exactGammaProp, Math.max(1., Math.abs(exactGammaProp)) * 1.e-1);
                assertEquals(resProp.get(Greek.THETA), exactThetaProp, Math.max(1., Math.abs(exactThetaProp)) * 1.e-1);

                assertEquals(resCash.get(Greek.FAIR_PRICE), appPriceCash, Math.max(1., Math.abs(appPriceCash)) * 1.e-1);
                assertEquals(resCash.get(Greek.DELTA), appDeltaCash, Math.max(1., Math.abs(appDeltaCash)) * 1.e-1);
                assertEquals(resCash.get(Greek.GAMMA), appGammaCash, Math.max(1., Math.abs(appGammaCash)) * 1.e-1);
                assertEquals(resCash.get(Greek.THETA), appThetaCash, Math.max(1., Math.abs(appThetaCash)));//theta is poorly approximated

                if (lattice instanceof CoxRossRubinsteinLatticeSpecification || lattice instanceof JarrowRuddLatticeSpecification || lattice instanceof TrigeorgisLatticeSpecification ||
                    lattice instanceof TianLatticeSpecification) {
                  final OptionFunctionProvider1D functionTri = new CappedPowerOptionFunctionProvider(strike, TIME, nStepsTri, isCall, POWER, cap);
                  final GreekResultCollection resPropTrinomial = TRINOMIAL.getGreeks(lattice, functionTri, SPOT, vol, interest, propDividend);
                  final GreekResultCollection resCashTrinomial = TRINOMIAL.getGreeks(lattice, functionTri, SPOT, vol, interest, cashDividend);

                  assertEquals(resPropTrinomial.get(Greek.FAIR_PRICE), exactPriceProp, Math.max(1., Math.abs(exactPriceProp)) * 1.e-2);
                  assertEquals(resPropTrinomial.get(Greek.DELTA), exactDeltaProp, Math.max(1., Math.abs(exactDeltaProp)) * 1.e-1);
                  assertEquals(resPropTrinomial.get(Greek.GAMMA), exactGammaProp, Math.max(1., Math.abs(exactGammaProp)) * 1.e-1);
                  assertEquals(resPropTrinomial.get(Greek.THETA), exactThetaProp, Math.max(1., Math.abs(exactThetaProp)) * 1.e-1);

                  assertEquals(resCashTrinomial.get(Greek.FAIR_PRICE), appPriceCash, Math.max(1., Math.abs(appPriceCash)) * 1.e-1);
                  assertEquals(resCashTrinomial.get(Greek.DELTA), appDeltaCash, Math.max(1., Math.abs(appDeltaCash)) * 1.e-1);
                  assertEquals(resCashTrinomial.get(Greek.GAMMA), appGammaCash, Math.max(1., Math.abs(appGammaCash)) * 1.e-1);
                  assertEquals(resCashTrinomial.get(Greek.THETA), appThetaCash, Math.max(1., Math.abs(appThetaCash)));//theta is poorly approximated
                }
              }
            }
          }
        }
      }
    }
  }

  /**
   * non-constant volatility and interest rate
   */
  @Test
  public void timeVaryingVolTest() {
    final LatticeSpecification lattice1 = new TimeVaryingLatticeSpecification();
    final double[] time_set = new double[] {0.5, 1.2 };
    final int steps = 301;

    final double[] vol = new double[steps];
    final double[] rate = new double[steps];
    final double[] dividend = new double[steps];
    final int stepsTri = 261;
    final double[] volTri = new double[stepsTri];
    final double[] rateTri = new double[stepsTri];
    final double[] dividendTri = new double[stepsTri];
    final double constA = 0.01;
    final double constB = 0.001;
    final double constC = 0.1;
    final double constD = 0.05;

    final boolean[] tfSet = new boolean[] {true, false };
    for (final boolean isCall : tfSet) {
      for (final double strike : STRIKES) {
        final double[] caps = new double[] {strike * 0.2, strike * 0.4 };
        for (final double cap : caps) {
          for (final double time : time_set) {
            for (int i = 0; i < steps; ++i) {
              rate[i] = constA + constB * i * time / steps;
              vol[i] = constC + constD * Math.sin(i * time / steps);
              dividend[i] = 0.005;
            }
            for (int i = 0; i < stepsTri; ++i) {
              rateTri[i] = constA + constB * i * time / steps;
              volTri[i] = constC + constD * Math.sin(i * time / steps);
              dividendTri[i] = 0.005;
            }
            final double rateRef = constA + 0.5 * constB * time;
            final double volRef = Math.sqrt(constC * constC + 0.5 * constD * constD + 2. * constC * constD / time * (1. - Math.cos(time)) - constD * constD * 0.25 / time * Math.sin(2. * time));

            final OptionFunctionProvider1D function = new CappedPowerOptionFunctionProvider(strike, time, steps, isCall, POWER, cap);
            final double resPrice = MODEL.getPrice(function, SPOT, vol, rate, dividend);
            final GreekResultCollection resGreeks = MODEL.getGreeks(function, SPOT, vol, rate, dividend);

            final double resPriceConst = MODEL.getPrice(lattice1, function, SPOT, volRef, rateRef, dividend[0]);
            final GreekResultCollection resGreeksConst = MODEL.getGreeks(lattice1, function, SPOT, volRef, rateRef, dividend[0]);
            assertEquals(resPrice, resPriceConst, Math.max(Math.abs(resPriceConst), 1.) * 1.e-2);
            assertEquals(resGreeks.get(Greek.FAIR_PRICE), resGreeksConst.get(Greek.FAIR_PRICE), Math.max(Math.abs(resGreeksConst.get(Greek.FAIR_PRICE)), 1.) * 1.e-2);
            assertEquals(resGreeks.get(Greek.DELTA), resGreeksConst.get(Greek.DELTA), Math.max(Math.abs(resGreeksConst.get(Greek.DELTA)), 1.) * 1.e-2);
            assertEquals(resGreeks.get(Greek.GAMMA), resGreeksConst.get(Greek.GAMMA), Math.max(Math.abs(resGreeksConst.get(Greek.GAMMA)), 1.) * 1.e-1);
            assertEquals(resGreeks.get(Greek.THETA), resGreeksConst.get(Greek.THETA), Math.max(Math.abs(resGreeksConst.get(Greek.THETA)), 1.));

            final OptionFunctionProvider1D functionTri = new CappedPowerOptionFunctionProvider(strike, time, stepsTri, isCall, POWER, cap);
            final double resPriceTrinomial = TRINOMIAL.getPrice(functionTri, SPOT, volTri, rateTri, dividendTri);
            assertEquals(resPriceTrinomial, resPriceConst, Math.max(Math.abs(resPriceConst), 1.) * 1.e-1);
            final GreekResultCollection resGreeksTrinomial = TRINOMIAL.getGreeks(functionTri, SPOT, volTri, rateTri, dividendTri);
            assertEquals(resGreeksTrinomial.get(Greek.FAIR_PRICE), resGreeksConst.get(Greek.FAIR_PRICE), Math.max(Math.abs(resGreeksConst.get(Greek.FAIR_PRICE)), 1.) * 0.1);
            assertEquals(resGreeksTrinomial.get(Greek.DELTA), resGreeksConst.get(Greek.DELTA), Math.max(Math.abs(resGreeksConst.get(Greek.DELTA)), 1.) * 0.1);
            assertEquals(resGreeksTrinomial.get(Greek.GAMMA), resGreeksConst.get(Greek.GAMMA), Math.max(Math.abs(resGreeksConst.get(Greek.GAMMA)), 1.) * 0.1);
            assertEquals(resGreeksTrinomial.get(Greek.THETA), resGreeksConst.get(Greek.THETA), Math.max(Math.abs(resGreeksConst.get(Greek.THETA)), 1.));
          }
        }
      }
    }
  }

  /**
   *
   */
  @Test
  public void getPowerTest() {
    final CappedPowerOptionFunctionProvider function = new CappedPowerOptionFunctionProvider(103., TIME, 1003, true, 4., 30.);
    assertEquals(function.getPower(), 4.);
  }

  /**
   *
   */
  @Test
  public void getCapTest() {
    final CappedPowerOptionFunctionProvider function = new CappedPowerOptionFunctionProvider(103., TIME, 1003, true, 4., 30.);
    assertEquals(function.getCap(), 30.);
  }

  /**
   *
   */
  @SuppressWarnings("unused")
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void negativePowerTest() {
    new CappedPowerOptionFunctionProvider(103., TIME, 1003, true, -12., 30.);
  }

  /**
   *
   */
  @SuppressWarnings("unused")
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void negativeCapTest() {
    new CappedPowerOptionFunctionProvider(103., TIME, 1003, true, 12., -30.);
  }

  /**
   *
   */
  @SuppressWarnings("unused")
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void tooLargeCaprTest() {
    new CappedPowerOptionFunctionProvider(103., TIME, 1003, false, 3., 130.);
  }

  /**
   *
   */
  @Test
  public void hashCodeEqualsTest() {
    final OptionFunctionProvider1D ref = new CappedPowerOptionFunctionProvider(103., 1., 1003, true, 12., 120.);
    final OptionFunctionProvider1D[] function = new OptionFunctionProvider1D[] {ref, new CappedPowerOptionFunctionProvider(103., 1., 1003, true, 12., 120.),
        new CappedPowerOptionFunctionProvider(103., 1., 1003, true, 12., 121.), new CappedPowerOptionFunctionProvider(103., 1., 1003, true, 11., 120.),
        new CappedPowerOptionFunctionProvider(103., 10., 1003, true, 12., 120.), new EuropeanVanillaOptionFunctionProvider(103., 1., 1003, true), null };
    final int len = function.length;
    for (int i = 0; i < len; ++i) {
      if (ref.equals(function[i])) {
        assertTrue(ref.hashCode() == function[i].hashCode());
      }
    }
    for (int i = 0; i < len - 1; ++i) {
      assertTrue(function[i].equals(ref) == ref.equals(function[i]));
    }
  }

  private double price(final double spot, final double strike, final double time, final double vol, final double interest, final double cost, final boolean isCall, final double power, final double cap) {
    final double sign = isCall ? 1. : -1.;
    final double e1 = (Math.log(spot / Math.pow(strike, 1. / power)) + (cost + (power - 0.5) * vol * vol) * time) / vol / Math.sqrt(time);
    final double e2 = e1 - power * vol * Math.sqrt(time);
    final double e3 = (Math.log(spot / Math.pow(strike + sign * cap, 1. / power)) + (cost + (power - 0.5) * vol * vol) * time) / vol / Math.sqrt(time);
    final double e4 = e3 - power * vol * Math.sqrt(time);
    return sign *
        (Math.pow(spot, power) * Math.exp(((power - 1.) * (interest + 0.5 * power * vol * vol) - power * (interest - cost)) * time) * (NORMAL.getCDF(sign * e1) - NORMAL.getCDF(sign * e3)) - Math
            .exp((-interest) * time) * (strike * NORMAL.getCDF(sign * e2) - (strike + sign * cap) * NORMAL.getCDF(sign * e4)));
  }

  private double delta(final double spot, final double strike, final double time, final double vol, final double interest, final double cost, final boolean isCall, final double power, final double cap) {
    final double sign = isCall ? 1. : -1.;
    final double e1 = (Math.log(spot / Math.pow(strike, 1. / power)) + (cost + (power - 0.5) * vol * vol) * time) / vol / Math.sqrt(time);
    final double e2 = e1 - power * vol * Math.sqrt(time);
    final double e3 = (Math.log(spot / Math.pow(strike + sign * cap, 1. / power)) + (cost + (power - 0.5) * vol * vol) * time) / vol / Math.sqrt(time);
    final double e4 = e3 - power * vol * Math.sqrt(time);
    final double de = 1. / spot / vol / Math.sqrt(time);
    final double first = sign * power * Math.pow(spot, power - 1) * Math.exp(((power - 1.) * (interest + 0.5 * power * vol * vol) - power * (interest - cost)) * time) *
        (NORMAL.getCDF(sign * e1) - NORMAL.getCDF(sign * e3));
    final double second = de * Math.pow(spot, power) * Math.exp(((power - 1.) * (interest + 0.5 * power * vol * vol) - power * (interest - cost)) * time) * (NORMAL.getPDF(e1) - NORMAL.getPDF(e3)) -
        de * Math.exp((-interest) * time) * (strike * NORMAL.getPDF(e2) - (strike + sign * cap) * NORMAL.getPDF(e4));
    return first + second;
  }

  private double gamma(final double spot, final double strike, final double time, final double vol, final double interest, final double cost, final boolean isCall, final double power, final double cap) {
    final double sign = isCall ? 1. : -1.;
    final double e1 = (Math.log(spot / Math.pow(strike, 1. / power)) + (cost + (power - 0.5) * vol * vol) * time) / vol / Math.sqrt(time);
    final double e2 = e1 - power * vol * Math.sqrt(time);
    final double e3 = (Math.log(spot / Math.pow(strike + sign * cap, 1. / power)) + (cost + (power - 0.5) * vol * vol) * time) / vol / Math.sqrt(time);
    final double e4 = e3 - power * vol * Math.sqrt(time);
    final double de = 1. / spot / vol / Math.sqrt(time);
    final double dde = -1. / spot / spot / vol / Math.sqrt(time);
    final double factor1 = Math.exp(((power - 1.) * (interest + 0.5 * power * vol * vol) - power * (interest - cost)) * time);

    final double first = sign * power * (power - 1) * Math.pow(spot, power - 2) * factor1 * (NORMAL.getCDF(sign * e1) - NORMAL.getCDF(sign * e3)) +
        2. * power * Math.pow(spot, power - 1) * factor1 * de * (NORMAL.getPDF(e1) - NORMAL.getPDF(e3));
    final double second = de * de * Math.pow(spot, power) * factor1 * (NORMAL.getPDF(e1) * (-e1) - NORMAL.getPDF(e3) * (-e3)) -
        de * de * Math.exp((-interest) * time) * (strike * NORMAL.getPDF(e2) * (-e2) - (strike + sign * cap) * NORMAL.getPDF(e4) * (-e4));
    final double third = dde * Math.pow(spot, power) * factor1 * (NORMAL.getPDF(e1) - NORMAL.getPDF(e3)) -
        dde * Math.exp((-interest) * time) * (strike * NORMAL.getPDF(e2) - (strike + sign * cap) * NORMAL.getPDF(e4));
    return first + second + third;
  }

  private double theta(final double spot, final double strike, final double time, final double vol, final double interest, final double cost, final boolean isCall, final double power, final double cap) {
    final double sign = isCall ? 1. : -1.;
    final double e1 = (Math.log(spot / Math.pow(strike, 1. / power)) + (cost + (power - 0.5) * vol * vol) * time) / vol / Math.sqrt(time);
    final double e2 = e1 - power * vol * Math.sqrt(time);
    final double e3 = (Math.log(spot / Math.pow(strike + sign * cap, 1. / power)) + (cost + (power - 0.5) * vol * vol) * time) / vol / Math.sqrt(time);
    final double e4 = e3 - power * vol * Math.sqrt(time);
    final double de1 = -0.5 * Math.log(spot / Math.pow(strike, 1. / power)) / vol / Math.pow(time, 1.5) + 0.5 * (cost + (power - 0.5) * vol * vol) / Math.sqrt(time) / vol;
    final double de2 = de1 - 0.5 * power * vol / Math.sqrt(time);
    final double de3 = -0.5 * Math.log(spot / Math.pow(strike + sign * cap, 1. / power)) / vol / Math.pow(time, 1.5) + 0.5 * (cost + (power - 0.5) * vol * vol) / Math.sqrt(time) / vol;
    final double de4 = de3 - 0.5 * power * vol / Math.sqrt(time);
    final double cst = ((power - 1.) * (interest + 0.5 * power * vol * vol) - power * (interest - cost));

    final double first = sign * (cst * Math.pow(spot, power) * Math.exp(cst * time) * (NORMAL.getCDF(sign * e1) - NORMAL.getCDF(sign * e3)) + interest * Math.exp((-interest) * time) *
        (strike * NORMAL.getCDF(sign * e2) - (strike + sign * cap) * NORMAL.getCDF(sign * e4)));
    final double second = Math.pow(spot, power) * Math.exp(((power - 1.) * (interest + 0.5 * power * vol * vol) - power * (interest - cost)) * time) *
        (NORMAL.getPDF(e1) * de1 - NORMAL.getPDF(e3) * de3) - Math.exp((-interest) * time) * (strike * NORMAL.getPDF(e2) * de2 - (strike + sign * cap) * NORMAL.getPDF(e4) * de4);
    return -first - second;
  }

  /**
   * test for analytic formula
   */
  @Test(enabled = false)
  public void functionTest() {
    final boolean[] tfSet = new boolean[] {true, false };
    final double eps = 1.e-6;
    for (final boolean isCall : tfSet) {
      for (final double strike : STRIKES) {
        final double[] caps = new double[] {strike * .2, strike * .3 };
        for (final double cap : caps) {
          for (final double interest : INTERESTS) {
            for (final double vol : VOLS) {
              for (final double dividend : DIVIDENDS) {
                final double delta = delta(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                final double gamma = gamma(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                final double theta = theta(SPOT, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                final double upSpot = price(SPOT + eps, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                final double downSpot = price(SPOT - eps, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                final double upSpotDelta = delta(SPOT + eps, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                final double downSpotDelta = delta(SPOT - eps, strike, TIME, vol, interest, interest - dividend, isCall, POWER, cap);
                final double upTime = price(SPOT, strike, TIME + eps, vol, interest, interest - dividend, isCall, POWER, cap);
                final double downTime = price(SPOT, strike, TIME - eps, vol, interest, interest - dividend, isCall, POWER, cap);
                assertEquals(delta, 0.5 * (upSpot - downSpot) / eps, eps);
                assertEquals(gamma, 0.5 * (upSpotDelta - downSpotDelta) / eps, eps);
                assertEquals(theta, -0.5 * (upTime - downTime) / eps, eps);
              }
            }
          }
        }
      }
    }
  }
}


text:
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Configuration;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using CsvHelper;
using Newtonsoft.Json;
using Orc.SuperchargedReact.Core;
using Orc.SuperchargedReact.Web;

namespace Orc.SuperchargedReact.Runner
{
    /// <summary>
    /// This is our dirty little performance testing program. Lots of stuff in here is commented out and only used for testing
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting");
            //  ThreadChecker();
            GeneratePerformaceReport();
            Console.WriteLine("end");
        }

        static void ThreadChecker()
        {
            var runner = new ReactRunner(@"C:\Users\Stephen\Documents\visual studio 2013\Projects\Orc.SuperchargedReact\Orc.SuperchargedReact.ExampleBundle\bundle.js", true, true, true, "global.SuperChargedReact.bootstrapper", new JsonSerializerSettings());

            Parallel.For(0, 100, new ParallelOptions() { MaxDegreeOfParallelism = 50 }, (i, state) =>
            {
                Console.WriteLine("Starting:" + i);
                var testString = "helloWorld" + i;
                var browserOutput = "";
                ReactPerformaceMeasurements measurements;
                var settings = new RenderSettings("reactApp", new { testString = testString }, "/tester");
                var output = runner.Execute( settings, out browserOutput,out measurements);
                if (!output.Contains(testString))
                {
                    throw new Exception("Not Thread Safe.... uh oh!");
                }
                Console.WriteLine("Complete:" + i);
            });
        }

        static void GeneratePerformaceReport()
        {
            var iterations = 50;

            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream))
            using (var csv = new CsvWriter(writer))
            {
                csv.WriteHeader(typeof(PerformaceTestResult));

              /*  csv.WriteRecords(DoTestsForSettings(iterations, false, false, false));
                csv.WriteRecords(DoTestsForSettings(iterations, false, false, true));
                csv.WriteRecords(DoTestsForSettings(iterations, false, true, false));
                csv.WriteRecords(DoTestsForSettings(iterations, false, true, true));

                csv.WriteRecords(DoTestsForSettings(iterations, true, false, false));
                csv.WriteRecords(DoTestsForSettings(iterations, true, false, true));

                csv.WriteRecords(DoTestsForSettings(iterations, true, true, false));
                */
                csv.WriteRecords(DoTestsForSettings(iterations, true, true, true));
                writer.Flush();
                stream.Position = 0;
                var text = reader.ReadToEnd();
                File.WriteAllText("Report.csv", text);
            }
        }

        static List<PerformaceTestResult> DoTestsForSettings(int testIterations, bool enableFileWatcher, bool enableCompilation, bool disableGlobalMembers)
        {
            List<PerformaceTestResult> results = new List<PerformaceTestResult>();
            for (int testi = 0; testi < testIterations; testi++)
            {
                var model = PerfTest(enableFileWatcher, enableCompilation, disableGlobalMembers);

                model.TestIteration = testi;
                model.EnableFileWatcher = enableFileWatcher;
                model.EnableCompilation = enableCompilation;
                model.DisableGlobalMembers = disableGlobalMembers;
                model.MemoryUsage = GC.GetTotalMemory(true);
                results.Add(model);
            }
            return results;
        }

        static PerformaceTestResult PerfTest(bool enableFileWatcher, bool enableCompilation, bool disableGlobalMembers)
        {
            var result = new PerformaceTestResult();
            Stopwatch init = new Stopwatch();
            init.Start();

            using (var runner =
                new ReactRunner(@"D:\work\Olympic\BookingEngine\Build\Olympic.BookingEngine\assets\js\bundle.js",
                    enableFileWatcher, enableCompilation, disableGlobalMembers, "global.SuperChargedReact.bootstrapper", new JsonSerializerSettings()))
            {

                init.Stop();

                result.InitializationTime = init.ElapsedMilliseconds;

                var times = new List<long>();
                Console.WriteLine("Benchmarking html generation");
                var props = File.ReadAllText("props.json");

                for (int i = 0; i < 20; i++)
                {
                    init.Reset();
                    string outputStr = "";
                    init.Start();
                    ReactPerformaceMeasurements measurements;
                    var settings = new RenderSettings("reactApp", new { testString = "testString" }, "/search/AccommodationOnly");
                    runner.Execute(settings, out outputStr, out measurements);
                    init.Stop();
                    times.Add(init.ElapsedMilliseconds);
                    //    Console.WriteLine(init.ElapsedMilliseconds);
                }

                result.Iterations = times.Count;
                result.Average = times.Average();
                result.First5GenerationsAverage = times.Take(5).Average();
                result.Last10GenerationsAverage = times.Skip(times.Count - 10).Average();

                result.QuickestGeneration = times.Min();
                result.LongestGeneration = times.Max();

            }
            return result;
        }

        public class PerformaceTestResult
        {
            public bool EnableFileWatcher { get; set; }
            public bool EnableCompilation { get; set; }
            public bool DisableGlobalMembers { get; set; }
            public int TestIteration { get; set; }

            public int Iterations { get; set; }

            public double Average { get; set; }
            public double First5GenerationsAverage { get; set; }
            public double Last10GenerationsAverage { get; set; }
            public long QuickestGeneration { get; set; }
            public long LongestGeneration { get; set; }
            public long InitializationTime { get; set; }

            public long MemoryUsage { get; set; }
        }

    }
}