text:
A PHP SubString manipulation library with multibyte support that extends Stringy. Offers OO method
chaining. Tested and compatible with PHP 5.4+ and HHVM.

This library extends and adds SubString functionality to `danielstjules/Stringy` you should check it's [documentation](https://github.com/danielstjules/Stringy/blob/master/README.md) for methods inherited by SubStringy.

[![Build Status](https://api.travis-ci.org/tcb13/SubStringy.svg?branch=master)](https://travis-ci.org/tcb13/SubStringy)

* [Installation](#installation)
* [OO and Chaining](#oo-and-chaining)
* [Use as a Trait](#use-as-a-trait)
* [Implemented Interfaces](#implemented-interfaces)
* [PHP 5.6 Creation](#php-56-creation)
* [Methods](#methods)
    * [substringAfterFirst](#substringafterfirst)
    * [substringAfterLast](#substringafterlast)
    * [substringBeforeFirst](#substringbeforefirst)
    * [substringBeforeLast](#substringbeforelast)
    * [substringBetween](#substringbetween)
    * [substringCount](#substringcount)
* [Links](#links)
* [Tests](#tests)
* [License](#license)

## Installation

If you're using Composer to manage dependencies, you can include the following
in your composer.json file:

```json
{
    "require": {
        "danielstjules/stringy": "^3.1",
        "tcb13/substringy": "^1.0"
    }
}
```

Then, after running `composer update` or `php composer.phar update`, you can
load the class using Composer's autoloading:

```php
require 'vendor/autoload.php';
```

Otherwise, you can simply require the file directly:

```php
require_once 'path/to/SubStringy/src/SubStringy.php';
```

And in either case, I'd suggest using an alias.

```php
use SubStringy\SubStringy as S;
```

## OO and Chaining

The library offers OO method chaining, as seen below:

```php
use Stringy\Stringy as S;
echo S::create('Fòô     Bàř', 'UTF-8')->collapseWhitespace()->swapCase();  // 'fÒÔ bÀŘ'
```

`Stringy\Stringy` has a __toString() method, which returns the current string
when the object is used in a string context, ie:
`(string) S::create('foo')  // 'foo'`

## Use as a Trait

The library also offers the possibility to be used a `trait`. With this trait you can build your own abstraction of `danielstjules/Stringy` and combine multiple extensions:

```php
namespace Vendor\YourPackage;

use Stringy\Stringy;
use SubStringy\SubStringyTrait;
use SliceableStringy\SliceableStringyTrait;

class MyStringy extends Stringy
{
    use SubStringyTrait;
    use SliceableStringyTrait;
}
```

On the example bellow we can use `MyStringy` to create `Stringy` objects enhanced with the functionality of both `SubStringy` and `SliceableStringy`:

```php
use YourPackage\MyStringy as S;
$sliceableSubstring = S::create('What are your plans today?')->substringAfterFirst('plans ');
echo $sliceableSubstring['4:6'];
```

## Implemented Interfaces

`SubStringy\SubStringy` implements the `IteratorAggregate` interface, meaning that
`foreach` can be used with an instance of the class:

``` php
$stringy = S::create('Fòô Bàř', 'UTF-8');
foreach ($stringy as $char) {
    echo $char;
}
// 'Fòô Bàř'
```

It implements the `Countable` interface, enabling the use of `count()` to
retrieve the number of characters in the string:

``` php
$stringy = S::create('Fòô', 'UTF-8');
count($stringy);  // 3
```

Furthermore, the `ArrayAccess` interface has been implemented. As a result,
`isset()` can be used to check if a character at a specific index exists. And
since `Stringy\Stringy` is immutable, any call to `offsetSet` or `offsetUnset`
will throw an exception. `offsetGet` has been implemented, however, and accepts
both positive and negative indexes. Invalid indexes result in an
`OutOfBoundsException`.

``` php
$stringy = S::create('Bàř', 'UTF-8');
echo $stringy[2];     // 'ř'
echo $stringy[-2];    // 'à'
isset($stringy[-4]);  // false

$stringy[3];          // OutOfBoundsException
$stringy[2] = 'a';    // Exception
```

## PHP 5.6 Creation

As of PHP 5.6, [`use function`](https://wiki.php.net/rfc/use_function) is
available for importing functions. SubStringy exposes a namespaced function,
`SubStringy\create`, which emits the same behaviour as `SubStringy\SubStringy::create()`.
If running PHP 5.6, or another runtime that supports the `use function` syntax,
you can take advantage of an even simpler API as seen below:

``` php
use function SubStringy\create as s;

// Instead of: S::create('Fòô     Bàř', 'UTF-8')
s('Fòô     Bàř', 'UTF-8')->collapseWhitespace()->swapCase();
```

## Methods

All methods that return a SubStringy object or string do not modify the original. SubStringy objects are immutable.

Since this library extends and adds SubString functionality to `danielstjules/Stringy` you should check it's documentation (https://github.com/danielstjules/Stringy/blob/master/README.md) for methods that can also be transparently used when working with SubStringy.

*Note: If `$encoding` is not given, it defaults to `mb_internal_encoding()`.*

#### substringAfterFirst

$stringy->substringAfterFirst(string $separator)

Gets the substring after the first occurrence of a separator. If no match is found returns false.

```php
S::create('What are your plans today?')->substringAfterFirst('plans ');
```

#### substringAfterLast

$stringy->substringAfterLast(string $separator)

Gets the substring after the last occurrence of a separator. If no match is found returns false.

```php
S::create('This is a String. How cool can a String be after all?')->substringAfterLast('String ');
```

#### substringBeforeFirst

$stringy->substringBeforeFirst(string $separator)

Gets the substring before the first occurrence of a separator. If no match is found returns false.

```php
S::create('What are your plans today?')->substringBeforeFirst(' plans');
```

#### substringBeforeLast

$stringy->substringBeforeLast(string $separator)

Gets the substring before the last occurrence of a separator. If no match is found returns false.

```php
S::create('What are your plans today? Any plans for tomorrow?')->substringBeforeLast(' plans');
```

#### substringBetween

$stringy->substringBetween(string $start, string $end)

Extracts a substring from between two substrings present on the current string.

```php
S::create('What are your plans today?')->substringBetween('your ', ' today');
```

#### substringCount

$stringy->substringCount(string $substr)

Count the number of substring occurrences on the current string

```php
S::create('how are you? are you sure you are ok?')->substringCount('are');
```

## Links

The following is a list of libraries that extend Stringy:

 * [SliceableStringy](https://github.com/danielstjules/SliceableStringy):
Python-like string slices in PHP

## Tests

From the project directory, tests can be ran using `phpunit`

## License

Released under the MIT License - see `LICENSE.txt` for details.


text:
<!DOCTYPE html>

<title>Send data files to ArrayExpress via FTP < Help < ArrayExpress < EMBL-EBI</title>

Send data files to ArrayExpress by FTP

ArrayExpress provides a FTP repository for submitters to upload a large volume of data files associated with their experiment submissions. FTP upload is also useful if you would like to send files to us prior to a submission (e.g. for us to check if they are in a suitable format).

Before you start transferring files, please note the following points:

File preparation: Please check our guidelines on submitting files for a microarray experiment, sequencing experiment or array design. E.g. microarray data files should not be compressed, but fastq files from sequencing experiments must be individually compressed by gzip or bzip2 (as a requirement from the Sequence Read Archive).

Data privacy: All ArrayExpress submitters use the same account to upload files (see below). As most of the files are un-/pre-published, we make all uploaded files "private", which means you will not be able to see any files or directories already on the FTP site, including those that you uploaded or created.

No whitespaces or special characters in file namesMake sure the file names are constructed only from alphanumerals [A-Z,a-z,0-9], underscores [_] and dots [.], with no whitespaces, brackets, other punctuations or symbols.

Unique/specific file names: Make sure your file names are unique/specific so you will not be overwriting other submitters' files (or risk your own files being overwritten likewise). E.g. "Bloggs_lab_Mar2014_sample1.fq.gz" is a better choice of file name than simply "sample1.fq.gz".

Finish your experiment submission (if applicable): Data files uploaded to ArrayExpress by FTP are only part of an experiment submission. The submission is only complete when experimental meta-data (e.g. sample information and protocols) are also submitted to ArrayExpress using Annotare. See submissions help page for further details.

Email us (for non-Annotare submitters): When the transfer is complete, please email us at arrayexpress@ebi.ac.uk with the names of files transferred and a short note on what the files are for.

Transferring files with Windows Explorer (drag and drop)

Make sure you've opened a Windows Explorer window and not an internet browser window as the latter is not designed for FTP file uploads. You can open an Explorer window by going to Start, followed by Computer or My Computer (if using Windows XP). If you need further help, here is a short tutorial with screenshots.

In the Windows Explorer window, enter ftp://aexpress:aexpress1@ftp-private.ebi.ac.uk/ in the address bar. This URL already contains the username aexpress and password aexpress1, so you're logged in automatically after being connected to the FTP server.

If there are no error messages from Windows, that means connection is successful. (Unfortunately, Windows does not provide notification confirming successful connection to an FTP server.)  When connected, you will see an almost "blank" Windows Explorer window which is similar to this:

You can start dragging files from your computer's file system and dropping them onto the logged-on Windows Explorer window.

Note: you will not be able to see any files or directories on the FTP site, including the files that you have uploaded. This is because we don't allow submitters to see each others' data files.

Transferring files with Mac/Unix/Windows terminal (command prompt)

 Connect to the FTP server using the command ftp ftp-private.ebi.ac.uk. The username is aexpress and password is aexpress1.  Use the put command to place one file (or mput for multiple files) into the default FTP directory.

To exit FTP, type quit. On exiting you will get a message printed to screen to tell you whether your transfer was successful.

Note: you will not be able to list the files in the directory or download files from the FTP site to your directory. This is because we don't allow submitters to see each others' data files.

Help

Help home

Quick Start guide

How to search

Other ways to get data

Programmatic access

FTP archives

ExpressionSet R objects

How to submit

Sequencing submissions

Third-party tools

FAQ

Learn more about our data

Data access policy

Accession codes

GEO data

Contact us

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html >

          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
          <title>ScalaTest 3.0.1  - org.scalatest.matchers.MatcherProducers</title>
          <meta name="description" content="ScalaTest 3.0.1 - org.scalatest.matchers.MatcherProducers" />
          <meta name="keywords" content="ScalaTest 3.0.1 org.scalatest.matchers.MatcherProducers" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

        ScalaTest 3.0.1
        < Back

            <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
            
            

Packages

        

        package

              root

Definition Classes

root

        

        package

              org

Definition Classes

root

        

        package

              scalatest

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

Definition Classes

org

        

        package

              matchers

Definition Classes

scalatest

                          BeMatcher

                        <a class="class" href="BePropertyMatchResult.html" title="The result of a HtmlTag(<code>Boolean</code>) property match operation, such as one performed by a
HtmlTag(<a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>),
which contains one field that indicates whether the match succeeded (HtmlTag(<em>i.e.</em>), the HtmlTag(<code>Boolean</code>)
property was HtmlTag(<code>true</code>)) and one field that provides
the name of the property.HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</em>)HtmlTag(</a>)HtmlTag(</code>)">
                        <a href="BePropertyMatchResult.html" title="The result of a HtmlTag(<code>Boolean</code>) property match operation, such as one performed by a
HtmlTag(<a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>),
which contains one field that indicates whether the match succeeded (HtmlTag(<em>i.e.</em>), the HtmlTag(<code>Boolean</code>)
property was HtmlTag(<code>true</code>)) and one field that provides
the name of the property.HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</em>)HtmlTag(</a>)HtmlTag(</code>)">
                          BePropertyMatchResult

                          BePropertyMatcher

                        <a class="class" href="HavePropertyMatchResult.html" title="The result of a property match operation such as one performed by a
HtmlTag(<a href="HavePropertyMatcher.html"><code>HavePropertyMatcher</code></a>),
which contains one field that indicates whether the match succeeded (HtmlTag(<em>i.e.</em>), the
property had its expected value), one field that provides
the name of the property, and two fields giving the expected and actual values.HtmlTag(</em>)HtmlTag(</a>)">
                        <a href="HavePropertyMatchResult.html" title="The result of a property match operation such as one performed by a
HtmlTag(<a href="HavePropertyMatcher.html"><code>HavePropertyMatcher</code></a>),
which contains one field that indicates whether the match succeeded (HtmlTag(<em>i.e.</em>), the
property had its expected value), one field that provides
the name of the property, and two fields giving the expected and actual values.HtmlTag(</em>)HtmlTag(</a>)">
                          HavePropertyMatchResult

                          HavePropertyMatcher

                          LazyArg

                          MatchFailed

                          MatchPatternHelper

                        <a class="class" href="MatchResult.html" title="The result of a match operation, such as one performed by a HtmlTag(<a href="Matcher.html"><code>Matcher</code></a>) or
HtmlTag(<a href="BeMatcher.html"><code>BeMatcher</code></a>), which
contains one field that indicates whether the match succeeded, four fields that provide
raw failure messages to report under different circumstances, four fields providing
arguments used to construct the final failure messages using raw failure messages
and a HtmlTag(<a href="../../Prettifier.html"><code>Prettifier</code></a>).HtmlTag(</a>)HtmlTag(</a>)HtmlTag(</a>)">
                        <a href="MatchResult.html" title="The result of a match operation, such as one performed by a HtmlTag(<a href="Matcher.html"><code>Matcher</code></a>) or
HtmlTag(<a href="BeMatcher.html"><code>BeMatcher</code></a>), which
contains one field that indicates whether the match succeeded, four fields that provide
raw failure messages to report under different circumstances, four fields providing
arguments used to construct the final failure messages using raw failure messages
and a HtmlTag(<a href="../../Prettifier.html"><code>Prettifier</code></a>).HtmlTag(</a>)HtmlTag(</a>)HtmlTag(</a>)">
                          MatchResult

                          MatchSucceeded

                          Matcher

                          MatcherFactory1

                          MatcherFactory2

                          MatcherFactory3

                          MatcherFactory4

                          MatcherFactory5

                          MatcherFactory6

                          MatcherFactory7

                          MatcherFactory8

                          MatcherFactory9

                          MatcherProducers

                          TypeMatcherHelper

t

org.scalatest.matchers

MatcherProducers

        

            Companion object MatcherProducers

        trait

        MatcherProducers extends AnyRef

Provides an implicit conversion on functions that produce Matchers, i.e.,
T => Matcher[T] that enables you to modify error messages when composing Matchers.

For an example of using MatcherProducers, see the Composing matchers
section in the main documentation for trait Matcher.

Source

MatcherProducers.scala

            Linear Supertypes

AnyRef, Any

              Known Subclasses

MatcherProducers

          

            <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />

          

            Ordering

Alphabetic

By Inheritance

                  Inherited

MatcherProducers

AnyRef

Any

Hide All

Show All

              Visibility

Public

All

Type Members

        

        class

              Composifier
            [T] extends AnyRef

Class used via an implicit conversion that adds composeTwice, mapResult, and
mapArgs methods to functions that produce a Matcher.

Class used via an implicit conversion that adds composeTwice, mapResult, and
mapArgs methods to functions that produce a Matcher.

Value Members

        

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        implicit
        def

        convertToComposifier[T](f: (T) ⇒ Matcher[T]): Composifier[T]

Implicit conversion that converts a function of T => Matcher[T] to an object that has
composeTwice, mapResult and mapArgs methods.

Implicit conversion that converts a function of T => Matcher[T] to an object that has
composeTwice, mapResult and mapArgs methods.

The following shows how this trait is used to compose twice and modify error messages:

import org.scalatest._
import matchers._
import MatcherProducers._

val f = be > (_: Int)
val g = (_: String).toInt

// f composeTwice g means: (f compose g) andThen (_ compose g)
val beAsIntsGreaterThan =
  f composeTwice g mapResult { mr =>
    mr.copy(
      failureMessageArgs =
        mr.failureMessageArgs.map((LazyArg(_) { "\"" + _.toString + "\".toInt"})),
      negatedFailureMessageArgs =
        mr.negatedFailureMessageArgs.map((LazyArg(_) { "\"" + _.toString + "\".toInt"})),
      midSentenceFailureMessageArgs =
        mr.midSentenceFailureMessageArgs.map((LazyArg(_) { "\"" + _.toString + "\".toInt"})),
      midSentenceNegatedFailureMessageArgs =
        mr.midSentenceNegatedFailureMessageArgs.map((LazyArg(_) { "\"" + _.toString + "\".toInt"}))
    )
  }

"7" should beAsIntsGreaterThan ("8")

The last assertion will fail with message like this:

"7".toInt was not greater than "8".toInt

T

the type used by function f

f

a function that takes a T and return a Matcher[T]

returns

an object that has composeTwice, mapResult and mapArgs methods.

        

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        

        def

        toString(): String

Definition Classes

AnyRef → Any

        

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\AdminApiBundle\Form\Type;

use Sylius\Bundle\AddressingBundle\Form\Type\AddressType as SyliusAddressType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\Constraints\Valid;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
final class AddressType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('shippingAddress', SyliusAddressType::class, [
                'shippable' => true,
                'constraints' => [new Valid()],
            ])
            ->add('billingAddress', SyliusAddressType::class, [
                'constraints' => [new Valid()],
            ])
            ->add('differentBillingAddress', CheckboxType::class, [
                'mapped' => false,
                'required' => false,
                'label' => 'sylius.form.checkout.addressing.different_billing_address',
            ])
            ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
                $orderData = $event->getData();

                if (isset($orderData['shippingAddress']) && (!isset($orderData['differentBillingAddress']) || false === $orderData['differentBillingAddress'])) {
                    $orderData['billingAddress'] = $orderData['shippingAddress'];

                    $event->setData($orderData);
                }
            })
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'sylius_admin_api_checkout_address';
    }
}


text:
package microfluidic

import scala.concurrent.duration._ // We would use our own duration. We use this one as a proof of concept.

case class Heat(f: Fluid, temperature: Double, duration: FiniteDuration) extends Fluid {
  def volume = f.volume
  def name = f.name
}

case class Mix(f1: Fluid, f2: Fluid, name: String) extends Fluid {

  /*
  * Question: Do not know how to compute the temperature? Seems that for the temperature we
  * need domain knowledge as it depends based on the reaction.
  * Is temperature something we can always predict based on inputs?
  */
  def temperature: Double = ???

  /*
  * Question: Is this always the case? Some fluids might evaporate, change density etc.
  * Is volume something we can always predict based on inputs?
  */
  def volume: Int = f1.volume + f2.volume
}

case class Split(f: Fluid, ratio: Int) extends Fluid {
  def volume = f.volume / ratio
  def name = f.name
  def temperature = f.temperature
}


text:
package fake

import (
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/client/testing/core"
)

func (c *FakeNodes) PatchStatus(nodeName string, data []byte) (*api.Node, error) {
	obj, err := c.Fake.Invokes(
		core.NewPatchSubresourceAction(nodesResource, "status"), &api.Node{})
	if obj == nil {
		return nil, err
	}

	return obj.(*api.Node), err
}


text:
<?php

/**
 * Configuration object that triggers customizable behavior.
 *
 * @warning This class is strongly defined: that means that the class
 *          will fail if an undefined directive is retrieved or set.
 *
 * @note Many classes that could (although many times don't) use the
 *       configuration object make it a mandatory parameter.  This is
 *       because a configuration object should always be forwarded,
 *       otherwise, you run the risk of missing a parameter and then
 *       being stumped when a configuration directive doesn't work.
 *
 * @todo Reconsider some of the public member variables
 */
class HTMLPurifier_Config
{

    /**
     * HTML Purifier's version
     */
    public $version = '4.4.0';

    /**
     * Bool indicator whether or not to automatically finalize
     * the object if a read operation is done
     */
    public $autoFinalize = true;

    // protected member variables

    /**
     * Namespace indexed array of serials for specific namespaces (see
     * getSerial() for more info).
     */
    protected $serials = array();

    /**
     * Serial for entire configuration object
     */
    protected $serial;

    /**
     * Parser for variables
     */
    protected $parser = null;

    /**
     * Reference HTMLPurifier_ConfigSchema for value checking
     * @note This is public for introspective purposes. Please don't
     *       abuse!
     */
    public $def;

    /**
     * Indexed array of definitions
     */
    protected $definitions;

    /**
     * Bool indicator whether or not config is finalized
     */
    protected $finalized = false;

    /**
     * Property list containing configuration directives.
     */
    protected $plist;

    /**
     * Whether or not a set is taking place due to an
     * alias lookup.
     */
    private $aliasMode;

    /**
     * Set to false if you do not want line and file numbers in errors
     * (useful when unit testing).  This will also compress some errors
     * and exceptions.
     */
    public $chatty = true;

    /**
     * Current lock; only gets to this namespace are allowed.
     */
    private $lock;

    /**
     * @param $definition HTMLPurifier_ConfigSchema that defines what directives
     *                    are allowed.
     */
    public function __construct($definition, $parent = null) {
        $parent = $parent ? $parent : $definition->defaultPlist;
        $this->plist = new HTMLPurifier_PropertyList($parent);
        $this->def = $definition; // keep a copy around for checking
        $this->parser = new HTMLPurifier_VarParser_Flexible();
    }

    /**
     * Convenience constructor that creates a config object based on a mixed var
     * @param mixed $config Variable that defines the state of the config
     *                      object. Can be: a HTMLPurifier_Config() object,
     *                      an array of directives based on loadArray(),
     *                      or a string filename of an ini file.
     * @param HTMLPurifier_ConfigSchema Schema object
     * @return Configured HTMLPurifier_Config object
     */
    public static function create($config, $schema = null) {
        if ($config instanceof HTMLPurifier_Config) {
            // pass-through
            return $config;
        }
        if (!$schema) {
            $ret = HTMLPurifier_Config::createDefault();
        } else {
            $ret = new HTMLPurifier_Config($schema);
        }
        if (is_string($config)) $ret->loadIni($config);
        elseif (is_array($config)) $ret->loadArray($config);
        return $ret;
    }

    /**
     * Creates a new config object that inherits from a previous one.
     * @param HTMLPurifier_Config $config Configuration object to inherit
     *        from.
     * @return HTMLPurifier_Config object with $config as its parent.
     */
    public static function inherit(HTMLPurifier_Config $config) {
        return new HTMLPurifier_Config($config->def, $config->plist);
    }

    /**
     * Convenience constructor that creates a default configuration object.
     * @return Default HTMLPurifier_Config object.
     */
    public static function createDefault() {
        $definition = HTMLPurifier_ConfigSchema::instance();
        $config = new HTMLPurifier_Config($definition);
        return $config;
    }

    /**
     * Retreives a value from the configuration.
     * @param $key String key
     */
    public function get($key, $a = null) {
        if ($a !== null) {
            $this->triggerError("Using deprecated API: use \$config->get('$key.$a') instead", E_USER_WARNING);
            $key = "$key.$a";
        }
        if (!$this->finalized) $this->autoFinalize();
        if (!isset($this->def->info[$key])) {
            // can't add % due to SimpleTest bug
            $this->triggerError('Cannot retrieve value of undefined directive ' . htmlspecialchars($key, ENT_COMPAT | ENT_HTML401, 'UTF-8', false),
                E_USER_WARNING);
            return;
        }
        if (isset($this->def->info[$key]->isAlias)) {
            $d = $this->def->info[$key];
            $this->triggerError('Cannot get value from aliased directive, use real name ' . $d->key,
                E_USER_ERROR);
            return;
        }
        if ($this->lock) {
            list($ns) = explode('.', $key);
            if ($ns !== $this->lock) {
                $this->triggerError('Cannot get value of namespace ' . $ns . ' when lock for ' . $this->lock . ' is active, this probably indicates a Definition setup method is accessing directives that are not within its namespace', E_USER_ERROR);
                return;
            }
        }
        return $this->plist->get($key);
    }

    /**
     * Retreives an array of directives to values from a given namespace
     * @param $namespace String namespace
     */
    public function getBatch($namespace) {
        if (!$this->finalized) $this->autoFinalize();
        $full = $this->getAll();
        if (!isset($full[$namespace])) {
            $this->triggerError('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace, ENT_COMPAT | ENT_HTML401, 'UTF-8', false),
                E_USER_WARNING);
            return;
        }
        return $full[$namespace];
    }

    /**
     * Returns a md5 signature of a segment of the configuration object
     * that uniquely identifies that particular configuration
     * @note Revision is handled specially and is removed from the batch
     *       before processing!
     * @param $namespace Namespace to get serial for
     */
    public function getBatchSerial($namespace) {
        if (empty($this->serials[$namespace])) {
            $batch = $this->getBatch($namespace);
            unset($batch['DefinitionRev']);
            $this->serials[$namespace] = md5(serialize($batch));
        }
        return $this->serials[$namespace];
    }

    /**
     * Returns a md5 signature for the entire configuration object
     * that uniquely identifies that particular configuration
     */
    public function getSerial() {
        if (empty($this->serial)) {
            $this->serial = md5(serialize($this->getAll()));
        }
        return $this->serial;
    }

    /**
     * Retrieves all directives, organized by namespace
     * @warning This is a pretty inefficient function, avoid if you can
     */
    public function getAll() {
        if (!$this->finalized) $this->autoFinalize();
        $ret = array();
        foreach ($this->plist->squash() as $name => $value) {
            list($ns, $key) = explode('.', $name, 2);
            $ret[$ns][$key] = $value;
        }
        return $ret;
    }

    /**
     * Sets a value to configuration.
     * @param $key String key
     * @param $value Mixed value
     */
    public function set($key, $value, $a = null) {
        if (strpos($key, '.') === false) {
            $namespace = $key;
            $directive = $value;
            $value = $a;
            $key = "$key.$directive";
            $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);
        } else {
            list($namespace) = explode('.', $key);
        }
        if ($this->isFinalized('Cannot set directive after finalization')) return;
        if (!isset($this->def->info[$key])) {
            $this->triggerError('Cannot set undefined directive ' . htmlspecialchars($key, ENT_COMPAT | ENT_HTML401, 'UTF-8', false) . ' to value',
                E_USER_WARNING);
            return;
        }
        $def = $this->def->info[$key];

        if (isset($def->isAlias)) {
            if ($this->aliasMode) {
                $this->triggerError('Double-aliases not allowed, please fix '.
                    'ConfigSchema bug with' . $key, E_USER_ERROR);
                return;
            }
            $this->aliasMode = true;
            $this->set($def->key, $value);
            $this->aliasMode = false;
            $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);
            return;
        }

        // Raw type might be negative when using the fully optimized form
        // of stdclass, which indicates allow_null == true
        $rtype = is_int($def) ? $def : $def->type;
        if ($rtype < 0) {
            $type = -$rtype;
            $allow_null = true;
        } else {
            $type = $rtype;
            $allow_null = isset($def->allow_null);
        }

        try {
            $value = $this->parser->parse($value, $type, $allow_null);
        } catch (HTMLPurifier_VarParserException $e) {
            $this->triggerError('Value for ' . $key . ' is of invalid type, should be ' . HTMLPurifier_VarParser::getTypeName($type), E_USER_WARNING);
            return;
        }
        if (is_string($value) && is_object($def)) {
            // resolve value alias if defined
            if (isset($def->aliases[$value])) {
                $value = $def->aliases[$value];
            }
            // check to see if the value is allowed
            if (isset($def->allowed) && !isset($def->allowed[$value])) {
                $this->triggerError('Value not supported, valid values are: ' .
                    $this->_listify($def->allowed), E_USER_WARNING);
                return;
            }
        }
        $this->plist->set($key, $value);

        // reset definitions if the directives they depend on changed
        // this is a very costly process, so it's discouraged
        // with finalization
        if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') {
            $this->definitions[$namespace] = null;
        }

        $this->serials[$namespace] = false;
    }

    /**
     * Convenience function for error reporting
     */
    private function _listify($lookup) {
        $list = array();
        foreach ($lookup as $name => $b) $list[] = $name;
        return implode(', ', $list);
    }

    /**
     * Retrieves object reference to the HTML definition.
     * @param $raw Return a copy that has not been setup yet. Must be
     *             called before it's been setup, otherwise won't work.
     * @param $optimized If true, this method may return null, to
     *             indicate that a cached version of the modified
     *             definition object is available and no further edits
     *             are necessary.  Consider using
     *             maybeGetRawHTMLDefinition, which is more explicitly
     *             named, instead.
     */
    public function getHTMLDefinition($raw = false, $optimized = false) {
        return $this->getDefinition('HTML', $raw, $optimized);
    }

    /**
     * Retrieves object reference to the CSS definition
     * @param $raw Return a copy that has not been setup yet. Must be
     *             called before it's been setup, otherwise won't work.
     * @param $optimized If true, this method may return null, to
     *             indicate that a cached version of the modified
     *             definition object is available and no further edits
     *             are necessary.  Consider using
     *             maybeGetRawCSSDefinition, which is more explicitly
     *             named, instead.
     */
    public function getCSSDefinition($raw = false, $optimized = false) {
        return $this->getDefinition('CSS', $raw, $optimized);
    }

    /**
     * Retrieves object reference to the URI definition
     * @param $raw Return a copy that has not been setup yet. Must be
     *             called before it's been setup, otherwise won't work.
     * @param $optimized If true, this method may return null, to
     *             indicate that a cached version of the modified
     *             definition object is available and no further edits
     *             are necessary.  Consider using
     *             maybeGetRawURIDefinition, which is more explicitly
     *             named, instead.
     */
    public function getURIDefinition($raw = false, $optimized = false) {
        return $this->getDefinition('URI', $raw, $optimized);
    }

    /**
     * Retrieves a definition
     * @param $type Type of definition: HTML, CSS, etc
     * @param $raw  Whether or not definition should be returned raw
     * @param $optimized Only has an effect when $raw is true.  Whether
     *        or not to return null if the result is already present in
     *        the cache.  This is off by default for backwards
     *        compatibility reasons, but you need to do things this
     *        way in order to ensure that caching is done properly.
     *        Check out enduser-customize.html for more details.
     *        We probably won't ever change this default, as much as the
     *        maybe semantics is the "right thing to do."
     */
    public function getDefinition($type, $raw = false, $optimized = false) {
        if ($optimized && !$raw) {
            throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false");
        }
        if (!$this->finalized) $this->autoFinalize();
        // temporarily suspend locks, so we can handle recursive definition calls
        $lock = $this->lock;
        $this->lock = null;
        $factory = HTMLPurifier_DefinitionCacheFactory::instance();
        $cache = $factory->create($type, $this);
        $this->lock = $lock;
        if (!$raw) {
            // full definition
            // ---------------
            // check if definition is in memory
            if (!empty($this->definitions[$type])) {
                $def = $this->definitions[$type];
                // check if the definition is setup
                if ($def->setup) {
                    return $def;
                } else {
                    $def->setup($this);
                    if ($def->optimized) $cache->add($def, $this);
                    return $def;
                }
            }
            // check if definition is in cache
            $def = $cache->get($this);
            if ($def) {
                // definition in cache, save to memory and return it
                $this->definitions[$type] = $def;
                return $def;
            }
            // initialize it
            $def = $this->initDefinition($type);
            // set it up
            $this->lock = $type;
            $def->setup($this);
            $this->lock = null;
            // save in cache
            $cache->add($def, $this);
            // return it
            return $def;
        } else {
            // raw definition
            // --------------
            // check preconditions
            $def = null;
            if ($optimized) {
                if (is_null($this->get($type . '.DefinitionID'))) {
                    // fatally error out if definition ID not set
                    throw new HTMLPurifier_Exception("Cannot retrieve raw version without specifying %$type.DefinitionID");
                }
            }
            if (!empty($this->definitions[$type])) {
                $def = $this->definitions[$type];
                if ($def->setup && !$optimized) {
                    $extra = $this->chatty ? " (try moving this code block earlier in your initialization)" : "";
                    throw new HTMLPurifier_Exception("Cannot retrieve raw definition after it has already been setup" . $extra);
                }
                if ($def->optimized === null) {
                    $extra = $this->chatty ? " (try flushing your cache)" : "";
                    throw new HTMLPurifier_Exception("Optimization status of definition is unknown" . $extra);
                }
                if ($def->optimized !== $optimized) {
                    $msg = $optimized ? "optimized" : "unoptimized";
                    $extra = $this->chatty ? " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)" : "";
                    throw new HTMLPurifier_Exception("Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra);
                }
            }
            // check if definition was in memory
            if ($def) {
                if ($def->setup) {
                    // invariant: $optimized === true (checked above)
                    return null;
                } else {
                    return $def;
                }
            }
            // if optimized, check if definition was in cache
            // (because we do the memory check first, this formulation
            // is prone to cache slamming, but I think
            // guaranteeing that either /all/ of the raw
            // setup code or /none/ of it is run is more important.)
            if ($optimized) {
                // This code path only gets run once; once we put
                // something in $definitions (which is guaranteed by the
                // trailing code), we always short-circuit above.
                $def = $cache->get($this);
                if ($def) {
                    // save the full definition for later, but don't
                    // return it yet
                    $this->definitions[$type] = $def;
                    return null;
                }
            }
            // check invariants for creation
            if (!$optimized) {
                if (!is_null($this->get($type . '.DefinitionID'))) {
                    if ($this->chatty) {
                        $this->triggerError("Due to a documentation error in previous version of HTML Purifier, your definitions are not being cached.  If this is OK, you can remove the %$type.DefinitionRev and %$type.DefinitionID declaration.  Otherwise, modify your code to use maybeGetRawDefinition, and test if the returned value is null before making any edits (if it is null, that means that a cached version is available, and no raw operations are necessary).  See Customize for more details", E_USER_WARNING);
                    } else {
                        $this->triggerError("Useless DefinitionID declaration", E_USER_WARNING);
                    }
                }
            }
            // initialize it
            $def = $this->initDefinition($type);
            $def->optimized = $optimized;
            return $def;
        }
        throw new HTMLPurifier_Exception("The impossible happened!");
    }

    private function initDefinition($type) {
        // quick checks failed, let's create the object
        if ($type == 'HTML') {
            $def = new HTMLPurifier_HTMLDefinition();
        } elseif ($type == 'CSS') {
            $def = new HTMLPurifier_CSSDefinition();
        } elseif ($type == 'URI') {
            $def = new HTMLPurifier_URIDefinition();
        } else {
            throw new HTMLPurifier_Exception("Definition of $type type not supported");
        }
        $this->definitions[$type] = $def;
        return $def;
    }

    public function maybeGetRawDefinition($name) {
        return $this->getDefinition($name, true, true);
    }

    public function maybeGetRawHTMLDefinition() {
        return $this->getDefinition('HTML', true, true);
    }

    public function maybeGetRawCSSDefinition() {
        return $this->getDefinition('CSS', true, true);
    }

    public function maybeGetRawURIDefinition() {
        return $this->getDefinition('URI', true, true);
    }

    /**
     * Loads configuration values from an array with the following structure:
     * Namespace.Directive => Value
     * @param $config_array Configuration associative array
     */
    public function loadArray($config_array) {
        if ($this->isFinalized('Cannot load directives after finalization')) return;
        foreach ($config_array as $key => $value) {
            $key = str_replace('_', '.', $key);
            if (strpos($key, '.') !== false) {
                $this->set($key, $value);
            } else {
                $namespace = $key;
                $namespace_values = $value;
                foreach ($namespace_values as $directive => $value) {
                    $this->set($namespace .'.'. $directive, $value);
                }
            }
        }
    }

    /**
     * Returns a list of array(namespace, directive) for all directives
     * that are allowed in a web-form context as per an allowed
     * namespaces/directives list.
     * @param $allowed List of allowed namespaces/directives
     */
    public static function getAllowedDirectivesForForm($allowed, $schema = null) {
        if (!$schema) {
            $schema = HTMLPurifier_ConfigSchema::instance();
        }
        if ($allowed !== true) {
             if (is_string($allowed)) $allowed = array($allowed);
             $allowed_ns = array();
             $allowed_directives = array();
             $blacklisted_directives = array();
             foreach ($allowed as $ns_or_directive) {
                 if (strpos($ns_or_directive, '.') !== false) {
                     // directive
                     if ($ns_or_directive[0] == '-') {
                         $blacklisted_directives[substr($ns_or_directive, 1)] = true;
                     } else {
                         $allowed_directives[$ns_or_directive] = true;
                     }
                 } else {
                     // namespace
                     $allowed_ns[$ns_or_directive] = true;
                 }
             }
        }
        $ret = array();
        foreach ($schema->info as $key => $def) {
            list($ns, $directive) = explode('.', $key, 2);
            if ($allowed !== true) {
                if (isset($blacklisted_directives["$ns.$directive"])) continue;
                if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) continue;
            }
            if (isset($def->isAlias)) continue;
            if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;
            $ret[] = array($ns, $directive);
        }
        return $ret;
    }

    /**
     * Loads configuration values from $_GET/$_POST that were posted
     * via ConfigForm
     * @param $array $_GET or $_POST array to import
     * @param $index Index/name that the config variables are in
     * @param $allowed List of allowed namespaces/directives
     * @param $mq_fix Boolean whether or not to enable magic quotes fix
     * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
     */
    public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
        $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
        $config = HTMLPurifier_Config::create($ret, $schema);
        return $config;
    }

    /**
     * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
     * @note Same parameters as loadArrayFromForm
     */
    public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) {
         $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
         $this->loadArray($ret);
    }

    /**
     * Prepares an array from a form into something usable for the more
     * strict parts of HTMLPurifier_Config
     */
    public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
        if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
        $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();

        $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
        $ret = array();
        foreach ($allowed as $key) {
            list($ns, $directive) = $key;
            $skey = "$ns.$directive";
            if (!empty($array["Null_$skey"])) {
                $ret[$ns][$directive] = null;
                continue;
            }
            if (!isset($array[$skey])) continue;
            $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
            $ret[$ns][$directive] = $value;
        }
        return $ret;
    }

    /**
     * Loads configuration values from an ini file
     * @param $filename Name of ini file
     */
    public function loadIni($filename) {
        if ($this->isFinalized('Cannot load directives after finalization')) return;
        $array = parse_ini_file($filename, true);
        $this->loadArray($array);
    }

    /**
     * Checks whether or not the configuration object is finalized.
     * @param $error String error message, or false for no error
     */
    public function isFinalized($error = false) {
        if ($this->finalized && $error) {
            $this->triggerError($error, E_USER_ERROR);
        }
        return $this->finalized;
    }

    /**
     * Finalizes configuration only if auto finalize is on and not
     * already finalized
     */
    public function autoFinalize() {
        if ($this->autoFinalize) {
            $this->finalize();
        } else {
            $this->plist->squash(true);
        }
    }

    /**
     * Finalizes a configuration object, prohibiting further change
     */
    public function finalize() {
        $this->finalized = true;
        $this->parser = null;
    }

    /**
     * Produces a nicely formatted error message by supplying the
     * stack frame information OUTSIDE of HTMLPurifier_Config.
     */
    protected function triggerError($msg, $no) {
        // determine previous stack frame
        $extra = '';
        if ($this->chatty) {
            $trace = debug_backtrace();
            // zip(tail(trace), trace) -- but PHP is not Haskell har har
            for ($i = 0, $c = count($trace); $i < $c - 1; $i++) {
                if ($trace[$i + 1]['class'] === 'HTMLPurifier_Config') {
                    continue;
                }
                $frame = $trace[$i];
                $extra = " invoked on line {$frame['line']} in file {$frame['file']}";
                break;
            }
        }
        trigger_error($msg . $extra, $no);
    }

    /**
     * Returns a serialized form of the configuration object that can
     * be reconstituted.
     */
    public function serialize() {
        $this->getDefinition('HTML');
        $this->getDefinition('CSS');
        $this->getDefinition('URI');
        return serialize($this);
    }

}

// vim: et sw=4 sts=4


text:
import * as cn from 'classnames'
import * as React from 'react'
import Base from '../../libs/Base'
import Pager from './Pager'
import './Pagination.less'

export interface INextProps {
  current: number,
  total: number,
  onClick: (page: number) => void
}

function Next ({total, current, onClick}: INextProps) {
  const disabled = current >= total
  return (

 !disabled && onClick(current + 1)}>

  )
}

export interface IPrevProps {
  current: number,
  total: number,
  onClick: (page: number) => void
}

function Prev ({current, onClick}: IPrevProps) {
  const disabled = current < 2
  return (

 !disabled && onClick(current - 1)}>

  )
}

export interface IPaginationProps {
  current?: number,
  total?: number,
  range?: number,
  layout?: string[],
  onChange?: (page: number) => void
}

export interface IPaginationState {}

export default class Pagination extends Base<IPaginationProps, IPaginationState> {

  constructor (props: IPaginationProps) {
    super(props)
    this.state = {}
  }

  onChange = (page: number) => {
    const {onChange} = this.props
    if (onChange) {
      onChange(page)
    }
  }

  renderContent = () => {
    const {layout = ['prev', 'whc-pager', 'next'], current = 1, total = 0, range = 3} = this.props
    const template = {
      'prev': (
        <Prev
          key='prev'
          current={current}
          total={total}
          onClick={this.onChange}/>
      ),
      'next': (
        <Next
          key='next'
          current={current}
          total={total}
          onClick={this.onChange}/>
      ),
      'whc-pager': (
        <Pager
          key='whc-pager'
          current={current}
          total={total}
          range={range}
          onClick={this.onChange}/>
      )
    }
    const content: JSX.Element[] = []
    layout.forEach((name) => {
      if (template[name]) {
        content.push(template[name])
      }
    })
    return content
  }

  render () {
    if (this.props.total && this.props.total > 0) {
      return (

          {this.renderContent()}

      )
    }
    return null
  }
}


text:
package io.ray.streaming.python.stream;

import io.ray.streaming.api.Language;
import io.ray.streaming.api.context.StreamingContext;
import io.ray.streaming.api.partition.Partition;
import io.ray.streaming.api.stream.DataStream;
import io.ray.streaming.api.stream.Stream;
import io.ray.streaming.python.PythonFunction;
import io.ray.streaming.python.PythonFunction.FunctionInterface;
import io.ray.streaming.python.PythonOperator;
import io.ray.streaming.python.PythonPartition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Represents a stream of data whose transformations will be executed in python.
 */
public class PythonDataStream extends Stream<PythonDataStream, Object> implements PythonStream {

  protected PythonDataStream(
      StreamingContext streamingContext,
      PythonOperator pythonOperator) {
    super(streamingContext, pythonOperator);
  }

  protected PythonDataStream(
      StreamingContext streamingContext,
      PythonOperator pythonOperator,
      Partition<Object> partition) {
    super(streamingContext, pythonOperator, partition);
  }

  public PythonDataStream(PythonDataStream input, PythonOperator pythonOperator) {
    super(input, pythonOperator);
  }

  public PythonDataStream(
      PythonDataStream input,
      PythonOperator pythonOperator,
      Partition<Object> partition) {
    super(input, pythonOperator, partition);
  }

  /**
   * Create a python stream that reference passed java stream. Changes in new stream will be
   * reflected in referenced stream and vice versa
   */
  public PythonDataStream(DataStream referencedStream) {
    super(referencedStream);
  }

  public PythonDataStream map(String moduleName, String funcName) {
    return map(new PythonFunction(moduleName, funcName));
  }

  /**
   * Apply a map function to this stream.
   *
   * @param func The python MapFunction.
   * @return A new PythonDataStream.
   */
  public PythonDataStream map(PythonFunction func) {
    func.setFunctionInterface(FunctionInterface.MAP_FUNCTION);
    return new PythonDataStream(this, new PythonOperator(func));
  }

  public PythonDataStream flatMap(String moduleName, String funcName) {
    return flatMap(new PythonFunction(moduleName, funcName));
  }

  /**
   * Apply a flat-map function to this stream.
   *
   * @param func The python FlapMapFunction.
   * @return A new PythonDataStream
   */
  public PythonDataStream flatMap(PythonFunction func) {
    func.setFunctionInterface(FunctionInterface.FLAT_MAP_FUNCTION);
    return new PythonDataStream(this, new PythonOperator(func));
  }

  public PythonDataStream filter(String moduleName, String funcName) {
    return filter(new PythonFunction(moduleName, funcName));
  }

  /**
   * Apply a filter function to this stream.
   *
   * @param func The python FilterFunction.
   * @return A new PythonDataStream that contains only the elements satisfying the given filter
   *     predicate.
   */
  public PythonDataStream filter(PythonFunction func) {
    func.setFunctionInterface(FunctionInterface.FILTER_FUNCTION);
    return new PythonDataStream(this, new PythonOperator(func));
  }

  /**
   * Apply union transformations to this stream by merging {@link PythonDataStream} outputs of the
   * same type with each other.
   *
   * @param stream The DataStream to union output with.
   * @param others The other DataStreams to union output with.
   * @return A new UnionStream.
   */
  public final PythonDataStream union(PythonDataStream stream, PythonDataStream... others) {
    List<PythonDataStream> streams = new ArrayList<>();
    streams.add(stream);
    streams.addAll(Arrays.asList(others));
    return union(streams);
  }

  /**
   * Apply union transformations to this stream by merging {@link PythonDataStream} outputs of the
   * same type with each other.
   *
   * @param streams The DataStreams to union output with.
   * @return A new UnionStream.
   */
  public final PythonDataStream union(List<PythonDataStream> streams) {
    if (this instanceof PythonUnionStream) {
      PythonUnionStream unionStream = (PythonUnionStream) this;
      streams.forEach(unionStream::addStream);
      return unionStream;
    } else {
      return new PythonUnionStream(this, streams);
    }
  }

  public PythonStreamSink sink(String moduleName, String funcName) {
    return sink(new PythonFunction(moduleName, funcName));
  }

  /**
   * Apply a sink function and get a StreamSink.
   *
   * @param func The python SinkFunction.
   * @return A new StreamSink.
   */
  public PythonStreamSink sink(PythonFunction func) {
    func.setFunctionInterface(FunctionInterface.SINK_FUNCTION);
    return new PythonStreamSink(this, new PythonOperator(func));
  }

  public PythonKeyDataStream keyBy(String moduleName, String funcName) {
    return keyBy(new PythonFunction(moduleName, funcName));
  }

  /**
   * Apply a key-by function to this stream.
   *
   * @param func the  python keyFunction.
   * @return A new KeyDataStream.
   */
  public PythonKeyDataStream keyBy(PythonFunction func) {
    checkPartitionCall();
    func.setFunctionInterface(FunctionInterface.KEY_FUNCTION);
    return new PythonKeyDataStream(this, new PythonOperator(func));
  }

  /**
   * Apply broadcast to this stream.
   *
   * @return This stream.
   */
  public PythonDataStream broadcast() {
    checkPartitionCall();
    return setPartition(PythonPartition.BroadcastPartition);
  }

  /**
   * Apply a partition to this stream.
   *
   * @param partition The partitioning strategy.
   * @return This stream.
   */
  public PythonDataStream partitionBy(PythonPartition partition) {
    checkPartitionCall();
    return setPartition(partition);
  }

  /**
   * If parent stream is a python stream, we can't call partition related methods in the java
   * stream.
   */
  private void checkPartitionCall() {
    if (getInputStream() != null && getInputStream().getLanguage() == Language.JAVA) {
      throw new RuntimeException("Partition related methods can't be called on a " +
          "python stream if parent stream is a java stream.");
    }
  }

  /**
   * Convert this stream as a java stream. The converted stream and this stream are the same logical
   * stream, which has same stream id. Changes in converted stream will be reflected in this stream
   * and vice versa.
   */
  public DataStream<Object> asJavaStream() {
    return new DataStream<>(this);
  }

  @Override
  public Language getLanguage() {
    return Language.PYTHON;
  }

}


text:
/*------------------------------------------------------------------------
 * filename - ewconio.c
 *
 * function(s)
 *        getch -  get keyboard character
 *        getche - get and echo keyboard character
 *        kbhit  - check for keyboard character available
 *        putch  - write character to display
 *-----------------------------------------------------------------------*/

/*
 *      C/C++ Run Time Library - Version 5.0
 *
 *      Copyright (c) 1991, 1992 by Borland International
 *      All Rights Reserved.
 *
 */

#include <conio.h>

int   _ReadKey(void);
void  _WriteChar(char Ch);
int   _KeyPressed(void);

int getch(void)
{
    return _ReadKey();
}

int getche(void)
{
    int c = _ReadKey();
    _WriteChar(c);
    return c;
}

int kbhit(void)
{
    return _KeyPressed();
}

int putch(int c)
{
    _WriteChar(c);
    return c;
}


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

<title>Uses of Class org.jsimpledb.core.NullSafeType (Java Class Library API)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.jsimpledb.core.NullSafeType

Packages that use NullSafeType

Package
Description

org.jsimpledb.core

Core classes for the JSimpleDB Java persistence layer.

Uses of NullSafeType in org.jsimpledb.core

Subclasses of NullSafeType in org.jsimpledb.core

Modifier and Type
Class and Description

class
EnumFieldType

The FieldType for EnumFields.

class
ReferenceFieldType

The FieldType for ReferenceFields.

class
StringEncodedType<T>

A FieldType implementation for any Java type that can be encoded uniquely as a String.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
from MySQLEngine import *
__all__ = ["MySQLEngine"]


text:
import React, { PropTypes } from 'react';

const CartProductDisplay = ({ id, name, price, description, handleRemoveFromCart, getCount }) => {

  return (

        {name} {`(${getCount(id)})`}

{description}

${price}

        <button onClick={() => handleRemoveFromCart(id)}>Remove from Cart</button>

  );
};

CartProductDisplay.propTypes = {
  id: PropTypes.number.isRequired,
  name: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
  price: PropTypes.number.isRequired,
  handleRemoveFromCart: PropTypes.func.isRequired,
  getCount: PropTypes.func.isRequired
};

export default CartProductDisplay;


text:
static int foo() {
}


text:
package fakes

import (
	"sync"

	"bosh-softlayer-cpi/softlayer/common"
)

type FakeVMDeleter struct {
	DeleteStub        func(cid int) error
	deleteMutex       sync.RWMutex
	deleteArgsForCall []struct {
		cid int
	}
	deleteReturns struct {
		result1 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeVMDeleter) Delete(cid int) error {
	fake.deleteMutex.Lock()
	fake.deleteArgsForCall = append(fake.deleteArgsForCall, struct {
		cid int
	}{cid})
	fake.recordInvocation("Delete", []interface{}{cid})
	fake.deleteMutex.Unlock()
	if fake.DeleteStub != nil {
		return fake.DeleteStub(cid)
	} else {
		return fake.deleteReturns.result1
	}
}

func (fake *FakeVMDeleter) DeleteCallCount() int {
	fake.deleteMutex.RLock()
	defer fake.deleteMutex.RUnlock()
	return len(fake.deleteArgsForCall)
}

func (fake *FakeVMDeleter) DeleteArgsForCall(i int) int {
	fake.deleteMutex.RLock()
	defer fake.deleteMutex.RUnlock()
	return fake.deleteArgsForCall[i].cid
}

func (fake *FakeVMDeleter) DeleteReturns(result1 error) {
	fake.DeleteStub = nil
	fake.deleteReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeVMDeleter) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.deleteMutex.RLock()
	defer fake.deleteMutex.RUnlock()
	return fake.invocations
}

func (fake *FakeVMDeleter) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ common.VMDeleter = new(FakeVMDeleter)


text:
require 'spec_helper'

describe 'ZabbixApi::Actions' do
  let(:actions_mock) { ZabbixApi::Actions.new(client) }
  let(:client) { double }

  describe '.method_name' do
    subject { actions_mock.method_name }

    it { is_expected.to eq 'action' }
  end

  describe '.identify' do
    subject { actions_mock.identify }

    it { is_expected.to eq 'name' }
  end
end


text: <manifest package="cn.bingoogolapple.qrcode.zxing"/>


text:
class AddSideDealDealHistory < ActiveRecord::Migration
  def self.up
    add_column :deal_histories,:is_side_deal,:boolean,:default => false
  end

  def self.down
    remove_column :deal_histories,:is_side_deal
  end
end


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

public class SkillShockWave : SkillBase {

    class SkillShockWaveState : SkillState
    {
        public Vector3 m_center;
        public HashSet<Fighter> m_objs=new HashSet<Fighter>();//已经影响的单位
        public int m_curCheckCount;
        public float m_curRadio;
    }

    public int m_damage=1000;
    public float m_maxRadio = 10;
    public float m_duration = 0.5f;
    public float m_checkStep = 1;//进行计算的步长

    void doDamage(SkillShockWaveState sk)
    {
      //  Debug.Log(sk.m_curRadio);
        GameObject[] gos=GameObject.FindGameObjectsWithTag("fighter");
        foreach (GameObject go in gos)
        {
            Fighter ft = go.GetComponent<Fighter>();
            if (sk.m_objs.Contains(ft) == true)
            {
                continue;
            }
            Vector3 v1 = sk.m_center;
            Vector3 v2 = ft.transform.position;
            v2.y = 0;
            float dis = Vector3.Distance(v1, v2);
            if(sk.m_objs.Contains(ft)==false&&dis<m_maxRadio&&sk.m_caster.m_groupName!=ft.m_groupName)
            {
                m_global.DoDamage(sk.m_caster,ft,m_damage);
                sk.m_objs.Add(ft);
            }
            if (dis < m_maxRadio)
            {
                sk.m_objs.Add(ft);
            }
        }

    }

    protected override void SkillUpdate(SkillState state)
    {
        SkillShockWaveState ss = state as SkillShockWaveState;
        float speed = m_maxRadio / m_duration;
        float n1=Time.deltaTime*speed;
        ss.m_curRadio+=n1;

        if (ss.m_curRadio > m_maxRadio)
        {
            ss.m_curRadio = m_maxRadio;
            doDamage(ss);
        }
        else
        {
            int n = (int)(ss.m_curRadio / m_checkStep);
            if (n > ss.m_curCheckCount)
            {
                doDamage(ss);
                ss.m_curCheckCount = n;
            }
        }

    }
    protected override SkillState SkillCreate()
    {
        SkillShockWaveState ss = new SkillShockWaveState();
        return ss;
    }
    protected override void SkillStart(SkillState state)
    {
        SkillShockWaveState ss = state as SkillShockWaveState;
        ss.m_center = ss.m_caster.transform.position;

     //   AddDeck(m_decks[0],state.m_caster.GetComponent<moveControler>(),state);
        Vector3 v1 = state.m_targetPos;
        v1.y = 0;
        AddDeck(m_decks[0], state,state.m_targetPos);

    }
    protected override void SkillEnd(SkillState state)
    {

    }

	// Use this for initialization
	void Start () {
        initSkill();
	}

	// Update is called once per frame
	void Update () {

	}
}


text:
package org.kaazing.gateway.transport.http.bridge.filter;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.statemachine.DecodingState;
import org.kaazing.gateway.transport.SslUtils;
import org.kaazing.mina.core.buffer.IoBufferAllocatorEx;
import org.kaazing.mina.core.session.IoSessionEx;

public class HttpRequestDecoder extends HttpMessageDecoder {

	@Override
	protected DecodingState initDecodingState(IoSession session) {
        IoSessionEx sessionEx = (IoSessionEx) session;
        IoBufferAllocatorEx<?> allocator = sessionEx.getBufferAllocator();
		return new HttpRequestDecodingState(allocator, SslUtils.isSecure(session));
	}

}


text:
#include "tensorflow/compiler/tf2xla/side_effect_util.h"

#include "absl/strings/numbers.h"
#include "tensorflow/core/graph/algorithm.h"

namespace tensorflow {

const char kXlaTokenInputNodesAttrName[] = "_xla_token_input_nodes";

const char kXlaTokenArgNodeName[] = "_xla_token_arg_node";

const char kXlaHasHostTransferAttrName[] = "_xla_has_host_transfer";

Status SetDeviceOrdinalAttributeForNode(Node* node, int device_ordinal) {
  if (!HasNodeAttr(node->def(), kXlaHasHostTransferAttrName)) {
    return errors::InvalidArgument("Node ", node->DebugString(),
                                   " does not have attribute ",
                                   kXlaHasHostTransferAttrName);
  }

  if (node->type_string() == "_XlaRecvAtHost" ||
      node->type_string() == "_XlaSendFromHost") {
    node->ClearAttr("device_ordinal");
    node->AddAttr("device_ordinal", device_ordinal);
  } else if (node->type_string() == "If") {
    AttrValue device_ordinal_value;
    device_ordinal_value.set_i(device_ordinal);
    for (const string& attr_name :
         std::vector<string>{"then_branch", "else_branch"}) {
      NameAttrList branch_func;
      TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), attr_name, &branch_func));
      (*branch_func.mutable_attr())["device_ordinal"] = device_ordinal_value;
      node->ClearAttr(attr_name);
      node->AddAttr(attr_name, branch_func);
    }
  } else if (node->type_string() == "While") {
    AttrValue device_ordinal_value;
    device_ordinal_value.set_i(device_ordinal);
    for (const string& attr_name : std::vector<string>{"cond", "body"}) {
      NameAttrList branch_func;
      TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), attr_name, &branch_func));
      (*branch_func.mutable_attr())["device_ordinal"] = device_ordinal_value;
      node->ClearAttr(attr_name);
      node->AddAttr(attr_name, branch_func);
    }
  } else {
    return errors::Internal("Unknown node type to set 'device_ordinal': ",
                            node->DebugString());
  }
  return Status::OK();
}

std::set<std::string> CalculateTokenInputsForOutputToken(const Graph& g) {
  std::set<std::string> results;
  Node* first_side_effecting_node_on_path = nullptr;
  ReverseDFS(g,
             [&](Node* n) {
               std::vector<string> token_input_nodes;
               if (!GetNodeAttr(n->attrs(), kXlaTokenInputNodesAttrName,
                                &token_input_nodes)
                        .ok() ||
                   token_input_nodes.empty()) {
                 return;
               }

               if (first_side_effecting_node_on_path != nullptr) {
                 return;
               }

               first_side_effecting_node_on_path = n;
               results.insert(n->name());
             },
             [&](Node* n) {
               if (first_side_effecting_node_on_path == n) {
                 first_side_effecting_node_on_path = nullptr;
               }
             },
             NodeComparatorName());
  return results;
}

bool HasSideEffectingNodes(const Graph& g) {
  for (Node* n : g.nodes()) {
    std::vector<string> token_input_nodes;
    if (GetNodeAttr(n->attrs(), kXlaTokenInputNodesAttrName, &token_input_nodes)
            .ok() &&
        !token_input_nodes.empty()) {
      return true;
    }
  }
  return false;
}

Status ParseHostComputeCoreList(absl::Span<const string> list_from_attr,
                                std::map<string, int>* host_compute_core) {
  for (const auto& hc_core : list_from_attr) {
    std::vector<string> parts = str_util::Split(hc_core, ":");
    if (parts.size() != 2) {
      return errors::InvalidArgument(
          "Malformed host_compute_core entry ", hc_core,
          " should be <cluster_name>:<core_number>.");
    }
    int core;
    if (!absl::numbers_internal::safe_strto32_base(parts[1], &core, 10)) {
      return errors::InvalidArgument("Malformed host_compute_core entry ",
                                     hc_core,
                                     " part after ':' should be an integer.");
    }
    if (host_compute_core->find(parts[0]) != host_compute_core->end()) {
      return errors::InvalidArgument(
          "Duplicate host_compute_core entry for cluster ", parts[0]);
    }
    (*host_compute_core)[parts[0]] = core;
  }
  return Status::OK();
}

}  // namespace tensorflow


text:
package io.reactivex.rxjava3.tck;

import java.util.Arrays;

import org.reactivestreams.Publisher;
import org.testng.annotations.Test;

import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.functions.Function;

@Test
public class ZipIterableTckTest extends BaseTck<Long> {

    @Override
    public Publisher<Long> createPublisher(long elements) {
        return
            Flowable.zip(Arrays.asList(
                    Flowable.fromIterable(iterate(elements)),
                    Flowable.fromIterable(iterate(elements))
                ),
                new Function<Object[], Long>() {
                    @Override
                    public Long apply(Object[] a) throws Exception {
                        return (Long)a[0] + (Long)a[1];
                    }
                }
            )
        ;
    }
}


text:
module Travis
  module Addons
    module Util
      require 'travis/addons/util/template'
      require 'travis/addons/util/result_message'
      require 'travis/addons/util/helpers'
    end
  end
end


text:
class S2CopyingEdgeCrosser;  // Forward declaration

// This class allows edges to be efficiently tested for intersection with a
// given fixed edge AB.  It is especially efficient when testing for
// intersection with an edge chain connecting vertices v0, v1, v2, ...
//
// Example usage:
//
//   void CountIntersections(const S2Point& a, const S2Point& b,
//                           const vector<pair<S2Point, S2Point>>& edges) {
//     int count = 0;
//     S2EdgeCrosser crosser(&a, &b);
//     for (const auto& edge : edges) {
//       if (crosser.CrossingSign(&edge.first, &edge.second) >= 0) {
//         ++count;
//       }
//     }
//     return count;
//   }
//
// This class expects that the client already has all the necessary vertices
// stored in memory, so that this class can refer to them with pointers and
// does not need to make its own copies.  If this is not the case (e.g., you
// want to pass temporary objects as vertices), see S2CopyingEdgeCrosser.
class S2EdgeCrosser {
 public:
  // Default constructor; must be followed by a call to Init().
  S2EdgeCrosser() {}

  // Convenience constructor that calls Init() with the given fixed edge AB.
  // The arguments "a" and "b" must point to values that persist for the
  // lifetime of the S2EdgeCrosser object (or until the next Init() call).
  S2EdgeCrosser(const S2Point* a, const S2Point* b);

  // Accessors for the constructor arguments.
  const S2Point* a() { return a_; }
  const S2Point* b() { return b_; }

  // Initialize the S2EdgeCrosser with the given fixed edge AB.  The arguments
  // "a" and "b" must point to values that persist for the lifetime of the
  // S2EdgeCrosser object (or until the next Init() call).
  void Init(const S2Point* a, const S2Point* b);

  // This function determines whether the edge AB intersects the edge CD.
  // Returns +1 if AB crosses CD at a point that is interior to both edges.
  // Returns  0 if any two vertices from different edges are the same.
  // Returns -1 otherwise.
  //
  // Note that if an edge is degenerate (A == B or C == D), the return value
  // is 0 if two vertices from different edges are the same and -1 otherwise.
  //
  // Properties of CrossingSign:
  //
  //  (1) CrossingSign(b,a,c,d) == CrossingSign(a,b,c,d)
  //  (2) CrossingSign(c,d,a,b) == CrossingSign(a,b,c,d)
  //  (3) CrossingSign(a,b,c,d) == 0 if a==c, a==d, b==c, b==d
  //  (3) CrossingSign(a,b,c,d) <= 0 if a==b or c==d (see above)
  //
  // This function implements an exact, consistent perturbation model such
  // that no three points are ever considered to be collinear.  This means
  // that even if you have 4 points A, B, C, D that lie exactly in a line
  // (say, around the equator), C and D will be treated as being slightly to
  // one side or the other of AB.  This is done in a way such that the
  // results are always consistent (see s2pred::Sign).
  //
  // Note that if you want to check an edge against a chain of other edges,
  // it is slightly more efficient to use the single-argument version of
  // CrossingSign below.
  //
  // The arguments must point to values that persist until the next call.
  int CrossingSign(const S2Point* c, const S2Point* d);

  // This method extends the concept of a "crossing" to the case where AB
  // and CD have a vertex in common.  The two edges may or may not cross,
  // according to the rules defined in VertexCrossing() below.  The rules
  // are designed so that point containment tests can be implemented simply
  // by counting edge crossings.  Similarly, determining whether one edge
  // chain crosses another edge chain can be implemented by counting.
  //
  // Returns true if CrossingSign(c, d) > 0, or AB and CD share a vertex
  // and VertexCrossing(a, b, c, d) returns true.
  //
  // The arguments must point to values that persist until the next call.
  bool EdgeOrVertexCrossing(const S2Point* c, const S2Point* d);

  ///////////////////////// Edge Chain Methods ///////////////////////////
  //
  // You don't need to use these unless you're trying to squeeze out every
  // last drop of performance.  Essentially all you are saving is a test
  // whether the first vertex of the current edge is the same as the second
  // vertex of the previous edge.  Example usage:
  //
  //   vector<S2Point> chain;
  //   crosser.RestartAt(&chain[0]);
  //   for (int i = 1; i < chain.size(); ++i) {
  //     if (crosser.EdgeOrVertexCrossing(&chain[i])) { ++count; }
  //   }

  // Convenience constructor that uses AB as the fixed edge, and C as the
  // first vertex of the vertex chain (equivalent to calling RestartAt(c)).
  //
  // The arguments must point to values that persist until the next call.
  S2EdgeCrosser(const S2Point* a, const S2Point* b, const S2Point* c);

  // Call this method when your chain 'jumps' to a new place.
  // The argument must point to a value that persists until the next call.
  void RestartAt(const S2Point* c);

  // Like CrossingSign above, but uses the last vertex passed to one of
  // the crossing methods (or RestartAt) as the first vertex of the current
  // edge.
  //
  // The argument must point to a value that persists until the next call.
  int CrossingSign(const S2Point* d);

  // Like EdgeOrVertexCrossing above, but uses the last vertex passed to one
  // of the crossing methods (or RestartAt) as the first vertex of the
  // current edge.
  //
  // The argument must point to a value that persists until the next call.
  bool EdgeOrVertexCrossing(const S2Point* d);

  // Returns the last vertex of the current edge chain being tested, i.e. the
  // C vertex that will be used to construct the edge CD when one of the
  // methods above is called.
  const S2Point* c() { return c_; }

 private:
  friend class S2CopyingEdgeCrosser;

  // These functions handle the "slow path" of CrossingSign().
  int CrossingSignInternal(const S2Point* d);
  int CrossingSignInternal2(const S2Point& d);

  // Used internally by S2CopyingEdgeCrosser.  Updates "c_" only.
  void set_c(const S2Point* c) { c_ = c; }

  // The fields below are constant after the call to Init().
  const S2Point* a_;
  const S2Point* b_;
  Vector3_d a_cross_b_;

  // To reduce the number of calls to s2pred::ExpensiveSign(), we compute an
  // outward-facing tangent at A and B if necessary.  If the plane
  // perpendicular to one of these tangents separates AB from CD (i.e., one
  // edge on each side) then there is no intersection.
  bool have_tangents_;  // True if the tangents have been computed.
  S2Point a_tangent_;   // Outward-facing tangent at A.
  S2Point b_tangent_;   // Outward-facing tangent at B.

  // The fields below are updated for each vertex in the chain.
  const S2Point* c_;       // Previous vertex in the vertex chain.
  int acb_;                // The orientation of triangle ACB.

  // The field below is a temporary used by CrossingSignInternal().
  int bda_;                // The orientation of triangle BDA.

  S2EdgeCrosser(const S2EdgeCrosser&) = delete;
  void operator=(const S2EdgeCrosser&) = delete;
};

// S2CopyingEdgeCrosser is exactly like S2EdgeCrosser, except that it makes its
// own copy of all arguments so that they do not need to persist between
// calls.  This is less efficient, but makes it possible to use points that
// are generated on demand and cannot conveniently be stored by the client.
class S2CopyingEdgeCrosser {
 public:
  // These methods are all exactly like S2EdgeCrosser, except that the
  // arguments can be temporaries.
  S2CopyingEdgeCrosser() {}
  S2CopyingEdgeCrosser(const S2Point& a, const S2Point& b);
  const S2Point& a() { return a_; }
  const S2Point& b() { return b_; }
  const S2Point& c() { return c_; }
  void Init(const S2Point& a, const S2Point& b);
  int CrossingSign(const S2Point& c, const S2Point& d);
  bool EdgeOrVertexCrossing(const S2Point& c, const S2Point& d);
  S2CopyingEdgeCrosser(const S2Point& a, const S2Point& b, const S2Point& c);
  void RestartAt(const S2Point& c);
  int CrossingSign(const S2Point& d);
  bool EdgeOrVertexCrossing(const S2Point& d);

 private:
  S2Point a_, b_, c_;
  // TODO(ericv): It would be more efficient to implement S2CopyingEdgeCrosser
  // directly rather than as a wrapper around S2EdgeCrosser.
  S2EdgeCrosser crosser_;

  S2CopyingEdgeCrosser(const S2CopyingEdgeCrosser&) = delete;
  void operator=(const S2CopyingEdgeCrosser&) = delete;
};

//////////////////   Implementation details follow   ////////////////////

inline S2EdgeCrosser::S2EdgeCrosser(const S2Point* a, const S2Point* b)
    : a_(a), b_(b), a_cross_b_(a_->CrossProd(*b_)), have_tangents_(false),
      c_(nullptr) {
  S2_DCHECK(S2::IsUnitLength(*a));
  S2_DCHECK(S2::IsUnitLength(*b));
}

inline void S2EdgeCrosser::Init(const S2Point* a, const S2Point* b) {
  a_ = a;
  b_ = b;
  a_cross_b_ = a->CrossProd(*b_);
  have_tangents_ = false;
  c_ = nullptr;
}

inline int S2EdgeCrosser::CrossingSign(const S2Point* c, const S2Point* d) {
  if (c != c_) RestartAt(c);
  return CrossingSign(d);
}

inline bool S2EdgeCrosser::EdgeOrVertexCrossing(const S2Point* c,
                                                const S2Point* d) {
  if (c != c_) RestartAt(c);
  return EdgeOrVertexCrossing(d);
}

inline S2EdgeCrosser::S2EdgeCrosser(
    const S2Point* a, const S2Point* b, const S2Point* c)
    : a_(a), b_(b), a_cross_b_(a_->CrossProd(*b_)), have_tangents_(false) {
  S2_DCHECK(S2::IsUnitLength(*a));
  S2_DCHECK(S2::IsUnitLength(*b));
  RestartAt(c);
}

inline void S2EdgeCrosser::RestartAt(const S2Point* c) {
  S2_DCHECK(S2::IsUnitLength(*c));
  c_ = c;
  acb_ = -s2pred::TriageSign(*a_, *b_, *c_, a_cross_b_);
}

inline int S2EdgeCrosser::CrossingSign(const S2Point* d) {
  S2_DCHECK(S2::IsUnitLength(*d));
  // For there to be an edge crossing, the triangles ACB, CBD, BDA, DAC must
  // all be oriented the same way (CW or CCW).  We keep the orientation of ACB
  // as part of our state.  When each new point D arrives, we compute the
  // orientation of BDA and check whether it matches ACB.  This checks whether
  // the points C and D are on opposite sides of the great circle through AB.

  // Recall that TriageSign is invariant with respect to rotating its
  // arguments, i.e. ABD has the same orientation as BDA.
  int bda = s2pred::TriageSign(*a_, *b_, *d, a_cross_b_);
  if (acb_ == -bda && bda != 0) {
    // The most common case -- triangles have opposite orientations.  Save the
    // current vertex D as the next vertex C, and also save the orientation of
    // the new triangle ACB (which is opposite to the current triangle BDA).
    c_ = d;
    acb_ = -bda;
    return -1;
  }
  bda_ = bda;
  return CrossingSignInternal(d);
}

inline bool S2EdgeCrosser::EdgeOrVertexCrossing(const S2Point* d) {
  // We need to copy c_ since it is clobbered by CrossingSign().
  const S2Point* c = c_;
  int crossing = CrossingSign(d);
  if (crossing < 0) return false;
  if (crossing > 0) return true;
  return S2::VertexCrossing(*a_, *b_, *c, *d);
}

inline S2CopyingEdgeCrosser::S2CopyingEdgeCrosser(const S2Point& a,
                                                  const S2Point& b)
    : a_(a), b_(b), c_(S2Point()), crosser_(&a_, &b_) {
}

inline void S2CopyingEdgeCrosser::Init(const S2Point& a, const S2Point& b) {
  a_ = a;
  b_ = b;
  c_ = S2Point();
  crosser_.Init(&a_, &b_);
}

inline int S2CopyingEdgeCrosser::CrossingSign(const S2Point& c,
                                              const S2Point& d) {
  if (c != c_ || crosser_.c_ == nullptr) RestartAt(c);
  return CrossingSign(d);
}

inline bool S2CopyingEdgeCrosser::EdgeOrVertexCrossing(
    const S2Point& c, const S2Point& d) {
  if (c != c_ || crosser_.c_ == nullptr) RestartAt(c);
  return EdgeOrVertexCrossing(d);
}

inline S2CopyingEdgeCrosser::S2CopyingEdgeCrosser(
    const S2Point& a, const S2Point& b, const S2Point& c)
    : a_(a), b_(b), c_(c), crosser_(&a_, &b_, &c) {
}

inline void S2CopyingEdgeCrosser::RestartAt(const S2Point& c) {
  c_ = c;
  crosser_.RestartAt(&c_);
}

inline int S2CopyingEdgeCrosser::CrossingSign(const S2Point& d) {
  int result = crosser_.CrossingSign(&d);
  c_ = d;
  crosser_.set_c(&c_);
  return result;
}

inline bool S2CopyingEdgeCrosser::EdgeOrVertexCrossing(const S2Point& d) {
  bool result = crosser_.EdgeOrVertexCrossing(&d);
  c_ = d;
  crosser_.set_c(&c_);
  return result;
}

#endif  // S2_S2EDGE_CROSSER_H_


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

	<package name="bsc-pdca" extends="bsc-default" namespace="/" >

		<action name="bsc.pdcaManagementAction" class="bsc.web.controller.PdcaManagementAction">
			<result name="input">/pages/pdca/pdca-management.jsp</result>
			<result name="success">/pages/pdca/pdca-management.jsp</result>
		</action>

		<action name="bsc.pdcaCreateAction" class="bsc.web.controller.PdcaManagementAction" method="create">
			<result name="input">/pages/pdca/pdca-create.jsp</result>
			<result name="success">/pages/pdca/pdca-create.jsp</result>
		</action>

		<action name="bsc.pdcaEditAction" class="bsc.web.controller.PdcaManagementAction" method="edit">
			<result name="input">/pages/pdca/pdca-edit.jsp</result>
			<result name="success">/pages/pdca/pdca-edit.jsp</result>
		</action>

		<!-- Confirm audit dialog -->
		<action name="bsc.pdcaConfirmDialogAction" class="bsc.web.controller.PdcaManagementAction" method="confirmDialog">
			<result name="input">/pages/pdca/pdca-confirm.jsp</result>
			<result name="success">/pages/pdca/pdca-confirm.jsp</result>
		</action>

		<!-- PDCA report -->
		<action name="bsc.pdcaReportAction" class="bsc.web.controller.PdcaReportAction">
			<result name="input">/pages/pdca/pdca-report.jsp</result>
			<result name="success">/pages/pdca/pdca-report.jsp</result>
		</action>

	</package>

	<package name="bsc-pdca-json" extends="bsc-default,json-default" namespace="/" >

		<default-interceptor-ref name="greenStepDefaultCustomStack" />

		<action name="bsc.pdcaManagementGridQueryAction" class="bsc.web.controller.PdcaManagementGridQueryAction" >
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<action name="bsc.pdcaSaveAction" class="bsc.web.controller.PdcaSaveOrUpdateAction" method="doSave">
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<action name="bsc.pdcaUpdateAction" class="bsc.web.controller.PdcaSaveOrUpdateAction" method="doUpdate">
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<action name="bsc.pdcaDeleteAction" class="bsc.web.controller.PdcaSaveOrUpdateAction" method="doDelete">
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<action name="bsc.pdcaStartProcessAction" class="bsc.web.controller.PdcaSaveOrUpdateAction" method="doStartProcess">
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<action name="bsc.pdcaLoadTaskDiagramAction" class="bsc.web.controller.PdcaSaveOrUpdateAction" method="doLoadTaskDiagram">
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<!-- Confirm audit dialog -->
		<action name="bsc.pdcaConfirmSaveAction" class="bsc.web.controller.PdcaSaveOrUpdateAction" method="doConfirmAuditTask">
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<!-- PDCA report -->
		<action name="bsc.pdcaReportContentQuery" class="bsc.web.controller.PdcaReportContentQueryAction" >
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<action name="bsc.pdcaReportExcelQuery" class="bsc.web.controller.PdcaReportContentQueryAction" method="doExcel">
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

		<action name="bsc.pdcaProjectRelatedQuery" class="bsc.web.controller.PdcaReportContentQueryAction" method="doProjectRelated">
			<result type="json">
  				<param name="contentType">text/html</param>
  				<param name="noCache">true</param>
			</result>
		</action>

	</package>

</struts>


text:
import calendar
from corehq.apps.reports.filters.select import YearFilter
from corehq.apps.reports.generic import GenericTabularReport
from corehq.apps.reports.standard import CustomProjectReport
from corehq.apps.users.models import CommCareUser
from custom.up_nrhm.filters import DrillDownOptionFilter, SampleFormatFilter, ASHAMonthFilter,\
    NRHMDatespanFilter, NRHMDatespanMixin
from custom.up_nrhm.reports.asha_facilitators_report import ASHAFacilitatorsReport
from custom.up_nrhm.reports.asha_functionality_checklist_report import ASHAFunctionalityChecklistReport
from custom.up_nrhm.reports.block_level_af_report import BlockLevelAFReport
from custom.up_nrhm.reports.block_level_month_report import BlockLevelMonthReport
from custom.up_nrhm.reports.district_functionality_report import DistrictFunctionalityReport

def total_rows(report):
    if report.report_config.get('sf') == "sf2":
        return {
            "total_under_facilitator": getattr(report, 'total_under_facilitator', 0),
            "total_with_checklist": getattr(report, 'total_with_checklist', 0)
        }
    return {}

class ASHAReports(GenericTabularReport, NRHMDatespanMixin, CustomProjectReport):
    fields = [SampleFormatFilter, NRHMDatespanFilter, DrillDownOptionFilter, ASHAMonthFilter, YearFilter]
    name = "ASHA Sangini Reports"
    slug = "asha_reports"
    show_all_rows = True
    default_rows = 20
    printable = True
    report_template_path = "up_nrhm/asha_report.html"
    extra_context_providers = [total_rows]
    no_value = '--'

    @property
    def report_subtitles(self):
        sf = self.report_config.get('sf')
        if sf:
            selected_af = self.request.GET.get('hierarchy_af')
            user = CommCareUser.get(selected_af)
            if sf in ['sf5', 'sf4', 'sf3']:
                return [
                    "Selected AF: {0} {1}".format(user.first_name, user.last_name),
                    "Last Reporting Month of the Quarter: {0} {1}".format(
                        calendar.month_name[int(self.request.GET.get('month'))],
                        self.request.GET.get('year')
                    )
                ]
            else:
                return [
                    "Selected AF: {0} {1}".format(user.first_name, user.last_name),
                    "For Date: {0} to {1}".format(self.datespan.startdate.strftime("%Y-%m-%d"),
                                                  self.datespan.enddate.strftime("%Y-%m-%d"))
                ]

    @property
    def report_config(self):
        config = {
            'sf': self.request.GET.get('sf'),
        }
        return config

    @property
    def report_context(self):
        context = super(ASHAReports, self).report_context
        context['sf'] = self.request.GET.get('sf')
        return context

    @property
    def report(self):
        config = self.report_config
        if config.get('sf') == 'sf5':
            return DistrictFunctionalityReport(self.request, domain=self.domain)
        elif config.get('sf') == 'sf4':
            return BlockLevelAFReport(self.request, domain=self.domain)
        elif config.get('sf') == 'sf3':
            return BlockLevelMonthReport(self.request, domain=self.domain)
        elif config.get('sf') == 'sf2':
            return ASHAFacilitatorsReport(self.request, domain=self.domain)
        else:
            return ASHAFunctionalityChecklistReport(self.request, domain=self.domain)

    @property
    def headers(self):
        return self.report.headers

    @property
    def rows(self):
        config = self.report_config
        if not config.get('sf'):
            rows = self.report.rows
        elif config.get('sf') == 'sf2':
            rows, self.total_under_facilitator, self.total_with_checklist = self.report.rows
        else:
            rows = self.report.rows[0]
        return rows


text:
package io.netty.handler.codec.http.cookie;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import io.netty.handler.codec.http.HttpHeaderDateFormat;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class ServerCookieEncoderTest {

    @Test
    public void testEncodingSingleCookieV0() throws ParseException {

        int maxAge = 50;

        String result =
                "myCookie=myValue; Max-Age=50; Expires=(.+?); Path=/apathsomewhere; Domain=.adomainsomewhere; Secure";
        Cookie cookie = new DefaultCookie("myCookie", "myValue");
        cookie.setDomain(".adomainsomewhere");
        cookie.setMaxAge(maxAge);
        cookie.setPath("/apathsomewhere");
        cookie.setSecure(true);

        String encodedCookie = ServerCookieEncoder.STRICT.encode(cookie);

        Matcher matcher = Pattern.compile(result).matcher(encodedCookie);
        assertTrue(matcher.find());
        Date expiresDate = HttpHeaderDateFormat.get().parse(matcher.group(1));
        long diff = (expiresDate.getTime() - System.currentTimeMillis()) / 1000;
        // 2 secs should be fine
        assertTrue(Math.abs(diff - maxAge) <= 2);
    }

    @Test
    public void testEncodingWithNoCookies() {
        String encodedCookie1 = ClientCookieEncoder.STRICT.encode();
        List<String> encodedCookie2 = ServerCookieEncoder.STRICT.encode();
        assertNull(encodedCookie1);
        assertNotNull(encodedCookie2);
        assertTrue(encodedCookie2.isEmpty());
    }

    @Test
    public void testEncodingMultipleCookiesStrict() {
        List<String> result = new ArrayList<String>();
        result.add("cookie2=value2");
        result.add("cookie1=value3");
        Cookie cookie1 = new DefaultCookie("cookie1", "value1");
        Cookie cookie2 = new DefaultCookie("cookie2", "value2");
        Cookie cookie3 = new DefaultCookie("cookie1", "value3");
        List<String> encodedCookies = ServerCookieEncoder.STRICT.encode(cookie1, cookie2, cookie3);
        assertEquals(result, encodedCookies);
    }

    @Test
    public void testEncodingMultipleCookiesLax() {
        List<String> result = new ArrayList<String>();
        result.add("cookie1=value1");
        result.add("cookie2=value2");
        result.add("cookie1=value3");
        Cookie cookie1 = new DefaultCookie("cookie1", "value1");
        Cookie cookie2 = new DefaultCookie("cookie2", "value2");
        Cookie cookie3 = new DefaultCookie("cookie1", "value3");
        List<String> encodedCookies = ServerCookieEncoder.LAX.encode(cookie1, cookie2, cookie3);
        assertEquals(result, encodedCookies);
    }
}