text:
"""
Making scipy ode solvers available via the ode API
Created on Thu Jan 28 14:59:25 2016

@author: benny
"""

from __future__ import print_function

integrator_info = \
"""
dopri5
~~~~~~
    This is an explicit runge-kutta method of order (4)5 due to Dormand & Prince
    (with stepsize control and dense output).
    The API of this solver is as the other scikit.odes ODE solvers

    Authors:

        E. Hairer and G. Wanner Universite de Geneve, Dept. de Mathematiques CH-1211 Geneve 24, Switzerland e-mail: ernst.hairer@math.unige.ch, gerhard.wanner@math.unige.ch

    This code is described in [HNW93].

    This integrator accepts the following options:

        atol : float or sequence absolute tolerance for solution, default 1e-12
        rtol : float or sequence relative tolerance for solution, default 1e-6
        nsteps : int Maximum number of (internally defined) steps allowed during one call to the solver. Default=500
        first_step : float
        max_step : float
        safety : float Safety factor on new step selection (default 0.9)
        ifactor : float
        dfactor : float Maximum factor to increase/decrease step size by in one step
        beta : float Beta parameter for stabilised step size control.
        verbosity : int Switch for printing messages (< 0 for no messages).

References
[HNW93]	(1, 2) E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary Differential Equations i. Nonstiff Problems. 2nd edition. Springer Series in Computational Mathematics, Springer-Verlag (1993)

dop853
~~~~~~
    This is an explicit runge-kutta method of order 8(5,3) due to Dormand & Prince
    (with stepsize control and dense output).
    Options and references the same as "dopri5".

"""
from collections import namedtuple
from enum import IntEnum
from warnings import warn

import numpy as np

from .ode import OdeBase

SolverReturn = namedtuple(
    "SolverReturn", [
        "flag", "values", "errors", "roots",
        "tstop", "message"
    ]
)

SolverVariables = namedtuple("SolverVariables", ["t", "y"])

class StatusEnumDOP(IntEnum):
    SUCCESS = 1
    SOLOUT  = 2

    INPUT_FAIL     = -1
    NMAX_FAIL      = -2
    STEPSIZE_FAIL  = -3
    STIFFNESS_FAIL = -4

    UNEXPECTED_IDID = -10

STATUS_MESSAGE = {
    StatusEnumDOP.SUCCESS: 'computation successful',
    StatusEnumDOP.SOLOUT: 'comput. successful (interrupted by solout)',
    StatusEnumDOP.INPUT_FAIL: 'input is not consistent',
    StatusEnumDOP.NMAX_FAIL: 'larger nmax is needed',
    StatusEnumDOP.STEPSIZE_FAIL: 'step size becomes too small',
    StatusEnumDOP.STIFFNESS_FAIL: 'problem is probably stiff (interrupted)',
    StatusEnumDOP.UNEXPECTED_IDID: 'Unexpected idid, check warnings for info',
}

class DOPSolveException(Exception):
    """Base class for exceptions raised by `DOP.validate_flags`."""
    def __init__(self, soln):
        self.soln = soln
        self.args = (self._message.format(soln),)

class DOPSolveFailed(DOPSolveException):
    """`DOP.solve` failed to reach endpoint"""
    _message = (
        "Solver failed with flag {0.flag} and finished at {0.errors.t}"
        "with values {0.errors.y}."
    )

class dopri5(OdeBase):
    __doc__ += integrator_info

    try:
        from scipy.integrate import ode as _runner
    except ImportError:
        print(sys.exc_info()[1])
        _runner = None

    name = 'dopri5'

    default_values = {
            'rtol': 1e-6,
            'atol': 1e-12,
            'nsteps': 500,
            'max_step': 0.0,
            'first_step': 0.0,  # determined by solver
            'safety': 0.9,
            'ifactor': 10.0,
            'dfactor': 0.2,
            'beta': 0.0,
            'verbosity': -1, # no messages if negative
            }

    def __init__(self, Rfn, **options):
        """
        Initialize the ODE Solver and it's default values

        Input:
            Rfn     - right-hand-side function
            options - additional options for initialization
        """
        self.options = self.default_values
        self.set_options(rfn=Rfn, **options)
        self._validate_flags = None
        self.solver = None
        self.initialized = False

    def set_options(self, **options):
        """
        Set specific options for the solver.

        Calling set_options a second time, normally resets the solver.
        """
        for (key, value) in options.items():
            self.options[key.lower()] = value
        self.initialized = False

    def _init_data(self):
        self.rfn = self.options['rfn']
        self.N = len(self.y0)

    def _wrap_Rfn(self, t, y):
        yout = np.empty(self.N, float)
        self.rfn(t, y, yout)
        return yout

    def init_step(self, t0, y0):
        """
        Initializes the solver and allocates memory.

        Input:
            t0     - initial time
            y0     - initial condition for y (can be list or numpy array)

        Return values:
         if old_api:
            not supported

         if old_api False:
            A named tuple, with entries:
                flag   = An integer flag (StatusEnumDop)
                values = Named tuple with entries t and y and ydot. y will
                            correspond to y_retn value and ydot to yp_retn!
                errors = Named tuple with entries t_err and y_err
                roots  = Named tuple with entries t_roots and y_roots
                tstop  = Named tuple with entries t_stop and y_tstop
                message= String with message in case of an error

        """
        self.y0 = y0
        self.t = t0
        self._init_data()

        self.solver = self._runner(self._wrap_Rfn)\
                        .set_integrator(self.name,
                            rtol = self.options['rtol'],
                            atol = self.options['atol'],
                            nsteps = self.options['nsteps'],
                            max_step = self.options['max_step'],
                            first_step = self.options['first_step'],  # determined by solver
                            safety = self.options['safety'],
                            ifactor = self.options['ifactor'],
                            dfactor = self.options['dfactor'],
                            beta = self.options['beta'],
                            verbosity = self.options['verbosity'])\
                        .set_initial_value(y0, t0)
        self.initialized = True
        y_retn  = np.empty(np.alen(y0), float)
        y_retn[:] = y0[:]
        soln = SolverReturn(
            flag=StatusEnumDOP.SUCCESS,
            values=SolverVariables(t=t0, y=y_retn),
            errors=SolverVariables(t=None, y=None),
            roots=SolverVariables(t=None, y=None),
            tstop=SolverVariables(t=None, y=None),
            message=STATUS_MESSAGE[StatusEnumDOP.SUCCESS]
        )
        if self._validate_flags:
            return self.validate_flags(soln)
        return soln

    def step(self, t, y_retn=None):
        """
        Method for calling successive next step of the ODE solver to allow
        more precise control over the solver. The 'init_step' method has to
        be called before the 'step' method.

        Input:
            t - A step is done towards time t, and output at t returned.
                This time can be higher or lower than the previous time.
                If option 'one_step_compute'==True, and the solver supports
                it, only one internal solver step is done in the direction
                of t starting at the current step.

                If old_api=True, the old behavior is used:
                 if t>0.0 then integration is performed until this time
                          and results at this time are returned in y_retn
                 if t<0.0 only one internal step is perfomed towards time abs(t)
                         and results after this one time step are returned
            y_retn - numpy vector (ndim = 1) in which the computed
                     value will be stored  (needs to be preallocated).  If
                     None y_retn is not used.
        Return values:
         if old_api:
             not supported

         if old_api False:
            A named tuple, with entries:
                flag   = An integer flag (StatusEnumDOP)
                values = Named tuple with entries t and y. y will
                            correspond to y_retn value
                errors = Named tuple with entries t_err and y_err
                roots  = Named tuple with entries t_roots and y_roots
                tstop  = Named tuple with entries t_stop and y_tstop
                message= String with message in case of an error

        """
        if not self.initialized == False:
            raise ValueError("DOPRI:step: init_step must be run before running the step method.")
        if t <= self.t:
            raise ValueError("Integration must be forward! t must be > previous timestep")
        y = self.solver.integrate(t)
        y_err = None
        t_err = None
        if not self.solver.successful():
            flag = StatusEnumDOP.UNEXPECTED_IDID
            y_err = y
            t_err = t
        else:
            flag = StatusEnumDOP.SUCCESS
            self.y = y
            self.t = self.solver.t

        return SolverReturn(
            flag=flag,
            values=SolverVariables(t=self.t, y=y),
            errors=SolverVariables(t=t_err, y=y_err),
            roots=SolverVariables(t=None, y=None),
            tstop=SolverVariables(t=None, y=None),
            message=STATUS_MESSAGE[flag]
        )

    def solve(self, tspan, y0):
        """
        Runs the solver.

        Input:
            tspan - an list/array of times at which the computed value will be
                    returned. Must contain the start time as first entry..
            y0    - list/numpy array of initial values

        Return values:
         if old_api
            Not supported
         if old_api False:
            A named tuple, with entries:
                flag   = An integer flag
                values = Named tuple with entries t and y
                errors = Named tuple with entries t and y
                roots  = Named tuple with entries t and y
                tstop  = Named tuple with entries t and y
                message= String with message in case of an error
        """
        self.initialized = False
        soln = self.init_step(tspan[0], y0)
        nrt = len(tspan)
        t_retn  = np.empty(np.shape(tspan), float)
        y_retn  = np.empty([np.alen(tspan), np.alen(y0)], float)

        t_retn[0] = tspan[0]
        y_retn[0, :] = y0

        idx = 1
        while self.solver.successful() and idx<nrt:
            time = tspan[idx]
            y = self.solver.integrate(time)
            t_retn[idx] = time
            y_retn[idx, :] = y
            idx += 1

        y_err = None
        t_err = None
        if not self.solver.successful():
            flag = StatusEnumDOP.UNEXPECTED_IDID
            y_err = y_retn[idx-1]
            t_err = t_retn[idx-1]
            # return values computed so far
            t_retn  = t_retn[0:idx-1]
            y_retn  = y_retn[0:idx-1, :]
        else:
            flag = StatusEnumDOP.SUCCESS

        soln = SolverReturn(
            flag=flag,
            values=SolverVariables(t=t_retn, y=y_retn),
            errors=SolverVariables(t=t_err, y=y_err),
            roots=SolverVariables(t=None, y=None),
            tstop=SolverVariables(t=None, y=None),
            message=STATUS_MESSAGE[flag]
        )
        if self._validate_flags:
            return self.validate_flags(soln)
        return soln

    def validate_flags(self, soln):
        """
        Validates the flag returned by `dopri.solve`.

        Validation happens using the following scheme:
         * failures (`flag` < 0) raise `DOPSolveFailed` or a subclass of it;
         * otherwise, return an instance of `SolverReturn`.

        """
        if soln.flag == StatusEnumDOP.SUCCESS:
            return soln
        if soln.flag < 0:
            raise DOPSolveFailed(soln)
        warn(WARNING_STR.format(soln.flag, *soln.err_values))
        return soln

class dop853(dopri5):
    name = 'dop853'
    default_values = {
            'rtol': 1e-6,
            'atol': 1e-12,
            'nsteps': 500,
            'max_step': 0.0,
            'first_step': 0.0,  # determined by solver
            'safety': 0.9,
            'ifactor': 6.0,
            'dfactor': 0.3,
            'beta': 0.0,
            'verbosity': -1, # no messages if negative
            }

if dopri5._runner:
    OdeBase.integrator_classes.append(dopri5)

if dop853._runner:
    OdeBase.integrator_classes.append(dop853)


text:
@section('js')
    {{ HTML::script(asset('//tinymce.cachefly.net/4.1/tinymce.min.js')) }}
    {{ HTML::script(asset('js/admin/form.js')) }}
@stop

@section('otherSideLink')
    @include('admin._navbar-public-link')
@stop

@include('admin._buttons-form')

{{ Form::hidden('id'); }}

@include('admin._image-fieldset', ['field' => 'image'])

has('start_date'))has-error @endif">
        {{ Form::label('start_date', trans('validation.attributes.start_date'), array('class' => 'control-label')) }}
        {{ Form::text('start_date', $model->present()->dateOrNow('start_date'), array('class' => 'datepicker form-control', 'data-value' => $model->present()->dateOrNow('start_date'), 'placeholder' => trans('validation.attributes.DDMMYYYY'))) }}
        {{ $errors->first('start_date', '
:message
') }}

has('start_time'))has-error @endif">
        {{ Form::label('start_time', trans('validation.attributes.start_time'), array('class' => 'control-label')) }}
        {{ Form::text('start_time', $model->present()->startTime, array('class' => 'form-control', 'placeholder' => trans('validation.attributes.HH:MM'))) }}
        {{ $errors->first('start_time', '
:message
') }}

has('end_date'))has-error @endif">
        {{ Form::label('end_date', trans('validation.attributes.end_date'), array('class' => 'control-label')) }}
        {{ Form::text('end_date', $model->present()->dateOrNow('end_date'), array('class' => 'datepicker form-control', 'data-value' => $model->present()->dateOrNow('end_date'), 'placeholder' => trans('validation.attributes.DDMMYYYY'))) }}
        {{ $errors->first('end_date', '
:message
') }}

has('end_time'))has-error @endif">
        {{ Form::label('end_time', trans('validation.attributes.end_time'), array('class' => 'control-label')) }}
        {{ Form::text('end_time', $model->present()->endTime, array('class' => 'form-control', 'placeholder' => trans('validation.attributes.HH:MM'))) }}
        {{ $errors->first('end_time', '
:message
') }}

@include('admin._tabs-lang')

    @foreach ($locales as $lang)

                {{ Form::label($lang.'[title]', trans('validation.attributes.title')) }}
                {{ Form::text($lang.'[title]', $model->translate($lang)->title, array('class' => 'form-control')) }}

has($lang.'.slug'))has-error @endif">
                {{ Form::label($lang.'[slug]', trans('validation.attributes.slug'), array('class' => 'control-label')) }}

                    {{ Form::text($lang.'[slug]', $model->translate($lang)->slug, array('class' => 'form-control')) }}

                        <button class="btn btn-default btn-slug @if($errors->has($lang.'.slug'))btn-danger @endif" type="button">@lang('validation.attributes.generate')</button>

                {{ $errors->first($lang.'.slug', '
:message
') }}

                {{ Form::checkbox($lang.'[status]', 1, $model->translate($lang)->status) }} @lang('validation.attributes.online')

            {{ Form::label($lang.'[summary]', trans('validation.attributes.summary')) }}
            {{ Form::textarea($lang.'[summary]', $model->translate($lang)->summary, array('class' => 'form-control', 'rows' => 4)) }}

            {{ Form::label($lang.'[body]', trans('validation.attributes.body')) }}
            {{ Form::textarea($lang.'[body]', $model->translate($lang)->body, array('class' => 'editor form-control')) }}

    @endforeach

redpajama_set_name: RedPajamaGithub


text:
package org.esupportail.publisher.config.apidoc;

import static org.springdoc.core.Constants.DEFAULT_GROUP_NAME;
import static org.springdoc.core.Constants.SPRINGDOC_SHOW_ACTUATOR;
import static org.springdoc.core.SpringDocUtils.getConfig;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.Optional;

import org.esupportail.publisher.config.Constants;
import org.esupportail.publisher.config.ESUPPublisherProperties;
import org.esupportail.publisher.config.apidoc.customizer.JHipsterOpenApiCustomizer;

import io.swagger.v3.oas.models.info.Info;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.GroupedOpenApi.Builder;
import org.springdoc.core.customizers.ActuatorOpenApiCustomizer;
import org.springdoc.core.customizers.ActuatorOperationCustomizer;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * OpenApi Groups configuration.
 *

 * Warning! When having a lot of REST endpoints, OpenApi can become a performance issue.
 * In that case, you can use the "no-api-docs" Spring profile, so that this bean is ignored.
 */
@Configuration
@Profile(Constants.SPRING_PROFILE_API_DOCS)
public class JHipsterSpringDocGroupsConfiguration {

    public static final String MANAGEMENT_GROUP_NAME = "management";

    static {
        getConfig().replaceWithClass(ByteBuffer.class, String.class);
    }

    static final String MANAGEMENT_TITLE_SUFFIX = "Management API";
    static final String MANAGEMENT_DESCRIPTION = "Management endpoints documentation";

    private final Logger log = LoggerFactory.getLogger(JHipsterSpringDocGroupsConfiguration.class);

    private final ESUPPublisherProperties properties;

    /**
     *
Constructor for OpenApiAutoConfiguration.

     *
     * @param esupPublisherProperties a {@link ESUPPublisherProperties} object.
     */
    public JHipsterSpringDocGroupsConfiguration(ESUPPublisherProperties esupPublisherProperties) {
        properties = esupPublisherProperties;
    }

    /**
     * JHipster OpenApi Customiser
     *
     * @return the Customizer of JHipster
     */
    @Bean
    public JHipsterOpenApiCustomizer jhipsterOpenApiCustomizer() {
        log.debug("Initializing JHipster OpenApi customizer");
        return new JHipsterOpenApiCustomizer(properties);
    }

    /**
     * OpenApi default group configuration.
     *
     * @return the GroupedOpenApi configuration
     */
    @Bean
    @ConditionalOnMissingBean(name = "openAPIDefaultGroupedOpenAPI")
    public GroupedOpenApi openAPIDefaultGroupedOpenAPI(
        List<OpenApiCustomiser> openApiCustomisers,
        List<OperationCustomizer> operationCustomizers,
        @Qualifier("apiFirstGroupedOpenAPI") Optional<GroupedOpenApi> apiFirstGroupedOpenAPI
    ) {
        log.debug("Initializing JHipster OpenApi default group");
        Builder builder = GroupedOpenApi.builder()
            .group(DEFAULT_GROUP_NAME)
            .pathsToMatch(properties.getApiDocs().getDefaultIncludePattern());
        openApiCustomisers.stream()
            .filter(customizer -> !(customizer instanceof ActuatorOpenApiCustomizer))
            .forEach(builder::addOpenApiCustomiser);
        operationCustomizers.stream()
            .filter(customizer -> !(customizer instanceof ActuatorOperationCustomizer))
            .forEach(builder::addOperationCustomizer);
        apiFirstGroupedOpenAPI.map(GroupedOpenApi::getPackagesToScan)
            .ifPresent(packagesToScan -> packagesToScan.forEach(builder::packagesToExclude));
        return builder.build();
    }

    /**
     * OpenApi management group configuration for the management endpoints (actuator) OpenAPI docs.
     *
     * @return the GroupedOpenApi configuration
     */
    @Bean
    @ConditionalOnClass(name = "org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties")
    @ConditionalOnMissingBean(name = "openAPIManagementGroupedOpenAPI")
    @ConditionalOnProperty(SPRINGDOC_SHOW_ACTUATOR)
    public GroupedOpenApi openAPIManagementGroupedOpenAPI(
        @Value("${spring.application.name:application}") String appName,
        ActuatorOpenApiCustomizer actuatorOpenApiCustomiser,
        ActuatorOperationCustomizer actuatorCustomizer
    ) {
        log.debug("Initializing JHipster OpenApi management group");
        return GroupedOpenApi.builder()
            .group(MANAGEMENT_GROUP_NAME)
            .addOpenApiCustomiser(openApi -> openApi.info(new Info()
                .title(StringUtils.capitalize(appName) + " " + MANAGEMENT_TITLE_SUFFIX)
                .description(MANAGEMENT_DESCRIPTION)
                .version(properties.getApiDocs().getVersion())
            ))
            .addOpenApiCustomiser(actuatorOpenApiCustomiser)
            .addOperationCustomizer(actuatorCustomizer)
            .pathsToMatch(properties.getApiDocs().getManagementIncludePattern())
            .build();
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Note Page Bingo Needed</title>
		<link>http://bvs.wikidot.com/forum/t-105711/note-page-bingo-needed</link>
		<description>Posts in the discussion thread "Note Page Bingo Needed" - Deedo of Emonds Village lvl. 42</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 05:13:26 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-105711#post-310518</guid>
				<title>Note Page Bingo Needed</title>
				<link>http://bvs.wikidot.com/forum/t-105711/note-page-bingo-needed#post-310518</link>
				<description></description>
				<pubDate>Mon, 17 Nov 2008 11:13:57 +0000</pubDate>
				<wikidot:authorName>Anonymous</wikidot:authorName>								<content:encoded>
					<![CDATA[

I need a Note Page Bingo on Deedo (Emonds/ Lvl.42) to get Anon.

If needed, i can bingo back with a note page. Just write a short message here after the bingo is done and i will give the favour back!

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
<?php

declare(strict_types=1);

namespace Omines\DataTablesBundle\Adapter\Doctrine\ORM;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\QueryBuilder;
use Omines\DataTablesBundle\Column\AbstractColumn;
use Omines\DataTablesBundle\DataTableState;

/**
 * AutomaticQueryBuilder.
 *
 * @author Niels Keurentjes <niels.keurentjes@omines.com>
 */
class AutomaticQueryBuilder implements QueryBuilderProcessorInterface
{
    /** @var EntityManagerInterface */
    private $em;

    /** @var ClassMetadata */
    private $metadata;

    /** @var string */
    private $entityName;

    /** @var string */
    private $entityShortName;

    /** @var array */
    private $selectColumns = [];

    /** @var array */
    private $joins = [];

    /**
     * AutomaticQueryBuilder constructor.
     */
    public function __construct(EntityManagerInterface $em, ClassMetadata $metadata)
    {
        $this->em = $em;
        $this->metadata = $metadata;

        $this->entityName = $this->metadata->getName();
        $this->entityShortName = mb_strtolower($this->metadata->getReflectionClass()->getShortName());
    }

    /**
     * {@inheritdoc}
     */
    public function process(QueryBuilder $builder, DataTableState $state)
    {
        if (empty($this->selectColumns) && empty($this->joins)) {
            foreach ($state->getDataTable()->getColumns() as $column) {
                $this->processColumn($column);
            }
        }
        $builder->from($this->entityName, $this->entityShortName);
        $this->setSelectFrom($builder);
        $this->setJoins($builder);
    }

    protected function processColumn(AbstractColumn $column)
    {
        $field = $column->getField();

        // Default to the column name if that corresponds to a field mapping
        if (!isset($field) && isset($this->metadata->fieldMappings[$column->getName()])) {
            $field = $column->getName();
        }
        if (null !== $field) {
            $this->addSelectColumns($column, $field);
        }
    }

    private function addSelectColumns(AbstractColumn $column, string $field)
    {
        $currentPart = $this->entityShortName;
        $currentAlias = $currentPart;
        $metadata = $this->metadata;

        $parts = explode('.', $field);

        if (count($parts) > 1 && $parts[0] === $currentPart) {
            array_shift($parts);
        }

        if (sizeof($parts) > 1 && $field = $metadata->hasField(implode('.', $parts))) {
            $this->addSelectColumn($currentAlias, implode('.', $parts));
        } else {
            while (count($parts) > 1) {
                $previousPart = $currentPart;
                $previousAlias = $currentAlias;
                $currentPart = array_shift($parts);
                $currentAlias = ($previousPart === $this->entityShortName ? '' : $previousPart . '_') . $currentPart;

                $this->joins[$previousAlias . '.' . $currentPart] = ['alias' => $currentAlias, 'type' => 'join'];

                $metadata = $this->setIdentifierFromAssociation($currentAlias, $currentPart, $metadata);
            }

            $this->addSelectColumn($currentAlias, $this->getIdentifier($metadata));
            $this->addSelectColumn($currentAlias, $parts[0]);
        }
    }

    private function addSelectColumn($columnTableName, $data)
    {
        if (isset($this->selectColumns[$columnTableName])) {
            if (!in_array($data, $this->selectColumns[$columnTableName], true)) {
                $this->selectColumns[$columnTableName][] = $data;
            }
        } else {
            $this->selectColumns[$columnTableName][] = $data;
        }

        return $this;
    }

    private function getIdentifier(ClassMetadata $metadata)
    {
        $identifiers = $metadata->getIdentifierFieldNames();

        return array_shift($identifiers);
    }

    private function setIdentifierFromAssociation(string $association, string $key, ClassMetadata $metadata)
    {
        $targetEntityClass = $metadata->getAssociationTargetClass($key);

        /** @var ClassMetadata $targetMetadata */
        $targetMetadata = $this->em->getMetadataFactory()->getMetadataFor($targetEntityClass);
        $this->addSelectColumn($association, $this->getIdentifier($targetMetadata));

        return $targetMetadata;
    }

    private function setSelectFrom(QueryBuilder $qb)
    {
        foreach ($this->selectColumns as $key => $value) {
            if (false === empty($key)) {
                $qb->addSelect('partial ' . $key . '.{' . implode(',', $value) . '}');
            } else {
                $qb->addSelect($value);
            }
        }

        return $this;
    }

    private function setJoins(QueryBuilder $qb)
    {
        foreach ($this->joins as $key => $value) {
            $qb->{$value['type']}($key, $value['alias']);
        }

        return $this;
    }
}


text:
"""
====================================================
Plot multinomial and One-vs-Rest Logistic Regression
====================================================

Plot decision surface of multinomial and One-vs-Rest Logistic Regression.
The hyperplanes corresponding to the three One-vs-Rest (OVR) classifiers
are represented by the dashed lines.
"""
print(__doc__)
# Authors: Tom Dupre la Tour <tom.dupre-la-tour@m4x.org>
# Licence: BSD 3 clause

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression

# make 3-class dataset for classification
centers = [[-5, 0], [0, 1.5], [5, -1]]
X, y = make_blobs(n_samples=1000, centers=centers, random_state=40)
transformation = [[0.4, 0.2], [-0.4, 1.2]]
X = np.dot(X, transformation)

for multi_class in ('multinomial', 'ovr'):
    clf = LogisticRegression(solver='sag', max_iter=100, random_state=42,
                             multi_class=multi_class).fit(X, y)

    # print the training scores
    print("training score : %.3f (%s)" % (clf.score(X, y), multi_class))

    # create a mesh to plot in
    h = .02  # step size in the mesh
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
    plt.title("Decision surface of LogisticRegression (%s)" % multi_class)
    plt.axis('tight')

    # Plot also the training points
    colors = "bry"
    for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired)

    # Plot the three one-against-all classifiers
    xmin, xmax = plt.xlim()
    ymin, ymax = plt.ylim()
    coef = clf.coef_
    intercept = clf.intercept_

    def plot_hyperplane(c, color):
        def line(x0):
            return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1]

        plt.plot([xmin, xmax], [line(xmin), line(xmax)],
                 ls="--", color=color)

    for i, color in zip(clf.classes_, colors):
        plot_hyperplane(i, color)

plt.show()


text:
@interface PodsDummy_JBChartView : NSObject
@end
@implementation PodsDummy_JBChartView
@end


text:
/*
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * TitleUpdatedListener.java
 * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
 */

package weka.gui.scripting.event;

/**
 * Interface for frames/dialogs that listen to changes of the title.
 *
 * @author  fracpete (fracpete at waikato dot ac dot nz)
 * @version $Revision: 8034 $
 */
public interface TitleUpdatedListener {

  /**
   * Gets called when the title of the frame/dialog needs updating.
   *
   * @param event	the event that got sent
   */
  public void titleUpdated(TitleUpdatedEvent event);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 56(3-4): 414 (1993)

#### Original name
Laboulbenia sphaerii Santam.

### Remarks
null


text:
package example.service;

import example.repo.Customer216Repository;

import org.springframework.stereotype.Service;

@Service
public class Customer216Service {
	public Customer216Service(Customer216Repository repo) {}
}


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

  <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title>
  <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.description }}{% endif %}">

  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
  <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}" />
<!-- font google-->
<link href='//fonts.googleapis.com/css?family=Open+Sans:400,300italic,300,400italic,600,700,600italic,700italic,800,800italic' rel='stylesheet' type='text/css'>
  <!-- Material Design Lite css Library -->
<link rel="stylesheet" href="//code.getmdl.io/1.1.3/material.grey-pink.min.css" />

  <!-- Material Design Fonts -->
  <link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons">

  <!-- Font Awesome-->
  <script src="https://use.fontawesome.com/448ff0c27a.js"></script>
  <!-- Custom theme css -->

  <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
  <link rel="stylesheet" href="{{ "/css/monokai.css" | prepend: site.baseurl }}">
  <link rel="stylesheet" href="{{ "/css/timeline.css" | prepend: site.baseurl }}">
  <script src="//apis.google.com/js/platform.js" async defer>
  {lang: 'es'}
</script>
</head>


text:
    <script type='text/javascript' src='../brown.min.js'></script>
    <script>
      brown = require('brown');
      html = brown.render( {"div":"{{foo}}"}, {foo:"bar"} )
      alert(html);
    </script>


text:
package org.elasticsearch.common.util.concurrent;

import com.google.common.collect.ImmutableList;
import org.elasticsearch.ElasticSearchGenerationException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReferenceArray;

/**
 * A list backed by an {@link AtomicReferenceArray} with potential null values, easily allowing
 * to get the concrete values as a list using {@link #asList()}.
 */
public class AtomicArray<E> {

    private static final AtomicArray EMPTY = new AtomicArray(0);

    @SuppressWarnings("unchecked")
    public static <E> E empty() {
        return (E) EMPTY;
    }

    private final AtomicReferenceArray<E> array;
    private volatile List<Entry<E>> nonNullList;

    public AtomicArray(int size) {
        array = new AtomicReferenceArray<E>(size);
    }

    /**
     * The size of the expected results, including potential null values.
     */
    public int length() {
        return array.length();
    }

    /**
     * Sets the element at position {@code i} to the given value.
     *
     * @param i     the index
     * @param value the new value
     */
    public void set(int i, E value) {
        array.set(i, value);
        if (nonNullList != null) { // read first, lighter, and most times it will be null...
            nonNullList = null;
        }
    }

    /**
     * Gets the current value at position {@code i}.
     *
     * @param i the index
     * @return the current value
     */
    public E get(int i) {
        return array.get(i);
    }

    /**
     * Returns the it as a non null list, with an Entry wrapping each value allowing to
     * retain its index.
     */
    public List<Entry<E>> asList() {
        if (nonNullList == null) {
            if (array == null || array.length() == 0) {
                nonNullList = ImmutableList.of();
            } else {
                List<Entry<E>> list = new ArrayList<Entry<E>>(array.length());
                for (int i = 0; i < array.length(); i++) {
                    E e = array.get(i);
                    if (e != null) {
                        list.add(new Entry<E>(i, e));
                    }
                }
                nonNullList = list;
            }
        }
        return nonNullList;
    }

    /**
     * Copies the content of the underlying atomic array to a normal one.
     */
    public E[] toArray(E[] a) {
        if (a.length != array.length()) {
            throw new ElasticSearchGenerationException("AtomicArrays can only be copied to arrays of the same size");
        }
        for (int i = 0; i < array.length(); i++) {
            a[i] = array.get(i);
        }
        return a;
    }

    /**
     * An entry within the array.
     */
    public static class Entry<E> {
        /**
         * The original index of the value within the array.
         */
        public final int index;
        /**
         * The value.
         */
        public final E value;

        public Entry(int index, E value) {
            this.index = index;
            this.value = value;
        }
    }
}


text:
description: A collection of protobufs dynamically constructed by descriptor protos.

<meta itemprop="name" content="expression_impl.proto.DescriptorPool" />
<meta itemprop="path" content="Stable" />
<meta itemprop="property" content="Add"/>
<meta itemprop="property" content="AddDescriptor"/>
<meta itemprop="property" content="AddEnumDescriptor"/>
<meta itemprop="property" content="AddExtensionDescriptor"/>
<meta itemprop="property" content="AddFileDescriptor"/>
<meta itemprop="property" content="AddSerializedFile"/>
<meta itemprop="property" content="AddServiceDescriptor"/>
<meta itemprop="property" content="FindAllExtensions"/>
<meta itemprop="property" content="FindEnumTypeByName"/>
<meta itemprop="property" content="FindExtensionByName"/>
<meta itemprop="property" content="FindExtensionByNumber"/>
<meta itemprop="property" content="FindFieldByName"/>
<meta itemprop="property" content="FindFileByName"/>
<meta itemprop="property" content="FindFileContainingSymbol"/>
<meta itemprop="property" content="FindMessageTypeByName"/>
<meta itemprop="property" content="FindMethodByName"/>
<meta itemprop="property" content="FindOneofByName"/>
<meta itemprop="property" content="FindServiceByName"/>
<meta itemprop="property" content="__init__"/>
<meta itemprop="property" content="__new__"/>

# expression_impl.proto.DescriptorPool

A collection of protobufs dynamically constructed by descriptor protos.

expression_impl.proto.DescriptorPool(
    descriptor_db=None
)

<colgroup><col width="214px"><col></colgroup>

Args

`descriptor_db`

A secondary source of file descriptors.

## Methods

Add

Add(
    file_desc_proto
)

Adds the FileDescriptorProto and its types to this pool.

<colgroup><col width="214px"><col></colgroup>

Args

file_desc_proto (FileDescriptorProto): The file descriptor to add.

AddDescriptor

AddDescriptor(
    *args, **kwargs
)

AddEnumDescriptor

AddEnumDescriptor(
    *args, **kwargs
)

AddExtensionDescriptor

AddExtensionDescriptor(
    *args, **kwargs
)

AddFileDescriptor

AddFileDescriptor(
    *args, **kwargs
)

AddSerializedFile

AddSerializedFile(
    serialized_file_desc_proto
)

Adds the FileDescriptorProto and its types to this pool.

<colgroup><col width="214px"><col></colgroup>

Args

serialized_file_desc_proto (bytes): A bytes string, serialization of the
:class:`FileDescriptorProto` to add.

AddServiceDescriptor

AddServiceDescriptor(
    *args, **kwargs
)

FindAllExtensions

FindAllExtensions(
    message_descriptor
)

Gets all the known extensions of a given message.

Extensions have to be registered to this pool by build related
:func:`Add` or :func:`AddExtensionDescriptor`.

<colgroup><col width="214px"><col></colgroup>

Args

message_descriptor (Descriptor): Descriptor of the extended message.

<colgroup><col width="214px"><col></colgroup>

Returns

list[FieldDescriptor]: Field descriptors describing the extensions.

FindEnumTypeByName

FindEnumTypeByName(
    full_name
)

Loads the named enum descriptor from the pool.

<colgroup><col width="214px"><col></colgroup>

Args

full_name (str): The full name of the enum descriptor to load.

<colgroup><col width="214px"><col></colgroup>

Returns

`EnumDescriptor`

The enum descriptor for the named type.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the enum cannot be found in the pool.

FindExtensionByName

FindExtensionByName(
    full_name
)

Loads the named extension descriptor from the pool.

<colgroup><col width="214px"><col></colgroup>

Args

full_name (str): The full name of the extension descriptor to load.

<colgroup><col width="214px"><col></colgroup>

Returns

`FieldDescriptor`

The field descriptor for the named extension.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the extension cannot be found in the pool.

FindExtensionByNumber

FindExtensionByNumber(
    message_descriptor, number
)

Gets the extension of the specified message with the specified number.

Extensions have to be registered to this pool by calling :func:`Add` or
:func:`AddExtensionDescriptor`.

<colgroup><col width="214px"><col></colgroup>

Args

message_descriptor (Descriptor): descriptor of the extended message.
number (int): Number of the extension field.

<colgroup><col width="214px"><col></colgroup>

Returns

`FieldDescriptor`

The descriptor for the extension.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

when no extension with the given number is known for the
specified message.

FindFieldByName

FindFieldByName(
    full_name
)

Loads the named field descriptor from the pool.

<colgroup><col width="214px"><col></colgroup>

Args

full_name (str): The full name of the field descriptor to load.

<colgroup><col width="214px"><col></colgroup>

Returns

`FieldDescriptor`

The field descriptor for the named field.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the field cannot be found in the pool.

FindFileByName

FindFileByName(
    file_name
)

Gets a FileDescriptor by file name.

<colgroup><col width="214px"><col></colgroup>

Args

file_name (str): The path to the file to get a descriptor for.

<colgroup><col width="214px"><col></colgroup>

Returns

`FileDescriptor`

The descriptor for the named file.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the file cannot be found in the pool.

FindFileContainingSymbol

FindFileContainingSymbol(
    symbol
)

Gets the FileDescriptor for the file containing the specified symbol.

<colgroup><col width="214px"><col></colgroup>

Args

symbol (str): The name of the symbol to search for.

<colgroup><col width="214px"><col></colgroup>

Returns

`FileDescriptor`

Descriptor for the file that contains the specified
symbol.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the file cannot be found in the pool.

FindMessageTypeByName

FindMessageTypeByName(
    full_name
)

Loads the named descriptor from the pool.

<colgroup><col width="214px"><col></colgroup>

Args

full_name (str): The full name of the descriptor to load.

<colgroup><col width="214px"><col></colgroup>

Returns

`Descriptor`

The descriptor for the named type.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the message cannot be found in the pool.

FindMethodByName

FindMethodByName(
    full_name
)

Loads the named service method descriptor from the pool.

<colgroup><col width="214px"><col></colgroup>

Args

full_name (str): The full name of the method descriptor to load.

<colgroup><col width="214px"><col></colgroup>

Returns

`MethodDescriptor`

The method descriptor for the service method.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the method cannot be found in the pool.

FindOneofByName

FindOneofByName(
    full_name
)

Loads the named oneof descriptor from the pool.

<colgroup><col width="214px"><col></colgroup>

Args

full_name (str): The full name of the oneof descriptor to load.

<colgroup><col width="214px"><col></colgroup>

Returns

`OneofDescriptor`

The oneof descriptor for the named oneof.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the oneof cannot be found in the pool.

FindServiceByName

FindServiceByName(
    full_name
)

Loads the named service descriptor from the pool.

<colgroup><col width="214px"><col></colgroup>

Args

full_name (str): The full name of the service descriptor to load.

<colgroup><col width="214px"><col></colgroup>

Returns

`ServiceDescriptor`

The service descriptor for the named service.

<colgroup><col width="214px"><col></colgroup>

Raises

`KeyError`

if the service cannot be found in the pool.


text:
import React, { PropTypes as T } from 'react'
import { browserHistory } from 'react-router'
import AuthService from '../../../../utils/AuthService'

export class Logout extends React.Component {
  static contextTypes = {
    router: T.object
  }

  static propTypes = {
    location: T.object,
    auth: T.instanceOf(AuthService)
  }

  componentWillMount() {
    this.props.auth.logout()
    browserHistory.replace('/login')
  }
}

export default Logout;


text:
"""
File: test_create_watermark.py
Date: 2015/06/15 10:21:24
"""

import os
import re
import sys
import time

_NOW_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'
_COMMON_PATH = _NOW_PATH + '../../../'
sys.path.insert(0, _COMMON_PATH)

import mediaBase
import media_config
from baidubce.services.media import media_client
from baidubce.exception import BceHttpClientError
from baidubce.exception import BceServerError
from baidubce.exception import BceClientError

import nose
from nose.tools import raises

class TestCreateWatermark(mediaBase.MediaBase):
    """test create watermark"""
    def __init__(self):
        """construction """
        mediaBase.MediaBase.__init__(self)
        self.watermark_id = None
        self.key = '120X90.jpg'
        self.client = media_client.MediaClient(media_config.config)

    def setUp(self):
        """create env"""
        time.sleep(2)

    def tearDown(self):
        """clear env"""
        time.sleep(2)
        if self.watermark_id:
            success = True
            try:
                self.client.delete_watermark(self.watermark_id)
                self.watermark_id = None
            except Exception as e:
                success = False
            nose.tools.assert_true(success)

    def test_create_watermark_normal(self):
        """create watermark normal"""
        success = True
        try:
            self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                    self.key).watermark_id
        except Exception as e:
            success = False
        nose.tools.assert_true(success)

    def test_create_watermark_with_bucket_chiness_name(self):
        """create watermark with chiness name"""
        try:
            self.watermark_id = self.client.create_watermark('中文bucket',
                self.key).watermark_id
        except BceHttpClientError as e:
            if isinstance(e.last_error, BceServerError):
                assert e.last_error.message.startswith(
                        "Bucket 中文bucket doesn't exist or isn't in bj region")
            else:
                assert True == False, 'not throw bceServerError'

    def test_create_watermark_with_bucket_not_exist(self):
        """create watermark with bucket not exist"""
        try:
            self.watermark_id = self.client.create_watermark('not_exist_bucket',
                self.key).watermark_id
        except BceHttpClientError as e:
            if isinstance(e.last_error, BceServerError):
                assert e.last_error.message.startswith(
                       "Bucket not_exist_bucket doesn't exist or isn't in bj region")
            else:
                assert True == False, 'not throw bceServerError'

    def test_create_watermark_with_JPG_Picture(self):
        """create watermark with jpg picture"""
        self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                self.key).watermark_id
        nose.tools.assert_is_not_none(self.watermark_id)

    def test_create_watermark_with_BMP_Picture(self):
        """create watermark with bmp picture"""
        self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                '水印图片.bmp').watermark_id
        nose.tools.assert_is_not_none(self.watermark_id)

    def test_create_watermark_with_PNG_Picture(self):
        """create watermark with png picture"""
        self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                '/pic/水印图片.png').watermark_id
        nose.tools.assert_is_not_none(self.watermark_id)

    def test_create_watermark_with_TIF_Picture(self):
        """create watermark with tif picture"""
        self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                '水印图片.tif').watermark_id
        nose.tools.assert_is_not_none(self.watermark_id)

    def test_create_watermark_with_PBM_Picture(self):
        """create watermark with pbm picture"""
        self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                'logo2.pbm').watermark_id
        nose.tools.assert_is_not_none(self.watermark_id)

    def test_create_watermark_with_GIF_Picture(self):
        """create watermark with gif picture"""
        self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                'logo.gif').watermark_id
        nose.tools.assert_is_not_none(self.watermark_id)

    def test_create_watermark_with_not_picture(self):
        """create watermark with not picture"""
        try:
            self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                '/watermark/testpic.txt').watermark_id
        except BceHttpClientError as e:
            if isinstance(e.last_error, BceServerError):
                assert e.last_error.message.startswith('invalid watermark format, only')
            else:
                assert True == False, 'not throw bceServerError'

    def test_create_watermark_with_not_exist_picture(self):
        """create watermark with not exist picture"""
        key = '/watermark/notexistpic.jpg'
        try:
            self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                key,).watermark_id
        except BceHttpClientError as e:
            if isinstance(e.last_error, BceServerError):
                assert e.last_error.message.startswith('bos object: %s does not exist' % key)
            else:
                assert True == False, 'not throw bceServerError'

    def test_create_watermark_verticaloffsetinpixel_negative(self):
        """create watermark vertical offset in pixel negative"""
        try:
            self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                'watermark/logo.gif', vertical_offset_in_pixel=-1,
                hori_offset_in_pixel=0).watermark_id
        except BceHttpClientError as e:
            if isinstance(e.last_error, BceServerError):
                assert e.last_error.message.startswith(
                        'verticalOffsetInPixel:verticalOffsetInPixel')
            else:
                assert True == False, 'not throw bceServerError'

    def test_create_watermark_verticaloffsetinpixel_string(self):
        """create watermark vertical off set pixel is string"""
        try:
            self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                'watermark/logo.gif', vertical_offset_in_pixel='13.21',
                hori_offset_in_pixel=0).watermark_id
        except TypeError as e:
            assert e.message.startswith('arg "vertical_offset_in_pixel"= ')

    def test_create_watermark_horizontaloffsetinpixel_negative(self):
        """create watermark horizontal offset in pixel negative"""
        with nose.tools.assert_raises_regexp(BceHttpClientError,
            'horizontalOffsetInPixel:horizontalOffsetInPixel=must be greater than or equal to 0'):
            self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                'watermark/logo.gif', vertical_offset_in_pixel=0,
                hori_offset_in_pixel=-1).watermark_id

    def test_create_watermark_with_watermark_bucket_none(self):
        """create watermark with watermark bucket none"""
        with nose.tools.assert_raises_regexp(ValueError,
                'arg "bucket" should not be None'):
            self.watermark_id = self.client.create_watermark(None,
                'watermark/logo.gif').watermark_id

    def test_create_watermark_with_watermark_key_none(self):
        """create watermark with watermark key none"""
        with nose.tools.assert_raises_regexp(ValueError,
                'arg "key" should not be None'):
            self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                    None).watermark_id

    def test_create_watermark_with_watermark_bucket_empty(self):
        """create watermark with watermark bucket '' """
        with nose.tools.assert_raises_regexp(BceClientError,
                'bucket can\'t be empty string'):
            self.watermark_id = self.client.create_watermark('',
                'watermark/logo.gif').watermark_id

    def test_create_watermark_with_watermark_key_empty(self):
        """create watermark with watermark key '' """
        with nose.tools.assert_raises_regexp(BceClientError,
                'key can\'t be empty string'):
            self.watermark_id = self.client.create_watermark(self.watermarkBucket,
                '').watermark_id


text:
// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "libcef/browser/browser_host_impl.h"

#include <commdlg.h>
#include <dwmapi.h>
#include <shellapi.h>
#include <shlobj.h>
#include <wininet.h>
#include <winspool.h>

#include "libcef/browser/content_browser_client.h"
#include "libcef/browser/context.h"
#include "libcef/browser/thread_util.h"
#include "libcef/browser/window_delegate_view.h"

#include "base/files/file_util.h"
#include "base/i18n/case_conversion.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/registry.h"
#include "base/win/scoped_comptr.h"
#include "base/win/windows_version.h"
#include "content/common/cursors/webcursor.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/common/file_chooser_params.h"
#include "grit/cef_strings.h"
#include "grit/ui_strings.h"
#include "grit/ui_unscaled_resources.h"
#include "net/base/mime_util.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/win/shell.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/win/hwnd_util.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h"
#include "ui/views/widget/widget.h"
#include "ui/views/win/hwnd_message_handler_delegate.h"
#include "ui/views/win/hwnd_util.h"

#pragma comment(lib, "dwmapi.lib")

namespace {

void WriteTempFileAndView(scoped_refptr<base::RefCountedString> str) {
  CEF_REQUIRE_FILET();

  base::FilePath tmp_file;
  if (!base::CreateTemporaryFile(&tmp_file))
    return;

  // The shell command will look at the file extension to identify the correct
  // program to open.
  tmp_file = tmp_file.AddExtension(L"txt");

  const std::string& data = str->data();
  int write_ct = base::WriteFile(tmp_file, data.c_str(), data.size());
  DCHECK_EQ(static_cast<int>(data.size()), write_ct);

  ui::win::OpenFileViaShell(tmp_file);
}

// From ui/base/dialogs/select_file_dialog_win.cc.

// Get the file type description from the registry. This will be "Text Document"
// for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't
// have an entry for the file type, we return false, true if the description was
// found. 'file_ext' must be in form ".txt".
static bool GetRegistryDescriptionFromExtension(const std::wstring& file_ext,
                                                std::wstring* reg_description) {
  DCHECK(reg_description);
  base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, file_ext.c_str(), KEY_READ);
  std::wstring reg_app;
  if (reg_ext.ReadValue(NULL, &reg_app) == ERROR_SUCCESS && !reg_app.empty()) {
    base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ);
    if (reg_link.ReadValue(NULL, reg_description) == ERROR_SUCCESS)
      return true;
  }
  return false;
}

// Set up a filter for a Save/Open dialog, which will consist of |file_ext| file
// extensions (internally separated by semicolons), |ext_desc| as the text
// descriptions of the |file_ext| types (optional), and (optionally) the default
// 'All Files' view. The purpose of the filter is to show only files of a
// particular type in a Windows Save/Open dialog box. The resulting filter is
// returned. The filters created here are:
//   1. only files that have 'file_ext' as their extension
//   2. all files (only added if 'include_all_files' is true)
// Example:
//   file_ext: { "*.txt", "*.htm;*.html" }
//   ext_desc: { "Text Document" }
//   returned: "Text Document\0*.txt\0HTML Document\0*.htm;*.html\0"
//             "All Files\0*.*\0\0" (in one big string)
// If a description is not provided for a file extension, it will be retrieved
// from the registry. If the file extension does not exist in the registry, it
// will be omitted from the filter, as it is likely a bogus extension.
std::wstring FormatFilterForExtensions(
    const std::vector<std::wstring>& file_ext,
    const std::vector<std::wstring>& ext_desc,
    bool include_all_files) {
  const std::wstring all_ext = L"*.*";
  const std::wstring all_desc =
      l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES) +
      L" (" + all_ext + L")";

  DCHECK(file_ext.size() >= ext_desc.size());

  if (file_ext.empty())
    include_all_files = true;

  std::wstring result;

  for (size_t i = 0; i < file_ext.size(); ++i) {
    std::wstring ext = file_ext[i];
    std::wstring desc;
    if (i < ext_desc.size())
      desc = ext_desc[i];

    if (ext.empty()) {
      // Force something reasonable to appear in the dialog box if there is no
      // extension provided.
      include_all_files = true;
      continue;
    }

    if (desc.empty()) {
      DCHECK(ext.find(L'.') != std::wstring::npos);
      std::wstring first_extension = ext.substr(ext.find(L'.'));
      size_t first_separator_index = first_extension.find(L';');
      if (first_separator_index != std::wstring::npos)
        first_extension = first_extension.substr(0, first_separator_index);

      // Find the extension name without the preceeding '.' character.
      std::wstring ext_name = first_extension;
      size_t ext_index = ext_name.find_first_not_of(L'.');
      if (ext_index != std::wstring::npos)
        ext_name = ext_name.substr(ext_index);

      if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) {
        // The extension doesn't exist in the registry.
        include_all_files = true;
      }
    }

    if (!desc.empty())
      desc += L" (" + ext + L")";
    else
      desc = ext;

    result.append(desc.c_str(), desc.size() + 1);  // Append NULL too.
    result.append(ext.c_str(), ext.size() + 1);
  }

  if (include_all_files) {
    result.append(all_desc.c_str(), all_desc.size() + 1);
    result.append(all_ext.c_str(), all_ext.size() + 1);
  }

  result.append(1, '\0');  // Double NULL required.
  return result;
}

std::wstring GetDescriptionFromMimeType(const std::string& mime_type) {
  // Check for wild card mime types and return an appropriate description.
  static const struct {
    const char* mime_type;
    int string_id;
  } kWildCardMimeTypes[] = {
    { "audio", IDS_APP_AUDIO_FILES },
    { "image", IDS_APP_IMAGE_FILES },
    { "text", IDS_APP_TEXT_FILES },
    { "video", IDS_APP_VIDEO_FILES },
  };

  for (size_t i = 0; i < arraysize(kWildCardMimeTypes); ++i) {
    if (mime_type == std::string(kWildCardMimeTypes[i].mime_type) + "/*")
      return l10n_util::GetStringUTF16(kWildCardMimeTypes[i].string_id);
  }

  return std::wstring();
}

std::wstring GetFilterString(
    const std::vector<base::string16>& accept_filters) {
  std::vector<std::wstring> extensions;
  std::vector<std::wstring> descriptions;

  for (size_t i = 0; i < accept_filters.size(); ++i) {
    const base::string16& filter = accept_filters[i];
    if (filter.empty())
      continue;

    size_t sep_index = filter.find('|');
    if (sep_index != base::string16::npos) {
      // Treat as a filter of the form "Filter Name|.ext1;.ext2;.ext3".
      const base::string16& desc = filter.substr(0, sep_index);
      const std::vector<base::string16>& ext =
          base::SplitString(filter.substr(sep_index + 1),
                            base::ASCIIToUTF16(";"),
                            base::TRIM_WHITESPACE,
                            base::SPLIT_WANT_NONEMPTY);
      std::wstring ext_str;
      for (size_t x = 0; x < ext.size(); ++x) {
        const base::string16& file_ext = ext[x];
        if (!file_ext.empty() && file_ext[0] == '.') {
          if (!ext_str.empty())
            ext_str += L";";
          ext_str += L"*" + file_ext;
        }
      }
      if (!ext_str.empty()) {
        extensions.push_back(ext_str);
        descriptions.push_back(desc);
      }
    } else if (filter[0] == L'.') {
      // Treat as an extension beginning with the '.' character.
      extensions.push_back(L"*" + filter);
      descriptions.push_back(std::wstring());
    } else {
      // Otherwise convert mime type to one or more extensions.
      const std::string& ascii = base::UTF16ToASCII(filter);
      std::vector<base::FilePath::StringType> ext;
      std::wstring ext_str;
      net::GetExtensionsForMimeType(ascii, &ext);
      if (!ext.empty()) {
        for (size_t x = 0; x < ext.size(); ++x) {
          if (x != 0)
            ext_str += L";";
          ext_str += L"*." + ext[x];
        }
        extensions.push_back(ext_str);
        descriptions.push_back(GetDescriptionFromMimeType(ascii));
      }
    }
  }

  return FormatFilterForExtensions(extensions, descriptions, true);
}

// from chrome/browser/views/shell_dialogs_win.cc

bool RunOpenFileDialog(const CefBrowserHostImpl::FileChooserParams& params,
                       HWND owner,
                       int* filter_index,
                       base::FilePath* path) {
  OPENFILENAME ofn;

  // We must do this otherwise the ofn's FlagsEx may be initialized to random
  // junk in release builds which can cause the Places Bar not to show up!
  ZeroMemory(&ofn, sizeof(ofn));
  ofn.lStructSize = sizeof(ofn);
  ofn.hwndOwner = owner;

  wchar_t filename[MAX_PATH] = {0};

  ofn.lpstrFile = filename;
  ofn.nMaxFile = MAX_PATH;

  std::wstring directory;
  if (!params.default_file_name.empty()) {
    if (params.default_file_name.EndsWithSeparator()) {
      // The value is only a directory.
      directory = params.default_file_name.value();
    } else {
      // The value is a file name and possibly a directory.
      base::wcslcpy(filename, params.default_file_name.value().c_str(),
          arraysize(filename));
      directory = params.default_file_name.DirName().value();
    }
  }
  if (!directory.empty())
    ofn.lpstrInitialDir = directory.c_str();

  std::wstring title;
  if (!params.title.empty())
    title = params.title;
  else
    title = l10n_util::GetStringUTF16(IDS_OPEN_FILE_DIALOG_TITLE);
  if (!title.empty())
    ofn.lpstrTitle = title.c_str();

  // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
  // without having to close Chrome first.
  ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER |
              OFN_ENABLESIZING;
  if (params.hidereadonly)
    ofn.Flags |= OFN_HIDEREADONLY;

  const std::wstring& filter = GetFilterString(params.accept_types);
  if (!filter.empty()) {
    ofn.lpstrFilter = filter.c_str();
    // Indices into |lpstrFilter| start at 1.
    ofn.nFilterIndex = *filter_index + 1;
  }

  bool success = !!GetOpenFileName(&ofn);
  if (success) {
    *filter_index = ofn.nFilterIndex == 0 ? 0 : ofn.nFilterIndex - 1;
    *path = base::FilePath(filename);
  }
  return success;
}

bool RunOpenMultiFileDialog(const CefBrowserHostImpl::FileChooserParams& params,
                            HWND owner,
                            int* filter_index,
                            std::vector<base::FilePath>* paths) {
  OPENFILENAME ofn;

  // We must do this otherwise the ofn's FlagsEx may be initialized to random
  // junk in release builds which can cause the Places Bar not to show up!
  ZeroMemory(&ofn, sizeof(ofn));
  ofn.lStructSize = sizeof(ofn);
  ofn.hwndOwner = owner;

  scoped_ptr<wchar_t[]> filename(new wchar_t[UNICODE_STRING_MAX_CHARS]);
  filename[0] = 0;

  ofn.lpstrFile = filename.get();
  ofn.nMaxFile = UNICODE_STRING_MAX_CHARS;

  std::wstring directory;
  if (!params.default_file_name.empty()) {
    if (params.default_file_name.EndsWithSeparator()) {
      // The value is only a directory.
      directory = params.default_file_name.value();
    } else {
      // The value is a file name and possibly a directory.
      directory = params.default_file_name.DirName().value();
    }
  }
  if (!directory.empty())
    ofn.lpstrInitialDir = directory.c_str();

  std::wstring title;
  if (!params.title.empty())
    title = params.title;
  else
    title = l10n_util::GetStringUTF16(IDS_OPEN_FILES_DIALOG_TITLE);
  if (!title.empty())
    ofn.lpstrTitle = title.c_str();

  // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
  // without having to close Chrome first.
  ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER |
              OFN_ALLOWMULTISELECT | OFN_ENABLESIZING;
  if (params.hidereadonly)
    ofn.Flags |= OFN_HIDEREADONLY;

  const std::wstring& filter = GetFilterString(params.accept_types);
  if (!filter.empty()) {
    ofn.lpstrFilter = filter.c_str();
    // Indices into |lpstrFilter| start at 1.
    ofn.nFilterIndex = *filter_index + 1;
  }

  bool success = !!GetOpenFileName(&ofn);

  if (success) {
    std::vector<base::FilePath> files;
    const wchar_t* selection = ofn.lpstrFile;
    while (*selection) {  // Empty string indicates end of list.
      files.push_back(base::FilePath(selection));
      // Skip over filename and null-terminator.
      selection += files.back().value().length() + 1;
    }
    if (files.empty()) {
      success = false;
    } else if (files.size() == 1) {
      // When there is one file, it contains the path and filename.
      paths->swap(files);
    } else {
      // Otherwise, the first string is the path, and the remainder are
      // filenames.
      std::vector<base::FilePath>::iterator path = files.begin();
      for (std::vector<base::FilePath>::iterator file = path + 1;
           file != files.end(); ++file) {
        paths->push_back(path->Append(*file));
      }
    }
  }

  if (success)
    *filter_index = ofn.nFilterIndex == 0 ? 0 : ofn.nFilterIndex - 1;

  return success;
}

// The callback function for when the select folder dialog is opened.
int CALLBACK BrowseCallbackProc(HWND window,
                                UINT message,
                                LPARAM parameter,
                                LPARAM data)
{
  if (message == BFFM_INITIALIZED) {
    // WParam is TRUE since passing a path.
    // data lParam member of the BROWSEINFO structure.
    SendMessage(window, BFFM_SETSELECTION, TRUE, (LPARAM)data);
  }
  return 0;
}

bool RunOpenFolderDialog(const CefBrowserHostImpl::FileChooserParams& params,
                         HWND owner,
                         base::FilePath* path) {
  wchar_t dir_buffer[MAX_PATH + 1] = {0};

  bool result = false;
  BROWSEINFO browse_info = {0};
  browse_info.hwndOwner = owner;
  browse_info.pszDisplayName = dir_buffer;
  browse_info.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS;

  std::wstring title;
  if (!params.title.empty())
    title = params.title;
  else
    title = l10n_util::GetStringUTF16(IDS_SELECT_FOLDER_DIALOG_TITLE);
  if (!title.empty())
    browse_info.lpszTitle = title.c_str();

  const std::wstring& file_path = params.default_file_name.value();
  if (!file_path.empty()) {
    // Highlight the current value.
    browse_info.lParam = (LPARAM)file_path.c_str();
    browse_info.lpfn = &BrowseCallbackProc;
  }

  LPITEMIDLIST list = SHBrowseForFolder(&browse_info);
  if (list) {
    STRRET out_dir_buffer;
    ZeroMemory(&out_dir_buffer, sizeof(out_dir_buffer));
    out_dir_buffer.uType = STRRET_WSTR;
    base::win::ScopedComPtr<IShellFolder> shell_folder;
    if (SHGetDesktopFolder(shell_folder.Receive()) == NOERROR) {
      HRESULT hr = shell_folder->GetDisplayNameOf(list, SHGDN_FORPARSING,
                                                  &out_dir_buffer);
      if (SUCCEEDED(hr) && out_dir_buffer.uType == STRRET_WSTR) {
        *path = base::FilePath(out_dir_buffer.pOleStr);
        CoTaskMemFree(out_dir_buffer.pOleStr);
        result = true;
      } else {
        // Use old way if we don't get what we want.
        wchar_t old_out_dir_buffer[MAX_PATH + 1];
        if (SHGetPathFromIDList(list, old_out_dir_buffer)) {
          *path = base::FilePath(old_out_dir_buffer);
          result = true;
        }
      }
    }
    CoTaskMemFree(list);
  }

  return result;
}

bool RunSaveFileDialog(const CefBrowserHostImpl::FileChooserParams& params,
                       HWND owner,
                       int* filter_index,
                       base::FilePath* path) {
  OPENFILENAME ofn;

  // We must do this otherwise the ofn's FlagsEx may be initialized to random
  // junk in release builds which can cause the Places Bar not to show up!
  ZeroMemory(&ofn, sizeof(ofn));
  ofn.lStructSize = sizeof(ofn);
  ofn.hwndOwner = owner;

  wchar_t filename[MAX_PATH] = {0};

  ofn.lpstrFile = filename;
  ofn.nMaxFile = MAX_PATH;

  std::wstring directory;
  if (!params.default_file_name.empty()) {
    if (params.default_file_name.EndsWithSeparator()) {
      // The value is only a directory.
      directory = params.default_file_name.value();
    } else {
      // The value is a file name and possibly a directory.
      base::wcslcpy(filename, params.default_file_name.value().c_str(),
          arraysize(filename));
      directory = params.default_file_name.DirName().value();
    }
  }
  if (!directory.empty())
    ofn.lpstrInitialDir = directory.c_str();

  std::wstring title;
  if (!params.title.empty())
    title = params.title;
  else
    title = l10n_util::GetStringUTF16(IDS_SAVE_AS_DIALOG_TITLE);
  if (!title.empty())
    ofn.lpstrTitle = title.c_str();

  // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory
  // without having to close Chrome first.
  ofn.Flags = OFN_EXPLORER | OFN_ENABLESIZING | OFN_NOCHANGEDIR |
              OFN_PATHMUSTEXIST;
  if (params.hidereadonly)
    ofn.Flags |= OFN_HIDEREADONLY;
  if (params.overwriteprompt)
    ofn.Flags |= OFN_OVERWRITEPROMPT;

  const std::wstring& filter = GetFilterString(params.accept_types);
  if (!filter.empty()) {
    ofn.lpstrFilter = filter.c_str();
    // Indices into |lpstrFilter| start at 1.
    ofn.nFilterIndex = *filter_index + 1;
    // If a filter is specified and the default file name is changed then append
    // a file extension to the new name.
    ofn.lpstrDefExt = L"";
  }

  bool success = !!GetSaveFileName(&ofn);
  if (success) {
    *filter_index = ofn.nFilterIndex == 0 ? 0 : ofn.nFilterIndex - 1;
    *path = base::FilePath(filename);
  }
  return success;
}

// According to Mozilla in uriloader/exthandler/win/nsOSHelperAppService.cpp:
// "Some versions of windows (Win2k before SP3, Win XP before SP1) crash in
// ShellExecute on long URLs (bug 161357 on bugzilla.mozilla.org). IE 5 and 6
// support URLS of 2083 chars in length, 2K is safe."
const int kMaxAddressLengthChars = 2048;

bool HasExternalHandler(const std::string& scheme) {
  base::win::RegKey key;
  const std::wstring registry_path =
      base::ASCIIToUTF16(scheme + "\\shell\\open\\command");
  key.Open(HKEY_CLASSES_ROOT, registry_path.c_str(), KEY_READ);
  if (key.Valid()) {
    DWORD size = 0;
    key.ReadValue(NULL, NULL, &size, NULL);
    if (size > 2) {
       // ShellExecute crashes the process when the command is empty.
       // We check for "2" because it always returns the trailing NULL.
       return true;
    }
  }

  return false;
}

WORD KeyStatesToWord() {
  static const USHORT kHighBitMaskShort = 0x8000;
  WORD result = 0;

  if (GetKeyState(VK_CONTROL) & kHighBitMaskShort)
    result |= MK_CONTROL;
  if (GetKeyState(VK_SHIFT) & kHighBitMaskShort)
    result |= MK_SHIFT;
  if (GetKeyState(VK_LBUTTON) & kHighBitMaskShort)
    result |= MK_LBUTTON;
  if (GetKeyState(VK_MBUTTON) & kHighBitMaskShort)
    result |= MK_MBUTTON;
  if (GetKeyState(VK_RBUTTON) & kHighBitMaskShort)
    result |= MK_RBUTTON;
  return result;
}

// From content/common/cursors/webcursor_win.cc.

using blink::WebCursorInfo;

LPCWSTR ToCursorID(WebCursorInfo::Type type) {
  switch (type) {
    case WebCursorInfo::TypePointer:
      return IDC_ARROW;
    case WebCursorInfo::TypeCross:
      return IDC_CROSS;
    case WebCursorInfo::TypeHand:
      return IDC_HAND;
    case WebCursorInfo::TypeIBeam:
      return IDC_IBEAM;
    case WebCursorInfo::TypeWait:
      return IDC_WAIT;
    case WebCursorInfo::TypeHelp:
      return IDC_HELP;
    case WebCursorInfo::TypeEastResize:
      return IDC_SIZEWE;
    case WebCursorInfo::TypeNorthResize:
      return IDC_SIZENS;
    case WebCursorInfo::TypeNorthEastResize:
      return IDC_SIZENESW;
    case WebCursorInfo::TypeNorthWestResize:
      return IDC_SIZENWSE;
    case WebCursorInfo::TypeSouthResize:
      return IDC_SIZENS;
    case WebCursorInfo::TypeSouthEastResize:
      return IDC_SIZENWSE;
    case WebCursorInfo::TypeSouthWestResize:
      return IDC_SIZENESW;
    case WebCursorInfo::TypeWestResize:
      return IDC_SIZEWE;
    case WebCursorInfo::TypeNorthSouthResize:
      return IDC_SIZENS;
    case WebCursorInfo::TypeEastWestResize:
      return IDC_SIZEWE;
    case WebCursorInfo::TypeNorthEastSouthWestResize:
      return IDC_SIZENESW;
    case WebCursorInfo::TypeNorthWestSouthEastResize:
      return IDC_SIZENWSE;
    case WebCursorInfo::TypeColumnResize:
      return MAKEINTRESOURCE(IDC_COLRESIZE);
    case WebCursorInfo::TypeRowResize:
      return MAKEINTRESOURCE(IDC_ROWRESIZE);
    case WebCursorInfo::TypeMiddlePanning:
      return MAKEINTRESOURCE(IDC_PAN_MIDDLE);
    case WebCursorInfo::TypeEastPanning:
      return MAKEINTRESOURCE(IDC_PAN_EAST);
    case WebCursorInfo::TypeNorthPanning:
      return MAKEINTRESOURCE(IDC_PAN_NORTH);
    case WebCursorInfo::TypeNorthEastPanning:
      return MAKEINTRESOURCE(IDC_PAN_NORTH_EAST);
    case WebCursorInfo::TypeNorthWestPanning:
      return MAKEINTRESOURCE(IDC_PAN_NORTH_WEST);
    case WebCursorInfo::TypeSouthPanning:
      return MAKEINTRESOURCE(IDC_PAN_SOUTH);
    case WebCursorInfo::TypeSouthEastPanning:
      return MAKEINTRESOURCE(IDC_PAN_SOUTH_EAST);
    case WebCursorInfo::TypeSouthWestPanning:
      return MAKEINTRESOURCE(IDC_PAN_SOUTH_WEST);
    case WebCursorInfo::TypeWestPanning:
      return MAKEINTRESOURCE(IDC_PAN_WEST);
    case WebCursorInfo::TypeMove:
      return IDC_SIZEALL;
    case WebCursorInfo::TypeVerticalText:
      return MAKEINTRESOURCE(IDC_VERTICALTEXT);
    case WebCursorInfo::TypeCell:
      return MAKEINTRESOURCE(IDC_CELL);
    case WebCursorInfo::TypeContextMenu:
      return IDC_ARROW;
    case WebCursorInfo::TypeAlias:
      return MAKEINTRESOURCE(IDC_ALIAS);
    case WebCursorInfo::TypeProgress:
      return IDC_APPSTARTING;
    case WebCursorInfo::TypeNoDrop:
      return IDC_NO;
    case WebCursorInfo::TypeCopy:
      return MAKEINTRESOURCE(IDC_COPYCUR);
    case WebCursorInfo::TypeNone:
      return MAKEINTRESOURCE(IDC_CURSOR_NONE);
    case WebCursorInfo::TypeNotAllowed:
      return IDC_NO;
    case WebCursorInfo::TypeZoomIn:
      return MAKEINTRESOURCE(IDC_ZOOMIN);
    case WebCursorInfo::TypeZoomOut:
      return MAKEINTRESOURCE(IDC_ZOOMOUT);
    case WebCursorInfo::TypeGrab:
      return MAKEINTRESOURCE(IDC_HAND_GRAB);
    case WebCursorInfo::TypeGrabbing:
      return MAKEINTRESOURCE(IDC_HAND_GRABBING);
  }
  NOTREACHED();
  return NULL;
}

bool IsSystemCursorID(LPCWSTR cursor_id) {
  return cursor_id >= IDC_ARROW;  // See WinUser.h
}

}  // namespace

// static
void CefBrowserHostImpl::RegisterWindowClass() {
  // Register the window class
  WNDCLASSEX wcex = {
    /* cbSize = */ sizeof(WNDCLASSEX),
    /* style = */ CS_HREDRAW | CS_VREDRAW,
    /* lpfnWndProc = */ CefBrowserHostImpl::WndProc,
    /* cbClsExtra = */ 0,
    /* cbWndExtra = */ 0,
    /* hInstance = */ ::GetModuleHandle(NULL),
    /* hIcon = */ NULL,
    /* hCursor = */ LoadCursor(NULL, IDC_ARROW),
    /* hbrBackground = */ 0,
    /* lpszMenuName = */ NULL,
    /* lpszClassName = */ CefBrowserHostImpl::GetWndClass(),
    /* hIconSm = */ NULL,
  };
  RegisterClassEx(&wcex);
}

// static
LPCTSTR CefBrowserHostImpl::GetWndClass() {
  return L"CefBrowserWindow";
}

// static
LRESULT CALLBACK CefBrowserHostImpl::WndProc(HWND hwnd, UINT message,
                                             WPARAM wParam, LPARAM lParam) {
  CefBrowserHostImpl* browser =
      static_cast<CefBrowserHostImpl*>(gfx::GetWindowUserData(hwnd));

  switch (message) {
  case WM_CLOSE:
    // Protect against multiple requests to close while the close is pending.
    if (browser && browser->destruction_state() <= DESTRUCTION_STATE_PENDING) {
      if (browser->destruction_state() == DESTRUCTION_STATE_NONE) {
        // Request that the browser close.
        browser->CloseBrowser(false);
      }

      // Cancel the close.
      return 0;
    }

    // Allow the close.
    break;

  case WM_DESTROY:
    if (browser) {
      // Clear the user data pointer.
      gfx::SetWindowUserData(hwnd, NULL);

      // Force the browser to be destroyed and release the reference added in
      // PlatformCreateWindow().
      browser->WindowDestroyed();
    }
    return 0;

  case WM_SIZE:
    if (browser && browser->window_widget_) {
      // Pass window resize events to the HWND for the DesktopNativeWidgetAura
      // root window. Passing size 0x0 (wParam == SIZE_MINIMIZED, for example)
      // will cause the widget to be hidden which reduces resource usage.
      RECT rc;
      GetClientRect(hwnd, &rc);
      SetWindowPos(HWNDForWidget(browser->window_widget_), NULL,
            rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,
            SWP_NOZORDER);
    }
    return 0;

  case WM_MOVING:
  case WM_MOVE:
    if (browser)
      browser->NotifyMoveOrResizeStarted();
    return 0;

  case WM_SETFOCUS:
    if (browser)
      browser->SetFocus(true);
    return 0;

  case WM_ERASEBKGND:
    return 0;
  }

  return DefWindowProc(hwnd, message, wParam, lParam);
}

ui::PlatformCursor CefBrowserHostImpl::GetPlatformCursor(
    blink::WebCursorInfo::Type type) {
  HMODULE module_handle = NULL;
  const wchar_t* cursor_id = ToCursorID(type);
  if (!IsSystemCursorID(cursor_id)) {
    module_handle = ::GetModuleHandle(
        CefContentBrowserClient::Get()->GetResourceDllName());
    if (!module_handle)
      module_handle = ::GetModuleHandle(NULL);
  }

  return LoadCursor(module_handle, cursor_id);
}

bool CefBrowserHostImpl::PlatformCreateWindow() {
  std::wstring windowName(CefString(&window_info_.window_name));

  // Create the new browser window.
  window_info_.window = CreateWindowEx(window_info_.ex_style,
      GetWndClass(), windowName.c_str(), window_info_.style,
      window_info_.x, window_info_.y, window_info_.width,
      window_info_.height, window_info_.parent_window, window_info_.menu,
      ::GetModuleHandle(NULL), NULL);

  // It's possible for CreateWindowEx to fail if the parent window was
  // destroyed between the call to CreateBrowser and the above one.
  DCHECK(window_info_.window != NULL);
  if (!window_info_.window)
    return false;

  // Set window user data to this object for future reference from the window
  // procedure.
  gfx::SetWindowUserData(window_info_.window, this);

  // Add a reference that will be released in the WM_DESTROY handler.
  AddRef();

  RECT cr;
  GetClientRect(window_info_.window, &cr);

  DCHECK(!window_widget_);

  SkColor background_color = SK_ColorWHITE;
  const CefSettings& settings = CefContext::Get()->settings();
  if (CefColorGetA(settings.background_color) > 0) {
    background_color = SkColorSetRGB(
        CefColorGetR(settings.background_color),
        CefColorGetG(settings.background_color),
        CefColorGetB(settings.background_color));
  }

  // Adjust for potential display scaling.
  gfx::Point point = gfx::Point(cr.right, cr.bottom);
  float scale = gfx::Screen::GetNativeScreen()->
      GetDisplayNearestPoint(point).device_scale_factor();
  point = gfx::ToFlooredPoint(gfx::ScalePoint(point, 1.0f / scale));

  CefWindowDelegateView* delegate_view =
      new CefWindowDelegateView(background_color);
  delegate_view->Init(window_info_.window,
                      web_contents(),
                      gfx::Rect(0, 0, point.x(), point.y()));

  window_widget_ = delegate_view->GetWidget();
  window_widget_->Show();

  return true;
}

void CefBrowserHostImpl::PlatformCloseWindow() {
  if (window_info_.window != NULL) {
    HWND frameWnd = GetAncestor(window_info_.window, GA_ROOT);
    PostMessage(frameWnd, WM_CLOSE, 0, 0);
  }
}

void CefBrowserHostImpl::PlatformSizeTo(int width, int height) {
  RECT rect = {0, 0, width, height};
  DWORD style = GetWindowLong(window_info_.window, GWL_STYLE);
  DWORD ex_style = GetWindowLong(window_info_.window, GWL_EXSTYLE);
  bool has_menu = !(style & WS_CHILD) && (GetMenu(window_info_.window) != NULL);

  // The size value is for the client area. Calculate the whole window size
  // based on the current style.
  AdjustWindowRectEx(&rect, style, has_menu, ex_style);

  // Size the window.
  SetWindowPos(window_info_.window, NULL, 0, 0, rect.right,
               rect.bottom, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}

void CefBrowserHostImpl::PlatformSetFocus(bool focus) {
  if (!focus)
    return;

  if (web_contents_) {
    // Give logical focus to the RenderWidgetHostViewAura in the views
    // hierarchy. This does not change the native keyboard focus.
    web_contents_->Focus();
  }

  if (window_widget_) {
    // Give native focus to the DesktopWindowTreeHostWin associated with the
    // root window.
    //
    // The DesktopWindowTreeHostWin HandleNativeFocus/HandleNativeBlur methods
    // are called in response to WM_SETFOCUS/WM_KILLFOCUS respectively. The
    // implementation has been patched to call HandleActivationChanged which
    // results in the following behaviors:
    // 1. Update focus/activation state of the aura::Window indirectly via
    //    wm::FocusController. This allows focus-related behaviors (e.g. focus
    //    rings, flashing caret, onFocus/onBlur JS events, etc.) to work as
    //    expected (see issue #1677).
    // 2. Update focus state of the ui::InputMethod. If this does not occur
    //    then InputMethodBase::GetTextInputClient will return NULL and
    //    InputMethodWin::OnChar will fail to sent character events to the
    //    renderer (see issue #1700).
    //
    // This differs from activation in Chrome which is handled via
    // HWNDMessageHandler::PostProcessActivateMessage (Widget::Show indirectly
    // calls HWNDMessageHandler::Activate which calls ::SetForegroundWindow
    // resulting in a WM_ACTIVATE message being sent to the window). The Chrome
    // code path doesn't work for CEF because IsTopLevelWindow in
    // hwnd_message_handler.cc will return false and consequently
    // HWNDMessageHandler::PostProcessActivateMessage will not be called.
    //
    // Activation events are usually reserved for the top-level window so
    // triggering activation based on focus events may be incorrect in some
    // circumstances. Revisit this implementation if additional problems are
    // discovered.
    ::SetFocus(HWNDForWidget(window_widget_));
  }
}

CefWindowHandle CefBrowserHostImpl::PlatformGetWindowHandle() {
  return IsWindowless() ? window_info_.parent_window : window_info_.window;
}

bool CefBrowserHostImpl::PlatformViewText(const std::string& text) {
  CEF_REQUIRE_UIT();

  std::string str = text;
  scoped_refptr<base::RefCountedString> str_ref =
      base::RefCountedString::TakeString(&str);
  CEF_POST_TASK(CEF_FILET, base::Bind(WriteTempFileAndView, str_ref));
  return true;
}

void CefBrowserHostImpl::PlatformHandleKeyboardEvent(
    const content::NativeWebKeyboardEvent& event) {
  // Any unhandled keyboard/character messages are sent to DefWindowProc so that
  // shortcut keys work correctly.
  if (event.os_event) {
    const MSG& msg = event.os_event->native_event();
    DefWindowProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
  } else {
    MSG msg = {};

    msg.hwnd = PlatformGetWindowHandle();
    if (!msg.hwnd)
      return;

    switch (event.type) {
      case blink::WebInputEvent::RawKeyDown:
        msg.message = event.isSystemKey ? WM_SYSKEYDOWN : WM_KEYDOWN;
        break;
      case blink::WebInputEvent::KeyUp:
        msg.message = event.isSystemKey ? WM_SYSKEYUP : WM_KEYUP;
        break;
      case blink::WebInputEvent::Char:
        msg.message = event.isSystemKey ? WM_SYSCHAR: WM_CHAR;
        break;
      default:
        NOTREACHED();
        return;
    }

    msg.wParam = event.windowsKeyCode;

    UINT scan_code = ::MapVirtualKeyW(event.windowsKeyCode, MAPVK_VK_TO_VSC);
    msg.lParam = (scan_code << 16) |  // key scan code
                                  1;  // key repeat count
    if (event.modifiers & content::NativeWebKeyboardEvent::AltKey)
      msg.lParam |= (1 << 29);

    DefWindowProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
  }
}

void CefBrowserHostImpl::PlatformRunFileChooser(
    const FileChooserParams& params,
    RunFileChooserCallback callback) {
  int filter_index = params.selected_accept_filter;
  std::vector<base::FilePath> files;

  HWND owner = PlatformGetWindowHandle();

  if (params.mode == content::FileChooserParams::Open) {
    base::FilePath file;
    if (RunOpenFileDialog(params, owner, &filter_index, &file))
      files.push_back(file);
  } else if (params.mode == content::FileChooserParams::OpenMultiple) {
    RunOpenMultiFileDialog(params, owner, &filter_index, &files);
  } else if (params.mode == content::FileChooserParams::UploadFolder) {
    base::FilePath file;
    if (RunOpenFolderDialog(params, owner, &file))
      files.push_back(file);
  } else if (params.mode == content::FileChooserParams::Save) {
    base::FilePath file;
    if (RunSaveFileDialog(params, owner, &filter_index, &file))
      files.push_back(file);
  } else {
    NOTIMPLEMENTED();
  }

  callback.Run(filter_index, files);
}

void CefBrowserHostImpl::PlatformHandleExternalProtocol(const GURL& url) {
  if (CEF_CURRENTLY_ON_FILET()) {
    if (!HasExternalHandler(url.scheme()))
      return;

    const std::string& address = url.spec();
    if (address.length() > kMaxAddressLengthChars)
      return;

    ShellExecuteA(NULL, "open", address.c_str(), NULL, NULL, SW_SHOWNORMAL);
  } else {
    // Execute on the FILE thread.
    CEF_POST_TASK(CEF_FILET,
        base::Bind(&CefBrowserHostImpl::PlatformHandleExternalProtocol, this,
                   url));
  }
}

void CefBrowserHostImpl::PlatformTranslateKeyEvent(
    content::NativeWebKeyboardEvent& result, const CefKeyEvent& key_event) {
  result.timeStampSeconds = GetMessageTime() / 1000.0;

  result.windowsKeyCode = key_event.windows_key_code;
  result.nativeKeyCode = key_event.native_key_code;
  result.isSystemKey = key_event.is_system_key ? 1 : 0;
  switch (key_event.type) {
  case KEYEVENT_RAWKEYDOWN:
  case KEYEVENT_KEYDOWN:
    result.type = blink::WebInputEvent::RawKeyDown;
    break;
  case KEYEVENT_KEYUP:
    result.type = blink::WebInputEvent::KeyUp;
    break;
  case KEYEVENT_CHAR:
    result.type = blink::WebInputEvent::Char;
    break;
  default:
    NOTREACHED();
  }

  if (result.type == blink::WebInputEvent::Char ||
      result.type == blink::WebInputEvent::RawKeyDown) {
    result.text[0] = result.windowsKeyCode;
    result.unmodifiedText[0] = result.windowsKeyCode;
  }
  if (result.type != blink::WebInputEvent::Char)
    result.setKeyIdentifierFromWindowsKeyCode();

  result.modifiers |= TranslateModifiers(key_event.modifiers);
}

void CefBrowserHostImpl::PlatformTranslateClickEvent(
    blink::WebMouseEvent& result,
    const CefMouseEvent& mouse_event,
    CefBrowserHost::MouseButtonType type,
    bool mouseUp, int clickCount) {
  PlatformTranslateMouseEvent(result, mouse_event);

  switch (type) {
  case MBT_LEFT:
    result.type = mouseUp ? blink::WebInputEvent::MouseUp :
                            blink::WebInputEvent::MouseDown;
    result.button = blink::WebMouseEvent::ButtonLeft;
    break;
  case MBT_MIDDLE:
    result.type = mouseUp ? blink::WebInputEvent::MouseUp :
                            blink::WebInputEvent::MouseDown;
    result.button = blink::WebMouseEvent::ButtonMiddle;
    break;
  case MBT_RIGHT:
    result.type = mouseUp ? blink::WebInputEvent::MouseUp :
                            blink::WebInputEvent::MouseDown;
    result.button = blink::WebMouseEvent::ButtonRight;
    break;
  default:
    NOTREACHED();
  }

  result.clickCount = clickCount;
}

void CefBrowserHostImpl::PlatformTranslateMoveEvent(
    blink::WebMouseEvent& result,
    const CefMouseEvent& mouse_event,
    bool mouseLeave) {
  PlatformTranslateMouseEvent(result, mouse_event);

  if (!mouseLeave) {
    result.type = blink::WebInputEvent::MouseMove;
    if (mouse_event.modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON)
      result.button = blink::WebMouseEvent::ButtonLeft;
    else if (mouse_event.modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON)
      result.button = blink::WebMouseEvent::ButtonMiddle;
    else if (mouse_event.modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON)
      result.button = blink::WebMouseEvent::ButtonRight;
    else
      result.button = blink::WebMouseEvent::ButtonNone;
  } else {
    result.type = blink::WebInputEvent::MouseLeave;
    result.button = blink::WebMouseEvent::ButtonNone;
  }

  result.clickCount = 0;
}

void CefBrowserHostImpl::PlatformTranslateWheelEvent(
    blink::WebMouseWheelEvent& result,
    const CefMouseEvent& mouse_event,
    int deltaX, int deltaY) {
  PlatformTranslateMouseEvent(result, mouse_event);

  result.type = blink::WebInputEvent::MouseWheel;
  result.button = blink::WebMouseEvent::ButtonNone;

  float wheelDelta;
  bool horizontalScroll = false;

  wheelDelta = static_cast<float>(deltaY ? deltaY : deltaX);

  horizontalScroll = (deltaY == 0);

  static const ULONG defaultScrollCharsPerWheelDelta = 1;
  static const FLOAT scrollbarPixelsPerLine = 100.0f / 3.0f;
  static const ULONG defaultScrollLinesPerWheelDelta = 3;
  wheelDelta /= WHEEL_DELTA;
  float scrollDelta = wheelDelta;
  if (horizontalScroll) {
    ULONG scrollChars = defaultScrollCharsPerWheelDelta;
    SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &scrollChars, 0);
    scrollDelta *= static_cast<FLOAT>(scrollChars) * scrollbarPixelsPerLine;
  } else {
    ULONG scrollLines = defaultScrollLinesPerWheelDelta;
    SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scrollLines, 0);
    if (scrollLines == WHEEL_PAGESCROLL)
      result.scrollByPage = true;
    if (!result.scrollByPage)
      scrollDelta *= static_cast<FLOAT>(scrollLines) * scrollbarPixelsPerLine;
  }

  // Set scroll amount based on above calculations.  WebKit expects positive
  // deltaY to mean "scroll up" and positive deltaX to mean "scroll left".
  if (horizontalScroll) {
    result.deltaX = scrollDelta;
    result.wheelTicksX = wheelDelta;
  } else {
    result.deltaY = scrollDelta;
    result.wheelTicksY = wheelDelta;
  }
}

void CefBrowserHostImpl::PlatformTranslateMouseEvent(
    blink::WebMouseEvent& result,
    const CefMouseEvent& mouse_event) {
  // position
  result.x = mouse_event.x;
  result.y = mouse_event.y;
  result.windowX = result.x;
  result.windowY = result.y;
  result.globalX = result.x;
  result.globalY = result.y;

  if (IsWindowless()) {
    CefRefPtr<CefRenderHandler> handler = client_->GetRenderHandler();
    if (handler.get()) {
      handler->GetScreenPoint(this, result.x, result.y, result.globalX,
                              result.globalY);
    }
  } else {
    POINT globalPoint = { result.x, result.y };
    ClientToScreen(GetWindowHandle(), &globalPoint);
    result.globalX = globalPoint.x;
    result.globalY = globalPoint.y;
  }

  // modifiers
  result.modifiers |= TranslateModifiers(mouse_event.modifiers);

  // timestamp
  result.timeStampSeconds = GetMessageTime() / 1000.0;
}

void CefBrowserHostImpl::PlatformNotifyMoveOrResizeStarted() {
  if (IsWindowless())
    return;

  if (!window_widget_)
    return;

  // Notify DesktopWindowTreeHostWin of move events so that screen rectangle
  // information is communicated to the renderer process and popups are
  // displayed in the correct location.
  views::DesktopWindowTreeHostWin* tree_host =
      static_cast<views::DesktopWindowTreeHostWin*>(
          aura::WindowTreeHost::GetForAcceleratedWidget(
              HWNDForWidget(window_widget_)));
  DCHECK(tree_host);
  if (tree_host) {
    // Cast to HWNDMessageHandlerDelegate so we can access HandleMove().
    static_cast<views::HWNDMessageHandlerDelegate*>(tree_host)->HandleMove();
  }
}