text:
<stl:stl xmlns:stl="http://developer.opentext.com/schemas/storyteller/layout"
         xmlns:xp="http://developer.opentext.com/schemas/storyteller/xmlpreprocessor" version="0.1">
  <stl:fixtures>
    <xp:fixture key="link:/fragments/native-content.xml">
      <stl:stl xmlns:stl="http://developer.opentext.com/schemas/storyteller/layout" version="0.1">
        <stl:style>
          .border { border:solid blue; }
        </stl:style>
        <stl:document>
          <stl:story w="100pt">
            <stl:p>[ <stl:span style="font-style:italic">Native story</stl:span> inside an embedded extern content  ]</stl:p>
            <stl:p>
              <stl:table class="table" w="100%">
                <stl:story>
                  <stl:row h="20pt">
                    <stl:cell class="border" w="50%"><stl:p style="text-align: justify"><stl:field xpath="/data/page[1]/heading"/></stl:p></stl:cell>
                    <stl:cell class="border" w="50%"><stl:p style="text-align: justify"><stl:field xpath="/data/page[2]/heading"/></stl:p></stl:cell>
                  </stl:row>
                </stl:story>
              </stl:table>
            </stl:p>
          </stl:story>
        </stl:document>
      </stl:stl>
    </xp:fixture>
    <xp:fixture key="link:/fragments/html-content.xml">
      <stl:stl xmlns:stl="http://developer.opentext.com/schemas/storyteller/layout" version="0.1">
        <stl:document>
          <stl:story format="XHTML">

[ XHTML story inside an embedded extern content ]

          </stl:story>
        </stl:document>
      </stl:stl>
    </xp:fixture>
  </stl:fixtures>
  <stl:data>
    <stl:source key="_default">
      <data>
        <character>
          <name>Freddy Kruger</name>
        </character>
        <character>
          <name>Homer J. Simpson</name>
        </character>
      </data>
    </stl:source>
    <stl:template>
      <data>
        <page number="?">
          <heading>?</heading>
        </page>
      </data>
    </stl:template>
    <stl:transformation key="_default">
      <tdt:transformation xmlns:tdt="http://developer.opentext.com/schemas/storyteller/transformation/tdt" version="1.0">
        <tdt:rule path="/data/page">
          <tdt:value key=".">/data/character</tdt:value>
          <tdt:value key="@number">position()</tdt:value>
        </tdt:rule>
        <tdt:rule path="/data/page/heading">
          <tdt:value key="text()">name</tdt:value>
        </tdt:rule>
      </tdt:transformation>
    </stl:transformation>
  </stl:data>

  <stl:document>
    <stl:page w="300pt" h="300pt">
      <stl:text x="20pt" y="20pt" w="260pt" h="260pt" style="fill:#aabbcc">
        <stl:story>
          <stl:p>Various kinds of substitutions:</stl:p>
          <stl:p/>
          <stl:p>1) Field substitution, page number ... <stl:field type="page-number"/></stl:p>
          <stl:p>2) Data substitution ... <stl:field xpath="concat( 'Mr. ', /data/page[@number=2]/heading )"/></stl:p>

          <stl:p>3a) ExternContent substitution (embedded) ... <stl:span style="color:blue"><stl:content uri="link:/fragments/native-content.xml" selector="/story[1]"/></stl:span></stl:p>
          <stl:p>3b) ExternContent substitution (embedded) ... <stl:content uri="link:/fragments/html-content.xml" selector="/story[1]"/></stl:p>
          <stl:p>3c) ExternContent substitution (linked RTF) ... <stl:content uri='wd:/Fragment.rtf' selector='/story[1]'/></stl:p>

          <stl:p>4a) Native repository substitution ... <stl:span style="color:blue"><stl:content uri="link:/fragments/native-content.xml"/></stl:span></stl:p>
          <stl:p>4b) HTML repository substitution ... <stl:content uri="wd:/Fragment.html"/></stl:p>
          <stl:p>5) Language substitution ... <stl:translation phrase="Label1"/></stl:p>
        </stl:story>
      </stl:text>
    </stl:page>
  </stl:document>
</stl:stl>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ 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.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.wso2.carbon</groupId>
        <artifactId>hl7</artifactId>
        <version>4.3.0-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.wso2.carbon</groupId>
    <artifactId>org.wso2.carbon.business.messaging.hl7.common</artifactId>
    <version>4.3.0-SNAPSHOT</version>
    <packaging>bundle</packaging>
    <name>WSO2 Carbon - HL7 Business Messaging - Common</name>
    <url>http://wso2.org</url>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>

                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
                        <DynamicImport-Package>*</DynamicImport-Package>
                        <Export-Package>
                            org.wso2.carbon.business.messaging.hl7.common.*,
                        </Export-Package>
                        <Import-Package>
                            org.apache.axis2.*; version="${axis2.osgi.version.range}",
                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
                            org.wso2.carbon.utils.*,
                            *;resolution:=optional
                        </Import-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.core</artifactId>
        </dependency>
        <dependency>
            <groupId>ca.uhn.hapi.wso2</groupId>
            <artifactId>hapi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.databridge.agent.thrift</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.databridge.commons</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.bam.data.publisher.util</artifactId>
        </dependency>
    </dependencies>

</project>

redpajama_set_name: RedPajamaGithub


text:
Eigen::VectorXd b(const aslam::backend::Optimizer * o)
{
	return o->b();
}
Eigen::VectorXd dx(const aslam::backend::Optimizer * o)
{
	return o->dx();
}
Eigen::VectorXd rhs(const aslam::backend::Optimizer * o)
{
	return o->rhs();
}

void exportOptimizer()
{
    using namespace boost::python;
    using namespace aslam::backend;

    class_<SolutionReturnValue>("SolutionReturnValue")
        .def_readwrite("JStart",&SolutionReturnValue::JStart)
        .def_readwrite("JFinal",&SolutionReturnValue::JFinal)
        .def_readwrite("iterations",&SolutionReturnValue::iterations)
        .def_readwrite("failedIterations",&SolutionReturnValue::failedIterations)
        .def_readwrite("lmLambdaFinal",&SolutionReturnValue::lmLambdaFinal)
        .def_readwrite("dXFinal",&SolutionReturnValue::dXFinal)
        .def_readwrite("dJFinal",&SolutionReturnValue::dJFinal)
        .def_readwrite("linearSolverFailure",&SolutionReturnValue::linearSolverFailure)
        ;

    class_<Optimizer, boost::shared_ptr<Optimizer> >("Optimizer",init<>())
        .def(init<OptimizerOptions>())
        .def("setProblem", static_cast<void(Optimizer::*)(boost::shared_ptr<OptimizationProblemBase>)>(&Optimizer::setProblem))

        /// \brief initialize the optimizer to run on an optimization problem.
        ///        This should be called before calling optimize()
        .def("initialize", &Optimizer::initialize)

        /// \brief initialize the linear solver specified in the optimizer options.
        .def("initializeLinearSolver", &Optimizer::initializeLinearSolver)

        /// \brief Run the optimization
        .def("optimize", &Optimizer::optimize)
        .def("optimizeDogLeg", &Optimizer::optimizeDogLeg)

        .def("buildGnMatrices", &Optimizer::buildGnMatrices)
        /// \brief Get the optimizer options.
        .add_property("options", make_function(&Optimizer::options,return_internal_reference<>()))

        /// \brief return the full Hessian
        .def("H", &Optimizer::H, return_internal_reference<>())

        /// \brief return the full rhs
        .def("rhs", &rhs)

        /// \brief return the reduced system lhs
        .def("A", &Optimizer::A, return_internal_reference<>())

        /// \brief return the reduced system rhs
        .def("b", &b)

        /// \brief return the reduced system dx
        .def("dx", &dx)

        /// The value of the objective function.
        .def("J", &Optimizer::J)

        // \todo Covariance calculations
        // void computeCovariances();
        // const Eigen::MatrixXd & getDenseBlockCovariance(int di1, int di2);
        // Eigen::MatrixXd getSparseSparseCovariance(int si1, int si2);
        // Eigen::MatrixXd getDenseSparseCovariance(int di, int si);

        /// \brief Evaluate the error at the current state.
        .def("evaluateError", &Optimizer::evaluateError)

        /// \brief Get dense design variable i.
        .def("denseVariable", &Optimizer::denseVariable, return_internal_reference<>())
        /// \brief Get sparse design variable i
        .def("sparseVariable", &Optimizer::sparseVariable, return_internal_reference<>())

        /// \brief how many dense design variables are involved in the problem
        .def("numDenseDesignVariables", &Optimizer::numDenseDesignVariables)

        /// \brief how many sparse design variables are involved in the problem
        .def("numSparseDesignVariables", &Optimizer::numSparseDesignVariables)

        .def("printTiming", &Optimizer::printTiming)

        .def("computeCovariances", &Optimizer::computeCovariances)
        .def("computeDiagonalCovariances", &Optimizer::computeDiagonalCovariances)
        // \todo Think of a nice way to expose this to Python
        //.def("computeCovarianceBlocks", &Optimizer::computeCovarianceBlocks)
        .def("getCovarianceBlock", &Optimizer::getCovarianceBlock,return_internal_reference<>())
        .def("P", &Optimizer::P,return_internal_reference<>())
        .def("getCovariance", &Optimizer::getCovariance,return_internal_reference<>())

        ;

    class_<Optimizer2, boost::shared_ptr<Optimizer2> >("Optimizer2",init<>())
        .def(init<Optimizer2Options>())
        .def("setProblem", &Optimizer2::setProblem)

        /// \brief initialize the optimizer to run on an optimization problem.
        ///        This should be called before calling optimize()
        .def("initialize", &Optimizer2::initialize)

        /// \brief initialize the linear solver specified in the optimizer options.
        .def("initializeLinearSolver", &Optimizer2::initializeLinearSolver)

        /// \brief Run the optimization
        .def("optimize", &Optimizer2::optimize)
        //.def("optimizeDogLeg", &Optimizer2::optimizeDogLeg)

        /// \brief Get the optimizer options.
        .add_property("options", make_function(&Optimizer2::options,return_internal_reference<>()))

        /// \brief return the full Hessian
        //.def("H", &Optimizer2::H, return_internal_reference<>())

        /// \brief return the full rhs
        //.def("rhs", &rhs)

        /// \brief return the reduced system lhs
        //.def("A", &Optimizer2::A, return_internal_reference<>())

        /// \brief return the reduced system rhs
        //.def("b", &b)

        /// \brief return the reduced system dx
        //.def("dx", &dx)

        /// The value of the objective function.
        .def("J", &Optimizer2::J)

        // \todo Covariance calculations
        // void computeCovariances();
        // const Eigen::MatrixXd & getDenseBlockCovariance(int di1, int di2);
        // Eigen::MatrixXd getSparseSparseCovariance(int si1, int si2);
        // Eigen::MatrixXd getDenseSparseCovariance(int di, int si);
        .def("computeCovariances", &Optimizer2::computeCovariances)
        .def("computeDiagonalCovariances", &Optimizer2::computeDiagonalCovariances)

        /// \brief Evaluate the error at the current state.
        .def("evaluateError", &Optimizer2::evaluateError)

        /// \brief Get dense design variable i.
        .def("densignVariable", &Optimizer2::designVariable, return_internal_reference<>())

        /// \brief how many dense design variables are involved in the problem
        .def("numDesignVariables", &Optimizer2::numDesignVariables)

        .def("printTiming", &Optimizer2::printTiming)
        .def("computeHessian", &Optimizer2::computeHessian)

        ;
}


text:
#ifndef _CIPHER_HMAC_ALL_H
#define _CIPHER_HMAC_ALL_H
#ifdef  __cplusplus
extern "C" {
#endif /* __cplusplus */

#define   SHA1_DIGEST_SIZE  20
#define SHA224_DIGEST_SIZE  28
#define SHA256_DIGEST_SIZE  32
#define SHA384_DIGEST_SIZE  48
#define SHA512_DIGEST_SIZE  64
#define    MD5_DIGEST_SIZE  16
    void hmac_md5(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha1(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha224(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha256(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha384(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);
    void hmac_sha512(unsigned char *key, int key_len,
        unsigned char *text, int text_len, unsigned char *hmac);

#ifdef  __cplusplus
}
#endif /* __cplusplus */
#endif /* _CIPHER_HMAC_ALL_H */


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>Gemfile - RDoc Documentation</title>

<link href="./fonts.css" rel="stylesheet">
<link href="./rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Pages

Gemfile

Gemfile.lock

README

Rakefile

application.js

games.js

pages.js.coffee

users.js.coffee

application.css

games.css.scss

pages.css.scss

scaffolds.css.scss

users.css.scss

index.json.jbuilder

show.json.jbuilder

index.json.jbuilder

show.json.jbuilder

config.ru

schema.rb~

development.log

404.html

422.html

500.html

favicon.ico

robots

source 'rubygems.org' ruby '2.1.0'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem
'rails', '4.1.1' # Use sqlite3 as the database for Active Record group
:development, :test do

gem 'sqlite3'

end group :production do

gem 'pg'
gem 'rails_12factor'

end # Use SCSS for stylesheets gem 'sass-rails', '~> 4.0.3' # Use
Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails',
'~> 4.0.0' # See github.com/sstephenson/execjs#readme
for more supported runtimes # gem 'therubyracer',  platforms: :ruby

# Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks
makes following links in your web application faster. Read more: github.com/rails/turbolinks
gem 'turbolinks' # Build JSON APIs with ease. Read more: github.com/rails/jbuilder gem
'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API
under doc/api. gem 'sdoc', '~> 0.4.0',          group: :doc

# Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7'

# Use unicorn as the app server # gem 'unicorn'

# Use Capistrano for deployment # gem 'capistrano-rails', group:
:development

# Use debugger # gem 'debugger', group: [:development, :test]

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin]

Validate

Generated by RDoc 4.1.1.

Based on Darkfish by Michael Granger.


text:
<?php
/**
 * Justboil.me - a TinyMCE image upload plugin
 * jbimages/config.php
 *
 * Released under Creative Commons Attribution 3.0 Unported License
 *
 * License: http://creativecommons.org/licenses/by/3.0/
 * Plugin info: http://justboil.me/
 * Author: Viktor Kuzhelnyi
 *
 * Version: 2.3 released 23/06/2013
 */

/*

  ------------------------------------------------------------------

  IMPORTANT NOTE! In case, when TinyMCE's folder is not protected with HTTP Authorisation,
  you should require is_allowed() function to return
  `TRUE` if user is authorised,
  `FALSE` - otherwise
    is_allowed() can be found in jbimages/is_allowed.php

  This is intended to protect upload script, if someone guesses it's url.

  So, here we go...

| -------------------------------------------------------------------
|
| Path to upload target folder, relative to domain name. NO TRAILING SLASH!
| Example: if an image is acessed via http://www.example.com/images/somefolder/image.jpg, you should specify here:
|
| $config['img_path'] = '/images/somefolder';
|
| -------------------------------------------------------------------*/

// Change the paths as per your folders

$config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/"."hoctiengnhat/uploads/images" ;
$config['img_path'] = "http://".$_SERVER['SERVER_NAME'].'/hoctiengnhat/uploads/images' ;

/*-------------------------------------------------------------------
|
| Allowed image filetypes. Specifying something other, than image types will result in error.
|
| $config['allowed_types'] = 'gif|jpg|png';
|
| -------------------------------------------------------------------*/

	$config['allowed_types'] = 'gif|jpg|png';

/*-------------------------------------------------------------------
|
| Maximum image file size in kilobytes. This value can't exceed value set in php.ini.
| Set to `0` if you want to use php.ini default:
|
| $config['max_size'] = 0;
|
| -------------------------------------------------------------------*/

	$config['max_size'] = 0;

/*-------------------------------------------------------------------
|
| Maximum image width. Set to `0` for no limit:
|
| $config['max_width'] = 0;
|
| -------------------------------------------------------------------*/

	$config['max_width'] = 0;

/*-------------------------------------------------------------------
|
| Maximum image height. Set to `0` for no limit:
|
| $config['max_height'] = 0;
|
| -------------------------------------------------------------------*/

	$config['max_height'] = 0;

/*-------------------------------------------------------------------
|
| Allow script to resize image that exceeds maximum width or maximum height (or both)
| If set to `TRUE`, image will be resized to fit maximum values (proportions are saved)
| If set to `FALSE`, user will recieve an error message.
|
| $config['allow_resize'] = TRUE;
|
| -------------------------------------------------------------------*/

	$config['allow_resize'] = TRUE;

/*-------------------------------------------------------------------
|
| Image name encryption
| If set to `TRUE`, image file name will be encrypted in something like 7fdd57742f0f7b02288feb62570c7813.jpg
| If set to `FALSE`, original filenames will be preserved
|
| $config['encrypt_name'] = TRUE;
|
| -------------------------------------------------------------------*/

	$config['encrypt_name'] = FALSE;

/*-------------------------------------------------------------------
|
| How to behave if 2 or more files with the same name are uploaded:
| `TRUE` - the entire file will be overwritten
| `FALSE` - a number will be added to the newly uploaded file name
|
| -------------------------------------------------------------------*/

	$config['overwrite'] = FALSE;

/*-------------------------------------------------------------------
|
| Target upload folder relative to document root. Most likely, you will not need to change this setting.
|
| -------------------------------------------------------------------*/

/*-------------------------------------------------------------------
|
| THAT IS ALL. HAVE A NICE DAY! )))
|
| -------------------------------------------------------------------*/
?>


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.SDL_BUTTON_X2MASK.html">

Redirecting to constant.SDL_BUTTON_X2MASK.html...


text:
package com.lumos.client;

public final class CommonConstants {
	public CommonConstants(){
		// can't instantiate me
	}
	public static final String EXTRA_MESSAGE = "com.lumos.client.pingme.EXTRA_MESSAGE";
	// snooze duration in ms (= 20 s)
	public static final int SNOOZE_DURATION = 20000;
	public static final int DEFAULT_TIMER_DURATION = 10000;
	public static final String EXTRA_TIMER = "com.lumos.client.pingme.EXTRA_TIMER";

	public static final String ACTION_SNOOZE="com.lumos.client.pingme.ACTION_SNOOZE";
	public static final String ACTION_PING = "com.lumos.client.pingme.ACTION_PING";
	public static final String ACTION_DISMISS = "com.lumos.client.pingme.ACTION_DISMISS";
	public static final int NOTIFICATION_ID = 001;

	public static final String DEBUG_TAG = "PingMe";
}


text:
<?php

class Campaigner_client {

	/* --------------------------------------------------------------
	 * PRIVATE PROPERTIES.
	 * ------------------------------------------------------------ */

	/**
	 * Client ID.
	 *
	 * @access	private
	 * @var		string
	 */
	private $_client_id = '';

	/**
	 * Client name.
	 *
	 * @access	private
	 * @var		string
	 */
	private $_client_name = '';

	/* --------------------------------------------------------------
	 * PUBLIC METHODS
	 * ------------------------------------------------------------ */

	/**
	 * Constructor.
	 *
	 * @access	public
	 * @param 	array 		$properties		Initial settings.
	 * @return	void
	 */
	public function __construct(Array $properties = array())
	{
		foreach ($properties AS $property => $value)
		{
			$method_name = 'set_' .$property;

			if (method_exists($this, $method_name))
			{
				$this->$method_name($value);
			}
		}
	}

	/**
	 * Returns client ID.
	 *
	 * @access	public
	 * @return	string
	 */
	public function get_client_id()
	{
		return $this->_client_id;
	}

	/**
	 * Returns client name.
	 *
	 * @access	public
	 * @return	string
	 */
	public function get_client_name()
	{
		return $this->_client_name;
	}

	/**
	 * Sets client ID.
	 *
	 * @access	public
	 * @param 	string		$client_id			The client ID.
	 * @return	string
	 */
	public function set_client_id($client_id)
	{
		if (is_string($client_id) OR is_int($client_id))
		{
			$this->_client_id = $client_id;
		}

		return $this->get_client_id();
	}

	/**
	 * Sets client name.
	 *
	 * @access	public
	 * @param 	string		$client_name		The client name.
	 * @return	string
	 */
	public function set_client_name($client_name)
	{
		if (is_string($client_name))
		{
			$this->_client_name = $client_name;
		}

		return $this->get_client_name();
	}

	/**
	 * Returns the instance as an array.
	 *
	 * @access	public
	 * @return	array
	 */
	public function to_array()
	{
		return array(
			'client_id'		=> $this->get_client_id(),
			'client_name'	=> $this->get_client_name()
		);
	}

}

/* End of file		: campaigner_client.php */
/* File location	: third_party/campaigner/classes/campaigner_client.php */


text:
layout: "docs_api"
title: Supersonic API reference
header_sub_title: Contact object
section_id: cordova
subsection_id: contacts
---

# ContactAddress

The `ContactAddress` object stores the properties of a single address
of a contact.  A `Contact` object may include more than one address in
a `ContactAddress[]` array.

## Properties

- __pref__: Set to `true` if this `ContactAddress` contains the user's preferred value. _(boolean)_

- __type__: A string indicating what type of field this is, _home_ for example. _(DOMString)_

- __formatted__: The full address formatted for display. _(DOMString)_

- __streetAddress__: The full street address. _(DOMString)_

- __locality__: The city or locality. _(DOMString)_

- __region__: The state or region. _(DOMString)_

- __postalCode__: The zip code or postal code. _(DOMString)_

- __country__: The country name. _(DOMString)_

## Example

```javascript
// display the address information for all contacts

function onSuccess(contacts) {
    for (var i = 0; i < contacts.length; i++) {
        for (var j = 0; j < contacts[i].addresses.length; j++) {
            alert("Pref: "         + contacts[i].addresses[j].pref          + "\n" +
                "Type: "           + contacts[i].addresses[j].type          + "\n" +
                "Formatted: "      + contacts[i].addresses[j].formatted     + "\n" +
                "Street Address: " + contacts[i].addresses[j].streetAddress + "\n" +
                "Locality: "       + contacts[i].addresses[j].locality      + "\n" +
                "Region: "         + contacts[i].addresses[j].region        + "\n" +
                "Postal Code: "    + contacts[i].addresses[j].postalCode    + "\n" +
                "Country: "        + contacts[i].addresses[j].country);
        }
    }
};

function onError(contactError) {
    alert('onError!');
};

// find all contacts
var options = new ContactFindOptions();
options.filter = "";
var filter = ["displayName", "addresses"];
navigator.contacts.find(filter, onSuccess, onError, options);
```

## iOS Quirks

- __pref__: Not supported on iOS devices, returning `false`.

- __formatted__: Currently not supported.


text:
import unittest
import datetime

from mycroft.util.lang import get_active_lang, set_active_lang
from mycroft.util.format import nice_number
from mycroft.util.format import nice_time
from mycroft.util.format import pronounce_number
from mycroft.util.lang.format_de import nice_response_de
from mycroft.util.lang.format_de import pronounce_ordinal_de
from mycroft.util.format import join_list

# fractions are not capitalized for now
NUMBERS_FIXTURE_DE = {
    1.435634: '1,436',
    2: '2',
    5.0: '5',
    1234567890: '1234567890',
    12345.67890: '12345,679',
    0.027: '0,027',
    0.5: 'ein halb',
    1.333: '1 und ein drittel',
    2.666: '2 und 2 drittel',
    0.25: 'ein viertel',
    1.25: '1 und ein viertel',
    0.75: '3 viertel',
    1.75: '1 und 3 viertel',
    3.4: '3 und 2 fünftel',
    16.8333: '16 und 5 sechstel',
    12.5714: '12 und 4 siebtel',
    9.625: '9 und 5 achtel',
    6.777: '6 und 7 neuntel',
    3.1: '3 und ein zehntel',
    2.272: '2 und 3 elftel',
    5.583: '5 und 7 zwölftel',
    8.384: '8 und 5 dreizehntel',
    0.071: 'ein vierzehntel',
    6.466: '6 und 7 fünfzehntel',
    8.312: '8 und 5 sechzehntel',
    2.176: '2 und 3 siebzehntel',
    200.722: '200 und 13 achtzehntel',
    7.421: '7 und 8 neunzehntel',
    0.05: 'ein zwanzigstel'
}

class TestNiceResponse(unittest.TestCase):
    def test_replace_ordinal(self):
        self.assertEqual(nice_response_de("dies ist der 31. mai"),
                         "dies ist der einunddreißigste mai")
        self.assertEqual(nice_response_de("es fängt am 31. mai an"),
                         "es fängt am einunddreißigsten mai an")
        self.assertEqual(nice_response_de("der 31. mai"),
                         "der einunddreißigste mai")
        self.assertEqual(nice_response_de("10 ^ 2"),
                         "10 hoch 2")

class TestNiceNumberFormat(unittest.TestCase):
    def setUp(self):
        self.old_lang = get_active_lang()
        set_active_lang("de-de")

    def tearDown(self):
        set_active_lang(self.old_lang)

    def test_convert_float_to_nice_number(self):
        for number, number_str in NUMBERS_FIXTURE_DE.items():
            self.assertEqual(nice_number(number), number_str,
                             'should format {} as {} and not {}'.format(
                                 number, number_str,
                                 nice_number(number)))

    def test_specify_denominator(self):
        self.assertEqual(nice_number(5.5,
                                     denominators=[1, 2, 3]), '5 und ein halb',
                         'should format 5.5 as 5 und ein halb not {}'.format(
                             nice_number(5.5, denominators=[1, 2, 3])))
        self.assertEqual(nice_number(2.333, denominators=[1, 2]),
                         '2,333',
                         'should format 2,333 as 2,333 not {}'.format(
                             nice_number(2.333,
                                         denominators=[1, 2])))

    def test_no_speech(self):
        self.assertEqual(nice_number(6.777, speech=False),
                         '6 7/9',
                         'should format 6.777 as 6 7/9 not {}'.format(
                             nice_number(6.777, speech=False)))
        self.assertEqual(nice_number(6.0, speech=False),
                         '6',
                         'should format 6.0 as 6 not {}'.format(
                             nice_number(6.0, speech=False)))

class TestPronounceOrdinal(unittest.TestCase):
    def test_convert_int_de(self):
        self.assertEqual(pronounce_ordinal_de(0),
                         "nullte")
        self.assertEqual(pronounce_ordinal_de(1),
                         "erste")
        self.assertEqual(pronounce_ordinal_de(3),
                         "dritte")
        self.assertEqual(pronounce_ordinal_de(5),
                         "fünfte")
        self.assertEqual(pronounce_ordinal_de(1000),
                         "eintausendste")
        self.assertEqual(pronounce_ordinal_de(123456),
                         "einhundertdreiundzwanzigtausendvierhundertsechsund"
                         "fünfzigste")

# def pronounce_number(number, lang="de-de", places=2):
class TestPronounceNumber(unittest.TestCase):
    def setUp(self):
        self.old_lang = get_active_lang()
        set_active_lang("de-de")

    def tearDown(self):
        set_active_lang(self.old_lang)

    def test_convert_int_de(self):
        self.assertEqual(pronounce_number(123456789123456789),
                         "einhundertdreiundzwanzig Billiarden "
                         "vierhundertsechsundfünfzig Billionen "
                         "siebenhundertneunundachtzig Milliarden "
                         "einhundertdreiundzwanzig Millionen "
                         "vierhundertsechsundfünfzigtausendsiebenhundert"
                         "neunundachtzig")
        self.assertEqual(pronounce_number(1), "eins")
        self.assertEqual(pronounce_number(10), "zehn")
        self.assertEqual(pronounce_number(15), "fünfzehn")
        self.assertEqual(pronounce_number(20), "zwanzig")
        self.assertEqual(pronounce_number(27), "siebenundzwanzig")
        self.assertEqual(pronounce_number(30), "dreißig")
        self.assertEqual(pronounce_number(33), "dreiunddreißig")

        self.assertEqual(pronounce_number(71), "einundsiebzig")
        self.assertEqual(pronounce_number(80), "achtzig")
        self.assertEqual(pronounce_number(74), "vierundsiebzig")
        self.assertEqual(pronounce_number(79), "neunundsiebzig")
        self.assertEqual(pronounce_number(91), "einundneunzig")
        self.assertEqual(pronounce_number(97), "siebenundneunzig")
        self.assertEqual(pronounce_number(300), "dreihundert")

    def test_convert_negative_int_de(self):
        self.assertEqual(pronounce_number(-1), "minus eins")
        self.assertEqual(pronounce_number(-10), "minus zehn")
        self.assertEqual(pronounce_number(-15), "minus fünfzehn")
        self.assertEqual(pronounce_number(-20), "minus zwanzig")
        self.assertEqual(pronounce_number(-27), "minus siebenundzwanzig")
        self.assertEqual(pronounce_number(-30), "minus dreißig")
        self.assertEqual(pronounce_number(-33), "minus dreiunddreißig")

    def test_convert_decimals_de(self):
        self.assertEqual(pronounce_number(1.234),
                         "eins Komma zwei drei")
        self.assertEqual(pronounce_number(21.234),
                         "einundzwanzig Komma zwei drei")
        self.assertEqual(pronounce_number(21.234, places=1),
                         "einundzwanzig Komma zwei")
        self.assertEqual(pronounce_number(21.234, places=0),
                         "einundzwanzig")
        self.assertEqual(pronounce_number(21.234, places=3),
                         "einundzwanzig Komma zwei drei vier")
        self.assertEqual(pronounce_number(21.234, places=4),
                         "einundzwanzig Komma zwei drei vier null")
        self.assertEqual(pronounce_number(21.234, places=5),
                         "einundzwanzig Komma zwei drei vier null null")
        self.assertEqual(pronounce_number(-1.234),
                         "minus eins Komma zwei drei")
        self.assertEqual(pronounce_number(-21.234),
                         "minus einundzwanzig Komma zwei drei")
        self.assertEqual(pronounce_number(-21.234, places=1),
                         "minus einundzwanzig Komma zwei")
        self.assertEqual(pronounce_number(-21.234, places=0),
                         "minus einundzwanzig")
        self.assertEqual(pronounce_number(-21.234, places=3),
                         "minus einundzwanzig Komma zwei drei vier")
        self.assertEqual(pronounce_number(-21.234, places=4),
                         "minus einundzwanzig Komma zwei drei vier null")
        self.assertEqual(pronounce_number(-21.234, places=5),
                         "minus einundzwanzig Komma zwei drei vier null null")

# def nice_time(dt, lang="de-de", speech=True, use_24hour=False,
#              use_ampm=False):
class TestNiceDateFormat_de(unittest.TestCase):
    def setUp(self):
        self.old_lang = get_active_lang()
        set_active_lang("de-de")

    def tearDown(self):
        set_active_lang(self.old_lang)

    def test_convert_times_de(self):
        dt = datetime.datetime(2017, 1, 31,
                               13, 22, 3)

        self.assertEqual(nice_time(dt),
                         "ein Uhr zweiundzwanzig")
        self.assertEqual(nice_time(dt, use_ampm=True),
                         "ein Uhr zweiundzwanzig nachmittags")
        self.assertEqual(nice_time(dt, speech=False),
                         "1:22")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_ampm=True),
                         "1:22 PM")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True),
                         "13:22")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True, use_ampm=True),
                         "13:22")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=True),
                         "dreizehn Uhr zweiundzwanzig")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=False),
                         "dreizehn Uhr zweiundzwanzig")

        dt = datetime.datetime(2017, 1, 31,
                               13, 0, 3)
        self.assertEqual(nice_time(dt),
                         "ein Uhr")
        self.assertEqual(nice_time(dt, use_ampm=True),
                         "ein Uhr nachmittags")
        self.assertEqual(nice_time(dt, speech=False),
                         "1:00")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_ampm=True),
                         "1:00 PM")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True),
                         "13:00")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True, use_ampm=True),
                         "13:00")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=True),
                         "dreizehn Uhr")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=False),
                         "dreizehn Uhr")

        dt = datetime.datetime(2017, 1, 31,
                               13, 2, 3)
        self.assertEqual(nice_time(dt),
                         "ein Uhr zwei")
        self.assertEqual(nice_time(dt, use_ampm=True),
                         "ein Uhr zwei nachmittags")
        self.assertEqual(nice_time(dt, speech=False),
                         "1:02")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_ampm=True),
                         "1:02 PM")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True),
                         "13:02")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True, use_ampm=True),
                         "13:02")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=True),
                         "dreizehn Uhr zwei")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=False),
                         "dreizehn Uhr zwei")

        dt = datetime.datetime(2017, 1, 31,
                               0, 2, 3)
        self.assertEqual(nice_time(dt),
                         "zwölf Uhr zwei")
        self.assertEqual(nice_time(dt, use_ampm=True),
                         "zwölf Uhr zwei nachts")
        self.assertEqual(nice_time(dt, speech=False),
                         "12:02")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_ampm=True),
                         "12:02 AM")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True),
                         "00:02")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True, use_ampm=True),
                         "00:02")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=True),
                         "null Uhr zwei")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=False),
                         "null Uhr zwei")

        dt = datetime.datetime(2017, 1, 31,
                               12, 15, 9)
        self.assertEqual(nice_time(dt),
                         "viertel eins")
        self.assertEqual(nice_time(dt, use_ampm=True),
                         "viertel eins nachmittags")
        self.assertEqual(nice_time(dt, speech=False),
                         "12:15")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_ampm=True),
                         "12:15 PM")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True),
                         "12:15")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True, use_ampm=True),
                         "12:15")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=True),
                         "zwölf Uhr fünfzehn")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=False),
                         "zwölf Uhr fünfzehn")

        dt = datetime.datetime(2017, 1, 31,
                               19, 40, 49)
        self.assertEqual(nice_time(dt),
                         "sieben Uhr vierzig")
        self.assertEqual(nice_time(dt, use_ampm=True),
                         "sieben Uhr vierzig abends")
        self.assertEqual(nice_time(dt, speech=False),
                         "7:40")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_ampm=True),
                         "7:40 PM")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True),
                         "19:40")
        self.assertEqual(nice_time(dt, speech=False,
                                   use_24hour=True, use_ampm=True),
                         "19:40")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=True),
                         "neunzehn Uhr vierzig")
        self.assertEqual(nice_time(dt, use_24hour=True,
                                   use_ampm=False),
                         "neunzehn Uhr vierzig")

        dt = datetime.datetime(2017, 1, 31,
                               1, 15, 00)
        self.assertEqual(nice_time(dt, use_24hour=True),
                         "ein Uhr fünfzehn")

        dt = datetime.datetime(2017, 1, 31,
                               1, 35, 00)
        self.assertEqual(nice_time(dt),
                         "ein Uhr fünfunddreißig")

        dt = datetime.datetime(2017, 1, 31,
                               1, 45, 00)
        self.assertEqual(nice_time(dt),
                         "dreiviertel zwei")

        dt = datetime.datetime(2017, 1, 31,
                               4, 50, 00)
        self.assertEqual(nice_time(dt),
                         "vier Uhr fünfzig")

        dt = datetime.datetime(2017, 1, 31,
                               5, 55, 00)
        self.assertEqual(nice_time(dt),
                         "fünf Uhr fünfundfünfzig")

        dt = datetime.datetime(2017, 1, 31,
                               5, 30, 00)
        self.assertEqual(nice_time(dt, use_ampm=True),
                         "halb sechs morgens")

class TestJoinList_de(unittest.TestCase):
    def setUp(self):
        self.old_lang = get_active_lang()
        set_active_lang("de-de")

    def tearDown(self):
        set_active_lang(self.old_lang)

    def test_join_list_de(self):
        self.assertEqual(join_list(['Hallo', 'Auf wieder Sehen'], 'and'),
                         'Hallo und Auf wieder Sehen')

        self.assertEqual(join_list(['A', 'B', 'C'], 'or'),
                         'A, B oder C')

if __name__ == "__main__":
    unittest.main()


text:
impl ::method::confirm::SelectMethod for ::Rabbitmq9_1 {
    type Payload = Select;
} // impl ::method::confirm::SelectMethod for ::Rabbitmq9_1

// generated by primalgen::codegen::spec-module::class_mod::method_struct
#[derive(Debug)]
pub struct Select {
    no_wait: bool,
} // struct Select

impl Select {
    pub fn new(no_wait: bool) -> Self {
        Select { no_wait: no_wait } // Select
    } // fn new()
    impl_properties! {
(no_wait, set_no_wait) -> bool,
} // impl_properties
} // impl Select
impl Default for Select {
    fn default() -> Self {
        Select::new(false)
    } // fn default()
} // impl Default for Select

impl ::Encodable for Select {
    fn encoded_size(&self) -> usize {
        1
    } // encoded_size
    fn write_encoded_to<W>(&self, writer: &mut W) -> ::std::io::Result<()>
        where W: ::std::io::Write
    {
        try!(::Encodable::write_encoded_to(&{
                                               let mut bits = ::bit_vec::BitVec::from_elem(8,
                                                                                false);
                                               bits.set(7, self.no_wait);
                                               bits
                                           },
                                           writer));

        ::std::result::Result::Ok(())
    } // fn write_encoded_to()
} // impl Encodable

#[test]
fn test_select_encodable_bytes_written_matches_len() {
    let payload: Select = Default::default();
    let expected_len = ::Encodable::encoded_size(&payload);
    let mut writer = ::std::io::Cursor::new(Vec::with_capacity(expected_len));
    ::Encodable::write_encoded_to(&payload, &mut writer).unwrap();
    let payload = writer.into_inner();

    if payload.len() != expected_len {
        panic!("Expected payload len {}, got {}, {:?}",
               expected_len,
               payload.len(),
               &payload[..]);
    }
}

impl ::ProtocolMethodPayload for Select {
    fn class(&self) -> ::Class {
        ::Class::Confirm
    }
    fn class_id(&self) -> u16 {
        85
    }
    fn class_name(&self) -> &'static str {
        "confirm"
    }
    fn method_id(&self) -> u16 {
        10
    }
    fn method_name(&self) -> &'static str {
        "select"
    }
} // impl ::ProtocolMethodPayload for Select
impl ::method::confirm::SetSelectMethodFields for Select {
    fn set_no_wait(&mut self, no_wait: bool) {
        self.set_no_wait(no_wait)
    } // set_no_wait()
} // impl ::method::confirm::SetSelectMethodFields for Select
impl From<Select> for ClassMethod {
    fn from(from: Select) -> Self {
        ClassMethod::Select(from)
    } // fn from()
} // impl From<Select> for ClassMethod

impl From<Select> for super::SpecMethod<'static> {
    fn from(from: Select) -> Self {
        super::SpecMethod::Confirm(from.into())
    } // fn default()
} // impl From<Select> for ::super::SpecMethod
impl ::method::confirm::SelectOkMethod for ::Rabbitmq9_1 {
    type Payload = SelectOk;
} // impl ::method::confirm::SelectOkMethod for ::Rabbitmq9_1

// generated by primalgen::codegen::spec-module::class_mod::method_struct
#[derive(Debug)]
pub struct SelectOk;

impl SelectOk {
    pub fn new() -> Self {
        SelectOk
    } // fn new()
} // impl SelectOk
impl Default for SelectOk {
    fn default() -> Self {
        SelectOk::new()
    } // fn default()
} // impl Default for SelectOk

impl ::Encodable for SelectOk {
    fn encoded_size(&self) -> usize {
        0
    } // encoded_size
    fn write_encoded_to<W>(&self, _: &mut W) -> ::std::io::Result<()>
        where W: ::std::io::Write
    {
        ::std::result::Result::Ok(())
    }
} // impl Encodable

#[test]
fn test_select_ok_encodable_bytes_written_matches_len() {
    let payload: SelectOk = Default::default();
    let expected_len = ::Encodable::encoded_size(&payload);
    let mut writer = ::std::io::Cursor::new(Vec::with_capacity(expected_len));
    ::Encodable::write_encoded_to(&payload, &mut writer).unwrap();
    let payload = writer.into_inner();

    if payload.len() != expected_len {
        panic!("Expected payload len {}, got {}, {:?}",
               expected_len,
               payload.len(),
               &payload[..]);
    }
}

impl ::ProtocolMethodPayload for SelectOk {
    fn class(&self) -> ::Class {
        ::Class::Confirm
    }
    fn class_id(&self) -> u16 {
        85
    }
    fn class_name(&self) -> &'static str {
        "confirm"
    }
    fn method_id(&self) -> u16 {
        11
    }
    fn method_name(&self) -> &'static str {
        "select-ok"
    }
} // impl ::ProtocolMethodPayload for SelectOk
impl From<SelectOk> for ClassMethod {
    fn from(from: SelectOk) -> Self {
        ClassMethod::SelectOk(from)
    } // fn from()
} // impl From<SelectOk> for ClassMethod

impl From<SelectOk> for super::SpecMethod<'static> {
    fn from(from: SelectOk) -> Self {
        super::SpecMethod::Confirm(from.into())
    } // fn default()
} // impl From<SelectOk> for ::super::SpecMethod

#[derive(Debug)]
pub enum ClassMethod {
    Select(Select),
    SelectOk(SelectOk),
} // enum ClassMethod

impl ::Encodable for ClassMethod {
    fn encoded_size(&self) -> usize {
        match *self {
            ClassMethod::Select(ref method) => ::Encodable::encoded_size(method),
            ClassMethod::SelectOk(ref method) => ::Encodable::encoded_size(method),

        } // match *self

    } // fn encoded_size
    fn write_encoded_to<W>(&self, _: &mut W) -> ::std::io::Result<()>
        where W: ::std::io::Write
    {
        unimplemented!()
    } // fn write_encoded_to()
} // impl ::Encodable for ClassMethod

impl<'a> ::ProtocolMethodPayload for ClassMethod {
    fn class(&self) -> ::Class {
        match *self {
            ClassMethod::Select(ref method) => ::ProtocolMethodPayload::class(method),
            ClassMethod::SelectOk(ref method) => ::ProtocolMethodPayload::class(method),

        } // match *self

    } // fn class

    fn class_id(&self) -> u16 {
        match *self {
            ClassMethod::Select(ref method) => ::ProtocolMethodPayload::class_id(method),
            ClassMethod::SelectOk(ref method) => ::ProtocolMethodPayload::class_id(method),

        } // match *self

    } // fn class_id

    fn class_name(&self) -> &'static str {
        match *self {
            ClassMethod::Select(ref method) => ::ProtocolMethodPayload::class_name(method),
            ClassMethod::SelectOk(ref method) => ::ProtocolMethodPayload::class_name(method),

        } // match *self

    } // fn class_name

    fn method_id(&self) -> u16 {
        match *self {
            ClassMethod::Select(ref method) => ::ProtocolMethodPayload::method_id(method),
            ClassMethod::SelectOk(ref method) => ::ProtocolMethodPayload::method_id(method),

        } // match *self

    } // fn method_id

    fn method_name(&self) -> &'static str {
        match *self {
            ClassMethod::Select(ref method) => ::ProtocolMethodPayload::method_name(method),
            ClassMethod::SelectOk(ref method) => ::ProtocolMethodPayload::method_name(method),

        } // match *self

    } // fn method_name
} // impl ProtocolMethodPayload for ClassMethod


text:
require "test_helper"
require "lowdown/mock"

module Lowdown
  describe Client do
    describe "concerning initialization" do
      parallelize_me!

      before do
        @certificate = Mock.certificate("com.example.MockAPNS")
        @uri = Client::DEVELOPMENT_URI
      end

      it "configures a connection to the production environment" do
        ext = OpenSSL::X509::Extension.new(Certificate::PRODUCTION_ENV_EXTENSION, "..")
        @certificate.certificate.extensions = [ext]
        client = Client.production(true, certificate: @certificate)
        client.connection.uri.must_equal Client::PRODUCTION_URI
      end

      it "configures a connection to the development environment" do
        ext = OpenSSL::X509::Extension.new(Certificate::DEVELOPMENT_ENV_EXTENSION, "..")
        @certificate.certificate.extensions = [ext]
        client = Client.production(false, certificate: @certificate)
        client.connection.uri.must_equal Client::DEVELOPMENT_URI
      end

      it "configures a connection with the given uri" do
        client = Client.client(uri: @uri, certificate: @certificate)
        client.connection.uri.must_equal @uri
      end

      it "configures a connection with PEM data" do
        client = Client.client(uri: @uri, certificate: @certificate.to_pem)
        client.connection.ssl_context.key.to_pem.must_equal @certificate.key.to_pem
        client.connection.ssl_context.cert.to_pem.must_equal @certificate.certificate.to_pem
      end

      it "has no default topic if the certificate is not a Universal Certificate" do
        @certificate.certificate.extensions = []
        client = Client.client(uri: @uri, certificate: @certificate)
        client.default_topic.must_equal nil
      end

      it "uses the app bundle ID as the default topic in case of a Universal Certificate" do
        client = Client.client(uri: @uri, certificate: @certificate)
        client.default_topic.must_equal "com.example.MockAPNS"
      end
    end

    describe "when initialized" do
      parallelize_me!

      before do
        @connection = Mock::Connection.new
        @client = Client.new(connection: @connection, default_topic: "com.example.MockAPNS")
      end

      it "opens the connection for the duration of the block and then closes it" do
        opened_connection = false
        @client.connect { opened_connection = @client.connection.connected? }
        opened_connection.must_equal true
        @client.connection.connected?.must_equal false
      end

      it "yields a request group" do
        yielded_group = nil
        @client.connect { |group| yielded_group = group }
        yielded_group.class.must_equal Client::RequestGroup
      end

      it "raises exceptions that crash connection actors in the caller thread" do
        @client.connect
        lambda do
          Timeout.timeout(5) do
            @client.group do |group|
              @client.connection.post(path: "/3/device/some-device-token",
                                      headers: { "test-close-connection" => "true" },
                                      body: "♥",
                                      delegate: group.callbacks)
            end
          end
        end.must_raise EOFError
      end

      describe "when sending a notification" do
        parallelize_me!

        before do
          @notification = Notification.new(
            :payload => { :alert => "Push it real good.", :url => "http://example/custom-attribute" },
            :token => "some-device-token",
            :id => 42,
            :expiration => Time.now,
            :priority => 10,
            :topic => "com.example.MockAPNS.voip"
          )
        end

        it "yields the response and context on completion" do
          yielded_response = yielded_context = nil
          @client.connect do |group|
            group.send_notification(@notification, context: :ok) do |response, context|
              yielded_response = response
              yielded_context = context
            end
          end
          yielded_response.id.end_with?("42").must_equal true
          yielded_context.must_equal :ok
        end

        describe "in general" do
          parallelize_me!

          before do
            @client.connect do |group|
              group.send_notification(@notification) {}
            end
            @request = @connection.requests.last
          end

          it "sends the formatted payload JSON encoded" do
            @request.body.must_equal @notification.formatted_payload.to_json
          end

          it "uses the device token in the request path" do
            @request.path.must_equal "/3/device/some-device-token"
          end

          it "specifies the notification identifier" do
            @request.headers["apns-id"].must_equal @notification.formatted_id
          end

          it "specifies the expiration time" do
            @request.headers["apns-expiration"].must_equal @notification.expiration.to_i
          end

          it "specifies the priority" do
            @request.headers["apns-priority"].must_equal 10
          end

          it "specifies the topic" do
            @request.headers["apns-topic"].must_equal "com.example.MockAPNS.voip"
          end
        end

        describe "when omitting data" do
          parallelize_me!

          before do
            @notification.expiration = nil
            @notification.id = nil
            @notification.priority = nil
            @notification.topic = nil
            @client.connect do |group|
              group.send_notification(@notification) {}
            end
            @request = @connection.requests.last
          end

          it "defaults the expiration time to 0" do
            @request.headers["apns-expiration"].must_equal 0
          end

          it "defaults the topic to the one extracted from the certificate" do
            @request.headers["apns-topic"].must_equal "com.example.MockAPNS"
          end

          it "omits the apns-priority header" do
            @request.headers.key?("apns-priority").must_equal false
          end
        end
      end
    end
  end
end


text:
package apple.avfoundation.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NUInt;

/**
 * [@enum] AVVariantPreferences
 *

 * These constants can be used in any combination as the value of variantPreferences.
 *

 * [@constant] AVVariantPreferenceNone
 * Indicates that only the basic behaviors of the player for choosing among variants should be applied, including
 * considerations of available bandwidth, compatibility of the indicated codec or codecs, the dimensions of visual
 * output, and the number of available audio output channels.
 * [@constant] AVVariantPreferenceScalabilityToLosslessAudio
 * Directs the item to permit the use of variants with lossless audio encodings, if sufficient bandwidth is available
 * for their use.
 */
@Generated
public final class AVVariantPreferences {
    @Generated
    private AVVariantPreferences() {
    }

    @Generated @NUInt public static final long None = 0x0000000000000000L;
    @Generated @NUInt public static final long ScalabilityToLosslessAudio = 0x0000000000000001L;
}


text:
<?php

namespace Google\AdsApi\AdWords\v201809\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class ProximityDistanceUnits
{
    const KILOMETERS = 'KILOMETERS';
    const MILES = 'MILES';

}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Messages extends CI_Model{

    public static $messages = [];

    public function __construct() {
        parent::__construct();
    }

    public static function setMessages($msg = false){
        if($msg){ self::$messages[] = $msg; }
    }

    public static function getMessages(){
        return self::$messages;
    }

    public static function hasMessages(){
        if(self::$messages){ return TRUE; }
    }

}


text:
NS_FS_BEGIN

const char* RotateAction::className()
{
	return FS_ROTATE_ACTION_CLASS_NAME;
}

RotateAction::RotateAction()
{
}

RotateAction* RotateAction::createFromTo(const Vector3& from,const Vector3& to,float time)
{
	RotateAction* ret=new RotateAction();
	ret->initWithFromTo(from,to,time);
	return ret;
}

RotateAction* RotateAction::createBy(const Vector3& from,const Vector3& by,float time)
{
	RotateAction* ret=new RotateAction();
	ret->initWithBy(from,by,time);
	return ret;
}

RotateAction* RotateAction::create(Curve3* curve,float time)
{
	RotateAction* ret=new RotateAction();
	ret->initWithCurve(curve,time);
	return ret;
}

void RotateAction::initWithFromTo(const Vector3& from,const Vector3& to,float time)
{
	LinearCurve3* curve=LinearCurve3::create(from,to);
	setCurve(curve);
	setTotalTime(time);
}

void RotateAction::initWithBy(const Vector3& from,const Vector3& by,float time)
{
	LinearCurve3* curve=LinearCurve3::create(from,from+by);
	setCurve(curve);
	setTotalTime(time);
}

void RotateAction::initWithCurve(Curve3* curve,float time)
{
	setCurve(curve);
	setTotalTime(time);
}

void RotateAction::step(ActionTarget* target,float percent)
{

	Entity* entity=dynamic_cast<Entity*>(target);
	Vector3 pos=getCurveValue(percent);

	if(m_markBit&CurveUsedMarkBit::USED_X)
	{
		entity->setRotateX(pos.x);
	}

	if(m_markBit&CurveUsedMarkBit::USED_Y)
	{
		entity->setRotateY(pos.y);
	}

	if(m_markBit&CurveUsedMarkBit::USED_Z)
	{
		entity->setRotateZ(pos.z);
	}
}

NS_FS_END


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        	<mapping resource="org/sakaiproject/shortenedurl/hbm/RandomisedUrl.hbm.xml" />
    </session-factory>
</hibernate-configuration>


text:
<?php if ( ! defined('BASEPATH')) {exit('No direct script access allowed');}

class Banco extends CI_Controller{

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->view('modules/menu/menu_bancos');
    }

    public function index() {
         $this->load->view('bancos/index');
    }

}

/*Fin del archivo my_controller.php*/


text:
<?php

class Register_model extends CI_Model
{
     function __construct()
     {
          // Call the Model constructor
          parent::__construct();

     }

 function add_user($code){

	  $data=array(
		'company'=>$this->input->post('company'),
		'user_email'=>$this->input->post('email'),
		'password'=> md5($this->input->post('password')),
		'mobile'=>$this->input->post('mobile'),
		'cart_type'=>$this->input->post('cart-type'),
		'fname'=>$this->input->post('fname'),
		'email_verification_code'=>$code
	  );

	 $this->db->from('user');
     $this->db->where('user_email',$this->input->post('email'));
	 $login = $this->db->get()->result();

    if ( is_array($login) && count($login) == 1 ) {
        return false;
    }
	else{
		$this->db->insert('user',$data);

		 $this->session->set_userdata($data);
		 return true;
	  }
 }
	function verifyEmailAddress($verificationcode){
	  $sql = "update trn_user set active_status='A' WHERE email_verification_code=?";
	  $this->db->query($sql, array($verificationcode));
	  return $this->db->affected_rows();
	 }

	 function verifyEmail($verificationcode){

	    $value= 1;
		$data = array(
				   'active' => $value
				);

		$this->db->from('user');
		$this->db->where('email_verification_code',$this->uri->segment(2));
		$this->db->update('user', $data);
		return $this->db->affected_rows();
	 }
}


text:
package ltistarter.oauth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth.common.signature.SharedConsumerSecretImpl;
import org.springframework.security.oauth.consumer.BaseProtectedResourceDetails;
import org.springframework.security.oauth.consumer.client.OAuthRestTemplate;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.common.AuthenticationScheme;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

import java.util.Map;

/**
 * OAuth handling utils
 */
public class OAuthUtils {

    final static Logger log = LoggerFactory.getLogger(OAuthUtils.class);

    public static ResponseEntity sendOAuth1Request(String url, String consumerKey, String sharedSecret, Map<String, String> params, Map<String, String> headers) {
        assert url != null;
        assert consumerKey != null;
        assert sharedSecret != null;
        BaseProtectedResourceDetails prd = new BaseProtectedResourceDetails();
        prd.setId("oauth");
        prd.setConsumerKey(consumerKey);
        prd.setSharedSecret(new SharedConsumerSecretImpl(sharedSecret));
        prd.setAdditionalParameters(params);
        prd.setAdditionalRequestHeaders(headers);
        OAuthRestTemplate restTemplate = new OAuthRestTemplate(prd);
        ResponseEntity<String> response = restTemplate.postForEntity(url, params, String.class, (Map<String, ?>) null);
        return response;
    }

    public static ResponseEntity sendOAuth2Request(String url, String clientId, String clientSecret, String accessTokenURI, Map<String, String> params) {
        assert url != null;
        assert clientId != null;
        assert clientSecret != null;
        AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
        BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails();
        resource.setClientAuthenticationScheme(AuthenticationScheme.form);
        resource.setClientId(clientId);
        resource.setClientSecret(clientSecret);
        resource.setAccessTokenUri(accessTokenURI);
        resource.setGrantType("access");
        OAuth2AccessToken accessToken = provider.obtainAccessToken(resource, new DefaultAccessTokenRequest());
        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource, new DefaultOAuth2ClientContext(accessToken));
        ResponseEntity<String> response = restTemplate.postForEntity(url, params, String.class, (Map<String, ?>) null);
        return response;
    }

}


text:
package utils

import org.apache.spark.{SparkConf, SparkContext}
import org.joda.time.{DurationFieldType, LocalDate, Months}
import play.api.Play

object SparkSQL extends Serializable {

  def getConfigProperty(propertyName: String, defaultPropertyValue: String) = Play.current.configuration.getString(propertyName).getOrElse(defaultPropertyValue)

  case class DataResponse(x: Seq[String], data: Map[String, Seq[Long]])

  val format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S")

  val driverHost = "localhost"

  val conf = new SparkConf(false)
    .setMaster("local[4]")
    .setAppName("play")
    .set("spark.logConf", "true")
    .set("spark.driver.host", s"$driverHost")

  val sc = new SparkContext(conf)

  val sqlContext = new org.apache.spark.sql.SQLContext(sc)

  val options = Map(
    "url" -> getConfigProperty("db.spark.url", ""),
    "user" -> getConfigProperty("db.spark.user", ""),
    "password" -> getConfigProperty("db.spark.password", ""),
    "dbtable" -> getConfigProperty("db.spark.dbtable", ""),
    "driver" -> getConfigProperty("db.spark.driver", "")
  )

  val jdbcDF = sqlContext.read.format("jdbc").options(options).load()
  val dateCategoryPairs = jdbcDF.map(x => (format.parse("" + x(4)), "" + x(1))).groupByKey()
  val dateCategoryPairsWithMappedValues = dateCategoryPairs.map(x => (x._1, x._2.map(y => (y, 1))))
  val finalPass = dateCategoryPairsWithMappedValues.map(x => (x._1, x._2.groupBy(_._1).map(y => (y._1, y._2.size))))
  finalPass.cache()

  def getCategoriesByDate(date: String): Map[String, Int] = {

    val filteredRDD = finalPass.filter {
      _._1.getTime <= format.parse(date + " 00:00:00.0").getTime
    }
    filteredRDD.flatMap(_._2).reduceByKey(_ + _).collect().toMap

  }

  def getDateRange(maybeString: String): DataResponse = {
    var dates = Seq.empty[String]
    var c3data = Map.empty[String, Seq[Long]]

    val from = LocalDate.fromDateFields(format.parse("2005-08-01 00:00:00.0"))
    val until = LocalDate.fromDateFields(format.parse("2015-08-01 00:00:00.0"))

    val numberOfMonth = Months.monthsBetween(from, until).get(DurationFieldType.months())
    val monthDates = for (f <- 0 to numberOfMonth) yield from.plusMonths(f)
    val reverseMonthDates = monthDates.reverse

    def loadDataForDay(date: LocalDate): Unit = {

      def updateMap(key: String, value: Long): Unit = c3data += key -> (c3data.getOrElse(key, Seq.empty[Long]) :+ value)

      dates = dates :+ date.toString
      val args = getCategoriesByDate(date.toString)
      args foreach { case (key, value) => updateMap(key, value) }
    }

    reverseMonthDates foreach (loadDataForDay(_))

    DataResponse(dates, c3data)
  }
}


text:
import logging

from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.query import QuerySet

from accelerator.models import CoreProfile
from accelerator_abstract.models.base_base_profile import (
    ENTREPRENEUR_USER_TYPE,
    EXPERT_USER_TYPE,
    MEMBER_USER_TYPE,
)

import swapper

EntrepreneurProfile = swapper.load_model('accelerator', "EntrepreneurProfile")
ExpertProfile = swapper.load_model('accelerator', "ExpertProfile")
MemberProfile = swapper.load_model('accelerator', "MemberProfile")
BaseProfile = swapper.load_model('accelerator', "BaseProfile")
User = get_user_model()

MISSING_BASE_PROFILE_TEMPLATE = ("Missing BaseProfile for user {}. "
                                 "Creating.")

logger = logging.getLogger(__file__)

EMAIL_KEY = 'email'
PK_KEY = 'pk'

PROFILE_CLASSES_AND_TYPES = [
    (ExpertProfile, EXPERT_USER_TYPE),
    (EntrepreneurProfile, ENTREPRENEUR_USER_TYPE),
    (MemberProfile, MEMBER_USER_TYPE)
]

MISSING_PROFILE_TEMPLATE = ("No CoreProfile Subclass found. Creating a "
                            "default profile of type '{}'")

INCORRECT_USER_TYPE_TEMPLATE = ("Incorrect user_type found. "
                                "Fixing from '{}' to '{}'")

class ProfileQuerySet(QuerySet):
    """return the appropriate user profile type given user_type"""

    def get(self, *args, **kwargs):
        if PK_KEY in kwargs.keys():
            self.user = User.objects.get(pk=kwargs[PK_KEY])
        elif EMAIL_KEY in kwargs.keys():
            self.user = User.objects.get(email=kwargs[EMAIL_KEY])

        profile_manager = self._profile_manager_by_user_type()

        profile = self._profile_for_inferred_profile_type(profile_manager)
        if profile:
            return profile
        else:
            self._add_base_profile_if_missing()
            return self._get_or_create_profile()

    def _profile_manager_by_user_type(self):
        try:
            self.base_profile = BaseProfile.manager.get(user=self.user)
        except ObjectDoesNotExist:
            self.base_profile = None
            return None
        profile_managers = {user_type: kls.objects for
                            kls, user_type in PROFILE_CLASSES_AND_TYPES}
        return profile_managers.get(self.base_profile.user_type, None)

    def _profile_for_inferred_profile_type(self, profile_manager):
        if profile_manager is None:
            return None
        return profile_manager.using(self._db).filter(user=self.user).first()

    def _add_base_profile_if_missing(self):
        if not self.base_profile:
            logger.warning(MISSING_BASE_PROFILE_TEMPLATE.format(self.user))
            self.base_profile = BaseProfile.manager.create(user=self.user)

    def _get_or_create_profile(self):
        return (self._get_profile_from_existing_profile_types() or
                self._create_default_profile())

    def _create_default_profile(self):
        logger.warning(MISSING_PROFILE_TEMPLATE.format(MEMBER_USER_TYPE))
        self.base_profile.user_type = MEMBER_USER_TYPE
        self.base_profile.save()
        member_profile = MemberProfile.objects.create(user=self.user)
        member_profile.save()
        return member_profile

    def _get_profile_from_existing_profile_types(self):
        profile = CoreProfile.objects.using(self._db).filter(
            user=self.user).first()
        for kls, user_type in PROFILE_CLASSES_AND_TYPES:
            if profile and profile.__class__ == kls:
                self._update_user_type(user_type)
                break
        return profile

    def _update_user_type(self, user_type):
        logger.warning(INCORRECT_USER_TYPE_TEMPLATE.format(
            self.base_profile.user_type or "", user_type))
        self.base_profile.user_type = user_type
        self.base_profile.save()


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Norm")]
[assembly: AssemblyDescription("(Yet Another) .NET ORM")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Norm")]
[assembly: AssemblyCopyright("Copyright © Brandon Wood 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Norm.Tests")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cb06643d-00f6-4457-9e77-4b0dc6dfa00a")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]


text:
class CreatePvs < ActiveRecord::Migration[5.1]
  def change
    create_table :pvs do |t|
      t.integer :work_id, null: false
      t.string :url, null: false
      t.string :title, null: false
      t.attachment :thumbnail
      t.integer :sort_number, null: false, default: 0
      t.string :aasm_state, null: false, default: "published"
      t.timestamps null: false
    end

    add_index :pvs, :work_id
    add_foreign_key :pvs, :works
  end
end


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class MenuGUI : MonoBehaviour, IObjects {

	private ObjectsController objects;
    /// <summary>
    /// メニュー部パネルのオブジェクト(インスペクタで初期化)
    /// </summary>
    [SerializeField]
    private GameObject panelMenu;
    /// <summary>
    ///  画面無効化用画像オブジェクト(インスペクタで初期化)
    /// </summary>
    [SerializeField]
    private GameObject uiDisabledMaskImgObject;
    /// <summary>
    ///  スロット番号入力部(インスペクタで初期化)
    /// </summary>
    [SerializeField]
    private InputField inputFieldSlot;
	/// <summary>
	///  画面無効化用画像(uiDisabledMaskingObjectより)
	/// </summary>
	private Image uiDisabledMaskImg;
	/// <summary>
	///  スロット番号
	/// </summary>
	private int slotNum = 0;
	/// <summary>
	///  スロット最小値
	/// </summary>
	private const int SLOT_MINIMIZE = 0;
	/// <summary>
	///  スロット最大値
	/// </summary>
	private const int SLOT_MAXIMIZE = 99;
	/// <summary>
	///  ボタン配列(start()で初期化.PanelMenu中のすべてのボタンを格納)
	/// </summary>
	private Button[] btnArray;
	/// <summary>
	///  ファイル選択インスタンス(start()で初期化.MenuGUIにアタッチ済み)
	/// </summary>
	private FileChooser fileChooser;
	/// <summary>
	///  ボタン有効・無効フラグ
	/// </summary>
	private bool isBtnsDisabled;

    public void Initialize(ObjectsController controller) {
        objects = controller;
        objects.Dialog.DialogFinished += new DialogFinishedEventHandler(DialogFinished);
    }

	// Use this for initialization
	void Start () {
		// スロット番号入力部初期化
		inputFieldSlot.text = slotNum.ToString ();
		// 初期化
		fileChooser = this.GetComponent<FileChooser> ();
		btnArray = panelMenu.GetComponentsInChildren<Button> ();
		isBtnsDisabled = false;

        // イベント登録
        fileChooser.OpenFileDialogFinished += new OpenFileDialogFinishedEventHander(OpenFileDialogFinished);
        fileChooser.SaveFileDialogFinished += new SaveFileDialogFinishedEventHander(SaveFileDialogFinished);

        // PanelMenuのColliderを調整(画面解像度により大きさが変わるので)
        BoxCollider2D collider = panelMenu.GetComponent<BoxCollider2D> ();
		Rect rect = panelMenu.GetComponent<RectTransform> ().rect;
		collider.size = rect.size;
		collider.offset = new Vector2 (rect.width / 2, rect.height / 2);

		//  画面無効用画像のサイズを調整(画面解像度により大きさが変わるので)
		RectTransform maskingRectTransform = uiDisabledMaskImgObject.GetComponent<RectTransform> ();
		maskingRectTransform.sizeDelta = objects.DispCanvasRectTransform.rect.size;
		//  画面無効用画像インスタンス設定.非表示に.
		uiDisabledMaskImg = uiDisabledMaskImgObject.GetComponent<Image> ();
		uiDisabledMaskImg.enabled = false;
	}

	void Update () {
		// アニメーション再生時は停止ボタン以外を無効化する
		if (objects.IsAnimationPlaying == true) {
			if (isBtnsDisabled == false) {
				foreach (Button btn in btnArray) {
					if (btn.name != "BtnStop")
						btn.enabled = false;
				}
				isBtnsDisabled = true;
			}
		}
		// ボタン無効化を解除
		else if (isBtnsDisabled == true) {
			foreach(Button btn in btnArray) {
				btn.enabled = true;
			}
			isBtnsDisabled = false;
		}

}
	/// <summary>
	///  ダイアログ終了メソッド(イベント呼び出し)
	/// </summary>
	/// <param name="isBtnOKClicked">If set to <c>true</c> : OKボタンがクリックされた</param>
	private void DialogFinished(bool isBtnOKClicked) {
		// OKボタンがクリックされた場合,全フレームをリセットする.
		uiDisabledMaskImg.enabled = false;
		if (isBtnOKClicked == true) {
			objects.PanelFrames.AllFramesReset ();
		}
	}
	/// <summary>
	///  OpenFileDialog終了通知メソッド(イベント呼び出し)
	/// </summary>
	/// <param name="path">選択されたファイルパス</param>
	/// <param name="errorMessage">エラーメッセージ</param>
	private void OpenFileDialogFinished(string path, string errorMessage) {
		// 画面有効化.フラグをリセット.
		uiDisabledMaskImg.enabled = false;
		objects.IsAllObjectWaitRequest = false;
		// パスがセットされていない→メソッド終了
		if (string.IsNullOrEmpty (path))
			return;
		// JSONファイルを読出し,モーションデータに変換・表示.
		string readStr;
		using (StreamReader reader = new StreamReader (path)) {
			readStr = reader.ReadToEnd ();
		}
		objects.PanelFrames.MotionFramesRead (readStr);
	}
	/// <summary>
	///  SaveFileDialog終了通知メソッド(イベント呼び出し)
	/// </summary>
	/// <param name="path">選択されたファイルパス</param>
	/// <param name="errorMessage">エラーメッセージ</param>
	private void SaveFileDialogFinished(string path, string errorMessage) {
		// 画面有効化.フラグをリセット.
		uiDisabledMaskImg.enabled = false;
		objects.IsAllObjectWaitRequest = false;
		// パスがセットされていない→メソッド終了
		if (string.IsNullOrEmpty (path))
			return;
		// 拡張子が入力されていないとき,拡張子をつける
		if (Path.GetExtension (path) != ".json") {
			path += ".json";
		}
		// モーションデータからJSONファイルに変換し,そのファイルを保存する
		string fileName = System.IO.Path.GetFileNameWithoutExtension (path);
		string jsonStr = objects.MotionData.MotionJSONDataCreate (fileName);
		using (FileStream stream = File.Create (path)) {
			using (StreamWriter writer = new StreamWriter (stream)) {
				writer.Write (jsonStr);
			}
		}
	}

	public void BtnOpen_Click() {
		// 画面無効化,フラグセットを行いOpenFileDialogを表示
		objects.IsAllObjectWaitRequest = true;
		uiDisabledMaskImg.enabled = true;
		fileChooser.OpenFileDialog_Show ();
	}
	public void BtnSave_Click() {
		// 画面無効化,フラグセットを行いSaveFileDialogを表示
		objects.IsAllObjectWaitRequest = true;
		uiDisabledMaskImg.enabled = true;
		fileChooser.SaveFileDialog_Show ();
	}
	public void BtnNew_Click() {
		objects.Dialog.Show ("本当に新規モーションを作成しますか?",
			"現在の作業内容が破棄されます." + System.Environment.NewLine + "保存がまだの場合は"キャンセル"をクリックしてください");
		uiDisabledMaskImg.enabled = true;
	}
	public void BtnDefaultPos_Click(GameObject motionDataObject) {
		// フレーム初期化
		objects.PanelFrames.FrameInitialize ();
	}
	public void BtnPlay_Click() {
		// アニメーション再生
		objects.PlenAnimation.AnimationPlay ();
	}
	public void BtnStop_Click() {
		// アニメーション停止
		objects.PlenAnimation.AnimationStop ();
	}
	public void BtnBackFrame_Click() {
		// ひとつ前のフレームを選択
		objects.PanelFrames.FrameGoBack ();
	}
	public void BtnForwardFrame_Click()
	{
		// ひとつ次のフレームを選択
		objects.PanelFrames.FrameGoNext ();
	}
	public void BtnInstall_Click() {
		// モーションインストールを行う
		string fileName = "fromMotionEditor";
		string jsonPath = ObjectsController.TmpFilePath + "/" + fileName + ".json";
		// JSONファイル作成.保存.
		string jsonStr = objects.MotionData.MotionJSONDataCreate (fileName);
		using (FileStream stream = File.Create (jsonPath)) {
			using (StreamWriter writer = new StreamWriter (stream)) {
				writer.Write (jsonStr);
			}
		}
		// 保存したJSONファイルをもとにモーションインストーラを起動.
		objects.MotionInstall.StartMotionInstallApp (@jsonPath,  @fileName);
	}
	public void BtnSync_Click() {
	}
	public void BtnMirror_Click() {
		objects.MotionData.ModelTurnOver ();
	}
	public void BtnMirrorRtoL_Click() {
		objects.MotionData.ModelMirror (true);
	}
	public void BtnMirrorLtoR_Click() {
		objects.MotionData.ModelMirror (false);
	}
	public void BtnCameraReset_Click() {
		objects.ModelViewController.CameraViewInitalize ();
	}
	public void BtnSample1_Click() {
		SampleMotionRead (1);
	}
	public void BtnSample2_Click() {
		SampleMotionRead (2);
	}
	public void BtnSample3_Click() {
		SampleMotionRead (3);
	}
	/// <summary>
	/// サンプルモーション読み込みメソッド
	/// </summary>
	/// <param name="index">Index</param>
	private void SampleMotionRead(int index) {
		string path = ObjectsController.SampleMotionDirPath + "Sample" + index.ToString () + ".json";
		// パスがセットされていない→メソッド終了
		if (string.IsNullOrEmpty (path))
			return;
		// JSONファイルを読出し,モーションデータに変換・表示.
		string readStr;
		using (StreamReader reader = new StreamReader (path)) {
			readStr = reader.ReadToEnd ();
		}
		objects.PanelFrames.MotionFramesRead (readStr);
	}
	/// <summary>
	///  スロット番号更新メソッド(イベント呼び出し.InputFieldSlotの値が変更された.)
	/// </summary>
	public void InputFieldSlotUpdate() {
		int tmp;
		// 入力された文字が数値か判別
		if (int.TryParse (inputFieldSlot.text, out tmp)) {
			// 入力された数値が最大値・最小値を超えていないか判別,値セット
			if (tmp > SLOT_MAXIMIZE) {
				slotNum = SLOT_MAXIMIZE;
				inputFieldSlot.text = SLOT_MAXIMIZE.ToString ();
			} else if (tmp < SLOT_MINIMIZE) {
				slotNum = SLOT_MINIMIZE;
				inputFieldSlot.text = SLOT_MINIMIZE.ToString ();
			} else {
				slotNum = tmp;
			}
			objects.MotionData.SlotNum = slotNum;
		} else {
			// 入力された文字が数値でなかったので復元
			inputFieldSlot.text = slotNum.ToString();
		}
	}
	/// <summary>
	///  スロット番号更新メソッド(InputFieldSlotの値を変更する)
	/// </summary>
	/// <param name="value">変更値(初期値:int.MinValue).</param>
	public void InputFieldSlotUpdate(int value = int.MinValue) {
		// valueが最大値・最小値を超えていないか判別し,値をセット
		if (value >= SLOT_MINIMIZE && value <= SLOT_MAXIMIZE) {
			slotNum = value;
			inputFieldSlot.text = value.ToString();
			objects.MotionData.SlotNum = value;
		}

	}

}


text:
class AddressPresenter < ModelPresenter
  delegate :prefecture, :city, :address1, :address2, :company_name, :division_name, to: :object

  def postal_code
    if md = object.postal_code.match(/\A(\d{3})(\d{4})\z/)
      md[1] + '-' + md[2]
    else
      object.postal_code
    end
  end

  def phones
    object.phones.map(&:number)
  end
end


text:
COREOS_IP=172.17.8.200 #defined in Vagrantfile

echo 'starting vagrant test env'
    # make sure we start with a clean slate
	vagrant destroy -f > /dev/null 2>&1
	output=`vagrant up`
	port=`echo $output | grep -Eo 'service-toolkit-test: 2375 => (\d+)' | awk '{print $4}'`
	# port=2375
	docker="docker -H 127.0.0.1:$port"
	docker_run="$docker run --rm --name test-service-toolkit "
	sleep 10 #it takes coreos a few seconds to make sure docker is up and running

echo 'building skippy/service_toolkit within test env'
	$docker build -q -t skippy/service_toolkit ../. > /dev/null 2>&1

function expect_success() {
	ret=$?
	if [ "$ret" -ne "0" ]; then
		printf '\033[31mFail\033[m\n'
		if [ "$1" != "" ]; then
			printf "   at label: $1\n"
		fi
		printf "\n\n"
	    exit $ret
	else
		printf '\033[32m.\033[m'
    fi
}

function print_success() {
	printf '\033[32m Pass\033[m\n'
}

function reset_locks() {
	vagrant ssh service-toolkit-test -- -A 'etcdctl rm --recursive /locks' > /dev/null 2>&1
}

function reset_services() {
	vagrant ssh service-toolkit-test -- -A 'etcdctl rm --recursive /services' > /dev/null 2>&1
}

function test_group_title() {
	echo -e "\n------------------ Checking: $1"
}

function test_title() {
	echo -n "   - $1: "
}

function expect_text() {
	echo $1 | grep -iE "$2" > /dev/null 2>&1
	expect_success "checking for '$2' amongst $1"
}

function expect() {
	test "$1" $2 "$3"
	expect_success "'$1' $2 '$3'"
}

test_group_title 'acquire-lease'
	#start clean!
	reset_locks

test_title 'attempt to acquire lease'
	output=`$docker_run skippy/service_toolkit acquire-lease --label=MyService --service-id=MyService-1 --host-ip=$COREOS_IP`
	expect_success "check1"
	expect_text "$output", 'acquired lease'
	output=`vagrant ssh service-toolkit-test -- -A 'etcdctl get /locks/myservice'`
	expect "$output" = "MyService-1"
	reset_locks
	print_success

test_title 'lease has a ttl'
	$docker_run skippy/service_toolkit acquire-lease --label=MyService --service-id=MyService-1 --host-ip=$COREOS_IP > /dev/null 2>&1
	expect_success "check1"
	output=`vagrant ssh service-toolkit-test -- -A 'curl -sL http://127.0.0.1:4001/v2/keys/locks/myservice'`
	expect_success "check2"
	ttl=`echo $output | grep -Eo '"ttl":\d+' | awk -F ':' '{print $2}'`
	expect_success "check3"
	test $ttl -gt 200
	expect_success "check4"
	reset_locks
	print_success

test_title 'cannot grab a lease until the old one expires'
	t1=`date +"%s"`
	$docker_run skippy/service_toolkit acquire-lease --label=MyService --service-id=MyService-1 --host-ip=$COREOS_IP --lease-timeout=5 > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit acquire-lease --label=MyService --service-id=MyService-2 --host-ip=$COREOS_IP`
	expect_success "check1"
	t2=`date +"%s"`
	expect_text "$output", 'acquired lease'
	output=`vagrant ssh service-toolkit-test -- -A 'etcdctl get /locks/myservice'`
	expect_success "check3"
	expect "$output" = "MyService-2"
	test $(expr $t2 - $t1) -ge 5
	expect_success "check5"
	test $(expr $t2 - $t1) -le 10
	expect_success "check6"
	reset_locks
	print_success

test_title 'acquire lease for a different service label when another lease is outstanding'
	output=`$docker_run skippy/service_toolkit acquire-lease --label=MyService --service-id=MyService-1 --host-ip=$COREOS_IP`
	expect_success "check1"
	expect_text "$output", 'acquired lease'
	t1=`date +"%s"`
	output=`$docker_run skippy/service_toolkit acquire-lease --label=MyService-other --service-id=MyService-1 --host-ip=$COREOS_IP`
	expect_success "check2"
	expect_text "$output", 'acquired lease'
	t2=`date +"%s"`
	output=`vagrant ssh service-toolkit-test -- -A 'etcdctl get /locks/myservice-other'`
	expect_success "check3"
	expect "$output" = "MyService-1"
	#make sure we didn't wait for a long time!
	test $(expr $t2 - $t1) -le 5
	expect_success "check5"
	reset_locks
	print_success

test_title 'acquire the same lease when the same service label and ID are asking for it'
	output=`$docker_run skippy/service_toolkit acquire-lease --label=MyService --service-id=MyService-1 --host-ip=$COREOS_IP`
	expect_success "check1"
	expect_text "$output", 'acquired lease'
	t1=`date +"%s"`
	output=`$docker_run skippy/service_toolkit acquire-lease --label=MyService --service-id=MyService-1 --host-ip=$COREOS_IP`
	expect_success "check2"
	expect_text "$output", 'acquired lease'
	t2=`date +"%s"`
	output=`vagrant ssh service-toolkit-test -- -A 'etcdctl get /locks/myservice'`
	expect_success "check3"
	expect "$output" = "MyService-1"
	#make sure we didn't wait for a long time!
	test $(expr $t2 - $t1) -le 5
	expect_success "check5"
	reset_locks
	print_success

test_group_title 'hosts'
	#start clean!
	reset_services

test_title 'returns an empty string when no hosts are present'
	output=`$docker_run skippy/service_toolkit hosts --label=MyService --host-ip=$COREOS_IP`
	expect_success "check1"
	expect "$output" = ""
	reset_services
	print_success

test_title 'returns a single host when one host is registered'
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice/hosts/10.0.0.1 junk' > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=MyService --host-ip=$COREOS_IP`
	expect_success "check1"
	expect "$output" = '10.0.0.1'
	reset_services
	print_success

test_title 'returns a comma delimited list when multiple hosts exist'
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice/hosts/10.0.0.1 junk' > /dev/null 2>&1
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice/hosts/10.0.0.2 junk' > /dev/null 2>&1
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice/hosts/10.0.0.10 junk' > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=MyService --host-ip=$COREOS_IP`
	expect_success "check1"
	expect "$output" = '10.0.0.1,10.0.0.10,10.0.0.2'
	reset_services
	print_success

test_title 'returns a comma delimited list only from the service specified'
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice/hosts/10.0.0.1 junk' > /dev/null 2>&1
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice-other/hosts/10.0.0.10 junk' > /dev/null 2>&1
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice/hosts/10.0.0.2 junk' > /dev/null 2>&1
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice-other/hosts/10.0.0.2 junk' > /dev/null 2>&1
	vagrant ssh service-toolkit-test -- -A 'etcdctl set /services/myservice/hosts/10.0.0.5 junk' > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=MyService --host-ip=$COREOS_IP`
	expect_success "check1"
	expect "$output" = '10.0.0.1,10.0.0.2,10.0.0.5'
	reset_services
	print_success

test_group_title 'watch'
	#start clean!
	reset_services

function clean_watch_shutdown() {
	$docker stop nginx > /dev/null 2>&1
	$docker rm nginx > /dev/null 2>&1
	$docker stop toolkit > /dev/null 2>&1
	$docker rm toolkit > /dev/null 2>&1
}

test_title 'adds a host if the monitor-url is successful'
	clean_watch_shutdown
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check1"
	expect "$output" = ''
	$docker run -d --name=nginx -p 8080:80 nginx > /dev/null 2>&1
	$docker run -d --name=toolkit skippy/service_toolkit watch --label=webServ --host-ip=$COREOS_IP --monitor-url=http://172.17.8.200:8080 > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check2"
	expect "$output" = '172.17.8.200'
	clean_watch_shutdown
	reset_services
	print_success

test_title 'does not add a host if the monitor-url is not successful'
	clean_watch_shutdown
	$docker run -d --name=toolkit skippy/service_toolkit watch --label=webServ --host-ip=$COREOS_IP --monitor-url=http://172.17.8.200:8000 > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check1"
	expect "$output" = ''
	sleep 9
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check2"
	expect "$output" = ''
	clean_watch_shutdown
	reset_services
	print_success

test_title 'removes the host if the monitor-url was successful and then is not'
	clean_watch_shutdown
	$docker run -d --name=nginx -p 8080:80 nginx > /dev/null 2>&1
	$docker run -d --name=toolkit skippy/service_toolkit watch --label=webServ --host-ip=$COREOS_IP --monitor-url=http://172.17.8.200:8080 > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check1"
	expect "$output" = '172.17.8.200'
	$docker kill nginx > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check2"
	expect "$output" = '172.17.8.200'
	sleep 9
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check3"
	expect "$output" = ''
	clean_watch_shutdown
	reset_services
	print_success

test_title 'if the monitoring instance suddenly dies, the IP address will eventually be removed'
	clean_watch_shutdown
	$docker run -d --name=nginx -p 8080:80 nginx > /dev/null 2>&1
	$docker run -d --name=toolkit skippy/service_toolkit watch --label=webServ --host-ip=$COREOS_IP --monitor-url=http://172.17.8.200:8080 > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check1"
	expect "$output" = '172.17.8.200'
	#lets kill, so it shutdowns without time to cleanup after itself
	$docker kill toolkit > /dev/null 2>&1
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check2"
	expect "$output" = '172.17.8.200'
	sleep 12
	output=`$docker_run skippy/service_toolkit hosts --label=webServ --host-ip=$COREOS_IP`
	expect_success "check3"
	expect "$output" = ''
	clean_watch_shutdown
	reset_services
	print_success

test_title 'adds a default package of information to etcd if the monitor-url is successful'
	clean_watch_shutdown
	$docker run -d --name=nginx -p 8080:80 nginx > /dev/null 2>&1
	$docker run -d --name=toolkit skippy/service_toolkit watch --label=webServ --host-ip=$COREOS_IP --monitor-url=http://172.17.8.200:8080 > /dev/null 2>&1

	output=`vagrant ssh service-toolkit-test -- -A 'etcdctl get /services/webserv/hosts/172.17.8.200'`
	expect_text "$output", '{"ip": ".+?", "host": ".+?", "label": ".+?"}'
	expect_text "$output", '"ip": "172.17.8.200"'
	expect_text "$output", '"label": "webserv"'
	clean_watch_shutdown
	reset_services
	print_success

printf '\n\033[32m Success! \033[m\n\n'
# CLEANUP!
vagrant destroy -f > /dev/null 2>&1


text:
export const BASIC_AUTH_PERMISSION = 'canBasicAuth';

// Permission descriptions
export const PERMISSION_DESCRIPTION = {
    [BASIC_AUTH_PERMISSION]: 'common.permissions.canBasicAuth',
};


text:
(function() {
    angular.module('CSM')
    .config(function($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: 'templates/pages/home/index.html'
        })
        .when('/team', {
            templateUrl: 'templates/pages/team/index.html'
        })
        .when('/mentors', {
            templateUrl: 'templates/pages/mentors/index.html'
        })
        .when('/students', {
            templateUrl: 'templates/pages/students/index.html'
        })
        .when('/partners', {
            templateUrl: 'templates/pages/partners/index.html'
        })
        .otherwise({
            redirectTo: '/'
        });
    });
})();


text:
from typing import cast

import pytest

import cirq

def test_flatten_op_tree():
    operations = [
        cirq.GateOperation(cirq.testing.SingleQubitGate(), [cirq.NamedQubit(str(i))])
        for i in range(10)
    ]

    # Empty tree.
    assert list(cirq.flatten_op_tree([[[]]])) == []

    # Just an item.
    assert list(cirq.flatten_op_tree(operations[0])) == operations[:1]

    # Flat list.
    assert list(cirq.flatten_op_tree(operations)) == operations

    # Tree.
    assert (
        list(cirq.flatten_op_tree((operations[0], operations[1:5], operations[5:]))) == operations
    )

    # Flatten moment.
    assert (
        list(cirq.flatten_op_tree((operations[0], cirq.Moment(operations[1:5]), operations[5:])))
        == operations
    )

    # Bad trees.
    with pytest.raises(TypeError):
        _ = list(cirq.flatten_op_tree(None))
    with pytest.raises(TypeError):
        _ = list(cirq.flatten_op_tree(5))
    with pytest.raises(TypeError):
        _ = list(cirq.flatten_op_tree([operations[0], (4,)]))

def test_flatten_to_ops_or_moments():
    operations = [
        cirq.GateOperation(cirq.testing.SingleQubitGate(), [cirq.NamedQubit(str(i))])
        for i in range(10)
    ]
    op_tree = [operations[0], cirq.Moment(operations[1:5]), operations[5:]]
    output = [operations[0], cirq.Moment(operations[1:5])] + operations[5:]
    assert list(cirq.flatten_to_ops_or_moments(op_tree)) == output
    assert list(cirq.flatten_op_tree(op_tree, preserve_moments=True)) == output

    # Bad trees.
    with pytest.raises(TypeError):
        _ = list(cirq.flatten_to_ops_or_moments(None))
    with pytest.raises(TypeError):
        _ = list(cirq.flatten_to_ops_or_moments(5))
    with pytest.raises(TypeError):
        _ = list(cirq.flatten_to_ops_or_moments([operations[0], (4,)]))

def test_freeze_op_tree():
    operations = [
        cirq.GateOperation(cirq.testing.SingleQubitGate(), [cirq.NamedQubit(str(i))])
        for i in range(10)
    ]

    # Empty tree.
    assert cirq.freeze_op_tree([[[]]]) == (((),),)

    # Just an item.
    assert cirq.freeze_op_tree(operations[0]) == operations[0]

    # Flat list.
    assert cirq.freeze_op_tree(operations) == tuple(operations)

    # Tree.
    assert cirq.freeze_op_tree(
        (operations[0], (operations[i] for i in range(1, 5)), operations[5:])
    ) == (operations[0], tuple(operations[1:5]), tuple(operations[5:]))

    # Bad trees.
    with pytest.raises(TypeError):
        cirq.freeze_op_tree(None)
    with pytest.raises(TypeError):
        cirq.freeze_op_tree(5)
    with pytest.raises(TypeError):
        _ = cirq.freeze_op_tree([operations[0], (4,)])

def test_transform_bad_tree():
    with pytest.raises(TypeError):
        _ = list(cirq.transform_op_tree(None))
    with pytest.raises(TypeError):
        _ = list(cirq.transform_op_tree(5))
    with pytest.raises(TypeError):
        _ = list(
            cirq.flatten_op_tree(
                cirq.transform_op_tree(
                    [cirq.GateOperation(cirq.Gate(), [cirq.NamedQubit('q')]), (4,)]
                )
            )
        )

def test_transform_leaves():
    gs = [cirq.testing.SingleQubitGate() for _ in range(10)]
    operations = [cirq.GateOperation(gs[i], [cirq.NamedQubit(str(i))]) for i in range(10)]
    expected = [cirq.GateOperation(gs[i], [cirq.NamedQubit(str(i) + 'a')]) for i in range(10)]

    def move_left(op: cirq.GateOperation):
        return cirq.GateOperation(
            op.gate, [cirq.NamedQubit(cast(cirq.NamedQubit, q).name + 'a') for q in op.qubits]
        )

    def move_tree_left_freeze(root):
        return cirq.freeze_op_tree(cirq.transform_op_tree(root, move_left))

    # Empty tree.
    assert move_tree_left_freeze([[[]]]) == (((),),)

    # Just an item.
    assert move_tree_left_freeze(operations[0]) == expected[0]

    # Flat list.
    assert move_tree_left_freeze(operations) == tuple(expected)

    # Tree.
    assert move_tree_left_freeze((operations[0], operations[1:5], operations[5:])) == (
        expected[0],
        tuple(expected[1:5]),
        tuple(expected[5:]),
    )

def test_transform_internal_nodes():
    operations = [
        cirq.GateOperation(cirq.testing.SingleQubitGate(), [cirq.LineQubit(2 * i)])
        for i in range(10)
    ]

    def skip_first(op):
        first = True
        for item in op:
            if not first:
                yield item
            first = False

    def skip_tree_freeze(root):
        return cirq.freeze_op_tree(cirq.transform_op_tree(root, iter_transformation=skip_first))

    # Empty tree.
    assert skip_tree_freeze([[[]]]) == ()
    assert skip_tree_freeze([[[]], [[], []]]) == (((),),)

    # Just an item.
    assert skip_tree_freeze(operations[0]) == operations[0]

    # Flat list.
    assert skip_tree_freeze(operations) == tuple(operations[1:])

    # Tree.
    assert skip_tree_freeze((operations[1:5], operations[0], operations[5:])) == (
        operations[0],
        tuple(operations[6:]),
    )


text:
RSpec::Matchers.define(:produce_tokens) do |expected|
  match do |actual|
    @expected = expected.join("\n")
    @actual = described_class.lex(actual).map(&:to_s).join("\n")
    values_match? @expected, @actual
  end

  diffable
end


text:
export default class MoneyConverter {

  static convertPenniesToPounds (amount: number): number {
    return amount / 100
  }

  static convertPoundsToPennies (amount: number): number {
    return Math.round(amount * 100)
  }
}


text:
from twisted.web import client

class HTTPClientFactory(client.HTTPClientFactory):
    USER_AGENT = "rmake-plugin/1.0"

    def __init__(self, url, *args, **kwargs):
        if 'agent' not in kwargs:
            kwargs.update(agent=self.USER_AGENT)
        client.HTTPClientFactory.__init__(self, url, *args, **kwargs)
        self.status = None
        self.deferred.addCallback(
            lambda data: (data, self.status, self.response_headers))