text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie (Servlet 4.0 API Documentation - Apache Tomcat 9.0.0.M11)</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Servlet 4.0 - Apache Tomcat 9.0.0.M11

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.servlet.http

Class Cookie

java.lang.Object

javax.servlet.http.Cookie

All Implemented Interfaces:

java.io.Serializable, java.lang.Cloneable

public class Cookie
extends java.lang.Object
implements java.lang.Cloneable, java.io.Serializable

Creates a cookie, a small amount of information sent by a servlet to a Web
 browser, saved by the browser, and later sent back to the server. A cookie's
 value can uniquely identify a client, so cookies are commonly used for
 session management.

 A cookie has a name, a single value, and optional attributes such as a
 comment, path and domain qualifiers, a maximum age, and a version number.
 Some Web browsers have bugs in how they handle the optional attributes, so
 use them sparingly to improve the interoperability of your servlets.

 The servlet sends cookies to the browser by using the
 HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP
 response headers to send cookies to the browser, one at a time. The browser
 is expected to support 20 cookies for each Web server, 300 cookies total, and
 may limit cookie size to 4 KB each.

 The browser returns cookies to the servlet by adding fields to HTTP request
 headers. Cookies can be retrieved from a request by using the
 HttpServletRequest.getCookies() method. Several cookies might have the
 same name but different path attributes.

 Cookies affect the caching of the Web pages that use them. HTTP 1.0 does not
 cache pages that use cookies created with this class. This class does not
 support the cache control defined with HTTP 1.1.

 This class supports both the RFC 2109 and the RFC 6265 specifications.
 By default, cookies are created using RFC 6265.

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

Cookie(java.lang.String name,
      java.lang.String value)

Constructs a cookie with a specified name and value.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.Object
clone()

Overrides the standard java.lang.Object.clone method to
 return a copy of this cookie.

java.lang.String
getComment()

Returns the comment describing the purpose of this cookie, or
 null if the cookie has no comment.

java.lang.String
getDomain()

Returns the domain name set for this cookie.

int
getMaxAge()

Returns the maximum age of the cookie, specified in seconds, By default,
 -1 indicating the cookie will persist until browser
 shutdown.

java.lang.String
getName()

Returns the name of the cookie.

java.lang.String
getPath()

Returns the path on the server to which the browser returns this cookie.

boolean
getSecure()

Returns true if the browser is sending cookies only over a
 secure protocol, or false if the browser can send cookies
 using any protocol.

java.lang.String
getValue()

Returns the value of the cookie.

int
getVersion()

Returns the version of the protocol this cookie complies with.

boolean
isHttpOnly()

Gets the flag that controls if this cookie will be hidden from scripts on
 the client side.

void
setComment(java.lang.String purpose)

Specifies a comment that describes a cookie's purpose.

void
setDomain(java.lang.String pattern)

Specifies the domain within which this cookie should be presented.

void
setHttpOnly(boolean httpOnly)

Sets the flag that controls if this cookie will be hidden from scripts on
 the client side.

void
setMaxAge(int expiry)

Sets the maximum age of the cookie in seconds.

void
setPath(java.lang.String uri)

Specifies a path for the cookie to which the client should return the
 cookie.

void
setSecure(boolean flag)

Indicates to the browser whether the cookie should only be sent using a
 secure protocol, such as HTTPS or SSL.

void
setValue(java.lang.String newValue)

Assigns a new value to a cookie after the cookie is created.

void
setVersion(int v)

Sets the version of the cookie protocol this cookie complies with.

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Cookie

public Cookie(java.lang.String name,
              java.lang.String value)

Constructs a cookie with a specified name and value.

 The name must conform to RFC 2109. That means it can contain only ASCII
 alphanumeric characters and cannot contain commas, semicolons, or white
 space or begin with a $ character. The cookie's name cannot be changed
 after creation.

 The value can be anything the server chooses to send. Its value is
 probably of interest only to the server. The cookie's value can be
 changed after creation with the setValue method.

 By default, cookies are created according to the Netscape cookie
 specification. The version can be changed with the
 setVersion method.

Parameters:

name - a String specifying the name of the cookie

value - a String specifying the value of the cookie

Throws:

java.lang.IllegalArgumentException - if the cookie name contains illegal characters (for example,
             a comma, space, or semicolon) or it is one of the tokens
             reserved for use by the cookie protocol

See Also:

setValue(java.lang.String),
setVersion(int)

Method Detail

setComment

public void setComment(java.lang.String purpose)

Specifies a comment that describes a cookie's purpose. The comment is
 useful if the browser presents the cookie to the user. Comments are not
 supported by Netscape Version 0 cookies.

Parameters:

purpose - a String specifying the comment to display to the
            user

See Also:

getComment()

getComment

public java.lang.String getComment()

Returns the comment describing the purpose of this cookie, or
 null if the cookie has no comment.

Returns:

a String containing the comment, or
         null if none

See Also:

setComment(java.lang.String)

setDomain

public void setDomain(java.lang.String pattern)

Specifies the domain within which this cookie should be presented.

 The form of the domain name is specified by RFC 2109. A domain name
 begins with a dot (.foo.com) and means that the cookie is
 visible to servers in a specified Domain Name System (DNS) zone (for
 example, www.foo.com, but not a.b.foo.com). By
 default, cookies are only returned to the server that sent them.

Parameters:

pattern - a String containing the domain name within which
            this cookie is visible; form is according to RFC 2109

See Also:

getDomain()

getDomain

public java.lang.String getDomain()

Returns the domain name set for this cookie. The form of the domain name
 is set by RFC 2109.

Returns:

a String containing the domain name

See Also:

setDomain(java.lang.String)

setMaxAge

public void setMaxAge(int expiry)

Sets the maximum age of the cookie in seconds.

 A positive value indicates that the cookie will expire after that many
 seconds have passed. Note that the value is the maximum age when
 the cookie will expire, not the cookie's current age.

 A negative value means that the cookie is not stored persistently and
 will be deleted when the Web browser exits. A zero value causes the
 cookie to be deleted.

Parameters:

expiry - an integer specifying the maximum age of the cookie in
            seconds; if negative, means the cookie is not stored; if zero,
            deletes the cookie

See Also:

getMaxAge()

getMaxAge

public int getMaxAge()

Returns the maximum age of the cookie, specified in seconds, By default,
 -1 indicating the cookie will persist until browser
 shutdown.

Returns:

an integer specifying the maximum age of the cookie in seconds; if
         negative, means the cookie persists until browser shutdown

See Also:

setMaxAge(int)

setPath

public void setPath(java.lang.String uri)

Specifies a path for the cookie to which the client should return the
 cookie.

 The cookie is visible to all the pages in the directory you specify, and
 all the pages in that directory's subdirectories. A cookie's path must
 include the servlet that set the cookie, for example, /catalog,
 which makes the cookie visible to all directories on the server under
 /catalog.

 Consult RFC 2109 (available on the Internet) for more information on
 setting path names for cookies.

Parameters:

uri - a String specifying a path

See Also:

getPath()

getPath

public java.lang.String getPath()

Returns the path on the server to which the browser returns this cookie.
 The cookie is visible to all subpaths on the server.

Returns:

a String specifying a path that contains a servlet
         name, for example, /catalog

See Also:

setPath(java.lang.String)

setSecure

public void setSecure(boolean flag)

Indicates to the browser whether the cookie should only be sent using a
 secure protocol, such as HTTPS or SSL.

 The default value is false.

Parameters:

flag - if true, sends the cookie from the browser to the
            server only when using a secure protocol; if
            false, sent on any protocol

See Also:

getSecure()

getSecure

public boolean getSecure()

Returns true if the browser is sending cookies only over a
 secure protocol, or false if the browser can send cookies
 using any protocol.

Returns:

true if the browser uses a secure protocol;
         otherwise, true

See Also:

setSecure(boolean)

getName

public java.lang.String getName()

Returns the name of the cookie. The name cannot be changed after
 creation.

Returns:

a String specifying the cookie's name

setValue

public void setValue(java.lang.String newValue)

Assigns a new value to a cookie after the cookie is created. If you use a
 binary value, you may want to use BASE64 encoding.

 With Version 0 cookies, values should not contain white space, brackets,
 parentheses, equals signs, commas, double quotes, slashes, question
 marks, at signs, colons, and semicolons. Empty values may not behave the
 same way on all browsers.

Parameters:

newValue - a String specifying the new value

See Also:

getValue(),
Cookie

getValue

public java.lang.String getValue()

Returns the value of the cookie.

Returns:

a String containing the cookie's present value

See Also:

setValue(java.lang.String),
Cookie

getVersion

public int getVersion()

Returns the version of the protocol this cookie complies with. Version 1
 complies with RFC 2109, and version 0 complies with the original cookie
 specification drafted by Netscape. Cookies provided by a browser use and
 identify the browser's cookie version.

Returns:

0 if the cookie complies with the original Netscape specification;
         1 if the cookie complies with RFC 2109

See Also:

setVersion(int)

setVersion

public void setVersion(int v)

Sets the version of the cookie protocol this cookie complies with.
 Version 0 complies with the original Netscape cookie specification.
 Version 1 complies with RFC 2109.

 Since RFC 2109 is still somewhat new, consider version 1 as experimental;
 do not use it yet on production sites.

Parameters:

v - 0 if the cookie should comply with the original Netscape
            specification; 1 if the cookie should comply with RFC 2109

See Also:

getVersion()

clone

public java.lang.Object clone()

Overrides the standard java.lang.Object.clone method to
 return a copy of this cookie.

Overrides:

clone in class java.lang.Object

setHttpOnly

public void setHttpOnly(boolean httpOnly)

Sets the flag that controls if this cookie will be hidden from scripts on
 the client side.

Parameters:

httpOnly - The new value of the flag

Since:

Servlet 3.0

isHttpOnly

public boolean isHttpOnly()

Gets the flag that controls if this cookie will be hidden from scripts on
 the client side.

Returns:

true if the cookie is hidden from scripts, else
          false

Since:

Servlet 3.0

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Servlet 4.0 - Apache Tomcat 9.0.0.M11

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.


text:
namespace King.Mapper.Generator
{
    using King.Data.Sql.Reflection.Models;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    #region ICodeGenerator
    /// <summary>
    /// Code Generator Interface
    /// </summary>
    public interface ICodeGenerator
    {
        #region Methods
        /// <summary>
        /// Generate Code
        /// </summary>
        /// <returns>Threading Task</returns>
        Task Generate();
        #endregion
    }
    #endregion

    #region IRender
    /// <summary>
    /// Render
    /// </summary>
    public interface IRender
    {
        #region Properties
        /// <summary>
        /// File Name
        /// </summary>
        string FileName
        {
            get;
        }
        #endregion

        #region Methods
        /// <summary>
        /// Render
        /// </summary>
        /// <returns>Output</returns>
        string Render();
        #endregion
    }
    #endregion

    #region IFileWriter
    /// <summary>
    /// File Writer
    /// </summary>
    public interface IFileWriter
    {
        #region Methods
        /// <summary>
        /// Write All
        /// </summary>
        /// <param name="renderers">Renderers</param>
        void WriteAll(IEnumerable<IRender> renderers);
        #endregion
    }
    #endregion

    #region IRenderFactory
    /// <summary>
    /// Render Factory
    /// </summary>
    public interface IRenderFactory
    {
        #region Methods
        /// <summary>
        /// Load Renderers with Manifest
        /// </summary>
        /// <param name="manifest">Manifest</param>
        /// <returns>Renderers</returns>
        IEnumerable<IRender> Load(IEnumerable<IDefinition> manifest);
        #endregion
    }
    #endregion
}

redpajama_set_name: RedPajamaGithub


text:
<!--

    (C) Copyright 2011-2015 FastConnect SAS
    (http://www.fastconnect.fr/) and others.

    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.

-->
<assembly
	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
	<id>bin-with-jars</id>
	<formats>
		<format>zip</format>
	</formats>
	<includeBaseDirectory>false</includeBaseDirectory>

	<files>
		<file>
			<outputDirectory>/</outputDirectory>
			<source>${project.package.directory}/${deploy.pom}</source>
			<destName>${deploy.pom}</destName>
		</file>
	</files>

	<moduleSets>
		<!-- moduleSet for EARs -->
		<moduleSet>
			<useAllReactorProjects>true</useAllReactorProjects>
			<includes>
				<include>*:bw-ear</include>
			</includes>
 			<binaries>
 				<outputDirectory>${package.bw.applications.root}/${module.properties.assembly.relative.path}/${module.artifactId}/</outputDirectory>
				<unpack>false</unpack>
				<includeDependencies>false</includeDependencies>
			</binaries>
		</moduleSet>
		<!-- moduleSet for deploy POMs ('bw-ear-deploy' packaging) -->
		<moduleSet>
			<useAllReactorProjects>true</useAllReactorProjects>
			<includes>
				<include>*:bw-ear</include>
			</includes>
 			<binaries>
 				<outputDirectory>${package.bw.applications.root}/${module.properties.assembly.relative.path}/${module.artifactId}/</outputDirectory>
 				<outputFileNameMapping>${module.properties.deploy.pom}</outputFileNameMapping>
				<unpack>false</unpack>
				<attachmentClassifier>deployment</attachmentClassifier>
				<includeDependencies>false</includeDependencies>
			</binaries>
		</moduleSet>
		<!-- moduleSet for final configuration XML file -->
		<moduleSet>
			<useAllReactorProjects>true</useAllReactorProjects>
			<includes>
				<include>*:bw-ear</include>
			</includes>
 			<binaries>
 				<outputDirectory>${package.bw.applications.root}/${module.properties.assembly.relative.path}/${module.artifactId}/</outputDirectory>
				<unpack>false</unpack>
				<attachmentClassifier>final</attachmentClassifier>
				<includeDependencies>false</includeDependencies>
			</binaries>
		</moduleSet>
		<!-- moduleSet for JARs (transitive dependencies of BW EARs) -->
		<moduleSet>
			<useAllReactorProjects>true</useAllReactorProjects>
			<includes>
				<include>*:bw-ear</include>
			</includes>
 			<binaries>
 				<outputDirectory>${package.bw.applications.root}/${module.properties.assembly.relative.path}/${module.artifactId}/</outputDirectory>
				<unpack>false</unpack>
 				<dependencySets>
					<dependencySet>
						<includes>
							<include>*:jar</include>
						</includes>
						<outputDirectory>libs/</outputDirectory>
						<scope>runtime</scope>
						<useProjectArtifact>false</useProjectArtifact>
						<unpack>false</unpack>
						<useTransitiveFiltering>true</useTransitiveFiltering>
					</dependencySet>
				</dependencySets>
			</binaries>
		</moduleSet>
	</moduleSets>

</assembly>


text:
delete a
from person a, person b
where a.email = b.email and a.id > b.id;


text:
#include <vector>
using std::vector;

#include <string>
using std::string;

#include <iostream>
using std::cout; using std::endl;

#include <initializer_list>
using std::initializer_list;

#include <sstream>
using std::ostringstream;

// chapter 7 will explain the code used in defining ErrCode
struct ErrCode {
	ErrCode(int i) : num(i) { }  // initializes objects of type ErrCode
	string msg()                 // member function of ErrCode
	{ ostringstream s; s << "ErrCode " << num; return s.str(); }
	int num;  // data member, note uninitialized
};

// version that takes an ErrCode and a list of strings
void error_msg(ErrCode e, initializer_list<string> il)
{
	cout << e.msg() << ": ";
	for (const auto &elem : il)
		cout << elem << " " ;
	cout << endl;
}

// overloaded version takes only a list of strings
void error_msg(initializer_list<string> il)
{
	for (auto beg = il.begin(); beg != il.end(); ++beg)
		cout << *beg << " " ;
	cout << endl;
}

// function to illustrate list initializing return value
vector<string> functionX()
{
	string expected = "description", actual = "some other case";
	// . . .
	if (expected.empty())
		return {};  // return an empty vector
	else if (expected == actual)
		return {"functionX", "okay"}; // return list-initialized vector
	else
		return {"functionX", expected, actual};
}

int main()
{
	string expected = "description", actual = "some other case";
	initializer_list<int> li = {0,1,2,3};

	// expected, actual are strings
	if (expected != actual)
		error_msg({"functionX", expected, actual});
	else
		error_msg({"functionX", "okay"});

	// expected, actual are strings
	if (expected != actual)
		error_msg(ErrCode(42), {"functionX", expected, actual});
	else
		error_msg(ErrCode(0), {"functionX", "okay"});

	// can pass an empty list, calls second version of error_msg
	error_msg({}); // prints blank line

	// call function that list initializes its return value
	// results is a vector<string>
	auto results = functionX();
	for (auto i : results)
		cout << i << " ";
	cout << endl;
}


text:
import UserProfile from './UserProfile';
import IUserAction from './IUserAction';
import UserSignup from './UserSignup';
import AccessLevel from './AccessLevel';
import ActionResult from 'core/models/ActionResult';
import { Api } from 'core/helpers';
import settings from 'core/settings';

const UserAction: IUserAction = {

    async getProfile(): Promise<UserProfile> {
        const profile = await Api.get('profile');
        return new UserProfile(profile);
    },

    async updateProfile(data: UserProfile): Promise<UserProfile> {
        const profile = await Api.patch('profile');
        return new UserProfile(profile);
    },

    async signup(data: any): Promise<any> {
        const response = await Api.post('account/register');
        const apiResponse: ActionResult = new ActionResult();
        apiResponse.redirect = settings.defaultRoute;
        apiResponse.message = response.message;
        return apiResponse;
    },

    async verifyAccount(data: any): Promise<any> {
         return await Api.patch('account/verifyAccount', data);
    },

    async changeEmail(data: any): Promise<any> {
        return await Api.patch('account/changeEmail', data);
    },

    async changeMobile(data: any): Promise<any> {
        return await Api.patch('account/changeMobile', data);
    },

    async changeAddress(data: any): Promise<any> {
        return await Api.patch('account/changeAddress', data);
    },

    async changePassword(data: any): Promise<any> {
        return await Api.patch('account/changePassword', data);
    },

    async isUsernameAvailable(username: string): Promise<any> {
         return await Api.get('account/isUsernameAvailable', { username });
    },

    async isEmailAvailable(email: string): Promise<any> {
        return await Api.get('account/isEmailAvailable', { email });
    },

    async isPhoneNumberAvailable(phoneNumber: string): Promise<any> {
        return await Api.get('account/isPhoneNumberAvailable', { phoneNumber });
    },

    async resetPassword(data: any): Promise<any> {
        return await Api.post('account/reset-password', data);
    },

    async requestUsernameChange(data: any): Promise<any> {
        return await Api.post('account/request-username-change', data);
    },

    async requestEmailChange(data: any): Promise<any> {
        return await Api.post('account/request-email-change', data);
    },
};

export default UserAction;


text:
///////////////////////////////////////////////////////////////////////////////////////////
//               Ö÷ҪʵÏÖiframeÄ£Äâxmlhttprequest£¬ÊµÏÖÎÞË¢ÐÂÌá½»
///////////////////////////////////////////////////////////////////////////////////////////
var currentRequest = null;
/**
*Ò³Ãæonloadʱ°ó¶¨Òþ²Øiframe
*·µ»ØÖµ£ºÎÞ
*/
function initAjaxRequestBox(){
var div = null;
div = document.createElement("div");
div.id = "myAjaxResultBox";
div.innerHTML = "<iframe name='myAjaxResultFrame' init=false style='display:none' onload='myAjaxResultFrame_onResult();'></iframe>";
document.body.appendChild(div);
}
if(window.document.all){
try{
window.attachEvent("onload" ,
function(e){
initAjaxRequestBox()
}
);
}
catch(e){}
}else{
window.addEventListener("load",
function(e){
initAjaxRequestBox()
},
false
);
}
/**
*Ìá½»ÇëÇóºó£¬½á¹û·µ»Ø'þ´¥·¢
*·µ»ØÖµ£ºÎÞ
*/
function myAjaxResultFrame_onResult(){
var myFrame = document.getElementsByName('myAjaxResultFrame')[0];
if(myFrame.inited==true){
if(myFrame.contentWindow.document.getElementById("XMLHttpResultDiv")){
var text = myFrame.contentWindow.document.getElementById("XMLHttpResultDiv").innerHTML;
}else{
var text = myFrame.contentWindow.document.body.innerHTML;
}
if(currentRequest)
{
currentRequest.setText(text);
currentRequest.onresult();
}
}else{
myFrame.inited = true;
}
}
/**
*AjaxRequest¶ÔÏó
*_method: Öµpost/get    ºÍformʹÓ÷½·¨Ò»ÖÂ
*_url:    Öµstring      ºÍformµÄactionÒ»ÖÂ
*_async:  Öµfalse/trueͬ²½/Òì²½  ÓÉÓÚÊÇiframeÌá½»£¬Ã»ÓÐÒì²½
*/
function AjaxRequest(_method,_url,_async){
var oThis = this;
var value = null;
var text = null;
var _form = document.getElementById("myAjaxRequestForm");
if(_form){
_form.removeNode(true);
}
_form = document.createElement("form");
document.body.appendChild(_form);
_form.method = _method;
_form.action = _url;
_form.target = "myAjaxResultFrame";
currentRequest = oThis;
//input²ÎÊý´«µÝ
this.setParameter = function(name,value) {
var _input = document.createElement("input");
_input.name=name;
_input.value=value;
_input.type="hidden";
_form.appendChild(_input);
}
//url²ÎÊý´«µÝ
this.send = function(v){
if(v==null || v==""){
_form.submit();
}else{
var parts = v.split('&');
for(var i=0;i<parts.length;i++){
var part = parts[i].split('=');
var name = part[0];
var value = part[1];
var _input = document.createElement("input");
_input.name=name;
_input.value=value;
_input.type="hidden";
_form.appendChild(_input);
}
_form.submit();
}
}
//ÌáÈ¡·µ»Ø×Ö¶Î
this.getText = function(){
return text;
}
this.setText = function(t){
text = t;
}
//ajaxÇëÇóÍê³É
this.onresult = function(){
}
}


text:
if [ $# -lt 1 ]; then
    cat <<EOF
cli.sh
rundata <name> : run the data cotainer
rmdata <name> : remove the data cotainer
rm : remove all stop cotainer
rmi : remove all untag image
run <container_name> <http_port> <base_img> : run with data-volume container
cmdssl <img_name> : enable ssl support
EOF
  exit 0
fi
if [ $1 == "rundata" ]; then
    if [ $# -lt 2 ]; then
      echo -e "Syntax Error, ex: cli.sh rundata <name>"
      exit 0
    fi
	cat <<EOF
docker run --name $2 -v /var/lib/mysql -v /var/www busybox /bin/true
docker ps -a | grep -w $2
EOF
fi
if [ $1 == "rmdata" ]; then
    if [ $# -lt 2 ]; then
      echo -e "Syntax Error, ex: cli.sh rmdata <name>"
      exit 0
    fi
	cat <<EOF
CID=\$(docker ps -a | grep -w '$2' | awk '{print \$1}')
docker rm \$CID
docker ps -a | grep -w busybox:latest
EOF
fi
if [ $1 == "run" ]; then
    if [ $# -lt 4 ]; then
      echo -e "Syntax Error, ex: cli.sh run <container_name> <http_port> <base_img>"
      exit 0
    fi
    cat <<EOF
echo "create new data container for dk-wptw"
docker run --name $2-data -v /var/lib/mysql -v /var/www busybox /bin/true
echo "run dk-wptw with data container"
docker run -d -p $3:80 --name $2 --volumes-from $2-data $4
docker ps && docker ps -q | xargs -n 1 docker inspect --format "{{ .Name }} {{ .NetworkSettings.IPAddress }}"
EOF
fi
if [ $1 == "psip" ]; then
    cat <<EOF
docker ps && docker ps -q | xargs -n 1 docker inspect --format "{{ .Name }} {{ .NetworkSettings.IPAddress }}"
EOF
fi
if [ $1 == "rm" ]; then
   echo 'docker rm $(docker ps -a -q)'
fi
if [ $1 == "stopall" ]; then
   echo 'docker stop $(docker ps -q)'
fi
if [ $1 == "rmi" ]; then
    cat <<EOF
docker rmi \$(docker images | grep "^<none>" | awk "{print $3}")
EOF
fi
if [ $1 == "enablessl" ]; then
    SUBJ="/C=TW/ST=Taichung/L=Xitun/OU=Y12STUDIO/O=WordPressDev/CN=dev.y12.tw"
    echo "-----> enable SSL $SUBJ"
    mkdir -p /etc/apache2/ssl
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crt -subj $SUBJ
    sed -i "s/define('WP_DEBUG', false);/define('WP_DEBUG', false);\r\ndefine('FORCE_SSL_ADMIN', true);/g" /var/www/wp-config.php
    a2enmod ssl
    a2ensite default-ssl.conf
fi
if [ $1 == "cmdssl" ]; then
    if [ $# -lt 2 ]; then
      echo -e "Syntax Error, ex: cli.sh cmdssl <img_name>"
      exit 0
    fi
    cat <<EOF
id=\$(docker run -d $2 /bin/bash -c "/cli.sh enablessl")
test \$(docker wait \$id) -eq 0
docker commit --run='{"Cmd": ["/bin/bash", "/start.sh"]}' \$id $2:ssl > /dev/null
echo "-----> Injected SSL with images: $2:ssl"
docker images | grep $2
EOF
fi


text:
class CanBeTaggedMigrationGenerator < Rails::Generators::Base
  include Rails::Generators::Migration
  source_root File.expand_path('../templates', __FILE__)

  def self.next_migration_number(dirname) #:nodoc:
    next_migration_number = current_migration_number(dirname) + 1
    ActiveRecord::Migration.next_migration_number(next_migration_number)
  end

  def create_migration
    migration_template "tags_migration.rb", "db/migrate/create_tags.rb"
    migration_template "tag_lines_migration.rb", "db/migrate/create_tag_lines.rb"
  end

end


text:
TechSmith Hyde
========================

Object to Entity mapper for Windows Azure, it **hy**drates and **de**hydrates objects to and from storage (Think ORM for table storage).

### Features
 * Super simple access to Azure Table Storage. Use your existing POCO C# objects and map Table Storage entities to them.
 * Easily unit test your code that accesses Table Storage with an in-memory test double. No complicated mocks or stubs required!
 * Automatically batches large reads & writes to optimize common operations.
 * Easily compose complex queries using the fluent interface.
 * Handles quirks of your local Azure emulator for you.

### Basic Example

```csharp
using TechSmith.Hyde;
using TechSmith.Hyde.Table;

public class Color
{
  public string HexColorCode
  {
    get;
    set;
  }
}

var storageAccount = new ConnectionStringCloudStorageAccount( "YourConnectionStringHere" );
var tableStorage = new AzureTableStorageProvider( storageAccount );

var color = tableStorage.CreateQuery<Color>( "MyColorsTable" )
                        .PartitionKeyEquals( "Red" )
                        .RowKeyEquals( "Crimson" );

```

More examples and getting started help can be found [on the wiki](https://github.com/TechSmith/hyde/wiki/Getting-Started)

###License
BSD 3-Clause, see http://www.opensource.org/licenses/BSD-3-Clause

### Getting started with development
 1. The first step is to get your developer machine setup. The easiest way to do so is to [run the machine setup script](tools/machinesetup.bat)
 1. Finally, farmiliarize yourself with the submission guidelines below.

### Submission guidelines
Follow these guidelines, in no particular order, to improve your chances of having a pull request merged in.

 * Add an issue for what you plan to add/improve/fix in the project to start a discussion prior to submitting the code.
 * Include unit and/or integration tests with code submissions.
 * Make each pull request atomic and exclusive; don't send pull requests for a huge list of changes.
 * Even better, commit in small manageable chunks.
 * Spaces, not tabs. Use 3 spaces. Brackets should be on their own line.
 * No regions
 * Code must build .NET 4.
 * If you didn't write the code you must provide a reference to where you obtained it and the license.

### FAQ - Technical Details
**Looking at my tables in Azure Table Storage, I notice that some fields contain the prefix "%HYDE_DATETIME%" while others do not. What's up with that?**
The C# DateTime struct supports a range from year 0001 to year 9999, while Table Storage only supports DateTimes from year 1601 to year 9999. To work around
this, if we cannot store a C# DateTime using a corresponding Table Storage DateTime, we store it as a string and tag it with its corresponding C# structure so that
we can retrieve it as the appropriate type in the future.


text:
<script>
  (function () {
    'use strict';
    anchors.options.placement = 'right';
    anchors.add();
  })();
</script>


text:
#include "recordTypeInfo.hh"

using namespace hadoop;

RecordTypeInfo::RecordTypeInfo()
{
  pStid = new StructTypeID();
}

RecordTypeInfo::RecordTypeInfo(const char *pName): name(pName)
{
  pStid = new StructTypeID();
}

/*RecordTypeInfo::RecordTypeInfo(const RecordTypeInfo& rti): name(rti.name)
{
  // clone the typeinfos from rti and add them
  for (unsigned int i=0; i<rti.typeInfos.size(); i++) {
    typeInfos.push_back(rti.typeInfos[i]->clone());
  }
  // clone the map
  for (std::map<std::string, RecordTypeInfo*>::const_iterator iter=rti.structRTIs.begin();
       iter!=rti.structRTIs.end(); ++iter) {
    structRTIs[iter->first] = iter->second->clone();
  }
}*/

RecordTypeInfo::~RecordTypeInfo()
{
  if (NULL != pStid)
    delete pStid;

  /*for (unsigned int i=0; i<typeInfos.size(); i++) {
    delete typeInfos[i];
  }
  typeInfos.clear();
  for (std::map<std::string, RecordTypeInfo*>::const_iterator iter=structRTIs.begin();
       iter!=structRTIs.end(); ++iter) {
    // delete the RTI objects
    delete iter->second;
  }
  structRTIs.clear();*/
}

void RecordTypeInfo::addField(const std::string* pFieldID, const TypeID* pTypeID)
{
  pStid->getFieldTypeInfos().push_back(new FieldTypeInfo(pFieldID, pTypeID));
}

void RecordTypeInfo::addAll(std::vector<FieldTypeInfo*>& vec)
{
  // we need to copy object clones into our own vector
  for (unsigned int i=0; i<vec.size(); i++) {
    pStid->getFieldTypeInfos().push_back(vec[i]->clone());
  }
}

// make a copy of typeInfos and return it
/*std::vector<TypeInfo*>& RecordTypeInfo::getClonedTypeInfos()
{
  std::vector<TypeInfo*>* pNewVec = new std::vector<TypeInfo*>();
  for (unsigned int i=0; i<typeInfos.size(); i++) {
    pNewVec->push_back(typeInfos[i]->clone());
  }
  return *pNewVec;
} */

const std::vector<FieldTypeInfo*>& RecordTypeInfo::getFieldTypeInfos() const
{
  return pStid->getFieldTypeInfos();
}

RecordTypeInfo* RecordTypeInfo::getNestedStructTypeInfo(const char *structName) const
{
  StructTypeID* p = pStid->findStruct(structName);
  if (NULL == p) return NULL;
  return new RecordTypeInfo(structName, p);
  /*std::string s(structName);
  std::map<std::string, RecordTypeInfo*>::const_iterator iter = structRTIs.find(s);
  if (iter == structRTIs.end()) {
    return NULL;
  }
  return iter->second;*/
}

void RecordTypeInfo::serialize(::hadoop::OArchive& a_, const char* tag) const
{
  a_.startRecord(*this, tag);
  // name
  a_.serialize(name, tag);
  /*// number of elements
  a_.serialize((int32_t)typeInfos.size(), tag);
  // write out each element
  for (std::vector<FieldTypeInfo*>::const_iterator iter=typeInfos.begin();
       iter!=typeInfos.end(); ++iter) {
    (*iter)->serialize(a_, tag);
    }*/
  pStid->serializeRest(a_, tag);
  a_.endRecord(*this, tag);
}

void RecordTypeInfo::print(int space) const
{
  for (int i=0; i<space; i++) {
    printf(" ");
  }
  printf("RecordTypeInfo::%s\n", name.c_str());
  pStid->print(space);
  /*for (unsigned i=0; i<typeInfos.size(); i++) {
    typeInfos[i]->print(space+2);
    }*/
}

void RecordTypeInfo::deserialize(::hadoop::IArchive& a_, const char* tag)
{
  a_.startRecord(*this, tag);
  // name
  a_.deserialize(name, tag);
  pStid->deserialize(a_, tag);
  a_.endRecord(*this, tag);
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="cse5236.parkingapp.List$PlaceholderFragment">

    <TextView
        android:text="Tap on a zone for more options"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/zoneoptions"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listtable"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/zoneoptions"
        android:layout_above="@id/footertable"
        android:padding="2dip">

        <TableRow
            android:id="@+id/listrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dip">

            <ListView
                android:id="@+id/zonelist"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

            </ListView>

            <ListView
                android:id="@+id/distancelist"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

            </ListView>

            <ListView
                android:id="@+id/pricelist"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

            </ListView>

        </TableRow>

    </TableLayout>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/footertable"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:padding="2dip">

        <TableRow
            android:id="@+id/footerrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dip"
            android:gravity="center">

            <Button
                android:id="@+id/parkingtype"
                android:layout_width="150dip"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="5dip"
                android:text="Parking Type"/>

            <Button
                android:id="@+id/backtodetails"
                android:layout_width="150dip"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="5dip"
                android:text="Map View" />

        </TableRow>

    </TableLayout>

</RelativeLayout>


text:
..
 This work is licensed under a Creative Commons Attribution 3.0 Unported
 License.

 http://creativecommons.org/licenses/by/3.0/legalcode

=============================
Enable multiattach of volumes
=============================

Include the URL of your launchpad blueprint:

https://blueprints.launchpad.net/cinder/+spec/multi-attach-v3-attach

The ability to attach a volume to multiple hosts/servers simultaneously
is a use case that has been asked for over the years.  The implementation
of the Attach workflow in Cinder however made this somewhat difficult and
less than robust.

With the new Cinder Attachment API's [1]_ this is
a bit easier because Attachments are treated as independent objects.

This spec proposes a set of changes to enable and control the use of
multiattach volumes from the Cinder side.

Problem description
===================

Currently we refuse to attach a volume that is already attached (in-use).
There are situations where a cloud user may have deployed a clustered
file-system on a Cinder volume and they would like the ability to attach
a volume to multiple hosts/servers at the same time.

Note that Cinder is not providing any sort of Filesystem checks or sharing
overlays on the volume, it's completely up to the user to handle this and
determine if they can in fact attach a volume to multiple locations without
incurring filesystem/data corruption.

The problem that we are proposing to solve with this spec is simply to enable
the ability to attach a volume to multiple locations, and provide the cloud
operator with policies to enable/disable the functionality for the cloud.  We
do NOT offer any mechanism to keep a user from corrupting their data or doing
something terrible.

Terminology
-----------

Multi-Attach RO:
  The ability to attach a volume as one would normally do (Read Write access)
  and then to attach that volume to another host(s)/server(s) in Read Only
  mode.  Note, this is actually tricky because this typically will require that
  the consumer (ie Nova/KVM) knows how to set and enforce Read Only on an
  attached volume.

Multi-Attach RW:
  The ability to attach a volume as one would normally do (Read Write access)
  and then to attach that volume to another host(s)/server(s).  In this case
  there is no differentiation between the initial attachment and any subsequent
  attachments.  They are all treated as independent items and are all Read
  Write volumes with no real distinction beyond what's provided with a single
  attachment.

The ability to set Read Only options on attachments will be handled as seperate
work in the from of an argument to ``attachment-create``.  That feature is
not considered part of the scope of this spec and will be handled independently.

Multi-Attach Capable Backend:
  Some backend devices just flat out may not support this.  Those that do are
  considered to be "Multi-Attach Capable" backend devices and need to report
  this in their capabilities.

Example Volume Types to communicate Multi Path info:

  {
  'multiattach': '<is> True',
  }

  It will be up to the Cinder scheduler to determine if the policy allows these
  types of volumes to be created, and it will then be up to the driver to form
  the corresponding Connection and Volume attributes appropriately in it's
  model returns.

  Again NOTE we will NOT allow retype of multiattachment setting for an `in-use`
  volume.

Use Cases
=========

* There are products that can be used like Oracle RAC that
  would make things like H/A databases via a shared Block device possible which
  is something of interest.
* The other use case that's been proposed is the
  ability to have things like passive stand-by servers/volumes.
* Analyzing/Fleecing an Instance from another Instance or host

Proposed change
===============

MultiAttach policy
------------------

Create a Cinder policy that enables/disables the ability to multi-attach
a volume.  This policy is a global policy for the endpoint and simply either
enables or disables the capability.

Additionally we'll want a specific policy to enable/disable the ability to
multiattach bootable volumes (volume with the bootable parameter set True).

MultiAttach capable volume type
-------------------------------

In order to ensure that a volume is created on a backend that supports multiple
attachments, it will need to be created on a backend that allows this.  The
only way to safely control this is be requiring that a type of
"multiattach" is created and used on volume creation.

If an additional attach request is made to a volume that is NOT of the type
multi-attach enabled the request should fail as the volume is already in-use,
and either a new volume should be created of the correct type, or the volume
should be retyped.  Of course if the policy allows and the type is correct the
additional attachment request should be processed and the existing
attachment(s) are left active and NOT interrupted.

To avoid various corner cases and confusion for users in what's allowed and
what's not, this spec proposes we set a hard-code rule that disallows the
retyping of attachment parameters of an `in-use` volume.  Regardless of what
those changes are; multi-->non-multi, non-multi-->multi.

Any retype command should inspect the multiattach keys and if there is any
change being requested in said keys the retype should fail immediately at the
API service.

NOTE that the default will be multiattach:False

There is an additional required task, the `--allow-multiattach`
parameter included with volume create needs to be deprecated and it needs to be
very explicit that that flag is NOT relevant to the implementation of
multi-attach that is being proposed in this spec and implemented in Cinder API
microversion xyz.

Special considerations for force-detach; recent changes have been added that
treat things like detach of attachments with no connector as `force detach`
operations.  This should be fine in a multi-attach scenario because the force
detach is ONLY issued against that instantiation of an attachment.  In other
words the only thing force detach does is ignore state checks and disconnects
the specified session, leaving others intact.  The process on the Cinder side
should follow the standard multi-attach detach process with the exception of
ignoring the status of the volume.

FWIW that call rarely works as users expect anyway, so maybe this will be
a good time to revisit it.  Perhaps deprecate it, and include a force parameter
to the attachment-delete API call itself?

Alternatives
------------

* Be cloudy and write clustered apps
* Use things like independent data instances
* Get over it, you probably don't really need this

Data model impact
-----------------

N/A
All of the needed changes to the data model should already be in place.
Inparticular the existing `multiattach` column on the volume object, which
will signal the consumer that they're working with a multiattach capable
volume.  So, if a volume of type multiattach:True is requested/created,
it's multiattach column is set to True, else False.

To elaborate on the create flow:
Admin creates a volume type `multiattach` with extra-specs:
{
'multiattach': '<is> True'
}

If a user desires a multiattach volume, he/she issues a create call specifying
the multiattach type:
`cinder create --volume-type multiattach --name my-mavol 20`

If there are NO backends reporting `multiattach: True` then scheduling
will fail.  Unfortunatly this process includes the task-flow retries and the
object will be created, the caller will get a 202 response, but after taskflow
and the scheduler finish retries and fail to find a backend the volume status
will be set to error.  It may be possible to speed this up if we need to and
put capability checks into the API layer so that we could respond immediately
with an Invalid Request. We do provide an API call now that pulls capabilities
from the system, so we could make that check upon receipt of the create request
and make sure it's possible to fulfill the request.  It would probably be wise
to cache this info based on the periodic capability reporting instead of
fetching it each time.

REST API impact
---------------

This has a number of impacts on the API, the most obvious of which is the fact
that you can attach a volume multiple times.  The other changes that may not be
so obvious are things like representing a volume's attachment status, and
managing state changes when a secondary attachment is processed or removed.

The current representation of volume-status is likely to be insufficent once
multiple attachments are enabled.

Security impact
---------------

N/A

Notifications impact
--------------------

N/A

Other end user impact
---------------------

User can potentially attach a volume to multiple servers, and corrupt their
data.

Performance Impact
------------------

N/A

Developer impact
----------------

Drivers will need to add a capabilities field "multiattach: True/False", and
do any special handling on their end for connecting/disconnecting volumes in
this category.

Implementation
==============

Assignee(s)
-----------

Primary assignee:
  None

Other contributors:
  None

Work Items
----------

* Update Cinder attach/detach to accomodate shared targets
  (most of this is being done independently, see `Dependencies`
  section for more info)
* Implement policy changes
* Implement changes to API to allow/ignore existing attachments on
  attachment-create calls.
* Update the attach/detach volume-status transitions to be multiattach aware
  and make sure they reflect the correct values.
* Update the detail volume view and possibly the summary view to clearly inform
  the user when a volume is attached to multiple servers.

Dependencies
============

* Handling of disconnects for devices using shared targets
  Initial work is under review here:  https://review.openstack.org/#/c/520676/
  Additionally, the API will need a micro version bump and additions to the
  response views for volumes.
* Required patches for service-uuid have already merged
  https://review.openstack.org/#/c/519025/

Testing
=======

https://review.openstack.org/#/c/266605/

New unit tests will be added to test the changed code and functional testing
will need to be added as well.

Documentation Impact
====================

This will require updates to both deployment guides as well as end-user guides.

References
==========

.. [1] https://specs.openstack.org/openstack/cinder-specs/specs/ocata/add-new-attach-apis.html

Related Nova spec:
https://specs.openstack.org/openstack/nova-specs/specs/queens/approved/cinder-volume-multi-attach.html


text:
package uk.ac.ebi.eva.pipeline.configuration.jobs.steps;

import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import uk.ac.ebi.eva.pipeline.Application;
import uk.ac.ebi.eva.pipeline.configuration.BeanNames;
import uk.ac.ebi.eva.pipeline.configuration.jobs.DropStudyJobConfiguration;
import uk.ac.ebi.eva.test.configuration.BatchTestConfiguration;
import uk.ac.ebi.eva.test.rules.TemporaryMongoRule;
import uk.ac.ebi.eva.test.utils.JobTestUtils;
import uk.ac.ebi.eva.utils.EvaJobParameterBuilder;

import java.util.Arrays;
import java.util.Collections;

import static uk.ac.ebi.eva.test.utils.DropStudyJobTestUtils.assertDropFiles;
import static uk.ac.ebi.eva.test.utils.JobTestUtils.assertCompleted;

/**
 * Test for {@link DropFilesByStudyStepConfiguration}
 */
@RunWith(SpringRunner.class)
@ActiveProfiles({Application.VARIANT_WRITER_MONGO_PROFILE, Application.VARIANT_ANNOTATION_MONGO_PROFILE})
@TestPropertySource({"classpath:common-configuration.properties", "classpath:test-mongo.properties"})
@ContextConfiguration(classes = {DropStudyJobConfiguration.class, BatchTestConfiguration.class})
public class DropFilesByStudyStepTest {

    private static final String COLLECTION_FILES_NAME = "files";

    private static final long EXPECTED_FILES_AFTER_DROP_STUDY = 1;

    private static final String STUDY_ID_TO_DROP = "studyToDrop";

    private static final String OTHER_STUDY_ID = "otherStudy";

    private static final String FILES_DOCUMENT = JobTestUtils.buildFilesDocumentString(STUDY_ID_TO_DROP, "fileOne");

    private static final String OTHER_FILES_DOCUMENT = JobTestUtils.buildFilesDocumentString(STUDY_ID_TO_DROP,
            "fileTwo");

    private static final String OTHER_STUDY_FILES_DOCUMENT = JobTestUtils.buildFilesDocumentString(OTHER_STUDY_ID,
            "fileThree");

    @Rule
    public TemporaryMongoRule mongoRule = new TemporaryMongoRule();

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Test
    public void testNoFilesToDrop() throws Exception {
        String databaseName = mongoRule.createDBAndInsertDocuments(COLLECTION_FILES_NAME,
                Collections.singletonList(OTHER_STUDY_FILES_DOCUMENT));

        checkDrop(databaseName, EXPECTED_FILES_AFTER_DROP_STUDY);
    }

    @Test
    public void testOneFileToDrop() throws Exception {
        String databaseName = mongoRule.createDBAndInsertDocuments(COLLECTION_FILES_NAME,
                Arrays.asList(FILES_DOCUMENT, OTHER_STUDY_FILES_DOCUMENT));

        checkDrop(databaseName, EXPECTED_FILES_AFTER_DROP_STUDY);
    }

    @Test
    public void testSeveralFilesToDrop() throws Exception {
        String databaseName = mongoRule.createDBAndInsertDocuments(COLLECTION_FILES_NAME,
                Arrays.asList(FILES_DOCUMENT, OTHER_FILES_DOCUMENT, OTHER_STUDY_FILES_DOCUMENT));

        checkDrop(databaseName, EXPECTED_FILES_AFTER_DROP_STUDY);
    }

    private void checkDrop(String databaseName, long expectedFilesAfterDropStudy) {
        JobParameters jobParameters = new EvaJobParameterBuilder()
                .collectionFilesName(COLLECTION_FILES_NAME)
                .databaseName(databaseName)
                .inputStudyId(STUDY_ID_TO_DROP)
                .toJobParameters();

        JobExecution jobExecution = jobLauncherTestUtils.launchStep(BeanNames.DROP_FILES_BY_STUDY_STEP,
                jobParameters);

        assertCompleted(jobExecution);

        MongoCollection<Document> filesCollection = mongoRule.getCollection(databaseName, COLLECTION_FILES_NAME);
        assertDropFiles(filesCollection, STUDY_ID_TO_DROP, expectedFilesAfterDropStudy);
    }

}


text:
from base64 import b64encode
from django import VERSION
from django.utils import six
from django.test import TestCase
from pyquery.pyquery import PyQuery
from server.forms.client_validation import SubscribeForm as ClientValidatedForm
from server.forms.combined_validation import SubscribeForm as CombinedValidatedForm
from djangular.forms.angular_base import NgBoundField

class NgFormValidationMixinTest(TestCase):
    def setUp(self):
        self.subscription_form = ClientValidatedForm()
        self.dom = PyQuery(str(self.subscription_form))
        self.form_name = b64encode(six.b(self.subscription_form.__class__.__name__)).rstrip(six.b('=')).decode("utf-8")
        self.maxDiff = None

    def test_form(self):
        self.assertEqual(self.subscription_form.form_name, six.b(self.form_name))

    def test_ng_length(self):
        first_name = self.dom('input[name=first_name]')
        self.assertEqual(len(first_name), 1)
        attrib = dict(first_name[0].attrib.items())
        self.assertDictContainsSubset({'ng-required': 'true'}, attrib)
        self.assertDictContainsSubset({'ng-minlength': '3'}, attrib)
        self.assertDictContainsSubset({'ng-maxlength': '20'}, attrib)
        lis = self.dom('label[for=id_first_name]').closest('th').next('td').children('ul.djng-field-errors > li')
        if VERSION[1] == 5:
            # Django < 1.6 not not know about minlength and maxlength
            self.assertEqual(len(lis), 2)
        else:
            self.assertEqual(len(lis), 4)
        attrib = dict(lis[0].attrib.items())
        self.assertDictContainsSubset({'ng-show': self.form_name + '.first_name.$error.required'}, attrib)
        attrib = dict(lis[1].attrib.items())
        self.assertDictContainsSubset({'ng-show': self.form_name + six.u('.first_name.$error.minlength')}, attrib)

    def test_type(self):
        email_field = self.dom('input[name=email]')
        self.assertEqual(len(email_field), 1)
        attrib = dict(email_field[0].attrib.items())
        self.assertNotIn('required', attrib)
        self.assertDictContainsSubset({'ng-model': 'email'}, attrib)
        if VERSION[1] == 5:
            self.assertDictContainsSubset({'type': 'text'}, attrib)
        else:
            self.assertDictContainsSubset({'type': 'email'}, attrib)

    def test_regex(self):
        last_name = self.dom('input[name=last_name]')
        self.assertEqual(len(last_name), 1)
        attrib = dict(last_name[0].attrib.items())
        self.assertDictContainsSubset({'ng-pattern': '/^[A-Z][a-z -]?/'}, attrib)

    def test_field_as_ul(self):
        bf = self.subscription_form['email']
        ul_dirty = ''.join((
            '
',
            '
This field is required.
',
            '
Enter a valid email address.
',
            '

'
            '
'))
        self.assertTrue(ul_dirty in bf.errors.as_ul())
        ul_pristine = '

'
        self.assertTrue(ul_pristine in bf.errors.as_ul())

    def test_field_as_text(self):
        bf = self.subscription_form['email']
        self.assertIsInstance(bf, NgBoundField)
        response = bf.errors.as_text()
        self.assertMultiLineEqual(response, '* This field is required.\n* Enter a valid email address.')

class NgFormValidationWithModelMixinTest(TestCase):
    def setUp(self):
        subscription_form = CombinedValidatedForm(scope_prefix='subscribe_data')
        self.dom = PyQuery(str(subscription_form))

    def test_ng_model(self):
        first_name = self.dom('input[name=first_name]')
        self.assertEqual(len(first_name), 1)
        attrib = dict(first_name[0].attrib.items())
        self.assertDictContainsSubset({'ng-model': 'subscribe_data[\'first_name\']'}, attrib)

    def test_decimal_field(self):
        weight = self.dom('input[name=weight]')
        self.assertEqual(len(weight), 1)
        attrib = dict(weight[0].attrib.items())
        if VERSION[1] == 5:
            self.assertDictContainsSubset({'type': 'text'}, attrib)
        else:
            self.assertDictContainsSubset({'type': 'number'}, attrib)
        self.assertDictContainsSubset({'min': '42'}, attrib)
        self.assertDictContainsSubset({'max': '95'}, attrib)
        self.assertDictContainsSubset({'ng-model': 'subscribe_data[\'weight\']'}, attrib)

    def test_float_field(self):
        height = self.dom('input[name=height]')
        self.assertEqual(len(height), 1)
        attrib = dict(height[0].attrib.items())
        if VERSION[1] == 5:
            self.assertDictContainsSubset({'type': 'text'}, attrib)
        else:
            self.assertDictContainsSubset({'type': 'number'}, attrib)
            self.assertDictContainsSubset({'min': '1.48'}, attrib)
            self.assertDictContainsSubset({'max': '1.95'}, attrib)
        self.assertDictContainsSubset({'ng-model': 'subscribe_data[\'height\']'}, attrib)


text:
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.MouseEvent
       (js_initMouseEvent, initMouseEvent, js_getScreenX, getScreenX,
        js_getScreenY, getScreenY, js_getClientX, getClientX,
        js_getClientY, getClientY, js_getCtrlKey, getCtrlKey,
        js_getShiftKey, getShiftKey, js_getAltKey, getAltKey,
        js_getMetaKey, getMetaKey, js_getButton, getButton,
        js_getRelatedTarget, getRelatedTarget, js_getMovementX,
        getMovementX, js_getMovementY, getMovementY, js_getOffsetX,
        getOffsetX, js_getOffsetY, getOffsetY, js_getX, getX, js_getY,
        getY, js_getFromElement, getFromElement, js_getToElement,
        getToElement, js_getDataTransfer, getDataTransfer, MouseEvent,
        castToMouseEvent, gTypeMouseEvent, IsMouseEvent, toMouseEvent)
       where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.JSFFI.Generated.Enums

foreign import javascript unsafe
        "$1[\"initMouseEvent\"]($2, $3, $4,\n$5, $6, $7, $8, $9, $10, $11,\n$12, $13, $14, $15, $16)"
        js_initMouseEvent ::
        MouseEvent ->
          JSString ->
            Bool ->
              Bool ->
                Nullable Window ->
                  Int ->
                    Int ->
                      Int ->
                        Int ->
                          Int ->
                            Bool ->
                              Bool -> Bool -> Bool -> Word -> Nullable EventTarget -> IO ()

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.initMouseEvent Mozilla MouseEvent.initMouseEvent documentation>
initMouseEvent ::
               (MonadIO m, IsMouseEvent self, ToJSString type',
                IsEventTarget relatedTarget) =>
                 self ->
                   type' ->
                     Bool ->
                       Bool ->
                         Maybe Window ->
                           Int ->
                             Int ->
                               Int ->
                                 Int ->
                                   Int ->
                                     Bool ->
                                       Bool -> Bool -> Bool -> Word -> Maybe relatedTarget -> m ()
initMouseEvent self type' canBubble cancelable view detail screenX
  screenY clientX clientY ctrlKey altKey shiftKey metaKey button
  relatedTarget
  = liftIO
      (js_initMouseEvent (toMouseEvent self) (toJSString type') canBubble
         cancelable
         (maybeToNullable view)
         detail
         screenX
         screenY
         clientX
         clientY
         ctrlKey
         altKey
         shiftKey
         metaKey
         button
         (maybeToNullable (fmap toEventTarget relatedTarget)))

foreign import javascript unsafe "$1[\"screenX\"]" js_getScreenX ::
        MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.screenX Mozilla MouseEvent.screenX documentation>
getScreenX :: (MonadIO m, IsMouseEvent self) => self -> m Int
getScreenX self = liftIO (js_getScreenX (toMouseEvent self))

foreign import javascript unsafe "$1[\"screenY\"]" js_getScreenY ::
        MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.screenY Mozilla MouseEvent.screenY documentation>
getScreenY :: (MonadIO m, IsMouseEvent self) => self -> m Int
getScreenY self = liftIO (js_getScreenY (toMouseEvent self))

foreign import javascript unsafe "$1[\"clientX\"]" js_getClientX ::
        MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.clientX Mozilla MouseEvent.clientX documentation>
getClientX :: (MonadIO m, IsMouseEvent self) => self -> m Int
getClientX self = liftIO (js_getClientX (toMouseEvent self))

foreign import javascript unsafe "$1[\"clientY\"]" js_getClientY ::
        MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.clientY Mozilla MouseEvent.clientY documentation>
getClientY :: (MonadIO m, IsMouseEvent self) => self -> m Int
getClientY self = liftIO (js_getClientY (toMouseEvent self))

foreign import javascript unsafe "($1[\"ctrlKey\"] ? 1 : 0)"
        js_getCtrlKey :: MouseEvent -> IO Bool

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.ctrlKey Mozilla MouseEvent.ctrlKey documentation>
getCtrlKey :: (MonadIO m, IsMouseEvent self) => self -> m Bool
getCtrlKey self = liftIO (js_getCtrlKey (toMouseEvent self))

foreign import javascript unsafe "($1[\"shiftKey\"] ? 1 : 0)"
        js_getShiftKey :: MouseEvent -> IO Bool

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.shiftKey Mozilla MouseEvent.shiftKey documentation>
getShiftKey :: (MonadIO m, IsMouseEvent self) => self -> m Bool
getShiftKey self = liftIO (js_getShiftKey (toMouseEvent self))

foreign import javascript unsafe "($1[\"altKey\"] ? 1 : 0)"
        js_getAltKey :: MouseEvent -> IO Bool

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.altKey Mozilla MouseEvent.altKey documentation>
getAltKey :: (MonadIO m, IsMouseEvent self) => self -> m Bool
getAltKey self = liftIO (js_getAltKey (toMouseEvent self))

foreign import javascript unsafe "($1[\"metaKey\"] ? 1 : 0)"
        js_getMetaKey :: MouseEvent -> IO Bool

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.metaKey Mozilla MouseEvent.metaKey documentation>
getMetaKey :: (MonadIO m, IsMouseEvent self) => self -> m Bool
getMetaKey self = liftIO (js_getMetaKey (toMouseEvent self))

foreign import javascript unsafe "$1[\"button\"]" js_getButton ::
        MouseEvent -> IO Word

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button Mozilla MouseEvent.button documentation>
getButton :: (MonadIO m, IsMouseEvent self) => self -> m Word
getButton self = liftIO (js_getButton (toMouseEvent self))

foreign import javascript unsafe "$1[\"relatedTarget\"]"
        js_getRelatedTarget :: MouseEvent -> IO (Nullable EventTarget)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.relatedTarget Mozilla MouseEvent.relatedTarget documentation>
getRelatedTarget ::
                 (MonadIO m, IsMouseEvent self) => self -> m (Maybe EventTarget)
getRelatedTarget self
  = liftIO
      (nullableToMaybe <$> (js_getRelatedTarget (toMouseEvent self)))

foreign import javascript unsafe "$1[\"movementX\"]"
        js_getMovementX :: MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.movementX Mozilla MouseEvent.movementX documentation>
getMovementX :: (MonadIO m, IsMouseEvent self) => self -> m Int
getMovementX self = liftIO (js_getMovementX (toMouseEvent self))

foreign import javascript unsafe "$1[\"movementY\"]"
        js_getMovementY :: MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.movementY Mozilla MouseEvent.movementY documentation>
getMovementY :: (MonadIO m, IsMouseEvent self) => self -> m Int
getMovementY self = liftIO (js_getMovementY (toMouseEvent self))

foreign import javascript unsafe "$1[\"offsetX\"]" js_getOffsetX ::
        MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.offsetX Mozilla MouseEvent.offsetX documentation>
getOffsetX :: (MonadIO m, IsMouseEvent self) => self -> m Int
getOffsetX self = liftIO (js_getOffsetX (toMouseEvent self))

foreign import javascript unsafe "$1[\"offsetY\"]" js_getOffsetY ::
        MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.offsetY Mozilla MouseEvent.offsetY documentation>
getOffsetY :: (MonadIO m, IsMouseEvent self) => self -> m Int
getOffsetY self = liftIO (js_getOffsetY (toMouseEvent self))

foreign import javascript unsafe "$1[\"x\"]" js_getX ::
        MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.x Mozilla MouseEvent.x documentation>
getX :: (MonadIO m, IsMouseEvent self) => self -> m Int
getX self = liftIO (js_getX (toMouseEvent self))

foreign import javascript unsafe "$1[\"y\"]" js_getY ::
        MouseEvent -> IO Int

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.y Mozilla MouseEvent.y documentation>
getY :: (MonadIO m, IsMouseEvent self) => self -> m Int
getY self = liftIO (js_getY (toMouseEvent self))

foreign import javascript unsafe "$1[\"fromElement\"]"
        js_getFromElement :: MouseEvent -> IO (Nullable Node)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.fromElement Mozilla MouseEvent.fromElement documentation>
getFromElement ::
               (MonadIO m, IsMouseEvent self) => self -> m (Maybe Node)
getFromElement self
  = liftIO
      (nullableToMaybe <$> (js_getFromElement (toMouseEvent self)))

foreign import javascript unsafe "$1[\"toElement\"]"
        js_getToElement :: MouseEvent -> IO (Nullable Node)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.toElement Mozilla MouseEvent.toElement documentation>
getToElement ::
             (MonadIO m, IsMouseEvent self) => self -> m (Maybe Node)
getToElement self
  = liftIO
      (nullableToMaybe <$> (js_getToElement (toMouseEvent self)))

foreign import javascript unsafe "$1[\"dataTransfer\"]"
        js_getDataTransfer :: MouseEvent -> IO (Nullable DataTransfer)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.dataTransfer Mozilla MouseEvent.dataTransfer documentation>
getDataTransfer ::
                (MonadIO m, IsMouseEvent self) => self -> m (Maybe DataTransfer)
getDataTransfer self
  = liftIO
      (nullableToMaybe <$> (js_getDataTransfer (toMouseEvent self)))


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: soc2013/dpl/head/usr.bin/make/for.c 229274 2011-12-30 11:02:40Z uqs $");

/*-
 * for.c --
 *	Functions to handle loops in a makefile.
 *
 * Interface:
 *	For_Eval 	Evaluate the loop in the passed line.
 *	For_Run		Run accumulated loop
 *
 */

#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#include "buf.h"
#include "for.h"
#include "globals.h"
#include "lst.h"
#include "parse.h"
#include "str.h"
#include "util.h"
#include "var.h"

/*
 * For statements are of the form:
 *
 * .for <variable> in <varlist>
 * ...
 * .endfor
 *
 * The trick is to look for the matching end inside for for loop
 * To do that, we count the current nesting level of the for loops.
 * and the .endfor statements, accumulating all the statements between
 * the initial .for loop and the matching .endfor;
 * then we evaluate the for loop for each variable in the varlist.
 */

static int	forLevel = 0;	/* Nesting level */
static char	*forVar;	/* Iteration variable */
static Buffer	*forBuf;	/* Commands in loop */
static Lst	forLst;		/* List of items */

/**
 * For_For
 *	Evaluate the for loop in the passed line. The line
 *	looks like this:
 *	    .for <variable> in <varlist>
 *	The line pointer points just behind the for.
 *
 * Results:
 *	TRUE: Syntax ok.
 *	FALSE: Syntax error.
 */
Boolean
For_For(char *line)
{
	char	*ptr;
	char	*wrd;
	char	*sub;
	Buffer	*buf;
	size_t	varlen;
	int	i;
	ArgArray words;

	ptr = line;

	/*
	 * Skip space between for and the variable.
	 */
	for (ptr++; *ptr && isspace((u_char)*ptr); ptr++)
		;

	/*
	 * Grab the variable
	 */
	for (wrd = ptr; *ptr && !isspace((u_char)*ptr); ptr++)
		;

	buf = Buf_Init(0);
	Buf_AppendRange(buf, wrd, ptr);
	forVar = Buf_GetAll(buf, &varlen);

	if (varlen == 0) {
		Buf_Destroy(buf, TRUE);
		Parse_Error(PARSE_FATAL, "missing variable in for");
		return (FALSE);
	}
	Buf_Destroy(buf, FALSE);

	/*
	 * Skip to 'in'.
	 */
	while (*ptr && isspace((u_char)*ptr))
		ptr++;

	/*
	 * Grab the `in'
	 */
	if (ptr[0] != 'i' || ptr[1] != 'n' || !isspace((u_char)ptr[2])) {
		free(forVar);
		Parse_Error(PARSE_FATAL, "missing `in' in for");
		fprintf(stderr, "%s\n", ptr);
		return (FALSE);
	}
	ptr += 3;

	/*
	 * Skip to values
	 */
	while (*ptr && isspace((u_char)*ptr))
		ptr++;

	/*
	 * Make a list with the remaining words
	 */
	sub = Buf_Peel(Var_Subst(ptr, VAR_CMD, FALSE));
	brk_string(&words, sub, FALSE);
	Lst_Init(&forLst);
	for (i = 1; i < words.argc; i++) {
		if (words.argv[i][0] != '\0')
			Lst_AtFront(&forLst, estrdup(words.argv[i]));
	}
	ArgArray_Done(&words);
	DEBUGF(FOR, ("For: Iterator %s List %s\n", forVar, sub));
	free(sub);

	forBuf = Buf_Init(0);
	forLevel++;
	return (TRUE);
}

/**
 * For_Eval
 *	Eat a line of the .for body looking for embedded .for loops
 *	and the .endfor
 */
Boolean
For_Eval(char *line)
{
	char *ptr;

	ptr = line;

	if (*ptr == '.') {
		/*
		 * Need to check for 'endfor' and 'for' to find the end
		 * of our loop or to find embedded for loops.
		 */
		for (ptr++; *ptr != '\0' && isspace((u_char)*ptr); ptr++)
			;

		/* XXX the isspace is wrong */
		if (strncmp(ptr, "endfor", 6) == 0 &&
		    (isspace((u_char)ptr[6]) || ptr[6] == '\0')) {
			DEBUGF(FOR, ("For: end for %d\n", forLevel));
			if (forLevel == 0) {
				/* should not be here */
				abort();
			}
			forLevel--;

		} else if (strncmp(ptr, "for", 3) == 0 &&
		    isspace((u_char)ptr[3])) {
			forLevel++;
			DEBUGF(FOR, ("For: new loop %d\n", forLevel));
		}
	}

	if (forLevel != 0) {
		/*
		 * Still in loop - append the line
		 */
		Buf_Append(forBuf, line);
		Buf_AddByte(forBuf, (Byte)'\n');
		return (TRUE);
	}

	return (FALSE);
}

/*-
 *-----------------------------------------------------------------------
 * For_Run --
 *	Run the for loop, imitating the actions of an include file
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	The values of the variables forLst, forVar and forBuf are freed.
 *
 *-----------------------------------------------------------------------
 */
void
For_Run(int lineno)
{
	Lst		values;	/* list of values for the variable */
	char		*var;	/* the variable's name */
	Buffer		*buf;	/* the contents of the for loop */
	const char	*val;	/* current value of loop variable */
	LstNode		*ln;
	char		*str;

	if (forVar == NULL || forBuf == NULL)
		return;

	/* copy the global variables to have them free for embedded fors */
	var = forVar;
	buf = forBuf;
	Lst_Init(&values);
	Lst_Concat(&values, &forLst, LST_CONCLINK);

	forVar = NULL;
	forBuf = NULL;

	LST_FOREACH(ln, &values) {
		val = Lst_Datum(ln);
		Var_SetGlobal(var, val);

		DEBUGF(FOR, ("--- %s = %s\n", var, val));
		str = Buf_Peel(Var_SubstOnly(var, Buf_Data(buf), FALSE));

		Parse_FromString(str, lineno);
		Var_Delete(var, VAR_GLOBAL);
	}

	free(var);
	Lst_Destroy(&values, free);
	Buf_Destroy(buf, TRUE);
}


text:
package text.parser

import text.normalizer._
import text.{StringNone, StringOption, StringSome}
import util.Config
import util.primitive._

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.Source
import scala.util.matching.Regex
import scala.util.matching.Regex.Match

/**
  * @author ynupc
  *         Created on 2016/02/21
  */
object SentenceQuotationParser {
  private type Quotation = (String, String)
  private type QuotationSentence = (Quotation, QuotedSentence)

  private final val quotations: Seq[Quotation] = {
    val buffer = ListBuffer.empty[Quotation]
    Source.fromFile(
      Config.resourceFile("parser", "quotation.csv").toFile
    ).getLines foreach {
      line: String =>
        val quotations: Array[String] = line.trim.split(',')
        if (2 <= quotations.length) {
          val headOpt: StringOption = StringOption(quotations.head.trim)
          val lastOpt: StringOption = StringOption(quotations.last.trim)
          if (headOpt.nonEmpty && lastOpt.nonEmpty) {
            buffer += ((headOpt.get, lastOpt.get))
          }
        }
    }
    buffer.result
  }

  private def getUnContainedNoun(text: String, nouns: Seq[String]): String = {
    nouns foreach {
      noun: String =>
        if (!text.contains(noun)) {
          return noun
        }
    }
    throw new NoSuchElementException("SentenceQuotationParser.getUnContainedNoun")
  }

  def parse(sentenceOpt: StringOption): Option[QuotedSentence] = {
    sentenceOpt match {
      case StringSome(sentence) =>
        Option(parse(sentence, ListBuffer.empty[String] ++ EscapeNoun.objects))
      case StringNone =>
        None
    }
  }

  private def getFirstMatchOpt(sentence: String): Option[(Quotation, Range)] = {
    val quotationRangeBuffer = ListBuffer.empty[(Quotation, Range)]
    var firstMatchOpt: Option[(Quotation, Range)] = None

    quotations foreach {
      quotation: Quotation =>
        val regex: Regex = ".+".quote(quotation).r
        regex.findFirstMatchIn(sentence) foreach {
          m: Match =>
            quotationRangeBuffer += ((quotation, Range(m.start, m.end)))
        }
    }

    if (quotationRangeBuffer.nonEmpty) {
      quotationRangeBuffer foreach {
        case (quotation, range) =>
          if (firstMatchOpt.isEmpty || (range.start < firstMatchOpt.get._2.start)) {
            firstMatchOpt = Some((quotation, range))
          }
        case _ =>
          //Do nothing
      }
    }

    firstMatchOpt
  }

  private def parse(sentence: String, nouns: ListBuffer[String]): QuotedSentence = {
    var parentSentence: String = sentence
    val childrenSentences = mutable.Map.empty[String, QuotationSentence]

    var firstMatchOpt: Option[(Quotation, Range)] = getFirstMatchOpt(sentence)

    while (firstMatchOpt.nonEmpty) {
      val (quotation, range): (Quotation, Range) = firstMatchOpt.get
      val start: Int = range.start
      val end:   Int = range.end
      val prefix:     String = parentSentence.substring(0, start)
      val quotedPart: String = parentSentence.substring(start, end)
      val suffix:     String = parentSentence.substring(end)
      val noun:       String = getUnContainedNoun(parentSentence, nouns)
      nouns -= noun
      parentSentence = noun.quote((prefix, suffix))
      childrenSentences.put(noun, (quotation, parse(quotedPart, nouns)))
      firstMatchOpt = getFirstMatchOpt(sentence)
    }

    new QuotedSentence(parentSentence, childrenSentences.toMap)
  }

  class QuotedSentence(val parentSentence: String,
                               val childrenSentences: Map[String, QuotationSentence]) {
    override def toString: String = {
      var text: String = parentSentence
      childrenSentences foreach {
        case (replacement, (quotation, sentence)) =>
          text = text.replaceAllLiteratim(
            replacement,
            sentence.toString.quote(quotation))
        case _ =>
          //Do nothing
      }
      text
    }
  }

  def splitAndQuotationParseJapaneseText(textOpt: StringOption): Seq[NormalizedQuotedSentence] = {
    val buffer = ListBuffer.empty[NormalizedQuotedSentence]
    JapaneseSentenceSplitter.split(textOpt) foreach {
      sentence =>
        parse(StringOption(sentence.text)) match {
          case Some(quotedSentence) =>
            buffer += new NormalizedQuotedSentence(sentence.originalText, quotedSentence)
          case None =>
            //Do nothing
        }
    }
    buffer.result
  }

  class NormalizedQuotedSentence(val originalText: String,
                                 val quotedSentence: QuotedSentence) {
    override def toString: String = quotedSentence.toString
  }
}


text:
namespace mxtest
{
    mx::core::IdentificationPtr tgenIdentification( TestMode v );
    void tgenIdentificationExpected(std::ostream& os, int indentLevel, TestMode v );
}

#endif


text:
{% extends path+"/citizen/app/_layout.html" %}

{% block app_nav %}{{ nav.app_nav('hearread',path) }}{% endblock %}

{% block case_content %}

Hearing and reading

Tony doesn't have any problem with this

{% endblock %}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Verh. Batav. Benootsch. Kunsten 11:164. 1826

#### Original name
null

### Remarks
null


text:
package db

import (
	"database/sql"
	"fmt"
	"io"
	"time"

	"github.com/builderscon/octav/octav/tools"
	"github.com/pkg/errors"
)

func compileRangeWhere(dst io.Writer, args *[]interface{}, since int64, rangeStart, rangeEnd time.Time) error {
	where := tools.GetBuffer()
	defer tools.ReleaseBuffer(where)

	where.WriteString(ConferenceTable)
	where.WriteString(".oid > ?")
	*args = append(*args, since)

	if !rangeStart.IsZero() {
		if where.Len() > 0 {
			where.WriteString(" AND ")
		}
		where.WriteString(ConferenceDateTable)
		where.WriteString(".open >= ?")
		*args = append(*args, rangeStart)
	}

	if !rangeEnd.IsZero() {
		if where.Len() > 0 {
			where.WriteString(" AND ")
		}
		where.WriteString(ConferenceDateTable)
		where.WriteString(".open <= ?")
		*args = append(*args, rangeEnd)
	}

	toWrite := where.Len()
	n, err := where.WriteTo(dst)
	if n != int64(toWrite) {
		if err != nil {
			return errors.Wrap(err, "failed to write where clause to destination")
		}
		return errors.New("failed to write entire where clause to destination")
	}
	return nil
}

func (v *ConferenceList) LoadFromQuery(tx *sql.Tx, status, organizerID []string, rangeStart, rangeEnd time.Time, since string, limit int) error {
	// We need the oid of "since"
	var sinceOID int64
	if since != "" {
		var vdb Conference
		if err := vdb.LoadByEID(tx, since); err != nil {
			return errors.Wrap(err, "failed to load reference row")
		}
		sinceOID = vdb.OID
	}

	qbuf := tools.GetBuffer()
	defer tools.ReleaseBuffer(qbuf)

	var hasDate bool
	if !rangeStart.IsZero() || !rangeEnd.IsZero() {
		hasDate = true
	}

	qbuf.WriteString(`SELECT DISTINCT `)
	qbuf.WriteString(ConferenceStdSelectColumns)
	qbuf.WriteString(` FROM `)
	qbuf.WriteString(ConferenceTable)
	if hasDate {
		qbuf.WriteString(` JOIN `)
		qbuf.WriteString(ConferenceDateTable)
		qbuf.WriteString(` ON `)
		qbuf.WriteString(ConferenceTable)
		qbuf.WriteString(`.eid = `)
		qbuf.WriteString(ConferenceDateTable)
		qbuf.WriteString(`.conference_id `)
	}
	if len(organizerID) > 0 {
		qbuf.WriteString(` JOIN `)
		qbuf.WriteString(ConferenceAdministratorTable)
		qbuf.WriteString(` ON `)
		qbuf.WriteString(ConferenceTable)
		qbuf.WriteString(`.eid = `)
		qbuf.WriteString(ConferenceAdministratorTable)
		qbuf.WriteString(`.conference_id `)
	}

	wherebuf := tools.GetBuffer()
	defer tools.ReleaseBuffer(wherebuf)

	var args []interface{}

	if !rangeStart.IsZero() || !rangeEnd.IsZero() {
		if err := compileRangeWhere(wherebuf, &args, sinceOID, rangeStart, rangeEnd); err != nil {
			return errors.Wrap(err, "failed to compile range where clause")
		}
	}

	if len(organizerID) > 0 {
		if wherebuf.Len() > 0 {
			wherebuf.WriteString(` AND `)
		}
		wherebuf.WriteString(ConferenceAdministratorTable)
		wherebuf.WriteString(`.user_id IN (`)
		for i, id := range organizerID {
			wherebuf.WriteByte('?')
			if i < len(organizerID)-1 {
				wherebuf.WriteByte(',')
			}
			args = append(args, id)
		}
		wherebuf.WriteByte(')')
	}

	if len(status) > 0 {
		if wherebuf.Len() > 0 {
			wherebuf.WriteString(` AND `)
		}
		wherebuf.WriteString(ConferenceTable)
		wherebuf.WriteString(`.status IN (`)
		for i, st := range status {
			wherebuf.WriteByte('?')
			if i < len(status)-1 {
				wherebuf.WriteByte(',')
			}
			args = append(args, st)
		}
		wherebuf.WriteByte(')')
	}

	if wherebuf.Len() > 0 {
		qbuf.WriteString(` WHERE `)
		wherebuf.WriteTo(qbuf)
	}

	qbuf.WriteString(` ORDER BY oid DESC`)
	fmt.Fprintf(qbuf, " LIMIT %d", limit)

	return v.execSQLAndExtract(tx, qbuf.String(), limit, args...)
}

func (v *ConferenceList) LoadByRange(tx *sql.Tx, since string, rangeStart, rangeEnd time.Time, limit int) error {
	// We need the oid of "since"
	var sinceOID int64
	if since != "" {
		var vdb Conference
		if err := vdb.LoadByEID(tx, since); err != nil {
			return errors.Wrap(err, "failed to load reference row")
		}
		sinceOID = vdb.OID
	}

	// Use JOIN later
	var args []interface{}
	qbuf := tools.GetBuffer()
	defer tools.ReleaseBuffer(qbuf)

	var hasDate bool
	if !rangeStart.IsZero() || !rangeEnd.IsZero() {
		hasDate = true
	}

	qbuf.WriteString(`SELECT `)
	qbuf.WriteString(ConferenceStdSelectColumns)
	qbuf.WriteString(` FROM `)
	qbuf.WriteString(ConferenceTable)
	if hasDate {
		qbuf.WriteString(` JOIN `)
		qbuf.WriteString(ConferenceDateTable)
		qbuf.WriteString(` ON `)
		qbuf.WriteString(ConferenceTable)
		qbuf.WriteString(`.eid = `)
		qbuf.WriteString(ConferenceDateTable)
		qbuf.WriteString(`.conference_id `)
	}

	qbuf.WriteString(` WHERE `)
	if err := compileRangeWhere(qbuf, &args, sinceOID, rangeStart, rangeEnd); err != nil {
		return errors.Wrap(err, "failed to compile range where clause")
	}

	if hasDate {
		qbuf.WriteString(` ORDER BY `)
		qbuf.WriteString(ConferenceDateTable)
		qbuf.WriteString(`.date DESC`)
	} else {
		qbuf.WriteString(` ORDER BY oid DESC`)
	}

	fmt.Fprintf(qbuf, " LIMIT %d", limit)
	return v.execSQLAndExtract(tx, qbuf.String(), limit, args...)
}

func (v *ConferenceList) execSQLAndExtract(tx *sql.Tx, sql string, limit int, args ...interface{}) error {
	rows, err := tx.Query(sql, args...)
	if err != nil {
		return err
	}

	res := make(ConferenceList, 0, limit)
	for rows.Next() {
		row := Conference{}
		if err := row.Scan(rows); err != nil {
			return err
		}
		res = append(res, row)
	}
	*v = res
	return nil
}

func ListConferencesByOrganizer(tx *sql.Tx, l *ConferenceList, orgID string, statuses []string, since string, limit int) error {
	stmt := tools.GetBuffer()
	defer tools.ReleaseBuffer(stmt)

	stmt.WriteString(`SELECT `)
	stmt.WriteString(ConferenceStdSelectColumns)
	stmt.WriteString(` FROM `)
	stmt.WriteString(ConferenceTable)
	stmt.WriteString(` JOIN `)
	stmt.WriteString(ConferenceAdministratorTable)
	stmt.WriteString(` ON `)
	stmt.WriteString(ConferenceTable)
	stmt.WriteString(`.eid = `)
	stmt.WriteString(ConferenceAdministratorTable)
	stmt.WriteString(`.conference_id WHERE `)
	stmt.WriteString(ConferenceTable)

	if len(statuses) == 0 {
		statuses = []string{"public"}
	}
	stmt.WriteString(`.status IN (`)
	for i := range statuses {
		stmt.WriteByte('?')
		if i != len(statuses)-1 {
			stmt.WriteByte(',')
		}
	}
	stmt.WriteString(`) AND `)
	stmt.WriteString(ConferenceAdministratorTable)
	stmt.WriteString(`.user_id = ? `)
	if since != "" {
		// Unimplemented
	}
	if limit > 0 {
		// Unimplemented
	}

	rows, err := tx.Query(stmt.String(), orgID)
	if err != nil {
		return errors.Wrap(err, "failed to execute query")
	}
	res := make(ConferenceList, 0, limit)
	for rows.Next() {
		row := Conference{}
		if err := row.Scan(rows); err != nil {
			return err
		}
		res = append(res, row)
	}
	*l = res
	return nil
}


text:
package com.sumologic.sumobot.plugins.chuck

import com.sumologic.sumobot.test.annotated.SumoBotSpec
import play.api.libs.json.Json

class ChuckNorrisTest extends SumoBotSpec {
  val jsonText = "{ \"type\": \"success\", \"value\": { \"id\": 518, \"joke\": \"Chuck Norris doesn't cheat death. He wins fair and square.\", \"categories\": [] } }"

  "ChuckNorris" should {
    "parse JSON" in {
      val json = Json.parse(jsonText)
      val joke = json \ "value" \ "joke"
      joke.as[String] should be ("Chuck Norris doesn't cheat death. He wins fair and square.")
    }
  }
}


text:
<?php

namespace Larabros\Elogram\Http\Sessions;

/**
 * Defines an interface for getting and setting values from a data store.
 *
 * @package    Elogram
 * @author     Hassan Khan <contact@hassankhan.me>
 * @link       https://github.com/larabros/elogram
 * @license    MIT
 */
interface DataStoreInterface
{
    /**
     * Get a value from a data store.
     *
     * @param string $key
     *
     * @return mixed
     */
    public function get($key);

    /**
     * Set a value in the data store.
     *
     * @param string $key
     * @param mixed  $value
     *
     * @return  void
     */
    public function set($key, $value);
}


text:
package se.unlogic.standardutils.collections;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class StrictHashMap<Key, Value> implements StrictMap<Key, Value>{

	HashMap<Key, Value> hashMap = new HashMap<Key, Value>();

	public Value put(Key key, Value value) throws KeyAlreadyCachedException {
		if (this.hashMap.containsKey(key)) {
			throw new KeyAlreadyCachedException(key);
		} else {
			return hashMap.put(key, value);
		}
	}

	public Value update(Key key, Value value) throws KeyNotCachedException {
		if (this.hashMap.containsKey(key)) {
			hashMap.remove(key);
			return hashMap.put(key, value);
		} else {
			throw new KeyNotCachedException(key);
		}
	}

	public Value remove(Object key) throws KeyNotCachedException {
		if (hashMap.containsKey(key)) {
			return hashMap.remove(key);
		} else {
			throw new KeyNotCachedException(key);
		}
	}

	public void clear() {
		hashMap.clear();
	}

	@Override
	public Object clone() {
		return hashMap.clone();
	}

	public boolean containsKey(Object key) {
		return hashMap.containsKey(key);
	}

	public boolean containsValue(Object value) {
		return hashMap.containsValue(value);
	}

	public Set<Entry<Key, Value>> entrySet() {
		return hashMap.entrySet();
	}

	@Override
	public boolean equals(Object o) {
		return hashMap.equals(o);
	}

	public Value get(Object key) {
		return hashMap.get(key);
	}

	@Override
	public int hashCode() {
		return hashMap.hashCode();
	}

	public boolean isEmpty() {
		return hashMap.isEmpty();
	}

	public Set<Key> keySet() {
		return hashMap.keySet();
	}

	public int size() {
		return hashMap.size();
	}

	@Override
	public String toString() {
		return hashMap.toString();
	}

	public Collection<Value> values() {
		return hashMap.values();
	}

	public void putAll(Map<? extends Key, ? extends Value> map) throws KeyAlreadyCachedException{

		for (Entry<? extends Key, ? extends Value> entry : map.entrySet()) {

			if (this.hashMap.containsKey(entry.getKey())) {
				throw new KeyAlreadyCachedException(entry.getKey());
			}
		}

		this.hashMap.putAll(map);
	}
}


text:
<!doctype html>

	<meta charset="utf-8">

	<title>Finding the Optimal k for k-means through examination of BIC</title>

	<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
	<meta name="author" content="Hakim El Hattab">

	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

	<link rel="stylesheet" href="css/reveal.css">
	<link rel="stylesheet" href="css/theme/black.css" id="theme">

	<link rel="stylesheet" href="./lib/css/zenburn.css">

	<link rel="stylesheet" href="fonts/gentona/gentona.css">
	<link rel="stylesheet" href="fonts/titling-gothic/titling-gothic.css">
	<link rel="stylesheet" href="fonts/quadon/quadon.css">
	<link rel="stylesheet" href="fonts/arnhem/arnhem.css">

Finding the Optimal k for k-means through examination of BIC for MoG

May 6, 2016

neurodata

600.692 Advanced Topics in Machine Learning: Modeling and Segmentation

						Ron S. Boger, PI: Joshua T. Vogelstein

How many clusters?

Definitions

Unimodal

Theory

Numercal Experiments

Results


text:
"""
Tests for `myscipkg2` module.
"""
import unittest
import myscipkg2

class TestMyscipkg2(unittest.TestCase):

    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<script src="../webcomponentsjs/webcomponents-hi.js"></script>
    <link rel="import" href="suggestions-holder.html">
    <link rel="import" href="../vaadin-combo-box/vaadin-combo-box.html">
	<style>
		body {
			margin: 0;
		}

		#holder {
			flex: 1;
		}

		vaadin-combo-box-overlay {
			width: 100%;
		}
	</style>
</head>
<body>
	<vaadin-combo-box style="display: none;"></vaadin-combo-box>
	<suggestions-holder id="holder"></suggestions-holder>
</body>
</html>


text:
class Nagira < Sinatra::Base
  # Singleton class. Handles updates to the of the Nagios external commands file.
  #
  # Example usage:
  #
  #    Writer.commands = <path to the external command execution file>
  #
  class Writer

    @@commands = nil

    def initialize(action)
      @action = action
    end

    # Send PUT update to Nagios::ExternalCommands
    #
    # @param action [Symbol] Nagios external command name
    # @param params [Hash] Parsed Hash from PUT request input.
    #
    # FIXME: This only accepts single service. Modify to use Arrays too
    def put(params)

      res = @@commands.write(
        params.merge({ :action => @action })
      )
      { :result => res[:result], :object => res[:data]}
    end

    def write
    end

    # State structure keep all the Nagios parsed state information for
    # :objects, :status, :config, etc. as well as "inflight" data.
    attr_accessor :state

    class << self

      def commands=(commands_file)
        @@commands = Nagios::ExternalCommands.new(commands_file)
      end

      def commands
        @@commands
      end

    end
  end
end


text:
package org.wso2.carbon.membership.scheme.kubernetes.api;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class KubernetesHttpApiEndpoint extends KubernetesApiEndpoint {

    private static final Log log = LogFactory.getLog(KubernetesHttpApiEndpoint.class);

    public KubernetesHttpApiEndpoint(URL url) {
        super(url);
    }

    @Override
    public void createConnection() throws IOException {
        if (log.isDebugEnabled()) {
            log.debug("Connecting to Kubernetes API server...");
        }
        connection = (HttpURLConnection) url.openConnection();
        if (log.isDebugEnabled()) {
            log.debug("Connected to Kubernetes API server successfully");
        }
    }

    @Override
    public void createConnection(String username, String password) throws IOException {
        if (log.isDebugEnabled()) {
            log.debug("Connecting to Kubernetes API server with basic auth...");
        }
        connection = (HttpURLConnection) url.openConnection();
        createBasicAuthenticationHeader(username, password);
        if (log.isDebugEnabled()) {
            log.debug("Connected to Kubernetes API server with basic auth successfully");
        }
    }

    @Override
    public void disconnect() {
        connection.disconnect();
        if (log.isDebugEnabled()) {
            log.debug("Disconnected from Kubernetes API server successfully");
        }
    }
}


text:
extern crate rustc_middle;
extern crate rustc_driver;

use rustc_driver::plugin::Registry;

#[no_mangle]
fn __rustc_plugin_registrar(_: &mut Registry) {}


text:
package com.example.pslin_sizebook;

import android.app.Application;
import android.widget.ArrayAdapter;

import java.util.ArrayList;

/**
 * Created by Pierre Lin on 2/1/2017.
 * This class exists to make recordsList and FILENAME global
 * so that all activities can access them
 */
//taken from http://stackoverflow.com/questions/11932178/in-android-how-to-make-array-list-available-to-one-or-more-activities
    //Feb 1, 2017, 19:54
public class MyApplication extends Application {

    public ArrayList<Record> recordsList = null;
    public static final String FILENAME = "file.sav";

    public MyApplication() {
        recordsList = new ArrayList<Record>();
    }
}


text:
#import <XCTest/XCTest.h>

#import <FBSimulatorControl/FBSimulatorControl.h>

#import "CoreSimulatorDoubles.h"
#import "FBSimulatorSetTestCase.h"

@interface FBSimulatorSetTests : FBSimulatorSetTestCase

@end

@implementation FBSimulatorSetTests

- (void)testInflatesSimulators
{
  [self createSetWithExistingSimDeviceSpecs:@[
    @{@"name" : FBDeviceModeliPhone5, @"state" : @(FBiOSTargetStateCreating)},
    @{@"name" : FBDeviceModeliPhone5, @"state" : @(FBiOSTargetStateShutdown)},
    @{@"name" : FBDeviceModeliPhone5, @"state" : @(FBiOSTargetStateBooted)},
    @{@"name" : FBDeviceModeliPhone6S, @"state" : @(FBiOSTargetStateShuttingDown)},
    @{@"name" : FBDeviceModeliPad2, @"state" : @(FBiOSTargetStateBooted)},
    @{@"name" : FBDeviceModeliPadAir, @"state" : @(FBiOSTargetStateBooted)},
    @{@"name" : FBDeviceModeliPadAir2, @"state" : @(FBiOSTargetStateCreating)},
    @{@"name" : FBDeviceModeliPhone5, @"state" : @(FBiOSTargetStateShutdown), @"os" : FBOSVersionNameiOS_10_0},
  ]];

  NSArray<FBSimulator *> *simulators = self.set.allSimulators;
  XCTAssertEqual(simulators.count, 8u);

  FBSimulator *simulator = simulators[0];
  XCTAssertEqualObjects(simulator.name, FBDeviceModeliPhone5);
  XCTAssertEqual(simulator.state, FBiOSTargetStateCreating);
  XCTAssertEqual(simulator.set, self.set);

  simulator = simulators[1];
  XCTAssertEqualObjects(simulator.name, FBDeviceModeliPhone5);
  XCTAssertEqual(simulator.state, FBiOSTargetStateShutdown);
  XCTAssertEqual(simulator.set, self.set);

  simulator = simulators[2];
  XCTAssertEqualObjects(simulator.name, FBDeviceModeliPhone5);
  XCTAssertEqual(simulator.state, FBiOSTargetStateBooted);
  XCTAssertEqual(simulator.set, self.set);

  simulator = simulators[3];
  XCTAssertEqualObjects(simulator.name, FBDeviceModeliPhone6S);
  XCTAssertEqual(simulator.state, FBiOSTargetStateShuttingDown);
  XCTAssertEqual(simulator.set, self.set);

  simulator = simulators[4];
  XCTAssertEqualObjects(simulator.name, FBDeviceModeliPad2);
  XCTAssertEqual(simulator.state, FBiOSTargetStateBooted);
  XCTAssertEqual(simulator.set, self.set);

  simulator = simulators[5];
  XCTAssertEqualObjects(simulator.name, FBDeviceModeliPadAir);
  XCTAssertEqual(simulator.state, FBiOSTargetStateBooted);
  XCTAssertEqual(simulator.set, self.set);

  simulator = simulators[6];
  XCTAssertEqualObjects(simulator.name, FBDeviceModeliPadAir2);
  XCTAssertEqual(simulator.state, FBiOSTargetStateCreating);
  XCTAssertEqual(simulator.set, self.set);

  simulator = simulators[7];
  XCTAssertEqualObjects(simulator.name, FBDeviceModeliPhone5);
  XCTAssertEqual(simulator.state, FBiOSTargetStateShutdown);
  XCTAssertEqual(simulator.set, self.set);
}

- (void)testReferencesForSimulatorsAreTheSame
{
  [self createSetWithExistingSimDeviceSpecs:@[
    @{@"name" : FBDeviceModeliPhone5, @"state" : @(FBiOSTargetStateCreating)},
    @{@"name" : FBDeviceModeliPhone5, @"state" : @(FBiOSTargetStateShutdown)},
    @{@"name" : FBDeviceModeliPhone5, @"state" : @(FBiOSTargetStateBooted)},
    @{@"name" : FBDeviceModeliPhone6S, @"state" : @(FBiOSTargetStateShuttingDown)},
    @{@"name" : FBDeviceModeliPad2, @"state" : @(FBiOSTargetStateBooted)},
    @{@"name" : FBDeviceModeliPadAir, @"state" : @(FBiOSTargetStateBooted)},
    @{@"name" : FBDeviceModeliPadAir2, @"state" : @(FBiOSTargetStateCreating)},
    @{@"name" : FBDeviceModeliPhone5, @"state" : @(FBiOSTargetStateShutdown), @"os" : FBOSVersionNameiOS_10_0},
  ]];

  NSArray *firstFetch = self.set.allSimulators;
  NSArray *secondFetch = self.set.allSimulators;
  XCTAssertEqualObjects(firstFetch, secondFetch);

  // Reference equality.
  for (NSUInteger index = 0; index < firstFetch.count; index++) {
    XCTAssertEqual(firstFetch[index], secondFetch[index]);
  }
}

@end