text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Futures & Options Trading for Risk Management - CME Group</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" id="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,initial-scale=1.0,user-scalable=0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <link rel="canonical" href="http://www.cmegroup.com/index.html"/>

<link rel="shortcut icon" href="/etc/clientlibs/cmegroup/cmegroupClientLibs/images/favicon.ico"/>
<link rel="apple-touch-icon-precomposed" href="/etc/clientlibs/cmegroup/cmegroupClientLibs/images/cme-icon-144x144.png" type="image/png"/>

	<meta name="title" content="Futures & Options Trading for Risk Management - CME Group" />

	<meta name="description" content="CME Group is the world's leading and most diverse derivatives marketplace offering the widest range of futures and options products for risk management." />

	<meta name="keywords" content="cme group, cme, cbot, nymex, manage risk, risk management, futures exchange, futures trading, trade futures, commodity/commodities exchange, derivatives trading, derivatives exchange, futures markets, futures and options trading, options exchange, commodity options, commodity future trading, commodity markets, chicago mercantile exchange, chicago board of trade, new york mercantile exchange" />

		<meta property="og:title" content="Futures & Options Trading for Risk Management - CME Group" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://www.cmegroup.com" />
<meta property="og:image" content="http://www.cmegroup.com/images/og-cme-group-li.jpg" />
<meta property="og:image" content="http://www.cmegroup.com/images/og-cme-group-fb.jpg" />
<meta property="og:description" content="CME Group is the world's leading and most diverse derivatives marketplace offering the widest range of futures and options products for risk management." />

<link rel="stylesheet" href="/etc/clientlibs/cmegroup/cmegroupClientLibs.css" type="text/css">

<link href="https://plus.google.com/103746993828734713990" rel="publisher"/>

<meta name="apple-itunes-app" content="app-id=958577007, affiliate-data=myAffiliateData, app-argument=myURL">

CME Group

                                Trading

                             All Products Home

											Agricultural

											Energy

											Equity Index

											FX

											Interest Rates

											Metals

											Options

											OTC

											Weather

											Real Estate

                             Technology

CME Globex

CME Direct

CME ClearPort

Straight Through Processing (STP)

Global Repository Services

Co-Location Services

CME Pivot

<link rel="stylesheet" href="/etc/clientlibs/cmegroup/cmeText/clientLibs.css" type="text/css">

                             Trading Services

Membership

Fees

Incentive Programs

Tools & Resources

Swap Execution Facility (SEF)

CME Europe

Read more

					         Economic Research

Reports on a variety of topics on the forefront of financial market trends

Read more

					         Holiday Calendar

Hours for floor and electronically traded futures and options during holidays

Read more

					         Find a Broker

Search our broker directory to start trading

                                Clearing

                             Clearing Home

Risk Management

Financial & Collateral Management

Financial and Regulatory Surveillance

Clearing Operations and Deliveries

Performance Bonds / Margins

                             Clearing Advisories

Read more

					         CME Clearing Europe

Our European Clearing House

Read more

					         Margin Services

Try our new interactive margin calculator and evaluate initial margin requirements

                                Regulation

                             Market Regulation Home

Investigations

Data Investigations

Market Surveillance

Enforcement

Regulatory Outreach

Advisory Notices

Subscription Center

                             Related Information

Rulebooks

Rule Filings

Disciplinary Notices

Arbitration

Position Limits

Registrar's Advisories

                             Market Regulation Advisory Notices

                             View All MRANs

                                Data

                             Market Data Home

                             Reports

Settlements

Volume & Open Interest

Daily Bulletin

Registrar Reports

                             Distributors

New & Existing Distributors

Licensed Distributor List

                             Intraday Data

Delayed Quotes

Block Trades

                             Subscription Based Data

												MDP (Streaming)

										Access our market data directly via our Market Data Platform

												E-Quotes

										Offering charting, analytics, real-time quotes and news on our  products

												Datamine (Historical)

										Comprehensive historical price information available on select CME Group contracts

                                Education

                             Education Home

Learn About Trading

Practice Trading

Risk Management/Hedging

Event Calendar

Podcasts

All Education Materials

Alternative Investment Resources

Read more

					         CME Institute

The CME Institute is your resource for trading education. Designed for new and advanced traders come explore our courses and practice on our simulator.

Read more

					         Futures Fundamentals

Learn the role of the futures markets in everyday life and the fundamentals of the derivatives markets.

                                About

                             About Us Home

Corporate Overview

Global Contacts

Partner Exchanges

Center for Innovation

Corporate Citizenship

Careers

Investor Relations

Media Room

                             News

                             View All News

                             Jobs

                             View All Jobs

                             Open Markets

                             Visit Open Markets

                            Login

CME Customer Center

CME Direct

Subscription Center

CME Group

                        		<gcse:searchbox-only resultsUrl="http://www.cmegroup.com/search/index.html">

                    <button class="searchExpander" role="button" title="Search"></button>

<link rel="stylesheet" href="/etc/clientlibs/cmegroup/cmePineappleDesign/common.css" type="text/css">

Now Trading: E-mini Russell 2000® Index Futures and Options

Coming Soon: Futures-Style Coal Options on NYMEX

Annual Survey Now Available in Seven Languages

July Rates Recap: Ultra 10 Surpasses 30M in 18 months

1

2

3

4

			Previous
			Next

CME Group is comprised of four Designated Contract Markets (DCMs). Further information on each exchange's rules and product listings can be found by clicking on the links to CME, CBOT, NYMEX, and COMEX.

Economic Research

                    View All Economic Research

ECB, BOE to Follow in Fed's Monetary Footsteps?

											ECB, BOE to Follow in Fed's Monetary Footsteps?

 By Erik Norland

July 11, 2017

The Fed has signaled multiple rate hikes in 2018 and 2019, which could be bullish for the dollar. How will the European Central Bank, Bank of England react?

Equities Divergence From Earnings a Red Flag?

											Equities Divergence From Earnings a Red Flag?

 By Erik Norland

July 10, 2017

High-flying equities are showing no signs of restraint despite lackluster growth in corporate earnings. Does the divergence forebode a market correction?

Will Fed Rate Hikes Stir Market Volatility?

											Will Fed Rate Hikes Stir Market Volatility?

 By Erik Norland

July 06, 2017

Years of low U.S. interest rates and Fed quantitative easing have sapped many markets of volatility. Will a series of rate hikes bring it back?

Delayed Quotes

Quotes are delayed by at least 10 minutes.

Buy Real Time QuotesBuy Historical Data

			Agricultural

						Product
						Last
						Change
						Chart
						Globex Vol

							ZCZ7
Corn Futures - DEC 2017

							405'2
							-9'0

									Show Price Chart

							180,959

							ZSX7
Soybean Futures - NOV 2017

							1039'2
							-4'0

									Show Price Chart

							132,671

							ZLZ7
Soybean Oil Futures - DEC 2017

							34.10
							-0.22

									Show Price Chart

							39,890

							ZMZ7
Soybean Meal Futures - DEC 2017

							345.5
							-0.7

									Show Price Chart

							48,203

							ZWU7
Chicago SRW Wheat Futures - SEP 2017

							542'2
							-10'6

									Show Price Chart

							62,123

							LEQ7
Live Cattle Futures - AUG 2017

							117.875
							+3.000

									Show Price Chart

							36,363

							HEQ7
Lean Hog Futures - AUG 2017

							82.850
							+0.600

									Show Price Chart

							15,115

			Energy

						Product
						Last
						Change
						Chart
						Globex Vol

							CLQ7
Crude Oil Futures - AUG 2017

							45.68
							+0.64

									Show Price Chart

							722,744

							NGQ7
Henry Hub Natural Gas Futures - AUG 2017

							2.977
							-0.070

									Show Price Chart

							102,318

							BZU7
Brent Last Day Financial Futures - SEP 2017

							47.98
							+0.46

									Show Price Chart

							24,363

							RBQ7
RBOB Gasoline Futures - AUG 2017

							1.5284
							+0.0101

									Show Price Chart

							38,132

							HOQ7
NY Harbor ULSD Futures - AUG 2017

							1.4836
							+0.0073

									Show Price Chart

							33,689

							QMQ7
E-mini Crude Oil Futures - AUG 2017

							45.700
							+0.650

									Show Price Chart

							13,021

							QGQ7
E-mini Natural Gas Futures - AUG 2017

							2.985
							-0.060

									Show Price Chart

							501

			Interest Rates

						Product
						Last
						Change
						Chart
						Globex Vol

							GEZ7
Eurodollar Futures - DEC 2017

							98.55
							+0.01

									Show Price Chart

							217,679

							ZTU7
2-Year T-Note Futures - SEP 2017

							108'037
							+0'017

									Show Price Chart

							252,008

							ZFU7
5-Year T-Note Futures - SEP 2017

							117'287
							+0'070

									Show Price Chart

							670,253

							ZNU7
10-Year T-Note Futures - SEP 2017

							125'180
							+0'125

									Show Price Chart

							1,207,111

							TNU7
Ultra 10-Year U.S. Treasury Note Futures - SEP 2017

							134'205
							+0'165

									Show Price Chart

							100,107

							ZBU7
U.S. Treasury Bond Futures - SEP 2017

							152'29
							+0'27

									Show Price Chart

							202,266

							UBU7
Ultra U.S. Treasury Bond Futures - SEP 2017

							164'17
							+1'00

									Show Price Chart

							81,890

			Equity

						Product
						Last
						Change
						Chart
						Globex Vol

							ESU7
E-mini S&P 500 Futures - SEP 2017

							2439.50
							+15.00

									Show Price Chart

							704,901

							NQU7
E-mini NASDAQ 100 Futures - SEP 2017

							5769.50
							+49.50

									Show Price Chart

							179,246

							YMU7
E-mini Dow ($5) Futures - SEP 2017

							21464
							+97

									Show Price Chart

							90,781

							NIYU7
Nikkei/Yen Futures - SEP 2017

							20145
							+25

									Show Price Chart

							33,520

							XAFU7
E-mini Financial Select Sector Futures - SEP 2017

							305.35
							-0.05

									Show Price Chart

							348

							RTYU7
E-mini  Russell 2000 Index Futures - SEP 2017

							1424.70
							+11.60

									Show Price Chart

							4,116

							EMDU7
E-mini S&P MidCap 400 Futures - SEP 2017

							1758.20
							+12.60

									Show Price Chart

							8,569

			FX

						Product
						Last
						Change
						Chart
						Globex Vol

							6AU7
Australian Dollar Futures - SEP 2017

							0.7668
							+0.0037

									Show Price Chart

							71,590

							6CU7
Canadian Dollar Futures - SEP 2017

							0.78695
							+0.01165

									Show Price Chart

							106,430

							6SU7
Swiss Franc Futures - SEP 2017

							1.0409
							-0.0022

									Show Price Chart

							21,152

							6EU7
Euro FX Futures - SEP 2017

							1.1453
							-0.0065

									Show Price Chart

							220,444

							6BU7
British Pound Futures - SEP 2017

							1.2918
							+0.0040

									Show Price Chart

							106,592

							6JU7
Japanese Yen Futures - SEP 2017

							0.008856
							+0.000045

									Show Price Chart

							131,968

							6MU7
Mexican Peso Futures - SEP 2017

							0.055690
							+0.000560

									Show Price Chart

							49,535

			Metals

						Product
						Last
						Change
						Chart
						Globex Vol

							GCQ7
Gold Futures - AUG 2017

							1220.4
							+5.7

									Show Price Chart

							219,164

							SIU7
Silver Futures - SEP 2017

							15.920
							+0.175

									Show Price Chart

							83,544

							PLV7
Platinum Futures - OCT 2017

							919.9
							+21.2

									Show Price Chart

							18,458

							PAU7
Palladium Futures - SEP 2017

							863.45
							+16.60

									Show Price Chart

							2,916

							HGU7
Copper Futures - SEP 2017

							2.6820
							+0.0100

									Show Price Chart

							51,516

							MGCQ7
E-micro Gold Futures - AUG 2017

							1220.3
							+5.6

									Show Price Chart

							3,478

							SILU7
1,000-oz. Silver Futures - SEP 2017

							15.880
							+0.135

									Show Price Chart

							109

Market Data Summary

Block trades, CME ClearPort most actives and Daily Volume and Open Interest Summary

	<input type="hidden"
				class="cmeAutoUpdateIcon cmeIOSSwitch" id="cmeAutoUpdateSwitch"
				checked="checked">

			Block Trades

						Product
						Type
						Exchange
						Price
						Qty
						Time

							CUU7
Chicago Ethanol (Platts) Futures

						FUT
						NYMEX
						15550
						5
						11:45:00

							CUQ7
Chicago Ethanol (Platts) Futures

						FUT
						NYMEX
						15600
						15
						11:44:00

							CLM8
Crude Oil Futures

						FUT
						NYMEX
						4700
						62
						11:44:00

							LOM8|4700C
Crude Oil Options

						OPT
						NYMEX
						530
						100
						11:44:00

							CLZ7
Crude Oil Futures

						FUT
						NYMEX
						4645
						300
						11:44:00

							CLG8
Crude Oil Futures

						FUT
						NYMEX
						4686
						300
						11:44:00

							CUU7
Chicago Ethanol (Platts) Futures

						FUT
						NYMEX
						15550
						5
						11:43:00

							G3V7|-450P
Natural Gas (Henry Hub) Last-day Financial 3 Month Spread Options

						OPT
						NYMEX
						18
						100
						11:42:00

							G3V7|-350P
Natural Gas (Henry Hub) Last-day Financial 3 Month Spread Options

						OPT
						NYMEX
						40
						100
						11:42:00

				Trade Date: 12 Jul 2017
				Last Updated: 12 Jul 2017 11:47:39 AM CT

				CME ClearPort

							Product
							Group
							Prior Vol
							Prior OI

										LN
Natural Gas Options (European)

									Energy
									69,710
									2,496,152

										CL
Crude Oil Futures

									Energy
									49,404
									2,133,575

										E0
Eurodollar 1yr MC Options

									Interest Rate
									36,000
									6,242,744

										LO
Crude Oil Options

									Energy
									30,140
									3,087,448

										RB
RBOB Gasoline Futures

									Energy
									17,897
									383,501

										NG
Henry Hub Natural Gas Futures

									Energy
									14,759
									1,347,125

										HO
NY Harbor ULSD Futures

									Energy
									14,653
									413,360

										E2
Eurodollar 2yr MC Options

									Interest Rate
									13,700
									5,817,698

										C1
Canadian Dollar Futures

									FX
									13,122
									161,065

									Trade Date: 11 Jul 2017 |

								FINAL

								Note: Prior Vol represents CME ClearPort only volume

				CME CF Bitcoin Products

							Bitcoin Reference Rate (BRR)

-

Last Updated

-

					Once-per-day reference rate on the U.S. dollar price of bitcoin

								Bitcoin Real Time Index (BRTI)

-

Last Updated

-

					Real-time bitcoin prices

<link rel="stylesheet" href="/etc/clientlibs/cmegroup/cmeBitcoinRealTimeIndex/clientLibs.css" type="text/css">

			Daily Volume & OI

			Trade Date
			CME Globex
			CME ClearPort
			Open Outcry
			Open Interest

					12 Jul 2017
					12139172
					153867
					821223

					11 Jul 2017
					13420369
					400794
					1354057
					114860443

					10 Jul 2017
					10789614
					380988
					570369
					114041435

					07 Jul 2017
					14334567
					350707
					977183
					113672300

					06 Jul 2017
					15050202
					405442
					947999
					113705315

					05 Jul 2017
					17115523
					332161
					1025583
					113408743

					03 Jul 2017
					10913783
					173488
					837148
					112976087

					30 Jun 2017
					15871009
					394120
					953524
					112617886

					29 Jun 2017
					18027614
					282078
					889890
					113250242

					28 Jun 2017
					15193014
					317405
					798635
					112344043

					27 Jun 2017
					14973644
					431610
					960932
					111923660

					26 Jun 2017
					10296405
					223857
					511528
					111998482

					23 Jun 2017
					10605901
					245502
					1066884
					111570576

					22 Jun 2017
					11656538
					325263
					1522873
					114741089

					21 Jun 2017
					12955927
					366062
					1040767
					113622480

					20 Jun 2017
					12842425
					326891
					866605
					113411905

					19 Jun 2017
					13062992
					316505
					967346
					114116033

					16 Jun 2017
					12460315
					468637
					1059905
					121164992

					15 Jun 2017
					17583753
					374835
					1560671
					129049907

					14 Jun 2017
					26706526
					733437
					2317291
					129063167

				Last Updated 12 Jul 2017 11:47:39 AM CT
				CME Europe not included in V/OI. All figures in millions.

Futures & Options Trading

As the world's leading and most diverse derivatives marketplace, CME Group is where the world comes to manage risk. CME Group exchanges offer the widest range of global benchmark products across all major asset classes, including futures and options based on interest rates, equity indexes, foreign exchange, energy, agricultural commodities, metals, weather and real estate. CME Group brings buyers and sellers together through the CME Globex electronic trading platform and trading facilities in New York and Chicago. CME Group also operates CME Clearing, one of the largest central counterparty clearing services in the world, which provides clearing and settlement services for exchange-traded contracts, as well as for over-the-counter derivatives transactions through CME ClearPort.

 Subscription Center

<select id="selectLanguage" style="float:right">
    <option value="en">English</option>
    <option value="es">Español</option>
    <option value="po">Português</option>
    <option value="fr">Français</option>
    <option value="de">Deutsch</option>
    <option value="it">Italiano</option>
    <option value="cn-s">中文(简体)</option>
    <option value="cn-t">中文(繁體)</option>
    <option value="ja">日本語</option>
    <option value="ko">한국어</option>
</select>

Send Us Feedback

Who We Are

CME Group is the world's leading and most diverse derivatives marketplace. The company is comprised of four Designated Contract Markets (DCMs). Further information on each exchange's rules and product listings can be found by clicking on the links to CME, CBOT, NYMEX and COMEX.

Contact Us

CME Group / Chicago HQ

Phone: +1 312 930 1000

Toll Free (US Only): +1 866 716 7274

Global Offices

Connect With Us

© 2017 CME Group Inc. All rights reserved.

Careers | Site Map | Disclaimer | Privacy Policy | Cookie Policy


text:
//  Copyright 2008,2011 Chris Thachuk, Herman De Beukelaer
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

package org.cimmyt.corehunter.measures;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.cimmyt.corehunter.Accession;

/**
 * <<Class summary>>
 *
 * @author Chris Thachuk <chris.thachuk@gmail.com>
 * @version $Rev$
 */
public abstract class DistanceMeasure extends Measure {
    //private static final int DEFAULT_ACCESSION_COUNT = 512;
    //private static final int MAX_ACCESSION_COUNT = 8192;
    //private List<List<Double>> M;
    private double[][] M;
    private Map<String,DistanceCachedResult> cachedResults;

    protected static final double MISSING_VAL = -1.0;

    protected DistanceMeasureType type; // states whether mean or min distance should be computed

    public DistanceMeasure(int accessionCount) {
	this("UM", "Unknown Measure", accessionCount, DistanceMeasureType.MEAN_DISTANCE);
    }

    /*public DistanceMeasure(String name, String description) {
	this(name, description, DEFAULT_ACCESSION_COUNT);
    }*/

    public DistanceMeasure(String name, String description, int accessionCount, DistanceMeasureType type) {
	super(name, description);

	//M = new ArrayList<List<Double>>(accessionCount);
	/*for(int i=0; i<accessionCount; i++) {
	    M.add(new ArrayList<Double>(i+1));
	    for(int j=0; j<=i; j++) {
		M.get(i).add(new Double(MISSING_VAL));
	    }
	}*/
        M = new double[accessionCount][];
        for(int i=0; i<accessionCount; i++) {
	    M[i] = new double[i+1];
	    for(int j=0; j<=i; j++) {
		M[i][j] = MISSING_VAL;
	    }
	}

	cachedResults = Collections.synchronizedMap(new HashMap<String,DistanceCachedResult>());

        this.type = type;
    }

    public double calculate(List<Accession> accessions, String id) {
	DistanceCachedResult cache = cachedResults.get(id);

	if (cache == null) {
	    cache = this.new DistanceCachedResult(accessions);
	    cachedResults.put(id, cache);
	}

	return calculate(accessions, cache);
    }

    public double calculate(List<Accession> accessions) {
	return calculate(accessions, new DistanceCachedResult(accessions));
    }

    public double calculate(List<Accession> accessions, DistanceCachedResult cache) {
        List<Accession> aAccessions = cache.getAddedAccessions(accessions);
        List<Accession> rAccessions = cache.getRemovedAccessions(accessions);
        List<Accession> cAccessions = cache.getCommonAccessions(accessions);

        double dist;

        if (type == DistanceMeasureType.MEAN_DISTANCE){

            double total = cache.getTotal();
            double count = cache.getCount();

            for(Accession a : aAccessions) {
                for(Accession b : cAccessions) {
                    dist = calculate(a,b);
                    total += dist;
                    count++;
                }
            }

            int size = aAccessions.size();
            for(int i=0; i<size-1; i++) {
                for(int j=i+1; j<size; j++) {
                    dist = calculate(aAccessions.get(i), aAccessions.get(j));
                    total += dist;
                    count++;
                }
            }

            for(Accession a : rAccessions) {
                for(Accession b : cAccessions) {
                    dist = calculate(a,b);
                    total -= dist;
                    count--;
                }
            }

            size = rAccessions.size();
            for(int i=0; i<size-1; i++) {
                for(int j=i+1; j<size; j++) {
                    dist = calculate(rAccessions.get(i), rAccessions.get(j));
                    total -= dist;
                    count--;
                }
            }

            // recache our results under this id
            cache.setTotal(total);
            cache.setCount(count);
            cache.setAccessions(accessions);

            return total/count;

        } else if (type == DistanceMeasureType.MIN_DISTANCE){

            TreeMap<Double, Integer> minFreqTable = cache.getMinFreqTable();

            // add new distances

            for(Accession a : aAccessions) {
                for(Accession b : cAccessions) {
                    dist = calculate(a,b);
                    Integer freq = minFreqTable.get(dist);
                    if(freq == null){
                        minFreqTable.put(dist, 1);
                    } else {
                        minFreqTable.put(dist, freq+1);
                    }
                }
            }

            int size = aAccessions.size();
            for(int i=0; i<size-1; i++) {
                for(int j=i+1; j<size; j++) {
                    dist = calculate(aAccessions.get(i), aAccessions.get(j));
                    Integer freq = minFreqTable.get(dist);
                    if(freq == null){
                        minFreqTable.put(dist, 1);
                    } else {
                        minFreqTable.put(dist, freq+1);
                    }
                }
            }

            // remove old distances

            for(Accession a : rAccessions) {
                for(Accession b : cAccessions) {
                    dist = calculate(a,b);
                    Integer freq = minFreqTable.get(dist);
                    freq--;
                    if(freq == 0){
                        minFreqTable.remove(dist);
                    } else if (freq > 0) {
                        minFreqTable.put(dist, freq);
                    } else {
                        System.err.println("Error in minimum distance cacheing scheme!"
                                           + "\nThis is a bug, please contact authors!");
                    }
                }
            }

            size = rAccessions.size();
            for(int i=0; i<size-1; i++) {
                for(int j=i+1; j<size; j++) {
                    dist = calculate(rAccessions.get(i), rAccessions.get(j));
                    Integer freq = minFreqTable.get(dist);
                    freq--;
                    if(freq == 0){
                        minFreqTable.remove(dist);
                    } else if (freq > 0) {
                        minFreqTable.put(dist, freq);
                    } else {
                        System.err.println("Error in minimum distance cacheing scheme!"
                                           + "\nThis is a bug, please contact authors!");
                    }
                }
            }

            // recache results
            cache.setAccessions(accessions);

            //System.out.println("Min cache size: " + minFreqTable.size());
            return minFreqTable.firstKey();

            /*
            //implementation without cache
            double minDist = Double.MAX_VALUE;
            int size = accessions.size();
            for(int i=0; i<size-1; i++) {
                for(int j=i+1; j<size; j++) {
                    dist = calculate(accessions.get(i), accessions.get(j));
                    if(dist<minDist){
                        minDist = dist;
                    }
                }
            }
            return minDist;*/

        } else {
            // THIS SHOULD NOT HAPPEN
            System.err.println("Unkown distance measure type -- this is a bug! Please contact authors.");
            System.exit(1);
            return -1;
        }

    }

    public abstract double calculate(Accession a1, Accession a2);

    protected double getMemoizedValue(int id1, int id2) {

	int a = Math.max(id1, id2);
	int b = Math.min(id1, id2);

        /*double ret;
	if (a >= M.size()) {
	    ret = MISSING_VAL;
	} else {
	    ret = M.get(a).get(b).doubleValue();
	}

        return ret;*/

        if(a >= M.length){
            return MISSING_VAL;
        } else {
            return M[a][b];
        }
    }

    protected void setMemoizedValue(int id1, int id2, double v) {

	int a = Math.max(id1, id2);
	int b = Math.min(id1, id2);

        /*if (a >= M.size()) {
	    if (a >= MAX_ACCESSION_COUNT) {
		return;
	    }

	    for(int i=M.size(); i<=a; i++) {
		M.add( new ArrayList<Double>(i+1) );
		for(int j=0; j<=i; j++) {
		    M.get(i).add(new Double(MISSING_VAL));
		}
	    }
	}

	M.get(a).set(b, new Double(v));*/
        if(a >= M.length){
            return;
        } else {
            M[a][b] = v;
        }
    }

    private class DistanceCachedResult extends CachedResult {
	private double pTotal;
	private double pCnt;

        private TreeMap<Double, Integer> minFreqTable;

	public DistanceCachedResult(List<Accession> accessions) {
	    super();
	    pTotal = 0.0;
	    pCnt = 0.0;

            minFreqTable = new TreeMap<Double, Integer>();
	}

	public double getTotal() {
	    return pTotal;
	}

	public double getCount() {
	    return pCnt;
	}

        public TreeMap<Double, Integer> getMinFreqTable(){
            return minFreqTable;
        }

	public void setTotal(double total) {
	    pTotal = total;
	}

	public void setCount(double count) {
	    pCnt = count;
	}

    }

}

redpajama_set_name: RedPajamaGithub


text:
class CoursesController < ApplicationController
	def index
		@courses = Course.all
	end
end


text:
import os, sys

sys.path.append(os.path.abspath(os.path.join(os.path.abspath(__file__), '../')))
sys.path.append(os.path.abspath(os.path.join(os.path.abspath(__file__), '../../')))
sys.path.append(os.path.abspath(os.path.join(os.path.abspath(__file__), '../../../')))
sys.path.append(os.path.abspath(os.path.join(os.path.abspath(__file__), '../../../../')))
sys.path.append(os.path.abspath(os.path.join(os.path.abspath(__file__), '../../../../../')))

import time, datetime
from mongoengine import *
from mongoengine.document import Document, EmbeddedDocument
from mongoengine.queryset import  QuerySetManager
from redis_model.models import MSortSetField
from redis_model.queue import Client

class TestUser(Document):
	username = StringField(max_length=14, required=True)
	gender = StringField(default='M', max_length=1)

	follower = MSortSetField("User", name="follower")
	follower.descrpition = "my follower friends"

	followee = MSortSetField("User", name="followee")
	followee.description = "follow me firends"

	client = Client()
	client.description = "client event dispatcher"

	def follow(self, user):
		if not self.is_follower(user):
			User.followee.zadd(user, self, score=time.time())
			User.follower.zadd(self, user, score=time.time())
			#send to background
			User.client.dispatch("follow.friend", {"user": str(self.id), "follower": str(user.id)})

	def unfollow(self, user):
		if self.is_follower(user):
			User.follower.zrem(self, user)
			User.followee.zrem(user, self)

	def is_follower(self, user):
		return User.follower.zscore(self, user) != None

	def is_followee(self, user):
		return User.followee.zscore(user, self) != None

	def followers(self):
		return User.follower.zrevrange(self, 0, 100)

	def followees(self):
		return User.followee.zrevrange(self, 0, 100)

if __name__ == "__main__":
	connect('test')
	User.objects.delete()

	edison = User()
	edison.username = "edison"
	edison.save()

	jason = User()
	jason.username = "jason"
	jason.save()

	mike = User()
	mike.username = "23mike"
	mike.save()

	#print "edison follow jason"
	edison.follow(jason)
	time.sleep(1)

	edison.follow(mike)
	time.sleep(1)
	#print "jason follow edison"
	jason.follow(edison)

	print " * " * 30
	print "edison's followees"
	for f in edison.followees():
		print f.username, f.id

	print " * " * 30
	print "edison's followers"
	for f in edison.followers():
		print f.username, f.id

	assert True == edison.is_follower(mike)
	edison.unfollow(mike)
	assert False == edison.is_follower(mike)


text:
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
using OfficeDevPnP.Core.Attributes;

namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions
{
    [TokenDefinitionDescription(
        Token = "{sitecollectiontermstoreid}",
        Description = "Returns the id of the given default site collection term store",
        Example = "{sitecollectiontermstoreid}",
        Returns = "9188a794-cfcf-48b6-9ac5-df2048e8aa5d")]
    internal class SiteCollectionTermStoreIdToken : VolatileTokenDefinition
    {
        public SiteCollectionTermStoreIdToken(Web web)
            : base(web, "{sitecollectiontermstoreid}")
        {
        }

        public override string GetReplaceValue()
        {
            if (CacheValue == null)
            {
                TaxonomySession session = TaxonomySession.GetTaxonomySession(TokenContext);
                var termStore = session.GetDefaultSiteCollectionTermStore();
                TokenContext.Load(termStore, t => t.Id);
                TokenContext.ExecuteQueryRetry();
                if (termStore != null)
                {
                    CacheValue = termStore.Id.ToString();
                }
            }
            return CacheValue;
        }
    }
}


text:
package org.springframework.jms.support.destination;

import jakarta.jms.Destination;
import jakarta.jms.JMSException;
import jakarta.jms.Session;

import org.springframework.lang.Nullable;

/**
 * Strategy interface for resolving JMS destinations.
 *
 *
Used by {@link org.springframework.jms.core.JmsTemplate} for resolving
 * destination names from simple {@link String Strings} to actual
 * {@link Destination} implementation instances.
 *
 *
The default {@link DestinationResolver} implementation used by
 * {@link org.springframework.jms.core.JmsTemplate} instances is the
 * {@link DynamicDestinationResolver} class. Consider using the
 * {@link JndiDestinationResolver} for more advanced scenarios.
 *
 * @author Juergen Hoeller
 * @since 1.1
 * @see org.springframework.jms.core.JmsTemplate#setDestinationResolver
 * @see org.springframework.jms.support.destination.DynamicDestinationResolver
 * @see org.springframework.jms.support.destination.JndiDestinationResolver
 */
@FunctionalInterface
public interface DestinationResolver {

	/**
	 * Resolve the given destination name, either as located resource
	 * or as dynamic destination.
	 * @param session the current JMS Session
	 * (may be {@code null} if the resolver implementation is able to work without it)
	 * @param destinationName the name of the destination
	 * @param pubSubDomain {@code true} if the domain is pub-sub, {@code false} if P2P
	 * @return the JMS destination (either a topic or a queue)
	 * @throws jakarta.jms.JMSException if the JMS Session failed to resolve the destination
	 * @throws DestinationResolutionException in case of general destination resolution failure
	 */
	Destination resolveDestinationName(@Nullable Session session, String destinationName, boolean pubSubDomain)
			throws JMSException;

}


text:
name             "c-icap"
maintainer       "Rostyslav Fridman"
maintainer_email "rostyslav.fridman@gmail.com"
license          "Apache 2.0"
description      "Installs/Configures c-icap and c-icap-modules"
long_description IO.read(File.join(File.dirname(__FILE__), "README.md"))
version          "1.0.1"

supports "centos"
supports "debian"
supports "fedora"
supports "redhat"
supports "ubuntu"

depends "checkinstall"


text:
package edu.jhuapl.dorset.nlp;

/**
 * Tokenizes a string using white space as a delimiter
 * <p>
 * Does not remove punctuation.
 */
public class WhiteSpaceTokenizer implements Tokenizer {

    @Override
    public String[] tokenize(String text) {
        return text.split("\\s+");
    }

}


text:
package net.spals.appbuilder.mapstore.core;

import net.spals.appbuilder.mapstore.core.model.MapQueryOptions;
import net.spals.appbuilder.mapstore.core.model.MapStoreKey;
import net.spals.appbuilder.mapstore.core.model.MapStoreTableKey;

import java.io.Closeable;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * A NoSQL storage service which holds data in maps.
 *
 * @author tkral
 */
public interface MapStore extends Closeable {

    /**
     * Creates a table with the given key.
     *
     * Note that this operation is idempotent
     * so a true response means that the table
     * exists after execution.
     *
     * @return true iff the table exists after execution
     */
    boolean createTable(
        String tableName,
        MapStoreTableKey tableKey
    );

    /**
     * Drops a table.
     *
     * @return true iff the drop was successful
     */
    boolean dropTable(String tableName);

    /**
     * Delete an item from the given table
     * with the give key.
     *
     * This should be idempotent if the item
     * does not exist.
     */
    void deleteItem(
        String tableName,
        MapStoreKey key
    );

    /**
     * Retrieves all items from the given table
     * with all keys.
     */
    List<Map<String, Object>> getAllItems(String tableName);

    /**
     * Retrieves an item from the given table
     * with the given key.
     *
     * Returns {@link Optional#empty()} if no
     * item exists with the given key.
     */
    Optional<Map<String, Object>> getItem(
        String tableName,
        MapStoreKey key
    );

    /**
     * Queries all items from the given table
     * which match the given {@link MapStoreKey}
     * range key operator.
     */
    List<Map<String, Object>> getItems(
        String tableName,
        MapStoreKey key,
        MapQueryOptions options
    );

    /**
     * Adds an item to the given table
     * under the given key.
     */
    Map<String, Object> putItem(
        String tableName,
        MapStoreKey key,
        Map<String, Object> payload
    );

    /**
     * Updates an item in the given table
     * under the given key.
     *
     * If no item exists at the given key,
     * this will fallback to {@link #putItem(String, MapStoreKey, Map)}
     * semantics.
     */
    Map<String, Object> updateItem(
        String tableName,
        MapStoreKey key,
        Map<String, Object> payload
    );
}


text:
/*
 * file: gps.h
 * created: 20160808
 * author(s): mr-augustine
 *
 * Lists the functions used to initialize and update the GPS sensor.
 *
 * The extern "C" construct allows the main Arduino program to use the
 * functions declared below.
 */
#ifndef _GPS_H_
#define _GPS_H_

#define GPGGA_START             "$GPGGA"
#define GPGSA_START             "$GPGSA"
#define GPRMC_START             "$GPRMC"
#define GPVTG_START             "$GPVTG"
#define START_LENGTH            6
#define GPS_CHECKSUM_LENGTH     2
#define GPS_INVALID_HEX_CHAR    0xFF
#define GPS_FIELD_BUFF_SZ       8
#define GPS_NO_FIX              '0'
#define GPS_TIME_WIDTH          6
#define GPS_SENTENCE_BUFF_SZ    128
#define GPS_SENTENCE_END        '\n'
#define GPS_SENTENCE_START      '$'
#define LAT_LONG_FIELD_LENGTH   9
#define NUM_GPS_SENTENCE_BUFFS  4

#ifdef __cplusplus
extern "C" {
  uint8_t gps_init(void);

  void gps_update(void);
}
#endif // #ifdef __cplusplus

#endif // #ifndef _GPS_H_


text:
namespace gfx {
class GLImage;
}

namespace gpu {
namespace gles2 {

// Interface used by the cmd decoder to lookup images.
class GPU_EXPORT ImageManager
    : public GpuMemoryBufferManagerInterface,
      public base::RefCounted<ImageManager> {
 public:
  ImageManager();

  // Overridden from GpuMemoryBufferManagerInterface:
  virtual bool RegisterGpuMemoryBuffer(int32 id,
                                       gfx::GpuMemoryBufferHandle buffer,
                                       size_t width,
                                       size_t height,
                                       unsigned internalformat) OVERRIDE;
  virtual void DestroyGpuMemoryBuffer(int32 id) OVERRIDE;

  void AddImage(gfx::GLImage* gl_image, int32 service_id);
  void RemoveImage(int32 service_id);
  gfx::GLImage* LookupImage(int32 service_id);

  // For Android specific workaround.
  void SetReleaseAfterUse();

 private:
  friend class base::RefCounted<ImageManager>;

  virtual ~ImageManager();

  typedef base::hash_map<uint32, scoped_refptr<gfx::GLImage> > GLImageMap;
  GLImageMap gl_images_;
  bool release_after_use_;

  DISALLOW_COPY_AND_ASSIGN(ImageManager);
};

}  // namespage gles2
}  // namespace gpu

#endif  // GPU_COMMAND_BUFFER_SERVICE_IMAGE_MANAGER_H_


text:
const toString = Object.prototype.toString;

/**
 * Encodes the given string as base64. This differs from normal btoa
 * as it supports all unicode characters
 * @param {string} str String to encode
 */
export function encodeBase64Unicode(str) {
  return window.btoa(
    encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (_, p1) =>
      String.fromCharCode('0x' + p1)
    )
  );
}

export function isPrimitive(data) {
  switch (toString.call(data)) {
    case '[object String]':
    case '[object Number]':
    case '[object Boolean]':
    case '[object Null]':
    case '[object Undefined]':
      return true;
  }

  return false;
}

export function equal(a, b) {
  let objectName = toString.call(a),
    isSameAsIn = other => (item, i) => equal(item, other[i]),
    hasSameIn = (a, b) => key => key in a && key in b && equal(a[key], b[key]),
    keysOfA;

  if (objectName !== toString.call(b)) {
    return false;
  }

  if (isPrimitive(a)) {
    return a === b;
  }

  if (Array.isArray(a)) {
    return a.length === b.length && a.every(isSameAsIn(b));
  }

  // At this point we assume it's an object
  keysOfA = Object.keys(a);

  if (keysOfA.length !== Object.keys(b).length) {
    return false;
  }

  return keysOfA.every(hasSameIn(a, b));
}

export function clone(data) {
  if (isPrimitive(data)) {
    return data;
  }

  if (Array.isArray(data)) {
    return data.map(clone);
  }

  let copy = Object.create(null);

  for (let i in data) {
    copy[i] = clone(data[i]);
  }

  return copy;
}

export function getRandomString() {
  return Math.random().toString(32).slice(-5);
}

export function validatePath(path) {
  if (path.indexOf('/') !== 0) {
    throw new Error(`Invalid path '${path}'. Path must start with leading '/'`);
  }
}

export function validateItem(item) {
  if (item === null) {
    return;
  }

  const allowed = ['data', 'type', 'path', 'createdAt', 'updatedAt'];
  const keys = Object.keys(item);

  if ('data' in item) {
    if (typeof item.data !== 'object' || item.data === null) {
      throw new TypeError(
        `'data' property in item must be a non-null object. Got ${typeof item.data}`
      );
    }
  }

  if ('type' in item) {
    if (typeof item.type !== 'string' && item.type !== null) {
      throw new TypeError(
        `'type' property in item must be a string or null. Got ${typeof item.type}`
      );
    }
  }

  for (let i = 0, k = keys.length; i < k; i++) {
    let key = keys[i];
    if (allowed.indexOf(key) === -1) {
      throw new Error(
        `Invalid property ${key}. Valid properties are ${allowed
          .slice(0, -1)
          .join(', ')} or ${allowed[allowed.length - 1]}.`
      );
    }
  }
}

export function toShortcodeAndUploads(data) {
  let uploads = [],
    mapped;

  const withShortcode = (url, ext, content) => {
    let name = getRandomString(),
      file = `${name}.${ext}`,
      shortcode = `[upload ${file}]`;

    uploads.push([file, content]);

    return shortcode;
  };

  mapped = deepMapIn(data, value => {
    if (typeof value === 'string') {
      return value.replace(
        /data:image\/(.+?);base64,([A-Za-z0-9+/=]+)/g,
        withShortcode
      );
    }

    return value;
  });

  return [mapped, uploads];
}

export function byModified(buffer) {
  return ([key]) => !buffer || !buffer[key] || buffer[key].modified;
}

export function deepMapIn(item, transform) {
  if (Array.isArray(item)) {
    return item.map(item => deepMapIn(item, transform));
  }

  if (typeof item === 'object' && item !== null) {
    let mapped = Object.create(null);
    for (let i in item) {
      mapped[i] = deepMapIn(item[i], transform);
    }

    return mapped;
  }

  return transform(item);
}

export function noop() {}

export const assign = Object.assign ? Object.assign.bind(Object) : (target) => {
  if (target == null) {
    throw new TypeError('Cannot convert undefined or null to object');
  }

  let to = Object(target);

  for (let index = 1; index < arguments.length; index++) {
    let nextSource = arguments[index];

    if (nextSource != null) {
      for (let nextKey in nextSource) {
        if (nextSource.hasOwnProperty(nextKey)) {
          to[nextKey] = nextSource[nextKey];
        }
      }
    }
  }
  return to;
};


text:
package datadog

import (
	"encoding/json"
	"fmt"

	schema "github.com/grafana/metrictank/schema"
	"github.com/raintank/tsdb-gw/api/models"
	"github.com/raintank/tsdb-gw/ingest"
	"github.com/raintank/tsdb-gw/publish"
	log "github.com/sirupsen/logrus"
)

// DataDogSeriesPayload struct to unmarshal datadog agent json
type DataDogSeriesPayload struct {
	Series []struct {
		Name   string       `json:"metric"`
		Points [][2]float64 `json:"points"`
		Tags   []string     `json:"tags"`
		Host   string       `json:"host"`
		Mtype  string       `json:"type"`
		Device string       `json:"device,omitempty"`
	} `json:"series"`
}

func DataDogSeries(ctx *models.Context) {
	if ctx.Req.Request.Body == nil {
		ctx.JSON(400, "no data included in request.")
		return
	}
	defer ctx.Req.Request.Body.Close()

	data, err := decodeJSON(ctx.Req.Request.Body, ctx.Req.Request.Header.Get("Content-Encoding") == "deflate")
	if err != nil {
		ctx.JSON(400, fmt.Sprintf("unable to decode request, reason: %v", err))
		return
	}

	var series DataDogSeriesPayload
	err = json.Unmarshal(data, &series)
	if err != nil {
		ctx.JSON(400, fmt.Sprintf("unable to unmarshal request, reason: %v", err))
		return
	}

	buf := make([]*schema.MetricData, 0)
	defer func(buf []*schema.MetricData) {
		for _, m := range buf {
			ingest.MetricPool.Put(m)
		}
	}(buf)

	for _, ts := range series.Series {
		tagSet := createTagSet(ts.Host, ts.Device, ts.Tags)
		for _, point := range ts.Points {
			md := ingest.MetricPool.Get()
			*md = schema.MetricData{
				Name:     ts.Name,
				Interval: 0,
				Value:    point[1],
				Unit:     "unknown",
				Time:     int64(point[0]),
				Mtype:    ts.Mtype,
				Tags:     tagSet,
				OrgId:    ctx.ID,
			}
			md.SetId()
			buf = append(buf, md)
		}
	}
	err = publish.Publish(buf)

	if err != nil {
		log.Errorf("failed to publish datadog series metrics. %s", err)
		ctx.JSON(500, err)
		return
	}
	ctx.JSON(200, "ok")
	return
}

// DataDogSeriesPayload struct to unmarshal datadog agent json
type DataDogCheckPayload []struct {
	Check     string   `json:"check"`
	Host      string   `json:"host_name"`
	Timestamp int64    `json:"timestamp"`
	Status    float64  `json:"status"`
	Message   string   `json:"message"`
	Tags      []string `json:"tags"`
}

func DataDogCheck(ctx *models.Context) {
	if ctx.Req.Request.Body == nil {
		ctx.JSON(400, "no data included in request.")
		return
	}
	defer ctx.Req.Request.Body.Close()

	data, err := decodeJSON(ctx.Req.Request.Body, ctx.Req.Request.Header.Get("Content-Encoding") == "deflate")
	if err != nil {
		ctx.JSON(400, fmt.Sprintf("unable to decode request, reason: %v", err))
	}

	var checks DataDogCheckPayload

	err = json.Unmarshal(data, &checks)
	if err != nil {
		ctx.JSON(400, fmt.Sprintf("unable to unmarshal request, reason: %v", err))
	}

	buf := make([]*schema.MetricData, 0)
	defer func(buf []*schema.MetricData) {
		for _, m := range buf {
			ingest.MetricPool.Put(m)
		}
	}(buf)

	for _, check := range checks {
		tagSet := createTagSet(check.Host, "", check.Tags)
		md := ingest.MetricPool.Get()
		*md = schema.MetricData{
			Name:     check.Check,
			Interval: 0,
			Value:    check.Status,
			Unit:     "unknown",
			Time:     check.Timestamp,
			Mtype:    "gauge",
			Tags:     tagSet,
			OrgId:    ctx.ID,
		}
		md.SetId()
		buf = append(buf, md)
	}

	err = publish.Publish(buf)

	if err != nil {
		log.Errorf("failed to publish datadog metrics. %s", err)
		ctx.JSON(500, err)
		return
	}

	ctx.JSON(200, "ok")
	return
}


text:
//===--- Target.h - Info about the current compilation target ---*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Info about the current compilation target.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_ABI_TARGET_H
#define SWIFT_ABI_TARGET_H

#if !defined(__has_builtin)
#define __has_builtin(x) 0
#endif

// Is the target platform a simulator? We can't use TargetConditionals
// when included from SwiftShims, so use the builtin.
#if __has_builtin(__is_target_environment)
# if __is_target_environment(simulator)
#  define SWIFT_TARGET_OS_SIMULATOR 1
# else
#  define SWIFT_TARGET_OS_SIMULATOR 0
# endif
#endif

#endif /* SWIFT_ABI_TARGET_H */


text:
using Gma.Netmf.Hardware.Lego.PowerFunctions.Control;

#endregion

namespace Gma.Netmf.Hardware.Lego.PowerFunctions.Actuators
{
    public class Connector
    {
        private readonly Output m_Output;
        private readonly RemoteControl m_RemoteControl;

        internal Connector(RemoteControl remoteControl, Output output)
        {
            m_RemoteControl = remoteControl;
            m_Output = output;
        }

        public RemoteControl RemoteControl
        {
            get { return m_RemoteControl; }
        }

        public Output Output
        {
            get { return m_Output; }
        }
    }
}


text:
class IGameListView;

class GuiGamelistOptions : public GuiComponent
{
public:
	GuiGamelistOptions(Window* window, SystemData* system);
	virtual ~GuiGamelistOptions();

	virtual bool input(InputConfig* config, Input input) override;
	virtual std::vector<HelpPrompt> getHelpPrompts() override;
	virtual HelpStyle getHelpStyle() override;

private:
	void openGamelistFilter();
	void openMetaDataEd();
	void startEditMode();
	void exitEditMode();
	void jumpToLetter();

	MenuComponent mMenu;

	typedef OptionListComponent<char> LetterList;
	std::shared_ptr<LetterList> mJumpToLetterList;

	typedef OptionListComponent<const FileData::SortType*> SortList;
	std::shared_ptr<SortList> mListSort;

	SystemData* mSystem;
	IGameListView* getGamelist();
	bool fromPlaceholder;
	bool mFiltersChanged;
};


text:
using System;
using UnityEngine;

namespace UnityEditor.VFX
{
    [VFXInfo(type = typeof(AnimationCurve))]
    class VFXSlotAnimationCurve : VFXSlot
    {
        public override VFXValue DefaultExpression(VFXValue.Mode mode)
        {
            return new VFXValue<AnimationCurve>(new AnimationCurve(), mode);
        }
    }
}


text:
package org.jabref.logic.integrity;

import java.util.Optional;

import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class PersonNamesCheckerTest {

    private PersonNamesChecker checker;

    @Before
    public void setUp() throws Exception {
        BibDatabaseContext databaseContext = new BibDatabaseContext();
        databaseContext.setMode(BibDatabaseMode.BIBTEX);
        checker = new PersonNamesChecker(databaseContext);
    }

    @Test
    public void complainAboutPersonStringWithTwoManyCommas() throws Exception {
        assertEquals(Optional.of("Names are not in the standard BibTeX format."),
                checker.checkValue("Test1, Test2, Test3, Test4, Test5, Test6"));
    }

    @Test
    public void doNotComplainAboutSecondNameInFront() throws Exception {
        assertEquals(Optional.empty(), checker.checkValue("M. J. Gotay"));
    }
}


text:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>

	<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
	<title>quaternion, vector and matrix types</title>
	<link href='reno.css' type='text/css' rel='stylesheet'/>

QVM: Quaternions, Vectors, Matrices

Quaternion, Vector and Matrix Types

#include <boost/qvm/quat.hpp>
#include <boost/qvm/vec.hpp>
#include <boost/qvm/mat.hpp>

namespace boost
{
    namespace qvm
    {
        //*** Quaternion, vector and matrix types ***

        template <class T>
        struct quat
        {
            T a[4];

            template <class R>
            operator R() const
            {
                R r;
                assign(r,*this);
                return r;
            }
        };

        template <class Quaternion>
        struct quat_traits;

        template <class T>
        struct quat_traits< quat<T> >
        {
            typedef T scalar_type;

            template <int I> static scalar_type read_element( quat<T> const & x ) { return x.a[I]; }
            template <int I> static scalar_type & write_element( quat<T> & x ) { return x.a[I]; }
        };

        template <class T,int Dim>
        struct vec
        {
            T a[Dim];

            template <class R>
            operator R() const
            {
                R r;
                assign(r,*this);
                return r;
            }
        };

        template <class Vector>
        struct vec_traits;

        template <class T,int Dim>
        struct vec_traits< vec<T,Dim> >
        {
            typedef T scalar_type;
            static int const dim=Dim;

            template <int I> static scalar_type read_element( vec<T,Dim> const & x ) { return x.a[I]; }
            template <int I> static scalar_type & write_element( vec<T,Dim> & x ) { return x.a[I]; }

            static scalar_type read_element_idx( int i, vec<T,Dim> const & x ) { return x.a[i]; }
            static scalar_type & write_element_idx( int i, vec<T,Dim> & x ) { return x.a[i]; }
        };

        template <class T,int Rows,int Cols>
        struct mat
        {
            T a[Rows][Cols];

            template <class R>
            operator R() const
                {
                R r;
                assign(r,*this);
                return r;
                }
        };

        template <class Matrix>
        struct mat_traits;

        template <class T,int Rows,int Cols>
        struct mat_traits< mat<T,Rows,Cols> >
        {
            typedef T scalar_type;
            static int const rows=Rows;
            static int const cols=Cols;

            template <int Row,int Col> static scalar_type read_element( mat<T,Rows,Cols> const & x ) { return x.a[Row][Col]; }
            template <int Row,int Col> static scalar_type & write_element( mat<T,Rows,Cols> & x ) { return x.a[Row][Col]; }

            static scalar_type read_element_idx( int row, int col, mat<T,Rows,Cols> const & x ) { return x.a[row][col]; }
            static scalar_type & write_element_idx( int row, int col, mat<T,Rows,Cols> & x ) { return x.a[row][col]; }
        };
    }
}

See also: Boost QVM | Synopsis

Copyright (c) 2008-2016 by Emil Dotchevski and Reverge Studios, Inc.

Distributed under the Boost Software License, Version 1.0.


text:
test_run = require('test_run').new()
errinj = box.error.injection

s = box.schema.space.create('test', {engine='vinyl'})
_ = s:create_index('primary')

test_run:cmd("setopt delimiter ';'")
function gen(i)
    local pad_size = 256
    local range_count = 5
    local pad = string.rep('x', pad_size + i)
    local n = (range_count + i) * math.floor(box.cfg.vinyl_range_size / pad_size)
    for k = 1,n do
        s:replace{k, i + k, pad}
    end
    pcall(box.snapshot)
end;
test_run:cmd("setopt delimiter ''");

errinj.set("ERRINJ_VY_GC", true)
for i=1,4 do gen(i) end
errinj.set("ERRINJ_VY_RANGE_SPLIT", true)
for i=5,6 do gen(i) end

-- Check that the total size of data stored on disk, the number of pages,
-- and the number of runs are the same before and after recovery.
tmp = box.schema.space.create('tmp')
_ = tmp:create_index('primary')
_ = tmp:insert{0, box.info.vinyl().db[s.id .. '/0']}

test_run:cmd('restart server default')

s = box.space.test
tmp = box.space.tmp

vyinfo1 = tmp:select(0)[1][2]
vyinfo2 = box.info.vinyl().db[s.id .. '/0']
vyinfo1.size == vyinfo2.size or {vyinfo1.size, vyinfo2.size}
vyinfo1.page_count == vyinfo2.page_count or {vyinfo1.page_count, vyinfo2.page_count}
vyinfo1.run_count == vyinfo2.run_count or {vyinfo1.run_count, vyinfo2.run_count}

tmp:drop()

test_run:cmd("setopt delimiter ';'")
function check(i)
    local pad_size = 256
    local range_count = 5
    local n = (range_count + i) * math.floor(box.cfg.vinyl_range_size / pad_size)
    local n_corrupted = 0
    for k=1,n do
        local v = s:get(k)
        if not v or v[2] ~= i + k then
			n_corrupted = n_corrupted + 1
		end
    end
    return n - s:count(), n_corrupted
end;
test_run:cmd("setopt delimiter ''");

check(6)

s:drop()


text:
'use strict';

define([
  'jquery',
  'underscore',
  'backbone',
  'helpers/handlebars<%= delimiter %>helpers',
  'apps/home/home<%= delimiter %>item<%= delimiter %>view'
], function ($, _, Backbone, helpers, HomeItemView) {
  helpers.initialize();

  describe('HomeItemView', function () {
    beforeEach(function () {
      this.model = new Backbone.Model({
        name: 'Home'
      });
      this.view = new HomeItemView({model: this.model});
      this.view.render();
    });

    it('render() should return the view object', function () {
      expect(this.view.render()).<%=assert.toequal%>(this.view);
    });
    it('id should equal 1', function () {
      expect(this.view.render().$('h2').text()).<%=assert.toequal%>('Home');
    });
  });
});


text:
package net.floodlightcontroller.loadbalancer;

import java.io.IOException;
import java.util.Collection;

import net.floodlightcontroller.packet.IPv4;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VipsResource extends ServerResource {
    protected static Logger log = LoggerFactory.getLogger(VipsResource.class);

    @Get("json")
    public Collection <LBVip> retrieve() {
        ILoadBalancerService lbs =
                (ILoadBalancerService)getContext().getAttributes().
                    get(ILoadBalancerService.class.getCanonicalName());

        String vipId = (String) getRequestAttributes().get("vip");
        if (vipId!=null)
            return lbs.listVip(vipId);
        else
            return lbs.listVips();
    }

    @Put
    @Post
    public LBVip createVip(String postData) {

        LBVip vip=null;
        try {
            vip=jsonToVip(postData);
        } catch (IOException e) {
            log.error("Could not parse JSON {}", e.getMessage());
        }

        ILoadBalancerService lbs =
                (ILoadBalancerService)getContext().getAttributes().
                    get(ILoadBalancerService.class.getCanonicalName());

        String vipId = (String) getRequestAttributes().get("vip");
        if (vipId != null)
            return lbs.updateVip(vip);
        else
            return lbs.createVip(vip);
    }

    @Delete
    public int removeVip() {

        String vipId = (String) getRequestAttributes().get("vip");

        ILoadBalancerService lbs =
                (ILoadBalancerService)getContext().getAttributes().
                    get(ILoadBalancerService.class.getCanonicalName());

        return lbs.removeVip(vipId);
    }

    protected LBVip jsonToVip(String json) throws IOException {

        if (json==null) return null;

        MappingJsonFactory f = new MappingJsonFactory();
        JsonParser jp;
        LBVip vip = new LBVip();

        try {
            jp = f.createJsonParser(json);
        } catch (JsonParseException e) {
            throw new IOException(e);
        }

        jp.nextToken();
        if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected START_OBJECT");
        }

        while (jp.nextToken() != JsonToken.END_OBJECT) {
            if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
                throw new IOException("Expected FIELD_NAME");
            }

            String n = jp.getCurrentName();
            jp.nextToken();
            if (jp.getText().equals(""))
                continue;

            if (n.equals("id")) {
                vip.id = jp.getText();
                continue;
            }
            if (n.equals("tenant_id")) {
                vip.tenantId = jp.getText();
                continue;
            }
            if (n.equals("name")) {
                vip.name = jp.getText();
                continue;
            }
            if (n.equals("network_id")) {
                vip.netId = jp.getText();
                continue;
            }
            if (n.equals("protocol")) {
                String tmp = jp.getText();
                if (tmp.equalsIgnoreCase("TCP")) {
                    vip.protocol = IPv4.PROTOCOL_TCP;
                } else if (tmp.equalsIgnoreCase("UDP")) {
                    vip.protocol = IPv4.PROTOCOL_UDP;
                } else if (tmp.equalsIgnoreCase("ICMP")) {
                    vip.protocol = IPv4.PROTOCOL_ICMP;
                }
                continue;
            }
            if (n.equals("address")) {
                vip.address = IPv4.toIPv4Address(jp.getText());
                continue;
            }
            if (n.equals("port")) {
                vip.port = Short.parseShort(jp.getText());
                continue;
            }
            if (n.equals("pool_id")) {
                vip.pools.add(jp.getText());
                continue;
            }

            log.warn("Unrecognized field {} in " +
                    "parsing Vips",
                    jp.getText());
        }
        jp.close();

        return vip;
    }

}


text:
require 'sinatra/base'

class EditRoute < Sinatra::Base
  get '/edit/:article_id' do
    @article_id = params[:article_id]
    File.open("data/blog_#{params[:article_id]}.txt", 'r:utf-8') do |file|
      @title = file.readline
      @body = file.read
    end
    erb :edit
  end
  post '/edit/:article_id' do
    File.open("data/blog_#{params[:article_id]}.txt", 'w:utf-8') do |file|
      file.write("#{params[:title]}\n#{params[:body]}")
    end
    erb :edited
  end
  run! if __FILE__ == $0
end


text:
package fr.alecharp.picshare.domain;

import java.time.LocalDate;
import java.util.*;

/**
 * @author Adrien Lecharpentier
 */
public class Event {
    private String id;

    private String title;
    private LocalDate date;
    private Set<Picture> pictures = new TreeSet<>(
            (p1, p2) -> p1.title().compareTo(p2.title())
    );

    private Event() {
        this(null, null);
    }

    public Event(String title, LocalDate date) {
        this(UUID.randomUUID().toString(), title, date);
    }

    public Event(String id, String title, LocalDate date) {
        this.id = id;
        this.title = title;
        this.date = date;
    }

    public String id() {
        return id;
    }

    public String title() {
        return title;
    }

    public LocalDate date() {
        return date;
    }

    public Set<Picture> pictures() {
        return Collections.unmodifiableSet(pictures);
    }

    public Event pictures(Set<Picture> pictures) {
        this.pictures.addAll(pictures);
        return this;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Event event = (Event) o;
        return Objects.equals(title, event.title) &&
                Objects.equals(date, event.date);
    }

    @Override
    public int hashCode() {
        return Objects.hash(date);
    }
}


text:
#import "NSObject.h"

@class DVTMacroDefinitionConditionSet, NSString, XCPropertyDefinition;

@interface Xcode3BuildPropertyRowContext : NSObject
{
    NSString *_configurationName;
    XCPropertyDefinition *_propertyDefinition;
    DVTMacroDefinitionConditionSet *_propertyConditionSet;
    NSString *_propertyDefinitionName;
    BOOL _conditional;
    NSString *_emphasizedTableColumnIdentifier;
}

@property(copy) NSString *emphasizedTableColumnIdentifier; // @synthesize emphasizedTableColumnIdentifier=_emphasizedTableColumnIdentifier;
@property(getter=isConditional) BOOL conditional; // @synthesize conditional=_conditional;
@property(copy, nonatomic) NSString *propertyDefinitionName; // @synthesize propertyDefinitionName=_propertyDefinitionName;
@property(copy) DVTMacroDefinitionConditionSet *propertyConditionSet; // @synthesize propertyConditionSet=_propertyConditionSet;
@property(retain) XCPropertyDefinition *propertyDefinition; // @synthesize propertyDefinition=_propertyDefinition;
@property(copy) NSString *configurationName; // @synthesize configurationName=_configurationName;
- (void).cxx_destruct;
- (id)newVariationForBuildSettingName:(id)arg1;
- (id)newVariationForConditionSet:(id)arg1;
- (id)newVariationForConfiguationName:(id)arg1;

@end


text:
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Moq;
using Xunit;

namespace Merq
{
	public class EventStreamSpec
	{
		[Fact]
		public void when_pushing_null_event_then_throws ()
		{
			var stream = new EventStream();

			Assert.Throws<ArgumentNullException> (() => stream.Push<object> (null));
		}

		[Fact]
		public void when_pushing_non_public_event_type_then_throws ()
		{
			var stream = new EventStream();

			Assert.Throws<NotSupportedException> (() => stream.Push (new NonPublicEvent ()));
		}

		[Fact]
		public void when_subscribing_non_public_event_type_then_throws ()
		{
			var stream = new EventStream();

			Assert.Throws<NotSupportedException> (() => stream.Of<NonPublicEvent> ());
		}

		[Fact]
		public void when_pushing_non_subscribed_event_then_does_not_call_subscriber ()
		{
			var stream = new EventStream();
			var called = false;

			using (var subscription = stream.Of<ConcreteEvent> ().Subscribe (c => called = true)) {
				stream.Push (new AnotherEvent ());
			}

			Assert.False (called);
		}

		[Fact]
		public void when_pushing_subscribed_nested_public_event_then_calls_subscriber ()
		{
			var stream = new EventStream();
			var called = false;

			using (var subscription = stream.Of<NestedPublicEvent> ().Subscribe (c => called = true)) {
				stream.Push (new NestedPublicEvent ());
			}

			Assert.True (called);
		}

		[Fact]
		public void when_pushing_subscribed_event_then_calls_subscriber ()
		{
			var stream = new EventStream();
			var called = false;

			using (var subscription = stream.Of<ConcreteEvent> ().Subscribe (c => called = true)) {
				stream.Push (new ConcreteEvent ());
			}

			Assert.True (called);
		}

		[Fact]
		public void when_pushing_subscribed_event_using_base_type_then_calls_subscriber ()
		{
			var stream = new EventStream();
			var called = false;

			using (var subscription = stream.Of<ConcreteEvent> ().Subscribe (c => called = true)) {
				BaseEvent @event = new ConcreteEvent();
				stream.Push (@event);
			}

			Assert.True (called);
		}

		[Fact]
		public void when_subscribing_as_event_interface_then_calls_subscriber ()
		{
			var stream = new EventStream();
			var called = false;

			using (var subscription = stream.Of<IBaseEvent> ().Subscribe (c => called = true)) {
				stream.Push (new ConcreteEvent ());
			}

			Assert.True (called);
		}

		[Fact]
		public void given_an_observable_when_subscribing_event_then_subscribes_to_observable ()
		{
			var subject = new Subject<ConcreteEvent>();
			var stream = new EventStream(subject);
			var called = false;

			using (var subscription = stream.Of<ConcreteEvent> ().Subscribe (c => called = true)) {
				subject.OnNext(new ConcreteEvent ());
			}

			Assert.True (called);
		}

		[Fact]
		public void given_two_observables_when_subscribing_base_event_then_receives_both ()
		{
			var subject1 = new Subject<ConcreteEvent>();
			var subject2 = new Subject<AnotherEvent>();
			var stream = new EventStream(subject1, subject2);
			var called = 0;

			using (var subscription = stream.Of<BaseEvent> ().Subscribe (c => called++)) {
				subject1.OnNext (new ConcreteEvent ());
				subject2.OnNext (new AnotherEvent ());
			}

			Assert.Equal (2, called);
		}

		[Fact]
		public void given_an_observable_when_pushing_compatible_event_then_subscriber_base_type_receives_both ()
		{
			var subject = new Subject<ConcreteEvent>();
			var stream = new EventStream(subject);
			var called = 0;

			using (var subscription = stream.Of<BaseEvent> ().Subscribe (c => called++)) {
				subject.OnNext (new ConcreteEvent ());
				stream.Push (new AnotherEvent ());
			}

			Assert.Equal (2, called);
		}

		public class NestedPublicEvent { }
	}

	public interface IBaseEvent { }

	public class BaseEvent : IBaseEvent
	{
	}

	public class ConcreteEvent : BaseEvent { }

	public class AnotherEvent : BaseEvent { }

	internal class NonPublicEvent { }
}


text:
#include <Core/Controller.h>

/*************************************************************************
 *
 * Implements Core::Controller methods pertaining buffering the request
 * body.
 *
 *************************************************************************/

namespace Passenger {
namespace Core {

using namespace std;
using namespace boost;

/****************************
 *
 * Private methods
 *
 ****************************/

void
Controller::beginBufferingBody(Client *client, Request *req) {
	TRACE_POINT();
	req->state = Request::BUFFERING_REQUEST_BODY;
	req->bodyChannel.start();
	req->bodyBuffer.reinitialize();
	req->bodyBuffer.stop();
	req->beginStopwatchLog(&req->stopwatchLogs.bufferingRequestBody, "buffering request body");
}

ServerKit::Channel::Result
Controller::whenBufferingBody_onRequestBody(Client *client, Request *req,
	const MemoryKit::mbuf &buffer, int errcode)
{
	TRACE_POINT();

	if (buffer.size() > 0) {
		// Data
		req->bodyBytesBuffered += buffer.size();
		SKC_TRACE(client, 3, "Buffering " << buffer.size() <<
			" bytes of client request body: \"" <<
			cEscapeString(StaticString(buffer.start, buffer.size())) <<
			"\"; " << req->bodyBytesBuffered << " bytes buffered so far");
		req->bodyBuffer.feed(buffer);
		return Channel::Result(buffer.size(), false);
	} else if (errcode == 0 || errcode == ECONNRESET) {
		// EOF
		SKC_TRACE(client, 2, "End of request body encountered");
		req->bodyBuffer.feed(MemoryKit::mbuf());
		if (req->bodyType == Request::RBT_CHUNKED) {
			// The data that we've stored in the body buffer is dechunked, so when forwarding
			// the buffered body to the app we must advertise it as being a fixed-length,
			// non-chunked body.
			const unsigned int UINT64_STRSIZE = sizeof("18446744073709551615");
			SKC_TRACE(client, 2, "Adjusting forwarding headers as fixed-length, non-chunked");
			ServerKit::Header *header = (ServerKit::Header *)
				psg_palloc(req->pool, sizeof(ServerKit::Header));
			char *contentLength = (char *) psg_pnalloc(req->pool, UINT64_STRSIZE);
			unsigned int size = integerToOtherBase<boost::uint64_t, 10>(
				req->bodyBytesBuffered, contentLength, UINT64_STRSIZE);

			psg_lstr_init(&header->key);
			psg_lstr_append(&header->key, req->pool, "content-length",
				sizeof("content-length") - 1);
			psg_lstr_init(&header->origKey);
			psg_lstr_append(&header->origKey, req->pool, "Content-Length",
				sizeof("Content-Length") - 1);
			psg_lstr_init(&header->val);
			psg_lstr_append(&header->val, req->pool, contentLength, size);

			header->hash = HashedStaticString("content-length",
				sizeof("content-length") - 1).hash();

			req->headers.erase(HTTP_TRANSFER_ENCODING);
			req->headers.insert(&header, req->pool);
		}
		req->endStopwatchLog(&req->stopwatchLogs.bufferingRequestBody);
		checkoutSession(client, req);
		return Channel::Result(0, true);
	} else {
		const unsigned int BUFSIZE = 1024;
		char *message = (char *) psg_pnalloc(req->pool, BUFSIZE);
		int size = snprintf(message, BUFSIZE,
			"error reading request body: %s (errno=%d)",
			ServerKit::getErrorDesc(errcode), errcode);
		disconnectWithError(&client, StaticString(message, size));
		return Channel::Result(0, true);
	}
}

} // namespace Core
} // namespace Passenger


text:
import {expect} from 'chai'
import {$hook} from 'ember-hook'
import wait from 'ember-test-helpers/wait'
import {beforeEach, describe, it} from 'mocha'

import {
  expectBunsenDateRendererWithState,
  expectCollapsibleHandles,
  expectOnChangeState,
  expectOnValidationState,
  openDatepickerBunsenDateRenderer
} from 'dummy/tests/helpers/ember-frost-bunsen'
import {setupFormComponentTest} from 'dummy/tests/helpers/utils'
import {deps} from 'ember-frost-bunsen/components/inputs/date'

/**
 * Click outside the date picker to close it
 * @param {Object} context - the test context
 */
function closePikaday (context) {
  context.$().click()
}

describe('Integration: Component / frost-bunsen-form / renderer / date', function () {
  const ctx = setupFormComponentTest({
    bunsenModel: {
      properties: {
        foo: {
          type: 'string'
        }
      },
      type: 'object'
    },
    bunsenView: {
      cells: [
        {
          model: 'foo',
          renderer: {
            name: 'date'
          }
        }
      ],
      type: 'form',
      version: '2.0'
    }
  })

  describe('Default values', function () {
    describe('when no value is given', function () {
      beforeEach(function () {
        this.set('bunsenView', {
          cells: [
            {
              collapsible: true,
              model: 'foo',
              renderer: {
                name: 'date'
              }
            }
          ],
          type: 'form',
          version: '2.0'
        })

        return wait()
      })

      it('defaults to an un-selected date', function () {
        expect($hook('bunsenForm-foo-datePicker-input').val()).to.equal('')
      })
    })

    describe('when defaultToCurrentDate is set to true in renderer options', function () {
      let format, currentDate
      beforeEach(function () {
        currentDate = '2017-09-01'
        format = ctx.sandbox.stub().returns(currentDate)
        ctx.sandbox.stub(deps, 'moment').returns({format})

        this.set('bunsenView', {
          cells: [
            {
              collapsible: true,
              model: 'foo',
              renderer: {
                defaultToCurrentDate: true,
                name: 'date'
              }
            }
          ],
          type: 'form',
          version: '2.0'
        })
        this.set('value', undefined)

        return wait()
      })

      it('defaults to the current date', function () {
        expect($hook('bunsenForm-foo-datePicker-input').val()).to.equal(currentDate)
      })
    })
  })

  it('renders as expected', function () {
    expectCollapsibleHandles(0)
    expectBunsenDateRendererWithState('foo', {label: 'Foo'})
    expectOnValidationState(ctx, {count: 1})
  })

  describe('when classes are defined in view', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            model: 'foo',
            renderer: {
              name: 'date'
            },
            classNames: {
              label: 'custom-label',
              value: 'custom-value'
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expect($hook('bunsenForm-foo').find('label.custom-label')).to.have.length(1)
      expect($hook('bunsenForm-foo').find('.custom-value input')).to.have.length(1)
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when hideLabel is set to true in view', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            hideLabel: true,
            model: 'foo',
            renderer: {
              name: 'date'
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {label: null})
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when hideLabel is set to false in view', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            hideLabel: false,
            model: 'foo',
            renderer: {
              name: 'date'
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {label: 'Foo'})
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when label defined in view', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            label: 'FooBar Baz',
            model: 'foo',
            renderer: {
              name: 'date'
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {label: 'FooBar Baz'})
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when collapsible set to true in view', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            collapsible: true,
            model: 'foo',
            renderer: {
              name: 'date'
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(1)
      expectBunsenDateRendererWithState('foo', {label: 'Foo'})
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when collapsible set to false in view', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            collapsible: false,
            model: 'foo',
            renderer: {
              name: 'date'
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {label: 'Foo'})
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when form explicitly enabled', function () {
    beforeEach(function () {
      this.set('disabled', false)
      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {label: 'Foo'})
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when form disabled', function () {
    beforeEach(function () {
      this.set('disabled', true)
      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {
        disabled: true,
        label: 'Foo'
      })
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when property explicitly enabled in view', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            disabled: false,
            model: 'foo',
            renderer: {
              name: 'date'
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {label: 'Foo'})
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when property disabled in view', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            disabled: true,
            model: 'foo',
            renderer: {
              name: 'date'
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {
        disabled: true,
        label: 'Foo'
      })
      expectOnValidationState(ctx, {count: 1})
    })
  })

  describe('when date is set', function () {
    beforeEach(function () {
      ctx.props.onValidation.reset()
      const interactor = openDatepickerBunsenDateRenderer('foo')
      interactor.selectDate(new Date(2017, 0, 24))
      closePikaday(this)
      return wait()
    })

    it('functions as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {
        hasValue: true,
        label: 'Foo'
      })
      expectOnChangeState(ctx, {foo: '2017-01-24'})
      expectOnValidationState(ctx, {count: 1})
    })

    describe('when date is unset', function () {
      beforeEach(function () {
        ctx.props.onValidation.reset()
        this.set('value', {})
        return wait()
      })

      it('functions as expected', function () {
        expectCollapsibleHandles(0)
        expectBunsenDateRendererWithState('foo', {
          label: 'Foo'
        })
        expectOnChangeState(ctx, {})
        expectOnValidationState(ctx, {count: 1})
      })
    })
  })

  describe('when field is required', function () {
    beforeEach(function () {
      ctx.props.onValidation.reset()

      this.set('bunsenModel', {
        properties: {
          foo: {
            type: 'string'
          }
        },
        required: ['foo'],
        type: 'object'
      })

      return wait()
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {label: 'Foo'})
      expectOnValidationState(ctx, {
        count: 1,
        errors: [
          {
            code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
            params: ['foo'],
            message: 'Field is required.',
            path: '#/foo',
            isRequiredError: true
          }
        ]
      })
    })

    describe('when date is set', function () {
      beforeEach(function () {
        ctx.props.onValidation.reset()

        this.set('value', {
          foo: '2017-01-24'
        })

        return wait()
      })

      it('functions as expected', function () {
        expectCollapsibleHandles(0)
        expectBunsenDateRendererWithState('foo', {
          hasValue: true,
          label: 'Foo'
        })
        expectOnChangeState(ctx, {foo: '2017-01-24'})
        expectOnValidationState(ctx, {count: 1})
      })

      describe('when date is unset', function () {
        beforeEach(function () {
          ctx.props.onValidation.reset()
          this.set('value', {})
          return wait()
        })

        it('functions as expected', function () {
          expectCollapsibleHandles(0)
          expectBunsenDateRendererWithState('foo', {label: 'Foo'})
          expectOnChangeState(ctx, {})
          expectOnValidationState(ctx, {
            count: 1,
            errors: [
              {
                code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
                params: ['foo'],
                message: 'Field is required.',
                path: '#/foo',
                isRequiredError: true
              }
            ]
          })
        })
      })
    })

    describe('when showAllErrors is false', function () {
      beforeEach(function () {
        ctx.props.onValidation.reset()
        this.set('showAllErrors', false)
        return wait()
      })

      it('renders as expected', function () {
        expectCollapsibleHandles(0)
        expectBunsenDateRendererWithState('foo', {label: 'Foo'})
        expectOnValidationState(ctx, {count: 0})
      })

      describe('when date is set', function () {
        beforeEach(function () {
          ctx.props.onValidation.reset()

          this.set('value', {
            foo: '2017-01-24'
          })

          return wait()
        })

        it('functions as expected', function () {
          expectCollapsibleHandles(0)
          expectBunsenDateRendererWithState('foo', {
            hasValue: true,
            label: 'Foo'
          })
          expectOnChangeState(ctx, {foo: '2017-01-24'})
          expectOnValidationState(ctx, {count: 1})
        })

        describe('when date is unset', function () {
          beforeEach(function () {
            ctx.props.onValidation.reset()
            this.set('value', {})
            return wait()
          })

          it('functions as expected', function () {
            expectCollapsibleHandles(0)
            expectBunsenDateRendererWithState('foo', {})
            expectOnChangeState(ctx, {})
            expectOnValidationState(ctx, {
              count: 1,
              errors: [
                {
                  code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
                  params: ['foo'],
                  message: 'Field is required.',
                  path: '#/foo',
                  isRequiredError: true
                }
              ]
            })
          })
        })
      })
    })

    describe('when showAllErrors is true', function () {
      beforeEach(function () {
        ctx.props.onValidation.reset()
        this.set('showAllErrors', true)
        return wait()
      })

      it('renders as expected', function () {
        expectCollapsibleHandles(0)
        expectBunsenDateRendererWithState('foo', {
          error: 'Field is required.',
          label: 'Foo'
        })
        expectOnValidationState(ctx, {count: 0})
      })

      describe('when date is set', function () {
        beforeEach(function () {
          ctx.props.onValidation.reset()

          this.set('value', {
            foo: '2017-01-24'
          })

          return wait()
        })

        it('functions as expected', function () {
          expectCollapsibleHandles(0)
          expectBunsenDateRendererWithState('foo', {
            hasValue: true,
            label: 'Foo'
          })
          expectOnChangeState(ctx, {foo: '2017-01-24'})
          expectOnValidationState(ctx, {count: 1})
        })

        describe('when date is unset', function () {
          beforeEach(function () {
            ctx.props.onValidation.reset()
            this.set('value', {})
            return wait()
          })

          it('functions as expected', function () {
            expectCollapsibleHandles(0)
            expectBunsenDateRendererWithState('foo', {
              error: 'Field is required.',
              label: 'Foo'
            })
            expectOnChangeState(ctx, {})
            expectOnValidationState(ctx, {
              count: 1,
              errors: [
                {
                  code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
                  params: ['foo'],
                  message: 'Field is required.',
                  path: '#/foo',
                  isRequiredError: true
                }
              ]
            })
          })
        })
      })
    })
  })

  // TODO: enable once https://github.com/ciena-frost/ember-frost-date-picker/issues/43 is resolved
  // MRD 2017-02-24
  describe.skip('when options passed in', function () {
    beforeEach(function () {
      this.set('bunsenView', {
        cells: [
          {
            model: 'foo',
            renderer: {
              name: 'date',
              options: {
                bar: true,
                baz: 'spam',
                foo: 1,
                isIconVisible: false
              }
            }
          }
        ],
        type: 'form',
        version: '2.0'
      })
    })

    it('renders as expected', function () {
      expectCollapsibleHandles(0)
      expectBunsenDateRendererWithState('foo', {label: 'Foo'})
      expectOnValidationState(ctx, {count: 1})
      expect($hook('bunsenForm-foo-datePicker-cal')).to.have.length(0)
    })
  })
})


text:
<?php
namespace wechat\controllers;

use Yii;
use yii\base\Event;
use yii\helpers\Url;

/**
 * Site controller
 */
class XieyiController extends FrontendController
{
    public function actionIndex()
    {
        return $this->view('index');
    }
}


text:
(function (angular) {

    'use strict';

    var pimcServiceModule = angular.module('pimcServiceModule');
    pimcServiceModule.service('pimcBaseDatosService',
        ['pimcService',
         '$q',
         '$http',
         function (pimcService, $q, $http) {
        var pimcBaseDatosServiceCtrl = this;

        pimcBaseDatosServiceCtrl.consultarPorID = function(elementoRelacional, elementoRelacionalID) {
            var consultaElementoRelacionalURL = pimcService.crearURLOperacion('Consulta', elementoRelacional);
            var idNombre = pimcService.idElementoRelaciona[elementoRelacional];
            if (!idNombre) {
                return $q.reject("Elemento Relacional no disponible")
            }
            var config = { params: {} };
            config.params[idNombre] = elementoRelacionalID;
            // Cargamos los personajes
            return $http.get(consultaElementoRelacionalURL, config).then(function (data) {
                //Obtener los datos JSON
                var valoresElementoRelacional = data.data;
                // Revisamos si se recibio algo
                if (Object.keys(valoresElementoRelacional).length == 0) {
                    return $q.reject("No se encontro nada en la base de datos")
                }
                return valoresElementoRelacional;
            });
        }

        pimcBaseDatosServiceCtrl.consultarBaseDatosParametros = function(baseDatos, parametros) {
            var consultarTodosElementosRelacionalURL = pimcService.crearURLOperacion('ConsultarTodos', baseDatos);
            var config = {};
            config.params = parametros;
            // Cargamos los personajes
            return $http.get(consultarTodosElementosRelacionalURL, config).then(function (data) {
                //Obtener los datos JSON
                var valoresElementoRelacional = data.data;
                // Revisamos si se recibio algo
                if (Object.keys(valoresElementoRelacional).length == 0) {
                    return $q.reject("No se encontro nada en la base de datos")
                }
                return valoresElementoRelacional;
            });
        }
        pimcBaseDatosServiceCtrl.insertarElemento = function(baseDatos, contenido) {
            if (! (contenido instanceof Object)) {
                return $q.reject("contenido debe ser un diccionario");
            }
            var insertarElementoURL = pimcService.crearURLOperacion('Insertar', baseDatos);
            return $http.post(insertarElementoURL, contenido).then(
                function (data) {
                    // Revisamos si la respuesta tiene elementos
                    if (Object.keys(data.data[0]).length != 0){
                        return data.data[0];
                    }
                    // No deberia llegar aca
                    $q.reject("Error al insertar nuevo elemento relacional");
                },
                function (error) {
                    $q.reject("Error al insertar elemento en la base de datos " + baseDatos);
                }
            );
        }
        pimcBaseDatosServiceCtrl.modificarElemento = function (baseDatos, contenido) {
            if (! (contenido instanceof Object)) {
                return $q.reject("contenido debe ser un diccionario");
            }
            var modificarElementoURL = pimcService.crearURLOperacion('Modificar', baseDatos);
            return $http.post(modificarElementoURL, contenido).then(
                function (data) {
                    // Revisamos si la respuesta tiene elementos
                    if (data.data[0] == 0){
                        return $q.reject("No se modifico nada en la base de datos");
                    } else {
                        return $q.resolve(data.data[0]);
                    }
                    // No deberia llegar aca
                    $q.reject("Error al modificar elemento relacional");
                },
                function (error) {
                    $q.reject("Error al modificar elemento en la base de datos " + baseDatos);
                }
            );
        }
        pimcBaseDatosServiceCtrl.eliminarElemento = function (baseDatos, contenido) {
            if (! (contenido instanceof Object)) {
                return $q.reject("contenido debe ser un diccionario");
            }
            var modificarElementoURL = pimcService.crearURLOperacion('Eliminar', baseDatos);
            return $http.delete(modificarElementoURL, {params: contenido}).then(
                function (data) {
                    // Revisamos si la respuesta tiene elementos
                    if (data.data[0] == 0){
                        return $q.reject("No se elimino nada en la base de datos");
                    } else {
                        return $q.resolve(data.data[0]);
                    }
                    // No deberia llegar aca
                    $q.reject("Error al eliminar elemento relacional");
                },
                function (error) {
                    $q.reject("Error al eliminar elemento en la base de datos " + baseDatos);
                }
            );
        }

    }]);
})(window.angular);