text:
namespace ppx {

static Profiler           sPerThreadProfilers[PPX_MAX_THREAD_PROFILERS];
static std::mutex         sThreadIndexMutex;
static unsigned int       sThreadCount = 0;
thread_local unsigned int sThreadIndex = UINT32_MAX;

static unsigned int GetThreadIndex()
{
    if (sThreadIndex == UINT32_MAX) {
        std::lock_guard<std::mutex> lock(sThreadIndexMutex);
        sThreadIndex = sThreadCount;
        sThreadCount = sThreadCount + 1;
    };
    return sThreadIndex;
}

// -------------------------------------------------------------------------------------------------

ProfilerScopedEventSample::ProfilerScopedEventSample(ProfilerEventToken token)
    : mToken(token)
{
    Timer::Timestamp(&mSample.startTimestamp);
}

ProfilerScopedEventSample::~ProfilerScopedEventSample()
{
    Timer::Timestamp(&mSample.endTimestamp);

    Profiler* pProfiler = Profiler::GetProfilerForThread();
    if (IsNull(pProfiler)) {
        PPX_ASSERT_MSG(false, "profiler is null!");
    }

    pProfiler->RecordSample(mToken, mSample);
}

// -------------------------------------------------------------------------------------------------

ProfilerEvent::ProfilerEvent(ProfilerEventType type, const std::string& name, ProfileEventRecordAction recordAction, const ProfilerEventToken& token)
    : mType(type),
      mName(name),
      mAction(recordAction),
      mToken(token)
{
}

ProfilerEvent::~ProfilerEvent()
{
}

void ProfilerEvent::RecordSample(const ProfilerEventSample& sample)
{
    if (mAction == PROFILER_EVENT_RECORD_ACTION_INSERT) {
        mSamples.push_back(sample);
    }
    else if (mAction == PROFILER_EVENT_RECORD_ACTION_AVERAGE) {
        uint64_t diff = (sample.endTimestamp - sample.startTimestamp);
        mSampleCount += 1;
        mSampleTotal += diff;
        mSampleMin = (diff < mSampleMin) ? diff : mSampleMin;
        mSampleMax = (diff > mSampleMax) ? diff : mSampleMax;
    }
    else {
        PPX_ASSERT_MSG(false, "unknown event record action");
    }
}

// -------------------------------------------------------------------------------------------------
// Profiler
// -------------------------------------------------------------------------------------------------
Profiler::Profiler()
{
}

Profiler::~Profiler()
{
}

Profiler* Profiler::GetProfilerForThread()
{
    unsigned int threadIndex = GetThreadIndex();
    Profiler*    pProfiler   = nullptr;
    if (threadIndex < PPX_MAX_THREAD_PROFILERS) {
        pProfiler = &sPerThreadProfilers[threadIndex];
    }
    return pProfiler;
}

Result Profiler::RegisterEvent(ProfilerEventType type, const std::string& name, ProfileEventRecordAction recordAction, ProfilerEventToken* pToken)
{
    PPX_ASSERT_NULL_ARG(pToken);
    if (IsNull(pToken)) {
        return ppx::ERROR_UNEXPECTED_NULL_ARGUMENT;
    }

    std::lock_guard<std::mutex> lock(sThreadIndexMutex);

    ProfilerEventToken token = XXH64(name.c_str(), name.length(), 0xDEADBEEF);

    for (size_t i = 0; i < PPX_MAX_THREAD_PROFILERS; ++i) {
        Result ppxres = sPerThreadProfilers[i].RegisterEventInternal(type, name, recordAction, token);
        if (Failed(ppxres)) {
            return ppxres;
        }
    }

    *pToken = token;

    return ppx::SUCCESS;
}

Result Profiler::RegisterGrfxApiFnEvent(const std::string& name, ProfilerEventToken* pToken)
{
    Result ppxres = RegisterEvent(PROFILER_EVENT_TYPE_GRFX_API_FN, name, PROFILER_EVENT_RECORD_ACTION_AVERAGE, pToken);
    return ppxres;
}

Result Profiler::RegisterEventInternal(ProfilerEventType type, const std::string& name, ProfileEventRecordAction recordAction, ProfilerEventToken token)
{
    auto it = FindIf(
        mEvents,
        [token](const ProfilerEvent& elem) -> bool {
            bool isSame = (elem.mToken == token);
            return isSame; });
    if (it != std::end(mEvents)) {
        return ppx::ERROR_DUPLICATE_ELEMENT;
    }

    mEvents.emplace_back(type, name, recordAction, token);

    return ppx::SUCCESS;
}

void Profiler::RecordSample(const ProfilerEventToken& token, const ProfilerEventSample& sample)
{
    auto it = FindIf(
        mEvents,
        [token](const ProfilerEvent& elem) -> bool {
            bool isSame = (elem.mToken == token);
            return isSame; });
    if (it != std::end(mEvents)) {
        ProfilerEvent& event = *it;
        event.RecordSample(sample);
    }
}

} // namespace ppx


text:
package com.secrettransaction.rogagserver.entity;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;

@Entity
public class AppUserAccount {

	public static final String TYPE_USERNAME = "USERNAME";
	public static final String TYPE_FACEBOOK = "FACEBOOK";
	public static final String TYPE_GOOGLE = "GOOGLE";

	@Id
	private String id;

	@Index
	private Key<AppUser> userKey;

	@Index
	private String type;

	/*
	 * username
	 * facebook id
	 * twitter id
	 */
	@Index
	private String username;

	@Index
	private String password;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Key<AppUser> getUserKey() {
		return userKey;
	}

	public void setUserKey(Key<AppUser> userKey) {
		this.userKey = userKey;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
		updateId();
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
		updateId();
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	private void updateId() {
		this.id = String.format("%s_%s", type, username);
	}

	public Key<AppUserAccount> key() {
		return Key.create(AppUserAccount.class, id);
	}
}

redpajama_set_name: RedPajamaGithub


text:
layout: desktop
uid: hello
title: 'helloSystem'
Category: Desktop
permalink: /desktop/hello
logo: hello.png
preview: helloSystem.jpg
home_page: https://hellosystem.github.io
description: helloSystem a desktop system for creators looking for simplicity, elegance and usability.It follows the general design principles of mac from 90s.
tagline: Simplicity, elegance & usability.
image: /assets/images/preview/helloSystem.jpg

screenshots:
  - helloSystem 0.5 screenshots: "/helloSystem-.05/"

---

**helloSystem** is a desktop system targeting users whose main focus is simplicity, elegance, and usability. It follows the general design principles put forward by mac in the 90s to give a consistent user experience.

The helloSystem is not planning to have a 1:1 replica of mac desktop. But, it will follow the general design guidelines of mac to provide a familiar experience for users migrating from the mac ecosystem.

With general principles, helloSystem provides a global menu bar, and other essential and familiar components in the macintosh systems. It will also focus on minimizing the configuration options, and thus complexity. It will provide a default system that will work out of the box.

The helloSystem is not yet ready for production use. You may try and explore the development releases, as explained on [the project's website](https://hellosystem.github.io/docs/user/getting-started.html).


text:
__version_info__ = (1, 0, 0)
__version__ = '.'.join(str(i) for i in __version_info__)

import socket
import time

try:
    from django.conf import settings
except:
    # Don't require Django if only using the UDP client.
    settings = None

TALLY_SOCKET = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def archives():
    """
    Returns a QuerySet of all enabled Archives.
    """
    from .models import Archive
    return Archive.objects.filter(enabled=True)

def tally(data, value=1, timestamp=None, host=None, port=None):
    """
    Sends a metric to the specified host:port
    """
    if host is None:
        host = getattr(settings, 'TALLY_HOST', None)
    if port is None:
        port = getattr(settings, 'TALLY_PORT', 8900)
    prefix = unicode(getattr(settings, 'TALLY_PREFIX', ''))
    if not isinstance(data, (list, tuple)):
        data = [data]
    value = float(value)
    if timestamp:
        if hasattr(timestamp, 'timetuple'):
            timestamp = time.mktime(timestamp.timetuple())
        timestamp = int(timestamp)
    rows = []
    for d in data:
        row = []
        if isinstance(d, (list, tuple)):
            # First element is the metric name.
            if len(d) >= 1:
                name = unicode(d[0])
                if not name.startswith(prefix):
                    name = prefix + name
                row.append(name)
            else:
                # If we get an empty list or tuple, ignore it.
                continue
            # Second element is the value. Use the default if none specified.
            if len(d) >= 2:
                row.append(float(d[1]))
            else:
                row.append(value)
            # Third element is the timestamp. Use the default if none specified and host is None,
            # otherwise leave it off and only send the server name and value.
            if len(d) >= 3:
                row.append(int(d[2]))
            elif host is None:
                row.append(timestamp or int(time.time()))
        else:
            name = unicode(d)
            if not name.startswith(prefix):
                name = prefix + name
            row.append(name)
            row.append(value)
            # If recording directly to the database, Archive.store expects 3-tuples with a timestamp.
            # Otherwise, let the server use its local time.
            if host is None:
                row.append(timestamp or int(time.time()))
        rows.append(row)
    if host is None:
        # If no host is specified, assume the tallies should be written to all Archives locally.
        for a in archives():
            a.store(rows)
            a.trim()
    else:
        # If a host and port are specified, send the tallies in a UDP packet.
        lines = []
        for row in rows:
            lines.append(u' '.join(unicode(p) for p in row))
        TALLY_SOCKET.sendto(u'\n'.join(lines).encode('utf-8'), (host, port))


text:
import logging

from django.conf import settings
from django.contrib.auth import logout

from .mixins import JWTCookieActionMixin
from metrics import inc_logouts

logger = logging.getLogger(__name__)

class LogoutBaseAction(object):
    """Logout base action"""
    def do(self, action_context, view, *args, **kwargs):
        return action_context

class DeleteDjangoAuthSessionAction(JWTCookieActionMixin, LogoutBaseAction):
    """ Delete the Django session """

    def do(self, action_context, view, *args, **kwargs):
        """Deletes the Django session"""
        logout(action_context.request)
        return super().do(action_context, view, *args, **kwargs)

class JWTDeleteCookieAction(JWTCookieActionMixin, LogoutBaseAction):
    """ Delete the cookie on the response """

    def do(self, action_context, view, *args, **kwargs):
        """Deletes the jwt token without calculating"""

        # Get the host for the cookie
        host = self.get_host(action_context.request)

        # Delete the cookie
        action_context.response.delete_cookie(key=settings.JWT_COOKIE_NAME,
                                              domain=host)

        logger.info("Delete JWT token on {0}".format(host))
        return super().do(action_context, view, *args, **kwargs)

class LogoutMetricsAction(LogoutBaseAction):
    """ Logouts the metric """

    def do(self, action_context, view, *args, **kwargs):
        """Deletes the Django session"""
        # Only logout on final redirect
        if action_context.extra_context["final_logout"]:
            inc_logouts()
        return super().do(action_context, view, *args, **kwargs)


text:
package com.github.cloudml.zen.ml.neuralNetwork

import com.github.cloudml.zen.ml.linalg.BLAS
import com.github.cloudml.zen.ml.util.SparkUtils._
import com.github.cloudml.zen.ml.util.Utils
import org.apache.spark.annotation.Experimental
import org.apache.spark.mllib.linalg.{Vector => SV, DenseVector => SDV, Vectors}
import com.github.cloudml.zen.ml.optimization._

/**
 * Equilibrated Gradient Descent the paper:
 * RMSProp and equilibrated adaptive learning rates for non-convex optimization
 * @param epsilon
 * @param momentum
 */
@Experimental
class EquilibratedUpdater(
  val epsilon: Double,
  val gamma: Double,
  val momentum: Double) extends Updater {
  require(momentum >= 0 && momentum < 1)
  @transient private var etaSum: SDV = null
  @transient private var momentumSum: SDV = null

  protected def l2(
    weightsOld: SV,
    gradient: SV,
    stepSize: Double,
    iter: Int,
    regParam: Double): Double = {
    0D
  }

  override def compute(
    weightsOld: SV,
    gradient: SV,
    stepSize: Double,
    iter: Int,
    regParam: Double): (SV, Double) = {
    if (etaSum == null) etaSum = new SDV(new Array[Double](weightsOld.size))
    val reg = l2(weightsOld, gradient, stepSize, iter, regParam)

    val grad = toBreeze(gradient)
    val e = toBreeze(etaSum)
    for (i <- 0 until grad.length) {
      e(i) += math.pow(grad(i) * Utils.random.nextGaussian(), 2)
    }

    etaSum.synchronized {
      for (i <- 0 until grad.length) {
        grad(i) = gamma * grad(i) / (epsilon + math.sqrt(etaSum(i) / iter))
      }
    }

    if (momentum > 0) {
      if (momentumSum == null) momentumSum = new SDV(new Array[Double](weightsOld.size))
      momentumSum.synchronized {
        BLAS.axpy(momentum, momentumSum, gradient)
        BLAS.copy(gradient, momentumSum)
      }
    }

    BLAS.axpy(-stepSize, gradient, weightsOld)
    (weightsOld, reg)
  }
}


text:
	<title>Thandie Newton's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Thandie Newton's panel show appearances

Thandie Newton (born 1972-11-06[ref]) has appeared in 1 episodes between 2010-2010.  Thandie Newton on IMDB. Thandie Newton on Wikipedia.

2010

2010-12-30 / Shooting Stars


text:
'use strict';

angular.module('pamexAngularApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'ngAnimate',
  'ui.bootstrap'
])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/operator/', {
        templateUrl: 'views/operator/index.html',
        controller: 'OperatorIndexCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });


text:
/** @file
 * @defgroup flashwrite_example_main main.c
 * @{
 * @ingroup flashwrite_example
 *
 * @brief This file contains the source code for a sample application using the Flash Write Application.
 *a
 */

#include <stdbool.h>
#include <stdio.h>
#include "nrf.h"
#include "bsp.h"
#include "app_uart.h"
#include "app_error.h"
#include "nordic_common.h"

#define UART_TX_BUF_SIZE 256                                                        /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE 1                                                          /**< UART RX buffer size. */

void uart_error_handle(app_uart_evt_t * p_event)
{
    if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_communication);
    }
    else if (p_event->evt_type == APP_UART_FIFO_ERROR)
    {
        APP_ERROR_HANDLER(p_event->data.error_code);
    }
}

/** @brief Function for erasing a page in flash.
 *
 * @param page_address Address of the first word in the page to be erased.
 */
static void flash_page_erase(uint32_t * page_address)
{
    // Turn on flash erase enable and wait until the NVMC is ready:
    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Een << NVMC_CONFIG_WEN_Pos);

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }

    // Erase page:
    NRF_NVMC->ERASEPAGE = (uint32_t)page_address;

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }

    // Turn off flash erase enable and wait until the NVMC is ready:
    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }
}

/** @brief Function for filling a page in flash with a value.
 *
 * @param[in] address Address of the first word in the page to be filled.
 * @param[in] value Value to be written to flash.
 */
static void flash_word_write(uint32_t * address, uint32_t value)
{
    // Turn on flash write enable and wait until the NVMC is ready:
    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos);

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }

    *address = value;

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }

    // Turn off flash write enable and wait until the NVMC is ready:
    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }
}

/**
 * @brief Function for application main entry.
 */
int main(void)
{
    uint32_t * addr;
    uint8_t    patwr;
    uint8_t    patrd;
    uint8_t    patold;
    uint32_t   i;
    uint32_t   pg_size;
    uint32_t   pg_num;

    uint32_t err_code;
    const app_uart_comm_params_t comm_params =
      {
          RX_PIN_NUMBER,
          TX_PIN_NUMBER,
          RTS_PIN_NUMBER,
          CTS_PIN_NUMBER,
          APP_UART_FLOW_CONTROL_ENABLED,
          false,
          UART_BAUDRATE_BAUDRATE_Baud38400
      };

    APP_UART_FIFO_INIT(&comm_params,
                         UART_RX_BUF_SIZE,
                         UART_TX_BUF_SIZE,
                         uart_error_handle,
                         APP_IRQ_PRIORITY_LOW,
                         err_code);

    APP_ERROR_CHECK(err_code);

    printf("Flashwrite example\n\r");
    patold  = 0;
    pg_size = NRF_FICR->CODEPAGESIZE;
    pg_num  = NRF_FICR->CODESIZE - 1;  // Use last page in flash

    while (true)
    {
        // Start address:
        addr = (uint32_t *)(pg_size * pg_num);
        // Erase page:
        flash_page_erase(addr);
        i = 0;

        do
        {
            printf("Enter char to write to flash\n\r");

            // Read char from uart, and write it to flash:
            do
            {
               err_code = app_uart_get(&patwr);
            }
            while(err_code == NRF_ERROR_NOT_FOUND);

            if (patold != patwr)
            {
                patold = patwr;
                flash_word_write(addr, (uint32_t)patwr);
                ++addr;
                i += 4;
                printf("'%c' was write to flash\n\r", patwr);
            }
            // Read from flash the last written data and send it back:
            patrd = (uint8_t)*(addr - 1);
            printf("'%c' was read from flash\n\r\n\r", patrd);
        }
        while (i < pg_size);
    }
}

/** @} */


text:
import React from 'react'
import DuckImage from '../assets/Duck.jpg'
import classes from './HomeView.scss'
import Search from 'components/Search'

const stevenImage = 'http://stevensegallery.com/500/360'

export const HomeView = () => (

You have a story. It deserves to be told.

      <Search />

)

export default HomeView


text:
package com.cmcm.greendamexplorer.core.engine.service.delete;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.cmcm.greendamexplorer.utils.FileUtils;

import android.os.RemoteException;

public class DeleteEngine extends IDeleteFiles.Stub {

    private List<String> mDeleteFiles = null;
    private IDeleteFilesCallback mCallback = null;
    private DeleteThread mThread = null;
    private long mAllDeleteFileSize = 0;
    private long mHasDeleteSize = 0;
    private int mProgress = 0;// 进度条
    private int mLastProgress = mProgress;

    private Object mLockObj = new Object();
    private boolean mIsRunning = true;
    private boolean mIsWait = false;

    @Override
    public void start(List<String> files) throws RemoteException {
        mDeleteFiles = files;
        mThread = new DeleteThread();
        if (mCallback != null) {
            init();
            mCallback.onStart();
        }
        if (!mThread.isAlive()) {
            mThread.start();
        }
    }

    private void init() {
        mIsRunning = true;
        mIsWait = false;
        mProgress = 0;
        mHasDeleteSize = 0;
        mAllDeleteFileSize = 0;
        mLastProgress = 0;
    }

    @Override
    public void cancel() throws RemoteException {
        mIsRunning = false;
        synchronized (mLockObj) {
            mLockObj.notify();
        }

        if (mCallback != null) {
            mCallback.onCancel(mHasDeleteSize);
        }
    }

    // 继续
    @Override
    public void resume() throws RemoteException {
        if (mIsRunning == true) {
            mIsWait = false;
            synchronized (mLockObj) {
                mLockObj.notify();
            }
            if (mCallback != null) {
                mCallback.onResume();
            }
        }
    }

    @Override
    public void pause() throws RemoteException {
        mIsWait = true;
    }

    @Override
    public void registerCallback(IDeleteFilesCallback callback) throws RemoteException {
        mCallback = callback;
    }

    @Override
    public void unregisterCallback(IDeleteFilesCallback callback) throws RemoteException {
        mCallback = null;
    }

    class DeleteThread extends Thread {
        @Override
        public void run() {

            if (mCallback != null) {
                try {
                    mCallback.postUpdate("正在统计中....", mAllDeleteFileSize, mHasDeleteSize, 2);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            mAllDeleteFileSize = FileUtils.getFileSize(mDeleteFiles);// 获取文件的总大小
            deleteFiles();

            if (mCallback != null) {
                try {
                    mCallback.onFinish(mHasDeleteSize);// 删除完成通知
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        private void deleteFiles() {
            for (int i = 0; i < mDeleteFiles.size(); i++) {

                if (!mIsRunning) {
                    break;
                }

                while (mIsWait) {
                    System.out.println("--->等待中");
                    synchronized (mLockObj) {
                        try {
                            mLockObj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                File file = new File(mDeleteFiles.get(i));
                if (file.exists() && file.canWrite()) {
                    if (file.isFile()) {// 是文件直接删除
                        updateToProgress(file);
                        file.delete();
                    } else if (file.isDirectory()) {
                        // 清空文件夹下的文件
                        clearFolder(file);
                        // 删除文件夹
                        file.delete();
                    }
                }
            }
        }

        // 更新到进度
        private void updateToProgress(File file) {
            mHasDeleteSize += file.length();
            mLastProgress = mProgress;
            if (mAllDeleteFileSize != 0) {
                mProgress = (int) (mHasDeleteSize * 100 / mAllDeleteFileSize);
            } else {
                mProgress = 100;
            }

            if (mProgress > mLastProgress) {
                if (mCallback != null) {
                    try {
                        mCallback.postUpdate(file.getCanonicalPath(), mAllDeleteFileSize, mHasDeleteSize, mProgress);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        private void clearFolder(File folder) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {

                    if (!mIsRunning) {
                        break;
                    }

                    while (mIsWait) {
                        System.out.println("--->等待中");
                        synchronized (mLockObj) {
                            try {
                                mLockObj.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    if (file.isFile()) {
                        updateToProgress(file);
                        file.delete();
                    } else if (file.isDirectory()) {

                        clearFolder(file);
                        file.delete();
                    }
                }
            }
        }

    }

}


text:
<?php

namespace Google\Service\Contentwarehouse;

class AssistantApiCarAssistantCapabilities extends \Google\Model
{
  /**
   * @var bool
   */
  public $shouldPuntMultiAssistantMode;

  /**
   * @param bool
   */
  public function setShouldPuntMultiAssistantMode($shouldPuntMultiAssistantMode)
  {
    $this->shouldPuntMultiAssistantMode = $shouldPuntMultiAssistantMode;
  }
  /**
   * @return bool
   */
  public function getShouldPuntMultiAssistantMode()
  {
    return $this->shouldPuntMultiAssistantMode;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AssistantApiCarAssistantCapabilities::class, 'Google_Service_Contentwarehouse_AssistantApiCarAssistantCapabilities');


text:
<!DOCTYPE html>

<title>Page Title</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />

Page Title

Page content goes here.

		<form action="<?php echo base_url() ;?>index.php/welcome/signIn">
			<button type="submit" value="Continue">Continue</button>
		</form>

Page Footer


text:
package com.opengamma.util.rest;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

/**
 * A JAX-RS exception mapper that ensures that the internal {@code WebApplicationException}
 * is not trapped by our mappers.
 */
@Provider
public class WebApplicationExceptionMapper
    extends AbstractExceptionMapper<WebApplicationException> {

  /**
   * Creates the mapper.
   */
  public WebApplicationExceptionMapper() {
  }

  //-------------------------------------------------------------------------
  @Override
  protected String buildHtmlErrorPage(WebApplicationException exception) {
    Map<String, String> data = new HashMap<>();
    int status = exception.getResponse().getStatus();
    switch (status) {
      case 400:  // bad request
        buildOutputMessage(exception, data);
        return createHtmlErrorPage("error-badrequest.html", data);
      case 404:  // not found
        return createHtmlErrorPage("error-notfound.html", data);
      case 503:  // service unavailable
        buildOutputMessage(exception, data);
        return createHtmlErrorPage("error-unavailable.html", data);
      default:
        buildOutputMessage(exception, data);
        return createHtmlErrorPage("error-servererror.html", data);
    }
  }

  @Override
  protected Response doHtmlResponse(WebApplicationException exception, String htmlPage) {
    return Response.status(exception.getResponse().getStatus()).entity(htmlPage).build();
  }

  @Override
  protected Response doRestfulResponse(WebApplicationException exception) {
    return exception.getResponse();
  }

}


text:
package db

const BLANK = ""

const (
	DELETE_OPERATION = 1
	INSERT_OPERATION = 2
	UPDATE_OPERATION = 3

	SentCollection       = "sent_notifications"
	StatsCollection      = "last_seen_at"
	TopicCollection      = "topics"
	UserLocaleCollection = "user_locales"

	SavedEmailCollection     = "saved_email"
	SavedPushCollection      = "saved_push"
	SavedWebCollection       = "saved_web"
	AvailableTopicCollection = "topics_available"

	ProcessedCollection = "processed"
)

type Processed struct {
	BaseModel    `bson:",inline"`
	User         string `bson:"user"`
	Organization string `bson:"org"`
}

type AvailableTopic struct {
	BaseModel `bson:",inline"`
	Ident     string   `json:"ident" bson:"ident" required:"true" form:"ident" binding:"required"`
	AppName   string   `json:"app_name" bson:"app_name" required:"true" form:"app_name" binding:"required"`
	SortIndex int      `json:"sortindex" bson:"sortindex" required:"true" form:"sortindex" binding:"required"`
	Channels  []string `json:"channels" bson:"channels" required:"true" form:"channels" binding:"required"`
}

type SentItem struct {
	BaseModel      `bson:",inline"`
	CreatedBy      string                 `json:"created_by" bson:"created_by" required:"true"`
	Organization   string                 `json:"org" bson:"org" required:"true"`
	AppName        string                 `json:"app_name" bson:"app_name" required:"true"`
	Topic          string                 `json:"topic" bson:"topic" required:"true"`
	User           string                 `json:"user" bson:"user" required:"true"`
	DestinationUri string                 `json:"destination_uri" bson:"destination_uri" required:"true"`
	Text           string                 `json:"text" bson:"text" required:"true"`
	IsRead         bool                   `json:"is_read" bson:"is_read"`
	Context        map[string]interface{} `json:"context" bson:"context"`
	Entity         string                 `json:"entity" bson:"entity" required:"true"`
}

type SavedItem struct {
	BaseModel `bson:",inline"`
	Data      interface{} `bson:"data"`
	Details   PendingItem `bson:"details"`
}

type PendingItem struct {
	BaseModel      `bson:",inline"`
	CreatedBy      string                 `json:"created_by" bson:"created_by" required:"true"`
	Organization   string                 `json:"org" bson:"org" required:"true"`
	AppName        string                 `json:"app_name" bson:"app_name" required:"true"`
	Topic          string                 `json:"topic" bson:"topic" required:"true"`
	IsPending      bool                   `json:"is_pending" bson:"is_pending" required:"true"`
	User           string                 `json:"user" bson:"user" required:"true"`
	DestinationUri string                 `json:"destination_uri" bson:"destination_uri" required:"true"`
	Context        map[string]interface{} `json:"context" bson:"context" required:"true"`
	IsRead         bool                   `json:"is_read" bson:"is_read"`
	Entity         string                 `json:"entity" bson:"entity" required:"true"`
}

func (self *PendingItem) IsValid() bool {
	if len(self.Context) == 0 {
		return false
	}
	return true
}

type LastSeen struct {
	BaseModel    `bson:",inline"`
	User         string `json:"user" bson:"user" required:"true"`
	Organization string `json:"org" bson:"org"`
	AppName      string `json:"app_name" bson:"app_name"`
	Timestamp    int64  `json:"timestamp" bson:"timestamp" required:"true"`
}

type Channel struct {
	Name    string `json:"name" bson:"name"`
	Enabled bool   `json:"enabled" bson:"enabled"`
	Default bool   `json:"default" bson:"default"`
	Locked  bool   `json:"locked" bson:"locked"`
}

type Topic struct {
	BaseModel    `bson:",inline"`
	User         string    `json:"user" bson:"user"`
	Organization string    `json:"org" bson:"org"`
	Channels     []Channel `json:"channels" bson:"channels" required:"true"`
	Ident        string    `json:"ident" bson:"ident" required:"true" form:"ident" binding:"required"`
}


text:
package app.controllers.api.masterdata;

import app.models.MdEselontbl;
import core.controllers.CRUDController;

public class MdEselontblController extends CRUDController<MdEselontbl>{

}


text:
use std::env;
use std::fs;
use std::path::Path;
fn main() {
    let out_dir = env::var("OUT_DIR").expect("OUT_DIR variable must be set");
    let dep_dir = Path::new(&out_dir).join("../../../deps");
    let cargo_home = env::var("CARGO_HOME").expect("CARGO_HOME variable must be set");
    let so_folder = Path::new(&cargo_home).join("kythe");

    let indexer = fs::read_dir(dep_dir).expect("deps folder not found").find(|entry| {
        entry.as_ref().unwrap().file_name().to_string_lossy().starts_with("libkythe_indexer")
    });

    let indexer = indexer.expect("indexer not found").unwrap();
    fs::create_dir_all(so_folder.as_path()).expect("failed to create kythe directory");
    fs::copy(indexer.path(), so_folder.join(indexer.file_name()))
        .expect("failed to copy indexer to kythe directory");
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Imagination.ServiceModels
{
    [ContentType("application/vnd.imgtec.objecttypes")]
    public class ObjectTypes: CollectionBase<ObjectType>
    {

    }
}


text:
g2gtools.sequence module
========================

.. automodule:: g2gtools.sequence
    :members:
    :undoc-members:
    :show-inheritance:


text:
package smilecra.hypertext.persons;

import com.fasterxml.jackson.annotation.JsonView;
import smilecra.hypertext.Service;
import smilecra.hypertext.Views;

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Collection;
import java.util.Optional;

import static javax.ws.rs.core.Response.created;

@Path("/persons")
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {

    private final Service service;

    @Inject
    public PersonResource(Service service) {
        this.service = service;
    }

    @GET
    @JsonView(Views.ListPersons.class)
    @Produces(MediaType.APPLICATION_JSON)
    public PersonCollection listPersons() {
        Collection<Person> ps = service.getPersons();
        PersonCollection personCollection = new PersonCollection(ps);
        addLinks(personCollection);
        return personCollection;
    }

    @GET
    @Path("{id}")
    public Optional<Person> getPerson(@PathParam("id") Integer id) {
        Optional<Person> p = service.getPerson(id);
        p.ifPresent(this::addLinks);
        return p;
    }

    @POST
    public Response createPerson(Person p) {
        service.createPerson(p);
        addLinks(p);

        return Response.created(p.getSelf())
                .entity(p)
                .build();
    }

    private void addLinks(PersonCollection personCollection) {
        URI self = UriBuilder.fromResource(PersonResource.class)
                .build();
        personCollection.setSelf(self);
        personCollection.getPersons().forEach(this::addLinks);
    }

    private void addLinks(Person p) {
        Integer id = p.getId();

        URI self = UriBuilder.fromResource(PersonResource.class)
                .path(PersonResource.class, "getPerson")
                .build(id);

        p.setSelf(self);
    }

}


text:
<?php

class ProyectosController extends Controller{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters(){
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules(){
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','agregar','volver','limpiar'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin','1094'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id){
		$modelParticipantes = new ParticipantesForm;

		if(isset($_POST['ParticipantesForm'])){
			$modelParticipantes->idParticipante = $_POST['ParticipantesForm']['idParticipante'];
			if($modelParticipantes->idParticipante != null){
			$modelPersona = Persona::model()->find('cedulaPersona=:cedulaPersona', array(':cedulaPersona'=>$modelParticipantes->idParticipante));
			$modelPersona->participacionProyectos_idProyectos = $id;
			if($modelPersona->update()){
				$this->redirect(array('view','id'=>$id));}}}

		if(isset($_POST['volver'])){
			$this->redirect(array('/proyectos/admin'));}

		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'modelParticipantes'=>$modelParticipantes,
		));}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate(){
		$model=new Proyectos;
		$modelParticipantes = new ParticipantesForm;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Proyectos'])){
			if ($_POST['Proyectos']['idProyectos']!=null) {
				$model->scenario='create';
			}
			$model->attributes=$_POST['Proyectos'];
			$model->certificado=CUploadedFile::getInstance($model,'image');
			$model->certificado->saveAs('/proyectoYII/images/'.CUploadedFile::getInstance($model,'image')->name);
			$cedulaPersona = Yii::app()->user->id;
			$usuario = Persona::model()->find('cedulaPersona=:cedulaPersona', array(':cedulaPersona'=>$cedulaPersona));
			$model->duenoPersona_idPersona = $usuario->idPersona;
			if($model->save()){
				if(isset($_POST['ParticipantesForm'])){
					$modelParticipantes->idParticipante = $_POST['ParticipantesForm']['idParticipante'];
					if($modelParticipantes->idParticipante != null){
						$modelPersona = Persona::model()->find('cedulaPersona=:cedulaPersona', array(':cedulaPersona'=>$modelParticipantes->idParticipante));
						$id =  $model->idProyectos;
						$modelPersona->participacionProyectos_idProyectos = $id;
						if($modelPersona->update()){
							$this->redirect(array('view','id'=>$id));}}}
				$this->redirect(array('view','id'=>$model->idProyectos));
				}}

		$this->render('create',array(
			'model'=>$model,
			'modelParticipantes'=>$modelParticipantes,
		));}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id){
		$model=$this->loadModel($id);
		$modelParticipantes = new ParticipantesForm;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Proyectos'])){
			$model->attributes=$_POST['Proyectos'];
			$model->certificado=CUploadedFile::getInstance($model,'certificado');
			//$model->certificado->saveAs('/proyectoYII/images/'.CUploadedFile::getInstance($model,'image')->name);
			if($model->save()){
				if(isset($_POST['ParticipantesForm'])){
				//$modelParticipantes->attributes =$_POST['ParticipantesForm'];
					$modelParticipantes->idParticipante = $_POST['ParticipantesForm']['idParticipante'];
					if($modelParticipantes->idParticipante != null){
						$modelPersona = Persona::model()->find('cedulaPersona=:cedulaPersona', array(':cedulaPersona'=>$modelParticipantes->idParticipante));
						$id =  $model->idProyectos;
						$modelPersona->participacionProyectos_idProyectos = $id;
						if($modelPersona->update())
							$this->redirect(array('view','id'=>$id));
					}
				}
				$this->redirect(array('view','id'=>$model->idProyectos));

			}
		}
		$this->render('update',array(
			'model'=>$model,
			'modelParticipantes'=>$modelParticipantes,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$modelProyecto = $this->loadModel($id);
		$criteria = new CDbCriteria();
		$criteria->select = 'idPersona, cedulaPersona, participacionProyectos_idProyectos';
		$criteria->condition = 'participacionProyectos_idProyectos= :proyectos';
		$criteria->params = array(':proyectos' => $id);
		$comments= Persona::model()->findAll($criteria);

		foreach ($comments as $key) {
			$modelPersona = Persona::model()->find('cedulaPersona=:cedulaPersona', array(':cedulaPersona'=>$key->cedulaPersona));
			$modelPersona->participacionProyectos_idProyectos = null;
			$modelPersona->update();
		}
		$modelProyecto->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax'])){
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));}}

	/**
	 * Lists all models.
	 */
	public function actionIndex(){
		$dataProvider=new CActiveDataProvider('Proyectos');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));}

	/**
	 * Manages all models.
	 */
	public function actionAdmin(){
		$model=new Proyectos('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Proyectos'])){
			$model->attributes=$_GET['Proyectos'];}

		$this->render('admin',array(
			'model'=>$model,
		));}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Proyectos the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id){
		$model=Proyectos::model()->findByPk($id);
		if($model===null){
			throw new CHttpException(404,'The requested page does not exist.');}
		return $model;}

	/**
	 * Performs the AJAX validation.
	 * @param Proyectos $model the model to be validated
	 */
	protected function performAjaxValidation($model){
		if(isset($_POST['ajax']) && $_POST['ajax']==='proyectos-form'){
			echo CActiveForm::validate($model);
			Yii::app()->end();}}

	public function actionLimpiar(){

		$model = new Proyectos;
		$modelParticipantes = new ParticipantesForm;
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		$this->render('update',array(
			'model'=>$model,
			'modelParticipantes'=>$modelParticipantes,
		));
	}
}


text:
package com.xinyiglass.springSample.dao.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import xygdev.commons.entity.PlsqlRetValue;
import xygdev.commons.entity.SqlResultSet;
import xygdev.commons.springjdbc.DevJdbcDaoSupport;
import xygdev.commons.util.TypeConvert;

import com.xinyiglass.springSample.dao.RespVODao;
import com.xinyiglass.springSample.entity.RespVO;
import com.xinyiglass.springSample.util.LogUtil;

public class RespVODaoImpl extends DevJdbcDaoSupport implements RespVODao{
	//insert
	public PlsqlRetValue insert(RespVO r) throws Exception{
		String sql ="Declare "
				+ "     l_resp_id number; "
				+ "  begin "
				+ "  XYG_ALB2B_RESP_PKG.INSERT_RESP( "
				+ "  :1"
				+ " ,:2"
				+ " ,:3"
                + " ,:4"
                + " ,:5"
                + " ,:6"
                + " ,:7"
				+ " ,:"+PlsqlRetValue.RETCODE
				+ " ,:"+PlsqlRetValue.ERRBUF
				+ " ); "
				+ "end;";
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("1", r.getRespId());
		paramMap.put("2", r.getRespCode());
		paramMap.put("3", r.getRespName());
		paramMap.put("4", r.getDescription());
		paramMap.put("5", r.getMenuId());
		paramMap.put("6", TypeConvert.u2tDate(r.getStartDate()));
		paramMap.put("7", TypeConvert.u2tDate(r.getEndDate()));
		return this.getDevJdbcTemplate().executeForRetValue(sql, paramMap);
	}

	//lock
	public PlsqlRetValue lock(RespVO r) throws Exception{
		String sql ="Declare "
				+ "     l_resp_id number; "
				+ "  begin "
				+ "  XYG_ALB2B_RESP_PKG.LOCK_RESP( "
				+ "  :1"
				+ " ,:2"
				+ " ,:3"
                + " ,:4"
                + " ,:5"
                + " ,:6"
                + " ,:7"
				+ " ,:"+PlsqlRetValue.RETCODE
				+ " ,:"+PlsqlRetValue.ERRBUF
				+ " ); "
				+ "end;";
		LogUtil.log("LOCK Resp ID:"+r.getRespId());
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("1", r.getRespId());
		paramMap.put("2", r.getRespCode());
		paramMap.put("3", r.getRespName());
		paramMap.put("4", r.getDescription());
		paramMap.put("5", r.getMenuId());
		paramMap.put("6", TypeConvert.u2tDate(r.getStartDate()));
		paramMap.put("7", TypeConvert.u2tDate(r.getEndDate()));
		return this.getDevJdbcTemplate().executeForRetValue(sql, paramMap);
	}

	//update
	public PlsqlRetValue update(RespVO r) throws Exception{
		String sql ="Declare "
				+ "     l_resp_id number; "
				+ "  begin "
				+ "  XYG_ALB2B_RESP_PKG.UPDATE_RESP( "
				+ "  :1"
				+ " ,:2"
				+ " ,:3"
                + " ,:4"
                + " ,:5"
                + " ,:6"
                + " ,:7"
				+ " ,:"+PlsqlRetValue.RETCODE
				+ " ,:"+PlsqlRetValue.ERRBUF
				+ " ); "
				+ "end;";
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("1", r.getRespId());
		paramMap.put("2", r.getRespCode());
		paramMap.put("3", r.getRespName());
		paramMap.put("4", r.getDescription());
		paramMap.put("5", r.getMenuId());
		paramMap.put("6", TypeConvert.u2tDate(r.getStartDate()));
		paramMap.put("7", TypeConvert.u2tDate(r.getEndDate()));
		return this.getDevJdbcTemplate().executeForRetValue(sql, paramMap);
	}

	public RespVO findByRespId(Long respId) throws Exception{
		Map<String,Object> paramMap=new  HashMap<String,Object>();
		String sql = "SELECT * FROM XYG_ALB2B_RESPONSIBILITY_V WHERE RESP_ID = :1";
		paramMap.put("1", respId);
		return this.getDevJdbcTemplate().queryForObject(sql, paramMap, new RespVO());
	}

	public SqlResultSet findByIdForJSON(Long respId) throws Exception{
		Map<String,Object> paramMap=new  HashMap<String,Object>();
		String sql = "SELECT * FROM XYG_ALB2B_RESPONSIBILITY_V WHERE RESP_ID = :1";
		paramMap.put("1", respId);
		return this.getDevJdbcTemplate().queryForResultSet(sql, paramMap);
	}

	public String findMenuId(Long respId) throws Exception{
		String sql = "SELECT MENU_ID FROM XYG_ALB2B_RESPONSIBILITY_V WHERE RESP_ID = :1";
		Map<String,Object> paramMap=new  HashMap<String,Object>();
		paramMap.put("1", respId);
		return this.getDevJdbcTemplate().queryForObjSingle(sql, paramMap).toString();
	}

	//测试专用
	@SuppressWarnings("resource")
	public static void main(String[] args){
	    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
	    RespVODao rDao= (RespVODao)context.getBean("RespVODao");
		try{
			Long respId=1L;
			String menuId = rDao.findMenuId(respId);
			System.out.println("MENU_ID:"+menuId);
		} catch (Exception EmptyResultDataAccessException) {
			EmptyResultDataAccessException.printStackTrace();
			System.out.println("无返回数据");
		}
	}

}


text:
<?php

namespace mako\tests\unit\http;

use mako\http\Request;
use mako\http\request\UploadedFile;
use mako\http\routing\Route;
use mako\security\Signer;
use mako\tests\TestCase;
use Mockery;
use RuntimeException;

/**
 * @group unit
 */
class RequestTest extends TestCase
{
	/**
	 *
	 */
	public function getServerData()
	{
		return
		[
			'HTTP_HOST' => 'example.local',
			'HTTP_CONNECTION' => 'keep-alive',
			'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,foo/bar; q=0.1,application/xml;q=0.9,image/webp,*/*;q=0.8',
			'HTTP_USER_AGENT' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36',
			'HTTP_DNT' => '1',
			'HTTP_ACCEPT_CHARSET' => 'UTF-8,FOO-1; q=0.1,UTF-16;q=0.9',
			'HTTP_ACCEPT_ENCODING' => 'gzip,foobar;q=0.1,deflate,sdch',
			'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8,da;q=0.6,fr;q=0.4,foo; q=0.1,nb;q=0.2,sv;q=0.2',
			'PATH' => '/usr/local/bin:/usr/bin:/bin',
			'SERVER_SIGNATURE' => '<address>Apache/2.4.6 (Ubuntu) Server at example.local Port 80</address>',
			'SERVER_SOFTWARE' => 'Apache/2.4.6 (Ubuntu)',
			'SERVER_NAME' => 'example.local',
			'SERVER_ADDR' => '10.17.2.9',
			'SERVER_PORT' => '80',
			'REMOTE_ADDR' => '10.17.12.209',
			'DOCUMENT_ROOT' => '/var/www',
			'REQUEST_SCHEME' => 'http',
			'CONTEXT_PREFIX' => '',
			'CONTEXT_DOCUMENT_ROOT' => '/var/www',
			'SERVER_ADMIN' => 'webmaster@localhost',
			'REMOTE_PORT' => '53058',
			'GATEWAY_INTERFACE' => 'CGI/1.1',
			'SERVER_PROTOCOL' => 'HTTP/1.1',
			'REQUEST_METHOD' => 'GET',
			'QUERY_STRING' => '',
			'REQUEST_TIME_FLOAT' => 1398338683.59,
			'REQUEST_TIME' => 1398338683,
			'REQUEST_URI' => '/index.php/test/',
			'SCRIPT_NAME' => '/index.php',
			'PHP_SELF' => '/index.php/test/',
			'SCRIPT_FILENAME' => '/var/www/index.php',
			'PATH_INFO' => '/test/',
		];
	}

	/**
	 *
	 */
	public function testScriptName(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertEquals('index.php', $request->getScriptName());

		//

		$server['SCRIPT_FILENAME'] = '/var/www/app.php';

		$request = new Request(['server' => $server]);

		$this->assertEquals('app.php', $request->getScriptName());

		//

		$server['SCRIPT_FILENAME'] = '/var/www/reactor';

		$request = new Request(['server' => $server]);

		$this->assertEquals('index.php', $request->getScriptName());
	}

	/**
	 *
	 */
	public function testScriptNameOverride(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server], null, 'foo.php');

		$this->assertEquals('foo.php', $request->getScriptName());
	}

	/**
	 *
	 */
	public function testAcceptableContentTypes(): void
	{
		$server = $this->getServerData();

		$acceptableContentTypes = ['text/html', 'application/xhtml+xml', 'image/webp', 'application/xml', '*/*', 'foo/bar'];

		$this->assertEquals($acceptableContentTypes, (new Request(['server' => $server]))->getHeaders()->getAcceptableContentTypes());
	}

	/**
	 *
	 */
	public function testAcceptableLanguages(): void
	{
		$server = $this->getServerData();

		$acceptableLanguages = ['en-US', 'en', 'da', 'fr', 'nb', 'sv', 'foo'];

		$this->assertEquals($acceptableLanguages, (new Request(['server' => $server]))->getHeaders()->getAcceptableLanguages());
	}

	/**
	 *
	 */
	public function testAcceptableCharsets(): void
	{
		$server = $this->getServerData();

		$acceptableCharsets = ['UTF-8', 'UTF-16', 'FOO-1'];

		$this->assertEquals($acceptableCharsets, (new Request(['server' => $server]))->getHeaders()->getAcceptableCharsets());
	}

	/**
	 *
	 */
	public function testAcceptableEncodings(): void
	{
		$server = $this->getServerData();

		$acceptableEncodings = ['gzip', 'deflate', 'sdch', 'foobar'];

		$this->assertEquals($acceptableEncodings, (new Request(['server' => $server]))->getHeaders()->getAcceptableEncodings());
	}

	/**
	 *
	 */
	public function testIP(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertEquals('10.17.12.209', $request->getIp());

		// Should fall back to localhost if an invalid IP is detected

		$server['REMOTE_ADDR'] = 'invalid ip';

		$request = new Request(['server' => $server]);

		$this->assertEquals(Request::REMOTE_ADDRESS_FALLBACK, $request->getIp());

		// Should ignore the X-Forwarded-For header if no list of trusted proxies is specified

		$server['REMOTE_ADDR'] = '10.17.12.214';

		$server['HTTP_X_FORWARDED_FOR'] = '10.17.13.0, 10.17.13.1, 10.17.12.212, 10.17.12.213';

		$request = new Request(['server' => $server]);

		$this->assertEquals('10.17.12.214', $request->getIp());

		// Should return the last IP in the chain since it doesn't match our trusted proxy

		$request = new Request(['server' => $server]);

		$request->setTrustedProxies(['10.17.12.214']);

		$this->assertEquals('10.17.12.213', $request->getIp());

		// Should return the IP forwarded by the first trusted proxy

		$request = new Request(['server' => $server]);

		$request->setTrustedProxies(['10.17.12.213', '10.17.12.214']);

		$this->assertEquals('10.17.12.212', $request->getIp());

		// Should return the IP forwarded by the first trusted proxy

		$request = new Request(['server' => $server]);

		$request->setTrustedProxies(['10.17.12.212', '10.17.12.213', '10.17.12.214']);

		$this->assertEquals('10.17.13.1', $request->getIp());

		// Should return the IP forwarded by the first trusted proxy

		$request = new Request(['server' => $server]);

		$request->setTrustedProxies(['10.17.12.0/24']);

		$this->assertEquals('10.17.13.1', $request->getIp());
	}

	/**
	 *
	 */
	public function testGetIpWithoutRemoteAddress(): void
	{
		$server = $this->getServerData();

		unset($server['REMOTE_ADDR']);

		$request = new Request(['server' => $server]);

		$this->assertSame(Request::REMOTE_ADDRESS_FALLBACK, $request->getIp());
	}

	/**
	 *
	 */
	public function testIsAjax(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertFalse($request->isAjax());

		//

		$server['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';

		$request = new Request(['server' => $server]);

		$this->assertTrue($request->isAjax());
	}

	/**
	 *
	 */
	public function testIsSecure(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertFalse($request->isSecure());

		//

		$server['HTTPS'] = 'off';

		$request = new Request(['server' => $server]);

		$this->assertFalse($request->isSecure());

		//

		$server['HTTPS'] = '0';

		$request = new Request(['server' => $server]);

		$this->assertFalse($request->isSecure());

		//

		$server['HTTPS'] = 'false';

		$request = new Request(['server' => $server]);

		$this->assertFalse($request->isSecure());

		//

		$server['HTTPS'] = 'on';

		$request = new Request(['server' => $server]);

		$this->assertTrue($request->isSecure());

		//

		$server['HTTPS'] = '1';

		$request = new Request(['server' => $server]);

		$this->assertTrue($request->isSecure());

		//

		$server['HTTPS'] = 'true';

		$request = new Request(['server' => $server]);

		$this->assertTrue($request->isSecure());

		//

		$server['HTTPS'] = 'false';
		$server['HTTP_X_FORWARDED_PROTO'] = 'https';
		$server['REMOTE_ADDR'] = '127.0.0.1';

		$request = new Request(['server' => $server]);

		$request->setTrustedProxies(['127.0.0.1']);

		$this->assertTrue($request->isSecure());
	}

	/**
	 *
	 */
	public function testIsSecureWithoutRemoteAddress(): void
	{
		$server = $this->getServerData();

		unset($server['REMOTE_ADDR']);

		$request = new Request(['server' => $server]);

		$this->assertFalse($request->isSecure());
	}

	/**
	 *
	 */
	public function testBasePath(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertEquals('', $request->getBasePath());

		//

		$server = $this->getServerData();

		$server['SCRIPT_NAME'] = '/foo/bar/index.php';

		$request = new Request(['server' => $server]);

		$this->assertEquals('/foo/bar', $request->getBasePath());
	}

	/**
	 *
	 */
	public function testBaseURL(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertEquals('http://example.local', $request->getBaseURL());

		//

		$server = $this->getServerData();

		$server['HTTPS'] = 'on';

		$request = new Request(['server' => $server]);

		$this->assertEquals('https://example.local', $request->getBaseURL());

		//

		$server = $this->getServerData();

		$server['HTTPS'] = 'on';

		$server['HTTP_HOST'] = 'example.local:8080';

		$request = new Request(['server' => $server]);

		$this->assertEquals('https://example.local:8080', $request->getBaseURL());

		//

		$server = $this->getServerData();

		$server['HTTPS'] = 'on';

		unset($server['HTTP_HOST']);

		$request = new Request(['server' => $server]);

		$this->assertEquals('https://example.local', $request->getBaseURL());

		//

		$server = $this->getServerData();

		$server['HTTPS'] = 'on';

		unset($server['HTTP_HOST']);

		$server['SERVER_PORT'] = '8080';

		$request = new Request(['server' => $server]);

		$this->assertEquals('https://example.local:8080', $request->getBaseURL());

		//

		$server = $this->getServerData();

		$server['SCRIPT_NAME'] = '/foo/bar/index.php';

		$request = new Request(['server' => $server]);

		$this->assertEquals('http://example.local/foo/bar', $request->getBaseURL());

		//

		$server = $this->getServerData();

		$server['HTTPS'] = 'off';
		$server['HTTP_X_FORWARDED_PROTO'] = 'https';
		$server['REMOTE_ADDR'] = '127.0.0.1';

		$request = new Request(['server' => $server]);

		$request->setTrustedProxies(['127.0.0.1']);

		$this->assertEquals('https://example.local', $request->getBaseURL());
	}

	/**
	 *
	 */
	public function testPath(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertEquals('/test/', $request->getPath());

		//

		unset($server['PATH_INFO']);

		$request = new Request(['server' => $server]);

		$this->assertEquals('/test/', $request->getPath());

		//

		$server['REQUEST_URI'] = '/app.php/test/';
		$server['SCRIPT_NAME'] = '/app.php';
		$server['SCRIPT_FILENAME'] = '/var/www/app.php';

		$request = new Request(['server' => $server]);

		$this->assertEquals('/test/', $request->getPath());

		//

		$request = new Request(['server' => $server, 'path' => '/foo/bar']);

		$this->assertEquals('/foo/bar', $request->getPath());
	}

	/**
	 *
	 */
	public function testPathWithLanguage(): void
	{
		$server = $this->getServerData();

		$server['PATH_INFO'] = '/no/test/';

		$request = new Request(['server' => $server, 'languages' => ['no' => ['strings' => 'nb_NO', 'locale' => [LC_ALL => ['nb_NO.UTF-8', 'nb_NO.utf8', 'C'], LC_NUMERIC => 'C']]]]);

		$this->assertEquals('/test/', $request->getPath());
	}

	/**
	 *
	 */
	public function testIsClean(): void
	{
		$request = new Request(['server' => ['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/index.php/foo']]);

		$this->assertFalse($request->isClean());

		//

		$request = new Request(['server' => ['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo']]);

		$this->assertTrue($request->isClean());
	}

	/**
	 *
	 */
	public function testLanguage(): void
	{
		$server = $this->getServerData();

		$server['PATH_INFO'] = '/no/test/';

		$request = new Request(['server' => $server, 'languages' => ['no' => ['strings' => 'nb_NO', 'locale' => [LC_ALL => ['nb_NO.UTF-8', 'nb_NO.utf8', 'C'], LC_NUMERIC => 'C']]]]);

		$this->assertEquals(['strings' => 'nb_NO', 'locale' => [LC_ALL => ['nb_NO.UTF-8', 'nb_NO.utf8', 'C'], LC_NUMERIC => 'C']], $request->getLanguage());
	}

	/**
	 *
	 */
	public function testLanguagePrefix(): void
	{
		$server = $this->getServerData();

		$server['PATH_INFO'] = '/no/test/';

		$request = new Request(['server' => $server, 'languages' => ['no' => ['strings' => 'nb_NO', 'locale' => [LC_ALL => ['nb_NO.UTF-8', 'nb_NO.utf8', 'C'], LC_NUMERIC => 'C']]]]);

		$this->assertEquals('no', $request->getLanguagePrefix());
	}

	/**
	 *
	 */
	public function testMethod(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertEquals('GET', $request->getMethod());

		//

		$request = new Request(['server' => $server, 'method' => 'PATCH']);

		$this->assertEquals('PATCH', $request->getMethod());

		//

		$server['REQUEST_METHOD'] = 'POST';

		$request = new Request(['server' => $server, 'post' => ['REQUEST_METHOD_OVERRIDE' => 'PUT']]);

		$this->assertEquals('PUT', $request->getMethod());

		//

		$server['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'OPTIONS';

		$request = new Request(['server' => $server]);

		$this->assertEquals('OPTIONS', $request->getMethod());
	}

	/**
	 *
	 */
	public function testRealMethod(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertEquals('GET', $request->getRealMethod());

		//

		$server['REQUEST_METHOD'] = 'POST';

		$request = new Request(['server' => $server, 'post' => ['REQUEST_METHOD_OVERRIDE' => 'PUT']]);

		$this->assertEquals('POST', $request->getRealMethod());

		//

		$server['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'OPTIONS';

		$request = new Request(['server' => $server]);

		$this->assertEquals('POST', $request->getRealMethod());
	}

	/**
	 *
	 */
	public function testIsFaked(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertFalse($request->isFaked());

		//

		$server['REQUEST_METHOD'] = 'POST';

		$request = new Request(['server' => $server, 'post' => ['REQUEST_METHOD_OVERRIDE' => 'PUT']]);

		$this->assertTrue($request->isFaked());

		//

		$server['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'OPTIONS';

		$request = new Request(['server' => $server]);

		$this->assertTrue($request->isFaked());
	}

	/**
	 *
	 */
	public function testUsername(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertNull($request->getUsername());

		//

		$server['PHP_AUTH_USER'] = 'foobar';

		$request = new Request(['server' => $server]);

		$this->assertEquals('foobar', $request->getUsername());
	}

	/**
	 *
	 */
	public function testPassword(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertNull($request->getPassword());

		//

		$server['PHP_AUTH_PW'] = 'foobar';

		$request = new Request(['server' => $server]);

		$this->assertEquals('foobar', $request->getPassword());
	}

	/**
	 *
	 */
	public function testCookie(): void
	{
		$cookies = ['foo' => 'bar'];

		$request = new Request(['cookies' => $cookies]);

		$this->assertNull($request->getCookies()->get('bar'));

		$this->assertFalse($request->getCookies()->get('bar', false));

		$this->assertEquals('bar', $request->getCookies()->get('foo'));
	}

	/**
	 *
	 */
	public function testSignedCookie(): void
	{
		/** @var \mako\security\Signer|\Mockery\MockInterface $signer */
		$signer = Mockery::mock(Signer::class);

		$signer->shouldReceive('validate')->withArgs(['bar'])->andReturn('bar');

		$signer->shouldReceive('validate')->withArgs(['bax'])->andReturn(false);

		$cookies = ['foo' => 'bar', 'baz' => 'bax'];

		$request = new Request(['cookies' => $cookies], $signer);

		$this->assertNull($request->getCookies()->getSigned('bar'));

		$this->assertFalse($request->getCookies()->getSigned('bar', false));

		$this->assertEquals('bar', $request->getCookies()->getSigned('foo'));

		$this->assertNull($request->getCookies()->getSigned('baz'));

		$this->assertFalse($request->getCookies()->getSigned('baz', false));
	}

	/**
	 *
	 */
	public function testSignedCookieException(): void
	{
		$this->expectException(RuntimeException::class);

		$request = new Request();

		$request->getCookies()->getSigned('foo');
	}

	/**
	 *
	 */
	public function testHeader(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertNull($request->getHeaders()->get('bar'));

		$this->assertFalse($request->getHeaders()->get('bar', false));

		$this->assertEquals('keep-alive', $request->getHeaders()->get('connection'));

		$this->assertEquals('keep-alive', $request->getHeaders()->get('ConNeCtIoN'));
	}

	/**
	 *
	 */
	public function testServer(): void
	{
		$server = $this->getServerData();

		$request = new Request(['server' => $server]);

		$this->assertNull($request->getServer()->get('bar'));

		$this->assertFalse($request->getServer()->get('bar', false));

		$this->assertEquals('example.local', $request->getServer()->get('HTTP_HOST'));

		$this->assertEquals($server, $request->getServer()->all());
	}

	/**
	 *
	 */
	public function testGet(): void
	{
		$get = ['foo' => 'bar', 'baz' => ['bax']];

		$request = new Request(['get' => $get]);

		$this->assertNull($request->getQuery()->get('bar'));

		$this->assertFalse($request->getQuery()->get('bar', false));

		$this->assertEquals('bar', $request->getQuery()->get('foo'));

		$this->assertEquals('bax', $request->getQuery()->get('baz.0'));

		$this->assertEquals($get, $request->getQuery()->all());
	}

	/**
	 *
	 */
	public function testPost(): void
	{
		$post = ['foo' => 'bar', 'baz' => ['bax']];

		$request = new Request(['post' => $post]);

		$this->assertNull($request->getPost()->get('bar'));

		$this->assertFalse($request->getPost()->get('bar', false));

		$this->assertEquals('bar', $request->getPost()->get('foo'));

		$this->assertEquals('bax', $request->getPost()->get('baz.0'));

		$this->assertEquals($post, $request->getPost()->all());
	}

	/**
	 *
	 */
	public function testBody(): void
	{
		$request = new Request(['body' => '{"foo":"bar","baz":["bax"]}']);

		$this->assertEquals('{"foo":"bar","baz":["bax"]}', $request->getRawBody());
	}

	/**
	 *
	 */
	public function testContentTypeWithNoHeader(): void
	{
		$request = new Request;

		$this->assertSame('', $request->getContentType());
	}

	/**
	 *
	 */
	public function testContentTypeWithHeader(): void
	{
		$server = $this->getServerData();

		$server['HTTP_CONTENT_TYPE'] = 'application/json';

		$request = new Request(['server' => $server]);

		$this->assertSame('application/json', $request->getContentType());
	}

	/**
	 *
	 */
	public function testContentTypeWithHeaderAndCharset(): void
	{
		$server = $this->getServerData();

		$server['HTTP_CONTENT_TYPE'] = 'application/json; charset=UTF-8';

		$request = new Request(['server' => $server]);

		$this->assertSame('application/json', $request->getContentType());
	}

	/**
	 *
	 */
	public function testJsonPutData(): void
	{
		$body = ['foo' => 'bar', 'baz' => ['bax']];

		$server = $this->getServerData();

		$server['HTTP_CONTENT_TYPE'] = 'application/json';

		$request = new Request(['server' => $server, 'body' => json_encode($body)]);

		$this->assertNull($request->getBody()->get('bar'));

		$this->assertFalse($request->getBody()->get('bar', false));

		$this->assertEquals('bar', $request->getBody()->get('foo'));

		$this->assertEquals('bax', $request->getBody()->get('baz.0'));

		$this->assertEquals($body, $request->getBody()->all());
	}

	/**
	 *
	 */
	public function testURLEncodedPutData(): void
	{
		$body = ['foo' => 'bar', 'baz' => ['bax']];

		$server = $this->getServerData();

		$server['HTTP_CONTENT_TYPE'] = 'application/x-www-form-urlencoded';

		$request = new Request(['server' => $server, 'body' => http_build_query($body)]);

		$this->assertNull($request->getBody()->get('bar'));

		$this->assertFalse($request->getBody()->get('bar', false));

		$this->assertEquals('bar', $request->getBody()->get('foo'));

		$this->assertEquals('bax', $request->getBody()->get('baz.0'));

		$this->assertEquals($body, $request->getBody()->all());
	}

	/**
	 *
	 */
	public function testSetRoute(): void
	{
		$request = new Request();

		/** @var \mako\http\routing\Route|\Mockery\MockInterface $route */
		$route = Mockery::mock(Route::class);

		$request->setRoute($route);

		$route = (function ()
		{
			return $this->route;
		})->bindTo($request, Request::class)();

		$this->assertInstanceOf(Route::class, $route);
	}

	/**
	 *
	 */
	public function testGetRoute(): void
	{
		$request = new Request();

		$this->assertNull($request->getRoute());

		/** @var \mako\http\routing\Route|\Mockery\MockInterface $route */
		$route = Mockery::mock(Route::class);

		$request->setRoute($route);

		$this->assertSame($route, $request->getRoute());
	}

	/**
	 *
	 */
	public function testSetAndGetAttribute(): void
	{
		$request = new Request();

		$this->assertNull($request->getAttribute('foo'));

		$this->assertFalse($request->getAttribute('foo', false));

		$request->setAttribute('foo', 123);

		$this->assertEquals(123, $request->getAttribute('foo'));

		$this->assertEquals(123, $request->getAttribute('foo', false));
	}

	/**
	 *
	 */
	public function testFile(): void
	{
		$request =
		[
			'files' =>
			[
				'upload' =>
				[
					'name'     => 'foo',
					'tmp_name' => '/tmp/qwerty',
					'type'     => 'foo/bar',
					'size'     => 123,
					'error'    => 0,
				],
			],
		];

		$request = new Request($request);

		//

		$file = $request->getFiles()->get('upload');

		$this->assertInstanceOf(UploadedFile::class, $file);

		$this->assertEquals('foo', $file->getReportedFilename());

		$this->assertEquals(123, $file->getReportedSize());

		$this->assertEquals('foo/bar', $file->getReportedMimeType());

		$this->assertEquals(0, $file->getErrorCode());
	}

	/**
	 *
	 */
	public function testFileMultiUpload(): void
	{
		$request =
		[
			'files' =>
			[
				'upload' =>
				[
					'name'     => ['foo', 'bar'],
					'tmp_name' => ['/tmp/qwerty', '/tmp/azerty'],
					'type'     => ['foo/bar', 'foo/bar'],
					'size'     => [123, 456],
					'error'    => [0, 0],
				],
			],
		];

		$request = new Request($request);

		//

		$file = $request->getFiles()->get('upload.0');

		$this->assertInstanceOf(UploadedFile::class, $file);

		$this->assertEquals('foo', $file->getReportedFilename());

		$this->assertEquals(123, $file->getReportedSize());

		$this->assertEquals('foo/bar', $file->getReportedMimeType());

		$this->assertEquals(0, $file->getErrorCode());

		//

		$file = $request->getFiles()->get('upload.1');

		$this->assertInstanceOf(UploadedFile::class, $file);

		$this->assertEquals('bar', $file->getReportedFilename());

		$this->assertEquals(456, $file->getReportedSize());

		$this->assertEquals('foo/bar', $file->getReportedMimeType());

		$this->assertEquals(0, $file->getErrorCode());
	}

	/**
	 *
	 */
	public function testFileNone(): void
	{
		$request = new Request;

		$this->assertEquals([], $request->getFiles()->all());

		$this->assertNull($request->getFiles()->get('foo'));

		$this->assertFalse($request->getFiles()->get('foo', false));
	}

	/**
	 *
	 */
	public function testGetDataWithGetRequest(): void
	{
		$get = ['foo' => 'bar', 'baz' => ['bax']];

		$request = new Request(['get' => $get]);

		$this->assertSame($request->getData()->all(), $request->getQuery()->all());
	}

	/**
	 *
	 */
	public function testGetDataWithPostRequestWithFormData(): void
	{
		$post = ['foo' => 'bar', 'baz' => ['bax']];

		//

		$server = ['REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/x-www-form-urlencoded'] + $this->getServerData();

		$request = new Request(['post' => $post, 'server' => $server]);

		$this->assertSame($request->getData()->all(), $request->getPost()->all());

		//

		$server = ['REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'multipart/form-data'] + $this->getServerData();

		$request = new Request(['post' => $post, 'server' => $server]);

		$this->assertSame($request->getData()->all(), $request->getPost()->all());
	}

	/**
	 *
	 */
	public function testGetDataWithPostRequestWithoutFormData(): void
	{
		$body = ['foo' => 'bar', 'baz' => ['bax']];

		//

		$server = ['REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/json'] + $this->getServerData();

		$request = new Request(['body' => json_encode($body), 'server' => $server]);

		$this->assertSame($request->getData()->all(), $request->getBody()->all());
	}

	/**
	 *
	 */
	public function testIsSafe(): void
	{
		$methods =
		[
			'CONNECT' => false,
			'DELETE'  => false,
			'GET'     => true,
			'HEAD'    => true,
			'OPTIONS' => true,
			'PATCH'   => false,
			'POST'    => false,
			'PUT'     => false,
			'TRACE'   => true,
		];

		foreach($methods as $method => $isSafe)
		{
			$request = new Request(['server' => ['REQUEST_METHOD' => $method]]);

			$this->assertSame($isSafe, $request->isSafe());
		}
	}

	/**
	 *
	 */
	public function testIsIdempotent(): void
	{
		$methods =
		[
			'CONNECT' => false,
			'DELETE'  => true,
			'GET'     => true,
			'HEAD'    => true,
			'OPTIONS' => true,
			'PATCH'   => false,
			'POST'    => false,
			'PUT'     => true,
			'TRACE'   => true,
		];

		foreach($methods as $method => $isIdempotent)
		{
			$request = new Request(['server' => ['REQUEST_METHOD' => $method]]);

			$this->assertSame($isIdempotent, $request->isIdempotent());
		}
	}

	/**
	 *
	 */
	public function testIsCacheable(): void
	{
		$methods =
		[
			'CONNECT' => false,
			'DELETE'  => false,
			'GET'     => true,
			'HEAD'    => true,
			'OPTIONS' => false,
			'PATCH'   => false,
			'POST'    => false,
			'PUT'     => false,
			'TRACE'   => false,
		];

		foreach($methods as $method => $isCacheable)
		{
			$request = new Request(['server' => ['REQUEST_METHOD' => $method]]);

			$this->assertSame($isCacheable, $request->isCacheable());
		}
	}
}


text:
package com.rometools.rome.feed.rss;

import java.io.Serializable;

import com.rometools.rome.feed.impl.ObjectBean;

/**
 * Bean for clouds of RSS feeds.
 *

 *
 * @author Alejandro Abdelnur
 *
 */
public class Cloud implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private final ObjectBean objBean;
    private String domain;
    private int port;
    private String path;
    private String registerProcedure;
    private String protocol;

    /**
     * Default constructor. All properties are set to null.
     *

     *
     */
    public Cloud() {
        objBean = new ObjectBean(this.getClass(), this);
    }

    /**
     * Creates a deep 'bean' clone of the object.
     *

     *
     * @return a clone of the object.
     * @throws CloneNotSupportedException thrown if an element of the object cannot be cloned.
     *
     */
    @Override
    public Object clone() throws CloneNotSupportedException {
        return objBean.clone();
    }

    /**
     * Indicates whether some other object is "equal to" this one as defined by the Object equals()
     * method.
     *

     *
     * @param other he reference object with which to compare.
     * @return true if 'this' object is equal to the 'other' object.
     *
     */
    @Override
    public boolean equals(final Object other) {
        return objBean.equals(other);
    }

    /**
     * Returns a hashcode value for the object.
     *

     * It follows the contract defined by the Object hashCode() method.
     *

     *
     * @return the hashcode of the bean object.
     *
     */
    @Override
    public int hashCode() {
        return objBean.hashCode();
    }

    /**
     * Returns the String representation for the object.
     *

     *
     * @return String representation for the object.
     *
     */
    @Override
    public String toString() {
        return objBean.toString();
    }

    /**
     * Returns the cloud domain.
     *

     *
     * @return the cloud domain, null if none.
     *
     */
    public String getDomain() {
        return domain;
    }

    /**
     * Sets the cloud domain.
     *

     *
     * @param domain the cloud domain to set, null if none.
     *
     */
    public void setDomain(final String domain) {
        this.domain = domain;
    }

    /**
     * Returns the cloud port.
     *

     *
     * @return the cloud port, null if none.
     *
     */
    public int getPort() {
        return port;
    }

    /**
     * Sets the cloud port.
     *

     *
     * @param port the cloud port to set, null if none.
     *
     */
    public void setPort(final int port) {
        this.port = port;
    }

    /**
     * Returns the cloud path.
     *

     *
     * @return the cloud path, null if none.
     *
     */
    public String getPath() {
        return path;
    }

    /**
     * Sets the cloud path.
     *

     *
     * @param path the cloud path to set, null if none.
     *
     */
    public void setPath(final String path) {
        this.path = path;
    }

    /**
     * Returns the cloud register procedure.
     *

     *
     * @return the cloud register procedure, null if none.
     *
     */
    public String getRegisterProcedure() {
        return registerProcedure;
    }

    /**
     * Sets the cloud register procedure.
     *

     *
     * @param registerProcedure the cloud register procedure to set, null if none.
     *
     */
    public void setRegisterProcedure(final String registerProcedure) {
        this.registerProcedure = registerProcedure;
    }

    /**
     * Returns the cloud protocol.
     *

     *
     * @return the cloud protocol, null if none.
     *
     */
    public String getProtocol() {
        return protocol;
    }

    /**
     * Sets the cloud protocol.
     *

     *
     * @param protocol the cloud protocol to set, null if none.
     *
     */
    public void setProtocol(final String protocol) {
        this.protocol = protocol;
    }

}