text:
<?php
namespace bunq\Model\Generated\Endpoint;

use bunq\Context\ApiContext;
use bunq\Http\ApiClient;
use bunq\Http\BunqResponse;
use bunq\Model\Core\BunqModel;
use bunq\Model\Generated\Object\PaymentBatchAnchoredPayment;

/**
 * Create a payment batch, or show the payment batches of a monetary
 * account.
 *
 * @generated
 */
class PaymentBatch extends BunqModel
{
    /**
     * Endpoint constants.
     */
    const ENDPOINT_URL_CREATE = 'user/%s/monetary-account/%s/payment-batch';
    const ENDPOINT_URL_UPDATE = 'user/%s/monetary-account/%s/payment-batch/%s';
    const ENDPOINT_URL_READ = 'user/%s/monetary-account/%s/payment-batch/%s';
    const ENDPOINT_URL_LISTING = 'user/%s/monetary-account/%s/payment-batch';

    /**
     * Field constants.
     */
    const FIELD_PAYMENTS = 'payments';

    /**
     * Object type.
     */
    const OBJECT_TYPE_GET = 'PaymentBatch';

    /**
     * The list of mutations that were made.
     *
     * @var PaymentBatchAnchoredPayment
     */
    protected $payments;

    /**
     * The list of payments we want to send in a single batch.
     *
     * @var Payment[]
     */
    protected $paymentsFieldForRequest;

    /**
     * @param Payment[] $payments The list of payments we want to send in a
     * single batch.
     */
    public function __construct(array  $payments)
    {
        $this->paymentsFieldForRequest = $payments;
    }

    /**
     * Create a payment batch by sending an array of single payment objects,
     * that will become part of the batch.
     *
     * @param Payment[] $payments The list of payments we want to send in a
     * single batch.
     * @param int|null $monetaryAccountId
     * @param string[] $customHeaders
     *
     * @return BunqResponseInt
     */
    public static function create(array  $payments, int $monetaryAccountId = null, array $customHeaders = []): BunqResponseInt
    {
        $apiClient = new ApiClient(static::getApiContext());
        $responseRaw = $apiClient->post(
            vsprintf(
                self::ENDPOINT_URL_CREATE,
                [static::determineUserId(), static::determineMonetaryAccountId($monetaryAccountId)]
            ),
            [self::FIELD_PAYMENTS => $payments],
            $customHeaders
        );

        return BunqResponseInt::castFromBunqResponse(
            static::processForId($responseRaw)
        );
    }

    /**
     * Revoke a bunq.to payment batch. The status of all the payments will be
     * set to REVOKED.
     *
     * @param int $paymentBatchId
     * @param int|null $monetaryAccountId
     * @param string[] $customHeaders
     *
     * @return BunqResponseInt
     */
    public static function update(int $paymentBatchId, int $monetaryAccountId = null, array $customHeaders = []): BunqResponseInt
    {
        $apiClient = new ApiClient(static::getApiContext());
        $responseRaw = $apiClient->put(
            vsprintf(
                self::ENDPOINT_URL_UPDATE,
                [static::determineUserId(), static::determineMonetaryAccountId($monetaryAccountId), $paymentBatchId]
            ),
            [],
            $customHeaders
        );

        return BunqResponseInt::castFromBunqResponse(
            static::processForId($responseRaw)
        );
    }

    /**
     * Return the details of a specific payment batch.
     *
     * @param int $paymentBatchId
     * @param int|null $monetaryAccountId
     * @param string[] $customHeaders
     *
     * @return BunqResponsePaymentBatch
     */
    public static function get(int $paymentBatchId, int $monetaryAccountId = null, array $customHeaders = []): BunqResponsePaymentBatch
    {
        $apiClient = new ApiClient(static::getApiContext());
        $responseRaw = $apiClient->get(
            vsprintf(
                self::ENDPOINT_URL_READ,
                [static::determineUserId(), static::determineMonetaryAccountId($monetaryAccountId), $paymentBatchId]
            ),
            [],
            $customHeaders
        );

        return BunqResponsePaymentBatch::castFromBunqResponse(
            static::fromJson($responseRaw, self::OBJECT_TYPE_GET)
        );
    }

    /**
     * Return all the payment batches for a monetary account.
     *
     * This method is called "listing" because "list" is a restricted PHP word
     * and cannot be used as constants, class names, function or method names.
     *
     * @param int|null $monetaryAccountId
     * @param string[] $params
     * @param string[] $customHeaders
     *
     * @return BunqResponsePaymentBatchList
     */
    public static function listing(int $monetaryAccountId = null, array $params = [], array $customHeaders = []): BunqResponsePaymentBatchList
    {
        $apiClient = new ApiClient(static::getApiContext());
        $responseRaw = $apiClient->get(
            vsprintf(
                self::ENDPOINT_URL_LISTING,
                [static::determineUserId(), static::determineMonetaryAccountId($monetaryAccountId)]
            ),
            $params,
            $customHeaders
        );

        return BunqResponsePaymentBatchList::castFromBunqResponse(
            static::fromJsonList($responseRaw, self::OBJECT_TYPE_GET)
        );
    }

    /**
     * The list of mutations that were made.
     *
     * @return PaymentBatchAnchoredPayment
     */
    public function getPayments()
    {
        return $this->payments;
    }

    /**
     * @deprecated User should not be able to set values via setters, use
     * constructor.
     *
     * @param PaymentBatchAnchoredPayment $payments
     */
    public function setPayments($payments)
    {
        $this->payments = $payments;
    }

    /**
     * @return bool
     */
    public function isAllFieldNull()
    {
        if (!is_null($this->payments)) {
            return false;
        }

        return true;
    }
}


text:
DROP TABLE users;
DROP TABLE pets;
DROP TABLE addresses;

redpajama_set_name: RedPajamaGithub


text:
require "json"

require_relative "base-manager"

module Toolset
    module PackageManagers
        class Composer < BaseManager
            def get_dependencies(path)
                if not File.exist?(path = path + "/composer.json")
                    raise IOError
                end

                manifest = JSON.parse(File.read(path))
                dependencies = []

                if manifest.key?("require")
                    dependencies.concat(manifest["require"].keys)
                end

                if manifest.key?("require-dev")
                    dependencies.concat(manifest["require-dev"].keys)
                end

                dependencies
            end
        end
    end
end


text:
#include "FE_GPU_API.h"

#define VERTEXL_LAYOUT_OFFSET(i) ((GLvoid*)(i))
//#ifdef FE_ATTRIB_OPENGL

void FE_GPU_CreateVAOCMD::updateGL3(){

    if(FE_GPU_Command::info->findVAO(name) != FE_GPU_Command::info->vaos.size()){
        string log = "FE: GPU: WARNING: Vertex Layout - '" + name + "' already exists\n";
        log += "................. Not creating vertex layout\n";
        //writeToLog(log);
        //cout << log << endl;
        return;
    }

    FE_GPU_VertexLayout vao;
    vao.name = this->name;

    glGenVertexArrays(1, &vao.vao_id);
    glGenBuffers(1, &vao.ib_id);

    FE_GPU_Command::info->vaos.push_back(vao);
}

void FE_GPU_CreateVAOCMD::flushGL3(FE_GPU_Thread*){}

/** OpenGL implementation of requesting VAO data
**/

void FE_GPU_SetupVAOCMD::updateGL3(){

    size_t ID = FE_GPU_Command::info->findVAO(name);
    if(ID == FE_GPU_Command::info->vaos.size()){
        string log = "FE: GPU: WARNING: Vertex Layout - '" + name + "' does not exist\n";
        log += "................. Not setting data of uninitialized vertex layout\n";
        writeToLog(log);
        cout << log << endl;
        return;
    }

    /// bind the dat sh** else the false freaking VAO will be modified
    FE_GPU_VertexLayout vao = FE_GPU_Command::info->vaos[ID];
    glBindVertexArray(vao.vao_id);

    for(size_t x=0; x < inputs.size(); x++){

        /// do error checking
        size_t vbo_id = FE_GPU_Command::info->findVBO(inputs[x].name);
        if(vbo_id == FE_GPU_Command::info->vbos.size()){
            string log = "FE: GPU: WARNING: Vertex Buffer - '" + inputs[x].name + "' does not exist\n";
            log += "................. Not adding a non-existent vertex buffer to vertex layout - '" + name + "'\n";
            writeToLog(log);
            cout << log << endl;
            return;
        }

        glBindBuffer(GL_ARRAY_BUFFER, FE_GPU_Command::info->vbos[vbo_id].vertex_id);
        glVertexAttribPointer(x, inputs[x].amount, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*inputs[x].stride, VERTEXL_LAYOUT_OFFSET(sizeof(GLfloat)*inputs[x].offset));
        glEnableVertexAttribArray(x);
    }
}
void FE_GPU_SetupVAOCMD::flushGL3(FE_GPU_Thread*){}

/** OpenGL implementation of setting VBO data
**/

void FE_GPU_SetVAOIBDataCMD::updateGL3(){

    size_t ID = FE_GPU_Command::info->findVAO(name);
    if(ID == FE_GPU_Command::info->vaos.size()){
        string log = "FE: GPU: WARNING: Vertex Layout - '" + name + "' does not exist\n";
        log += ".................. Not setting data of uninitialized vertex layout\n";
        writeToLog(log);
        cout << log << endl;
        return;
    }

    FE_GPU_VertexLayout vao = FE_GPU_Command::info->vaos[ID];
    vao.capacity = memory_size;

    /// determine usage of the buffer
    GLenum buf_usage;
    switch(usage){
        case FE_GPU_STATIC: buf_usage = GL_STATIC_DRAW; break;
        case FE_GPU_DYNAMIC: buf_usage = GL_DYNAMIC_DRAW; break;
        case FE_GPU_STREAM: buf_usage = GL_STREAM_DRAW; break;
        default: buf_usage = GL_STATIC_DRAW;
    }
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vao.ib_id);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, memory_size*sizeof(GLuint), NULL, buf_usage);
}
void FE_GPU_SetVAOIBDataCMD::flushGL3(FE_GPU_Thread*){}

/**
  */
void FE_GPU_SetVAOIBSubDataCMD::updateGL3(){

    size_t ID = FE_GPU_Command::info->findVAO(name);
    if(ID == FE_GPU_Command::info->vaos.size()){
        string log = "FE: GPU: WARNING: Vertex Buffer - '" + name + "' does not exist\n";
        log += "................. Not setting data of uninitialized vertex buffer\n";
        writeToLog(log);
        cout << log << endl;
        return;
    }
    FE_GPU_VertexLayout vao = FE_GPU_Command::info->vaos[ID];

    /// copy to c-array
    GLuint actual_data[data.size()];
    copy(data.begin(), data.end(), actual_data);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vao.ib_id);
    glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, sizeof(actual_data), actual_data);
}

void FE_GPU_SetVAOIBSubDataCMD::flushGL3(FE_GPU_Thread*){}

void FE_GPU_DestroyVAOCMD::updateGL3(){

    size_t ID = FE_GPU_Command::info->findVAO(name);
    if(ID == FE_GPU_Command::info->vaos.size()){
        string log = "FE: GPU: WARNING: Vertex Buffer - '" + name + "' does not exist\n";
        log += "................. Not destroying uninitialized vertex buffer\n";
        writeToLog(log);
        cout << log << endl;
        return;
    }
    FE_GPU_VertexLayout vao = FE_GPU_Command::info->vaos[ID];

    glDeleteVertexArrays(1, &vao.vao_id);
    glDeleteBuffers(1, &vao.ib_id);
}

void FE_GPU_DestroyVAOCMD::flushGL3(FE_GPU_Thread*){}
//#endif


text:
using namespace muduo;
using namespace muduo::net;

class SudokuServer
{
 public:
  SudokuServer(EventLoop* loop, const InetAddress& listenAddr, int numThreads)
    : server_(loop, listenAddr, "SudokuServer"),
      numThreads_(numThreads),
      startTime_(Timestamp::now())
  {
    server_.setConnectionCallback(
        std::bind(&SudokuServer::onConnection, this, _1));
    server_.setMessageCallback(
        std::bind(&SudokuServer::onMessage, this, _1, _2, _3));
    server_.setThreadNum(numThreads);
  }

  void start()
  {
    LOG_INFO << "starting " << numThreads_ << " threads.";
    server_.start();
  }

 private:
  void onConnection(const TcpConnectionPtr& conn)
  {
    LOG_TRACE << conn->peerAddress().toIpPort() << " -> "
        << conn->localAddress().toIpPort() << " is "
        << (conn->connected() ? "UP" : "DOWN");
  }

  void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp)
  {
    LOG_DEBUG << conn->name();
    size_t len = buf->readableBytes();
    while (len >= kCells + 2)
    {
      const char* crlf = buf->findCRLF();
      if (crlf)
      {
        string request(buf->peek(), crlf);
        buf->retrieveUntil(crlf + 2);
        len = buf->readableBytes();
        if (!processRequest(conn, request))
        {
          conn->send("Bad Request!\r\n");
          conn->shutdown();
          break;
        }
      }
      else if (len > 100) // id + ":" + kCells + "\r\n"
      {
        conn->send("Id too long!\r\n");
        conn->shutdown();
        break;
      }
      else
      {
        break;
      }
    }
  }

  bool processRequest(const TcpConnectionPtr& conn, const string& request)
  {
    string id;
    string puzzle;
    bool goodRequest = true;

    string::const_iterator colon = find(request.begin(), request.end(), ':');
    if (colon != request.end())
    {
      id.assign(request.begin(), colon);
      puzzle.assign(colon+1, request.end());
    }
    else
    {
      puzzle = request;
    }

    if (puzzle.size() == implicit_cast<size_t>(kCells))
    {
      LOG_DEBUG << conn->name();
      string result = solveSudoku(puzzle);
      if (id.empty())
      {
        conn->send(result+"\r\n");
      }
      else
      {
        conn->send(id+":"+result+"\r\n");
      }
    }
    else
    {
      goodRequest = false;
    }
    return goodRequest;
  }

  TcpServer server_;
  int numThreads_;
  Timestamp startTime_;
};

int main(int argc, char* argv[])
{
  LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid();
  int numThreads = 0;
  if (argc > 1)
  {
    numThreads = atoi(argv[1]);
  }
  EventLoop loop;
  InetAddress listenAddr(9981);
  SudokuServer server(&loop, listenAddr, numThreads);

  server.start();

  loop.loop();
}


text:
"""
VMware vRealize Workflow implementation and supporting objects.

Copyright (c) 2017, Lior P. Abitbol <liorabitbol@gmail.com>
"""

import logging
import requests
import time

from .config import URL_RUN_WORKFLOW_BY_ID
from .utils import format_url

class WorkflowRunError(Exception):
    """Workflow Run Exception."""
    pass

class Workflow:

    @property
    def description(self):
        return self._description

    @property
    def has_input_parameters(self):
        if len(self._input_parameters) > 0:
            return True
        return False

    @property
    def href(self):
        return self._href

    @property
    def id(self):
        return self._id

    @property
    def input_parameters(self):
        return self._input_parameters

    @property
    def name(self):
        return self._name

    @property
    def version(self):
        return self._version

    def __init__(self, session):
        """
        Returns a new Workflow instance.

        :param session:
         Session object contains vRO appliance and authentication data.
        """
        self.log = logging.getLogger(__class__.__name__)

        self._jdata = None
        self._description = None
        self._name = None
        self._href = None
        self._id = None
        self._version = None
        self._input_parameters = WorkflowParameters()

        if session.url is None or session.basic_auth is None:
            self.log.error("Session object is invalid, it is missing Url and/or authentication data.")
            raise ValueError("Session object is invalid!")

        self.session = session

    def _get_input_parameters(self):
        coll = WorkflowParameters()
        if self._jdata.get("input-parameters"):
            for p in self._jdata.get("input-parameters"):
                coll.add(name=p.get("name"),
                         value=p.get("value"),
                         _type=p.get("type"),
                         description=p.get("description"))
        return coll

    def load_from_json(self, data):
        """
        Loads Workflow data into this instance from JSON.

        :param data:
         A JSON representation of a vRO Workflow.
        """
        self._jdata = data

        try:
            self._description = data.get("description")
            self._name = data.get("name")
            self._href = data.get("href")
            self._id = data.get("id")
            self._version = data.get("version")
            self._input_parameters = self._get_input_parameters()
        except Exception as ex:
            self.log.error("Error reading JSON attributes: %s" % ex)

    def json(self):
        """Returns this instance in JSON."""
        return self._jdata

    def start(self, params=None):
        """
        Starts the Workflow.

        :param params:
         A WorkflowParameters object.
        """
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

        if params is None:
            data = "{}"
        else:
            if type(params) is not WorkflowParameters:
                raise ValueError("Expected a WorkflowParameters object!")
            data = params.to_json()

        url = format_url(URL_RUN_WORKFLOW_BY_ID,
                         base_url=self.session.url,
                         id=self.id)

        r = requests.post(url,
                          auth=self.session.basic_auth,
                          verify=self.session.verify_ssl,
                          headers=headers,
                          data=data)

        r.raise_for_status()

        if r.status_code == 202:
            print(r.headers.get("Location"))
            run = WorkflowRun(session=self.session)
            run.href = r.headers.get("Location")
            run.update()
            return run

        raise WorkflowRunError("Failed to start Workflow!")

class _WorkflowParameter:

    def __init__(self, name=None, value=None, _type=None, scope=None, description=None):
        """
        Returns a new _WorkflowParameter instance.

        :param name: parameter name
        :param value:  parameter value
        :param _type: parameter value
        :param scope: parameter scope
        :param description: parameter description
        """
        self.name = name
        self.value = value
        self.type = _type
        self.scope = scope
        self.description = description

class WorkflowParameters:

    def __init__(self):
        """Returns a new WorkflowParameters instance.

        This collection object holds one or more vRO parameters.
        """
        self._params = list()

    def __len__(self):
        return len(self._params)

    def __iter__(self):
        for param in self._params:
            yield param

    def add(self, name, value, _type="string", scope="local", description=None):
        """
        Add a parameter to the collection.

        :param name: parameter name
        :param value: parameter value
        :param _type: parameter type, default is 'string'
        :param scope: parameter scope, default is 'local'
        :param description: parameter description, default is None
        """
        self._params.append(_WorkflowParameter(name, value, _type, scope, description))

    def to_json(self):
        """Returns this instance in JSON format."""
        data = '{"parameters":['

        num_of_params = len(self._params)
        cur_param = 1

        for param in self._params:
            data += '{"type":"%s","scope":"%s","name":"%s","description":"%s","value":{"%s":{"value":"%s"}}}' % (
                param.type, param.scope, param.name, param.description, param.type, param.value
            )
            if cur_param < num_of_params:
                data += ","
            cur_param += 1

        data += "]}"

        return data

    def to_xml(self):
        """Returns this instance in XML format."""
        data = '<execution-context xmlns="http://www.vmware.com/vco"><parameters>'

        for param in self._parameters:
            data += '<parameter name="%s" type="%s"><%s>%s</%s></parameter>' % (
                param.name, param.type, param.type, param.value, param.type
            )

        data += '</parameters></execution-context>'

        return data

class WorkflowRun:

    @property
    def end_date(self):
        return self._end_date

    @property
    def href(self):
        return self._href

    @href.setter
    def href(self, value):
        self._href = value

    @property
    def id(self):
        return self._id

    @property
    def name(self):
        return self._name

    @property
    def start_date(self):
        return self._start_date

    @property
    def started_by(self):
        return self._started_by

    @property
    def state(self):
        return self._state

    def __init__(self, session):
        """Returns a new WorkflowRun instance.

        WorkflowRun objects are returned by Workflow when they are started.

        :param session:
        """
        self.log = logging.getLogger(__class__.__name__)

        if session.url is None or session.basic_auth is None:
            self.log.error("Session object is invalid, missing Url and/or basic authentication!")
            raise ValueError("Session object is invalid!")

        self.session = session
        self.log.debug("Session.url = %s" % session.url)

        # Initialize instance attributes
        self._jdata = None
        self._end_date = None
        self._href = None
        self._id = None
        self._name = None
        self._start_date = None
        self._started_by = None
        self._state = None

    def load_from_json(self, data):
        """Load Workflow Run data from JSON."""
        self._jdata = data

        self._end_date = self._jdata.get("end-date")
        self._href = self._jdata.get("href")
        self._id = self._jdata.get("id")
        self._name = self._jdata.get("name")
        self._start_date = self._jdata.get("start-date")
        self._started_by = self._jdata.get("started-by")
        self._state = self._jdata.get("state")

    def wait_until_complete(self, timeout=300, poll=10, states=[]):
        """Wait until this Workflow Run instance completes, cancels or fails.

        :param timeout:
         The timeout (in seconds) to wait before giving up.
         By default, timeout is 300 seconds. Timeout rate must be 5
         or more seconds, and greater than poll rate.

        :param poll:
         The poll rate (in seconds) to check the Workflow run state.
         By default, poll rate is 10 seconds. Poll rate must be 1 or
         more seconds, and less than timeout rate.

        :param states:
         A list of Workflow states to check against while waiting.
         If the state matches the Workflow Run State, this method
         will complete.
         By default, this method will check for the following states:
         - completed
         - canceled
         - failed
        """
        if timeout < 5:
            raise ValueError("Timeout must be 5 or more seconds!")
        if poll < 1:
            raise ValueError("Poll rate must be 1 or more seconds!")
        if poll > timeout:
            raise ValueError("Poll rate cannot be greater than timeout!")

        finished_states = ["completed", "canceled", "failed"]

        current_try = 0
        retries = int(timeout/poll)
        end = False

        self.log.debug("Wait settings: Timeout=%s | Poll=%s | Retry=%s of %s" %
                       (timeout, poll, current_try, retries))

        while end is not True:
            current_try += 1
            self.update()

            if self.state in finished_states:
                end = True
            elif len(states) > 0 and self.state in states:
                end = True
            elif current_try >= retries:
                end = True
            else:
                time.sleep(poll)

    def update(self):
        """Update the state, logs and content of this Workflow Run."""
        if self.href is None:
            raise ValueError("Cannot update Workflow Run, 'href' data is not defined!")

        r = requests.get(self.href,
                         auth=self.session.basic_auth,
                         verify=self.session.verify_ssl,
                         headers={"Content-Type": "application/json"})

        r.raise_for_status()

        self.load_from_json(r.json())


text:
package uk.ac.york.gjc510.battle.space;

import uk.ac.york.gjc510.battle.ship.Ship;

public interface Space
{
	public Ship get(short x, short y);

	public void set(short x, short y, Ship ship);

	public void add(short x, short y, Ship ship);

	public void del(short x, short y);

	public Ship[][] raw();
}


text:
var behest = require('behest');
var omdb = require('omdb');

function plugin() {
  return function(irc) {
    irc.on('message', function(evt) {
      var from = evt.from;
      var to = evt.to;
      var message = evt.message;

      if (!behest.isValid(message)) {
        return;
      }

      var command = behest(message);
      if (command.command === 'movie') {
        var destination = to.charAt(0) === '#' ? to : from;

        omdb.get(command.params.join(' '), function(error, movie) {
          if (error) {
            irc.send(destination, 'Error looking up movie.');
            return;
          }

          if (!movie) {
            irc.send(destination, 'Movie not found.');
            return;
          }

          irc.send(destination, movie.title + ' (' + movie.year + ')');
          irc.send(destination, '| ' + movie.imdb.rating + '/10');
          irc.send(destination, '| ' + movie.genres.join(', '));
          irc.send(destination, '| http://imdb.com/title/' + movie.imdb.id);
        });
      }
    });
  };
}

module.exports = plugin;


text:
This solution shows a method for creating a chat room within a SharePoint web part.  The solution uses details from the user's
profile to identify the sender of the message and uses SignalR to push messages out to each instance of the chat room.

### Full walkthrough ###

A full walkthrough of the development process (including deployment to Azure) can be found at -
[http://blog.jonathanhuss.com/building-a-sharepoint-online-chat-room-with-signalr-and-azure](http://blog.jonathanhuss.com/building-a-sharepoint-online-chat-room-with-signalr-and-azure)

### Applies to ###
- Office 365 / SharePoint Online

### Prerequisites ###
N/A

### Solution ###
Solution | Author(s)
---------|----------
BusinessApps.ChatRoom | Jonathan Huss (**Microsoft**)

### Version history ###

Version  | Date | Comments
---------| -----| --------
1.0 | April 3rd, 2015 | Initial Release

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

----------

### User Interface ###

The user interface is fairly simply, but could be extended heavily.  The user inferface contains a message window, a message
input box, and send button.  As messages are received from SignalR, they're added to the message window.  Timestamps are
also added to the messages that are localized to the client's timezone via JavaScript.  Deployed as a web part, the rendered
user interface looks like this:

![The web page which shows the chat interface](http://blog.jonathanhuss.com/wp-content/uploads/2015/04/image_thumb29.png)

### SignalR Bits ###
The SignalR components in this solution consist of a server and a client.  The server is contained in the ChatHub.cs C# class
and defines the operations that can occur between server and client.  In this case, we've defined three operations:  joinRoom,
pushMessage, and leaveRoom.  When messages are sent from the chat room, they're passed to the server using standard AJAX
calls.  The server then pushes those messages out to the other members of the chat room using SignalR.

The server side SignalR code looks like this:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace BusinessApps.ChatRoomWeb.Hubs
{
    public class ChatHub : Hub
    {
        public void PushMessage(string userName, string photoUrl, string timestamp, string message)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.pushMessage(userName, photoUrl, timestamp, message);
        }

        public void JoinRoom(string userName)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.joinRoom(userName);
        }

        public void LeaveRoom(string userName)
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.leaveRoom(userName);
        }
    }
}
```

The client side code is in JavaScript and contains definitions that match the three operations defined in the ChatHub.  The
relevant client side code looks like this:

```
function StartHub() {
    var chatHub = $.connection.chatHub;

    chatHub.client.pushMessage = function (userName, photoUrl, timeStamp, message) {
        ReceiveMessage(userName, photoUrl, timeStamp, message);
    };

    chatHub.client.joinRoom = function (userName) {
        ReceiveJoinRoom(userName);
    };

    chatHub.client.leaveRoom = function (userName) {
        ReceiveLeaveRoom(userName);
    };

    $.connection.hub.start();
}

function SendMessage() {
    var textBox = $("#message-box textarea");

    if (textBox.val() != "") {
        $.ajax({
            type: "GET",
            url: "/Home/SendMessage" + location.search + "&message=" + textBox.val(),
            cache: false
        });

        textBox.val("");
    }

    textBox.focus();
}

function ReceiveMessage(userName, photoUrl, timeStamp, message) {
    var localTimeStamp = new Date(timeStamp + " UTC");

    AddMessage(
        '<div class=\'message\'>' +
            '<img class=\'message-sender-image\' src=\'' + photoUrl + '\' alt=\'Photo of ' + userName + '\'/>' +
            '<div class=\'message-right\'>' +
                '<div class=\'message-sender\'>' + userName + '</div>' +
                '<div class=\'message-timestamp\'>' + localTimeStamp.toLocaleTimeString() + '</div>' +
                '<div class=\'message-content\'>' + message + '</div>' +
            '</div>' +
        '</div>'
        );
}

function ReceiveJoinRoom(userName) {
    AddMessage(
            '<div class=\'system-message\'>' +
                userName + " has joined the room." +
            '</div>'
            );
}

function ReceiveLeaveRoom(userName) {
    AddMessage(
            '<div class=\'system-message\'>' +
                userName + " has left the room." +
            '</div>'
            );
}
```

### Server Side Operations ###

When a user joins the chat room, the Controller connects to SharePoint to retrieve the user's DisplayName and Email properties.
It then creates a URL to the user's profile image based on the Email property.  The DisplayName and PhotoUrl are then
cached for retrieval later.  When the user sends a message, that information is retrieved from the cache, and, along with
the message itself, is pushed out to the other users of the chat room.  The relevant Controller code looks like this:

```
[SharePointContextFilter]
public void SendMessage(string message)
{
    if (Session["UserAccountName"] == null || HttpRuntime.Cache[Session["UserAccountName"].ToString()] == null)
        GetUserDetails();

    UserInfo userInfo = (UserInfo)HttpRuntime.Cache[Session["UserAccountName"].ToString()];

    _chatHub.PushMessage(userInfo.DisplayName, userInfo.PhotoUrl, DateTime.UtcNow.ToString(), message);
}

private void GetUserDetails()
{
    var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

    using (var clientContext = spContext.CreateUserClientContextForSPHost())
    {
        if (clientContext != null)
        {
            PeopleManager peopleManager = new PeopleManager(clientContext);
            PersonProperties properties = peopleManager.GetMyProperties();
            clientContext.Load(properties);
            clientContext.ExecuteQuery();

            UserInfo userInfo = new UserInfo()
            {
                DisplayName = properties.DisplayName,
                PhotoUrl = spContext.SPHostUrl + "/_layouts/userphoto.aspx?accountname=" + properties.Email,
                LastPing = DateTime.Now
            };

            HttpRuntime.Cache.Add(properties.AccountName, userInfo, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 3, 0), CacheItemPriority.Normal, new CacheItemRemovedCallback(CacheRemovalCallback));

            Session["UserAccountName"] = properties.AccountName;
        }
    }
}
```

### Pinging ###

One of the challenges is detecting when a user leaves the chat room.  If the user simply clicks on a link to another page,
that is easy to catch via JavaScript.  However, if they close the browser entirely, that is undetectable.  The solution
is to have the client side code ping the server periodically, letting the server know the client is still connected -
much like the idea of a [heartbeat](http://en.wikipedia.org/wiki/Heartbeat_%28computing%29).  The cache is configured
for a 3 minute sliding expiration.  When the ping is received, the sliding expiration window in the cache is extended.
Depending on the exact sliding window, if 8 or 9 consecutive pings are missed, the server expires the cache entry and assumes
that the user has left the chat room, resulting in a leaveRoom SignalR message being sent.

<img src="https://telemetry.sharepointpnp.com/pnp/samples/BusinessApps.ChatRoom" />


text:
<?php

  // Sets the variables $host, $database, $user, $password
	if( (include '../config/config.php') === false) {
		throw new Exception("The config/config.php is missing! No information about database available.");
	}

	// mysql_connect - call for compatibility-reasons. The API is deprecated (http://php.net/manual/de/function.mysql-connect.php)
    $connection = mysql_connect($host, $user, $password);
    if(!$connection) {
		//throw new Exception("Unable to connect! Please check username and password");
	 }

    if(!mysql_select_db($database)) {
    	throw new Exception("Requested database does not exist!");
	}

	$db = new PDO("mysql:host=$host;dbname=$database", $user, $password);

	return $db;


text:
import gym
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union

from ray.rllib.models.catalog import ModelCatalog
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.torch.torch_action_dist import TorchDistributionWrapper
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.policy.policy import Policy, LEARNER_STATS_KEY
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.policy.torch_policy import TorchPolicy
from ray.rllib.policy.view_requirement import ViewRequirement
from ray.rllib.utils import add_mixins, force_list
from ray.rllib.utils.annotations import override, DeveloperAPI
from ray.rllib.utils.framework import try_import_torch
from ray.rllib.utils.torch_ops import convert_to_non_torch_type
from ray.rllib.utils.typing import TensorType, TrainerConfigDict

torch, _ = try_import_torch()

@DeveloperAPI
def build_torch_policy(
        name: str,
        *,
        loss_fn: Optional[Callable[[
            Policy, ModelV2, Type[TorchDistributionWrapper], SampleBatch
        ], Union[TensorType, List[TensorType]]]],
        get_default_config: Optional[Callable[[], TrainerConfigDict]] = None,
        stats_fn: Optional[Callable[[Policy, SampleBatch], Dict[
            str, TensorType]]] = None,
        postprocess_fn: Optional[Callable[[
            Policy, SampleBatch, Optional[Dict[Any, SampleBatch]], Optional[
                "MultiAgentEpisode"]
        ], SampleBatch]] = None,
        extra_action_out_fn: Optional[Callable[[
            Policy, Dict[str, TensorType], List[TensorType], ModelV2,
            TorchDistributionWrapper
        ], Dict[str, TensorType]]] = None,
        extra_grad_process_fn: Optional[Callable[[
            Policy, "torch.optim.Optimizer", TensorType
        ], Dict[str, TensorType]]] = None,
        # TODO: (sven) Replace "fetches" with "process".
        extra_learn_fetches_fn: Optional[Callable[[Policy], Dict[
            str, TensorType]]] = None,
        optimizer_fn: Optional[Callable[[Policy, TrainerConfigDict],
                                        "torch.optim.Optimizer"]] = None,
        validate_spaces: Optional[Callable[
            [Policy, gym.Space, gym.Space, TrainerConfigDict], None]] = None,
        before_init: Optional[Callable[
            [Policy, gym.Space, gym.Space, TrainerConfigDict], None]] = None,
        before_loss_init: Optional[Callable[[
            Policy, gym.spaces.Space, gym.spaces.Space, TrainerConfigDict
        ], None]] = None,
        after_init: Optional[Callable[
            [Policy, gym.Space, gym.Space, TrainerConfigDict], None]] = None,
        _after_loss_init: Optional[Callable[[
            Policy, gym.spaces.Space, gym.spaces.Space, TrainerConfigDict
        ], None]] = None,
        action_sampler_fn: Optional[Callable[[TensorType, List[
            TensorType]], Tuple[TensorType, TensorType]]] = None,
        action_distribution_fn: Optional[Callable[[
            Policy, ModelV2, TensorType, TensorType, TensorType
        ], Tuple[TensorType, type, List[TensorType]]]] = None,
        make_model: Optional[Callable[[
            Policy, gym.spaces.Space, gym.spaces.Space, TrainerConfigDict
        ], ModelV2]] = None,
        make_model_and_action_dist: Optional[Callable[[
            Policy, gym.spaces.Space, gym.spaces.Space, TrainerConfigDict
        ], Tuple[ModelV2, Type[TorchDistributionWrapper]]]] = None,
        apply_gradients_fn: Optional[Callable[
            [Policy, "torch.optim.Optimizer"], None]] = None,
        mixins: Optional[List[type]] = None,
        view_requirements_fn: Optional[Callable[[Policy], Dict[
            str, ViewRequirement]]] = None,
        get_batch_divisibility_req: Optional[Callable[[Policy], int]] = None
) -> Type[TorchPolicy]:
    """Helper function for creating a torch policy class at runtime.

    Args:
        name (str): name of the policy (e.g., "PPOTorchPolicy")
        loss_fn (Optional[Callable[[Policy, ModelV2,
            Type[TorchDistributionWrapper], SampleBatch], Union[TensorType,
            List[TensorType]]]]): Callable that returns a loss tensor.
        get_default_config (Optional[Callable[[None], TrainerConfigDict]]):
            Optional callable that returns the default config to merge with any
            overrides. If None, uses only(!) the user-provided
            PartialTrainerConfigDict as dict for this Policy.
        postprocess_fn (Optional[Callable[[Policy, SampleBatch,
            Optional[Dict[Any, SampleBatch]], Optional["MultiAgentEpisode"]],
            SampleBatch]]): Optional callable for post-processing experience
            batches (called after the super's `postprocess_trajectory` method).
        stats_fn (Optional[Callable[[Policy, SampleBatch],
            Dict[str, TensorType]]]): Optional callable that returns a dict of
            values given the policy and training batch. If None,
            will use `TorchPolicy.extra_grad_info()` instead. The stats dict is
            used for logging (e.g. in TensorBoard).
        extra_action_out_fn (Optional[Callable[[Policy, Dict[str, TensorType],
            List[TensorType], ModelV2, TorchDistributionWrapper]], Dict[str,
            TensorType]]]): Optional callable that returns a dict of extra
            values to include in experiences. If None, no extra computations
            will be performed.
        extra_grad_process_fn (Optional[Callable[[Policy,
            "torch.optim.Optimizer", TensorType], Dict[str, TensorType]]]):
            Optional callable that is called after gradients are computed and
            returns a processing info dict. If None, will call the
            `TorchPolicy.extra_grad_process()` method instead.
        # TODO: (sven) dissolve naming mismatch between "learn" and "compute.."
        extra_learn_fetches_fn (Optional[Callable[[Policy],
            Dict[str, TensorType]]]): Optional callable that returns a dict of
            extra tensors from the policy after loss evaluation. If None,
            will call the `TorchPolicy.extra_compute_grad_fetches()` method
            instead.
        optimizer_fn (Optional[Callable[[Policy, TrainerConfigDict],
            "torch.optim.Optimizer"]]): Optional callable that returns a
            torch optimizer given the policy and config. If None, will call
            the `TorchPolicy.optimizer()` method instead (which returns a
            torch Adam optimizer).
        validate_spaces (Optional[Callable[[Policy, gym.Space, gym.Space,
            TrainerConfigDict], None]]): Optional callable that takes the
            Policy, observation_space, action_space, and config to check for
            correctness. If None, no spaces checking will be done.
        before_init (Optional[Callable[[Policy, gym.Space, gym.Space,
            TrainerConfigDict], None]]): Optional callable to run at the
            beginning of `Policy.__init__` that takes the same arguments as
            the Policy constructor. If None, this step will be skipped.
        before_loss_init (Optional[Callable[[Policy, gym.spaces.Space,
            gym.spaces.Space, TrainerConfigDict], None]]): Optional callable to
            run prior to loss init. If None, this step will be skipped.
        after_init (Optional[Callable[[Policy, gym.Space, gym.Space,
            TrainerConfigDict], None]]): DEPRECATED: Use `before_loss_init`
            instead.
        _after_loss_init (Optional[Callable[[Policy, gym.spaces.Space,
            gym.spaces.Space, TrainerConfigDict], None]]): Optional callable to
            run after the loss init. If None, this step will be skipped.
            This will be deprecated at some point and renamed into `after_init`
            to match `build_tf_policy()` behavior.
        action_sampler_fn (Optional[Callable[[TensorType, List[TensorType]],
            Tuple[TensorType, TensorType]]]): Optional callable returning a
            sampled action and its log-likelihood given some (obs and state)
            inputs. If None, will either use `action_distribution_fn` or
            compute actions by calling self.model, then sampling from the
            so parameterized action distribution.
        action_distribution_fn (Optional[Callable[[Policy, ModelV2, TensorType,
            TensorType, TensorType], Tuple[TensorType,
            Type[TorchDistributionWrapper], List[TensorType]]]]): A callable
            that takes the Policy, Model, the observation batch, an
            explore-flag, a timestep, and an is_training flag and returns a
            tuple of a) distribution inputs (parameters), b) a dist-class to
            generate an action distribution object from, and c) internal-state
            outputs (empty list if not applicable). If None, will either use
            `action_sampler_fn` or compute actions by calling self.model,
            then sampling from the parameterized action distribution.
        make_model (Optional[Callable[[Policy, gym.spaces.Space,
            gym.spaces.Space, TrainerConfigDict], ModelV2]]): Optional callable
            that takes the same arguments as Policy.__init__ and returns a
            model instance. The distribution class will be determined
            automatically. Note: Only one of `make_model` or
            `make_model_and_action_dist` should be provided. If both are None,
            a default Model will be created.
        make_model_and_action_dist (Optional[Callable[[Policy,
            gym.spaces.Space, gym.spaces.Space, TrainerConfigDict],
            Tuple[ModelV2, Type[TorchDistributionWrapper]]]]): Optional
            callable that takes the same arguments as Policy.__init__ and
            returns a tuple of model instance and torch action distribution
            class.
            Note: Only one of `make_model` or `make_model_and_action_dist`
            should be provided. If both are None, a default Model will be
            created.
        apply_gradients_fn (Optional[Callable[[Policy,
            "torch.optim.Optimizer"], None]]): Optional callable that
            takes a grads list and applies these to the Model's parameters.
            If None, will call the `TorchPolicy.apply_gradients()` method
            instead.
        mixins (Optional[List[type]]): Optional list of any class mixins for
            the returned policy class. These mixins will be applied in order
            and will have higher precedence than the TorchPolicy class.
        view_requirements_fn (Optional[Callable[[Policy],
            Dict[str, ViewRequirement]]]): An optional callable to retrieve
            additional train view requirements for this policy.
        get_batch_divisibility_req (Optional[Callable[[Policy], int]]):
            Optional callable that returns the divisibility requirement for
            sample batches. If None, will assume a value of 1.

    Returns:
        Type[TorchPolicy]: TorchPolicy child class constructed from the
            specified args.
    """

    original_kwargs = locals().copy()
    base = add_mixins(TorchPolicy, mixins)

    class policy_cls(base):
        def __init__(self, obs_space, action_space, config):
            if get_default_config:
                config = dict(get_default_config(), **config)
            self.config = config

            if validate_spaces:
                validate_spaces(self, obs_space, action_space, self.config)

            if before_init:
                before_init(self, obs_space, action_space, self.config)

            # Model is customized (use default action dist class).
            if make_model:
                assert make_model_and_action_dist is None, \
                    "Either `make_model` or `make_model_and_action_dist`" \
                    " must be None!"
                self.model = make_model(self, obs_space, action_space, config)
                dist_class, _ = ModelCatalog.get_action_dist(
                    action_space, self.config["model"], framework="torch")
            # Model and action dist class are customized.
            elif make_model_and_action_dist:
                self.model, dist_class = make_model_and_action_dist(
                    self, obs_space, action_space, config)
            # Use default model and default action dist.
            else:
                dist_class, logit_dim = ModelCatalog.get_action_dist(
                    action_space, self.config["model"], framework="torch")
                self.model = ModelCatalog.get_model_v2(
                    obs_space=obs_space,
                    action_space=action_space,
                    num_outputs=logit_dim,
                    model_config=self.config["model"],
                    framework="torch")

            # Make sure, we passed in a correct Model factory.
            assert isinstance(self.model, TorchModelV2), \
                "ERROR: Generated Model must be a TorchModelV2 object!"

            TorchPolicy.__init__(
                self,
                observation_space=obs_space,
                action_space=action_space,
                config=config,
                model=self.model,
                loss=loss_fn,
                action_distribution_class=dist_class,
                action_sampler_fn=action_sampler_fn,
                action_distribution_fn=action_distribution_fn,
                max_seq_len=config["model"]["max_seq_len"],
                get_batch_divisibility_req=get_batch_divisibility_req,
            )

            # Update this Policy's ViewRequirements (if function given).
            if callable(view_requirements_fn):
                self.view_requirements.update(view_requirements_fn(self))
            # Merge Model's view requirements into Policy's.
            self.view_requirements.update(
                self.model.inference_view_requirements)

            _before_loss_init = before_loss_init or after_init
            if _before_loss_init:
                _before_loss_init(self, self.observation_space,
                                  self.action_space, config)

            # Perform test runs through postprocessing- and loss functions.
            self._initialize_loss_from_dummy_batch(
                auto_remove_unneeded_view_reqs=True,
                stats_fn=stats_fn,
            )

            if _after_loss_init:
                _after_loss_init(self, obs_space, action_space, config)

            # Got to reset global_timestep again after this fake run-through.
            self.global_timestep = 0

        @override(Policy)
        def postprocess_trajectory(self,
                                   sample_batch,
                                   other_agent_batches=None,
                                   episode=None):
            # Do all post-processing always with no_grad().
            # Not using this here will introduce a memory leak (issue #6962).
            with torch.no_grad():
                # Call super's postprocess_trajectory first.
                sample_batch = super().postprocess_trajectory(
                    sample_batch, other_agent_batches, episode)
                if postprocess_fn:
                    return postprocess_fn(self, sample_batch,
                                          other_agent_batches, episode)

                return sample_batch

        @override(TorchPolicy)
        def extra_grad_process(self, optimizer, loss):
            """Called after optimizer.zero_grad() and loss.backward() calls.

            Allows for gradient processing before optimizer.step() is called.
            E.g. for gradient clipping.
            """
            if extra_grad_process_fn:
                return extra_grad_process_fn(self, optimizer, loss)
            else:
                return TorchPolicy.extra_grad_process(self, optimizer, loss)

        @override(TorchPolicy)
        def extra_compute_grad_fetches(self):
            if extra_learn_fetches_fn:
                fetches = convert_to_non_torch_type(
                    extra_learn_fetches_fn(self))
                # Auto-add empty learner stats dict if needed.
                return dict({LEARNER_STATS_KEY: {}}, **fetches)
            else:
                return TorchPolicy.extra_compute_grad_fetches(self)

        @override(TorchPolicy)
        def apply_gradients(self, gradients):
            if apply_gradients_fn:
                apply_gradients_fn(self, gradients)
            else:
                TorchPolicy.apply_gradients(self, gradients)

        @override(TorchPolicy)
        def extra_action_out(self, input_dict, state_batches, model,
                             action_dist):
            with torch.no_grad():
                if extra_action_out_fn:
                    stats_dict = extra_action_out_fn(
                        self, input_dict, state_batches, model, action_dist)
                else:
                    stats_dict = TorchPolicy.extra_action_out(
                        self, input_dict, state_batches, model, action_dist)
                return convert_to_non_torch_type(stats_dict)

        @override(TorchPolicy)
        def optimizer(self):
            if optimizer_fn:
                optimizers = optimizer_fn(self, self.config)
            else:
                optimizers = TorchPolicy.optimizer(self)
            optimizers = force_list(optimizers)
            if getattr(self, "exploration", None):
                optimizers = self.exploration.get_exploration_optimizer(
                    optimizers)
            return optimizers

        @override(TorchPolicy)
        def extra_grad_info(self, train_batch):
            with torch.no_grad():
                if stats_fn:
                    stats_dict = stats_fn(self, train_batch)
                else:
                    stats_dict = TorchPolicy.extra_grad_info(self, train_batch)
                return convert_to_non_torch_type(stats_dict)

    def with_updates(**overrides):
        """Allows creating a TorchPolicy cls based on settings of another one.

        Keyword Args:
            **overrides: The settings (passed into `build_torch_policy`) that
                should be different from the class that this method is called
                on.

        Returns:
            type: A new TorchPolicy sub-class.

        Examples:
        >> MySpecialDQNPolicyClass = DQNTorchPolicy.with_updates(
        ..    name="MySpecialDQNPolicyClass",
        ..    loss_function=[some_new_loss_function],
        .. )
        """
        return build_torch_policy(**dict(original_kwargs, **overrides))

    policy_cls.with_updates = staticmethod(with_updates)
    policy_cls.__name__ = name
    policy_cls.__qualname__ = name
    return policy_cls


text:
package jwthelper

import (
	"net/http"
	"time"
)

// CookieOption represent cookie option.
type CookieOption struct {
	f func(c *http.Cookie)
}

// CookieName returns the option for cookie name.
// It'll use "jwt" as cookie name by default.
func CookieName(name string) CookieOption {
	return CookieOption{func(c *http.Cookie) {
		c.Name = name
	}}
}

// CookiePath returns the option for cookie path.
func CookiePath(path string) CookieOption {
	return CookieOption{func(c *http.Cookie) {
		c.Path = path
	}}
}

// CookieDomain returns the option for cookie domain.
func CookieDomain(domain string) CookieOption {
	return CookieOption{func(c *http.Cookie) {
		c.Domain = domain
	}}
}

// CookieExpires returns the option for cookie expires.
func CookieExpires(expires time.Time) CookieOption {
	return CookieOption{func(c *http.Cookie) {
		c.Expires = expires
	}}
}

// CookieMaxAge returns the option for cookie max age.
func CookieMaxAge(maxAge int) CookieOption {
	return CookieOption{func(c *http.Cookie) {
		c.MaxAge = maxAge
	}}
}

// CookieSecure returns the option for secure cookie.
func CookieSecure(secure bool) CookieOption {
	return CookieOption{func(c *http.Cookie) {
		c.Secure = secure
	}}
}

// CookieHttpOnly returns the option for HTTP only cookie.
func CookieHttpOnly(httpOnly bool) CookieOption {
	return CookieOption{func(c *http.Cookie) {
		c.HttpOnly = httpOnly
	}}
}

// NewCookie news a cookie contains JWT token.
//
//     Params:
//         tokenString: JWT token string. It'll be set as cookie value.
//         options: Cookie options(optional).
//                  Use helper functions to get options: CookieName(), CookieDomain()...
//     Comments:
//         It'll set cookie name to "jwt" if no name option specified.
func NewCookie(tokenString string, options ...CookieOption) *http.Cookie {
	cookie := http.Cookie{
		// Use "jwt" as cookie name by default.
		Name:     "jwt",
		Value:    tokenString,
		Secure:   false,
		HttpOnly: false,
	}

	// Override default cookie with customized options.
	for _, op := range options {
		op.f(&cookie)
	}

	return &cookie
}


text:
/**
	View to display the various itinerary items in a list

	Options
		section		Indicates which section of the itinerary should be highlighted when the view is rendered
						Supply view constants (ItineraryListView.CEREMONY)
						If none is provided, no section will be highlighted

	Triggers
		When any of the itinerary items are clicked, a "click" event is triggered to indicate which item was clicked
		See the view triggers for specific names

*/
define([
	'backbone',
	'marionette',
	'backbone.radio',
	'mixins/MapLocationInfoView/MapLocationInfoView',
	'text!apps/Itinerary/ItineraryListView.html'
], function(
	Backbone,
	Marionette,
	Radio,
	MapLocationInfoView,
	Templates
) {

	// constants representing each itinerary item in the ist
	//	exported as static view constants
	var CEREMONY = "ceremony";
	var RECEPTION = "reception";
	var LODGING = "hotel";
	var REGISTRY = "registry";
	var RSVP = "rsvp";

	return Marionette.View.extend({

		className: "itinerary-list-view",
		template: _.template($(Templates).filter("#itinerary-list-layout").html()),

		regions: {
			details: "section.itinerary-item-details"
		},

		ui: {
			listContainer: "section.itinerary-list",
			ceremony: ".itinerary-list-item.ceremony",
			reception: ".itinerary-list-item.reception",
			lodging: ".itinerary-list-item.hotel",
			registry: ".itinerary-list-item.registry",
			rsvp: ".itinerary-list-item.rsvp",
		},

		triggers: {
			"click @ui.ceremony": "click:ceremony",
			"click @ui.reception": "click:reception",
			"click @ui.lodging": "click:lodging",
			"click @ui.registry": "click:registry",
			"click @ui.rsvp": "click:rsvp"
		},

		/**
			Highlights an itinerary item in the list by the given section ID
			@param	const	sectionID		The section ID of the itinerary item, check view constants (ItineraryListView.CEREMONY, etc.)

		*/
		highlightItinerary: function(sectionID) {

			$(".itinerary-list-item", this.el).removeClass("active");
			$(".itinerary-list-item."+sectionID, this.el).addClass("active");

		},

		/**
		*/
		onClickCeremony: function() {
			this.highlightItinerary(CEREMONY);
			Backbone.history.navigate("ceremony");
			Radio.channel("itinerary").trigger("show:ceremony");
		},

		/**
		*/
		onClickReception: function() {
			this.highlightItinerary(RECEPTION);
			Backbone.history.navigate("reception");
			Radio.channel("itinerary").trigger("show:reception");
		},

		/**
		*/
		onClickLodging: function() {
			this.highlightItinerary(LODGING);
			Backbone.history.navigate("lodging");
			Radio.channel("itinerary").trigger("show:lodging");
		},

		/**
		*/
		onClickRegistry: function() {
			this.highlightItinerary(REGISTRY);
			Backbone.history.navigate("registry");
			Radio.channel("itinerary").trigger("show:registry");
		},

		/**
		*/
		onClickRsvp: function() {
			this.highlightItinerary(RSVP);
			Backbone.history.navigate("rsvp");
			Radio.channel("itinerary").trigger("show:rsvp");
		},

		/**
			Populates the list of itinerary items before the view is attached to the DOM

		*/
		onBeforeAttach: function() {

			// template to render itinerary items with a subheading
			var listItemTemplate = _.template($(Templates).filter("#itinerary-list-item").html());

			// template to render itinerary items with informational text
			var listItemInfoTemplate = _.template($(Templates).filter("#itinerary-list-info-item").html());

			// template to render itinerary items with informational text and no link
			var listItemInfoNoLinkTemplate = _.template($(Templates).filter("#itinerary-list-info-item-no-link").html());

			this.$el.append(listItemTemplate({
				class_name: "ceremony",
				heading: "2:00pm Ceremony",
				subheading: "Cave Spring Vineyard",
				action: "Tap for directions",
				href: "#ceremony"
			}));

			this.$el.append(listItemTemplate({
				class_name: "reception",
				heading: "5:00pm Reception",
				subheading: "Inn on the Twenty",
				action: "Tap for directions and menu",
				href: "#reception"
			}));

			this.$el.append(listItemInfoTemplate({
				class_name: "hotel",
				heading: "Where to Stay",
				information: "Rooms have been held at both Inn on the Twenty as well as the Jordan House.",
				action: "Tap for booking information",
				href: "#lodging"
			}));

			this.$el.append(listItemTemplate({
				class_name: "registry",
				heading: "Registry",
				subheading: "Hudson's Bay",
				action: "Tap for information",
				href: "#registry"
			}));

			this.$el.append(listItemInfoTemplate({
				class_name: "rsvp",
				heading: "RSVP",
				information: "Please respond by August 4th.",
				action: "Tap for information",
				href: "#rsvp"
			}));

			// highlight the appropriate section, if one was specified
			if (!_.isUndefined(this.options.section)) {
				this.highlightItinerary(this.options.section);
			}

		}

	}, {
		CEREMONY: CEREMONY,
		RECEPTION: RECEPTION,
		LODGING: LODGING,
		REGISTRY: REGISTRY,
		RSVP: RSVP,
	});

});


text:
import os

import pytest

import vaping
from vaping import plugin
from vaping.config import parse_interval

def test_parse_interval():
    assert 1 == parse_interval("1s")
    assert 0.5 == parse_interval("500ms")
    assert 300 == parse_interval("5m")
    assert 3600 == parse_interval("1h")
    assert 86400 == parse_interval("1d")

    assert 90 == parse_interval("1m30s")
    assert 90.5 == parse_interval("1m30.5s")
    assert 3661 == parse_interval("1h1m1s")
    assert 86401 == parse_interval("1d1s")
    assert 1800 == parse_interval("0.5h")

    with pytest.raises(ValueError):
        parse_interval("1x")

def test_probe_plugin_name(config_dir):
    """
    checks that vaping correct errors if a probe is named the same as a plugin
    """
    config_dir = os.path.join(config_dir, "dupe")

    with pytest.raises(ValueError) as excinfo:
        vaping.daemon.Vaping(config_dir=config_dir)
    assert "probes may not share names with plugins" in str(excinfo.value)

def test_plugin_legacy_groups():

    """
    test legacy plugin groups
    TODO: remove with vaping 2.0
    """

    probe = plugin.get_probe(
        {
            "type": "fping",
            "name": "probe_b",
            "interval": "3s",
            "dns": {"hosts": [{"host": "1.1.1.1", "name": "Cloudflare"}]},
        },
        {},
    )

    expected = {"dns": {"hosts": [{"host": "1.1.1.1", "name": "Cloudflare"}]}}

    assert probe.groups == expected

def test_plugin_groups():

    """
    test plugin groups as per #44 implementation
    """

    probe = plugin.get_probe(
        {
            "type": "fping",
            "name": "probe_c",
            "interval": "3s",
            "groups": [
                {"name": "dns", "hosts": [{"host": "1.1.1.1", "name": "Cloudflare"}]}
            ],
        },
        {},
    )

    expected = {
        "dns": {"name": "dns", "hosts": [{"host": "1.1.1.1", "name": "Cloudflare"}]}
    }

    assert probe.groups == expected


text:
var connect = require('connect'),
	api = require('./api'),
	port = parseInt(process.env.PORT) || 8000;

var server = connect.createServer(
	connect.logger(),
	connect.errorHandler({ dumpExceptions: true, showStack: true })
);
// Serve static resources.
server.use("/",
    connect.conditionalGet(),
    connect.cache(),
    connect.gzip(),
	connect.staticProvider(__dirname + '/public')
);
// Serve the API responses.
server.use("/api",
	connect.bodyDecoder(),
	connect.cookieDecoder(),
	connect.router(api.router)
);
server.listen(port);
console.log('Nodify server running at http://127.0.0.1:' + port);

process.addListener('uncaughtException', function (err) {
	console.log(err.stack);
});


text:
#pragma once
#include <aws/codepipeline/CodePipeline_EXPORTS.h>
#include <aws/codepipeline/CodePipelineRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/codepipeline/model/StageRetryMode.h>
#include <utility>

namespace Aws
{
namespace CodePipeline
{
namespace Model
{

  /**
   *
Represents the input of a RetryStageExecution
   * action.

See Also:
   AWS
   * API Reference

   */
  class AWS_CODEPIPELINE_API RetryStageExecutionRequest : public CodePipelineRequest
  {
  public:
    RetryStageExecutionRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "RetryStageExecution"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the pipeline that contains the failed stage.

     */
    inline const Aws::String& GetPipelineName() const{ return m_pipelineName; }

    /**
     *
The name of the pipeline that contains the failed stage.

     */
    inline bool PipelineNameHasBeenSet() const { return m_pipelineNameHasBeenSet; }

    /**
     *
The name of the pipeline that contains the failed stage.

     */
    inline void SetPipelineName(const Aws::String& value) { m_pipelineNameHasBeenSet = true; m_pipelineName = value; }

    /**
     *
The name of the pipeline that contains the failed stage.

     */
    inline void SetPipelineName(Aws::String&& value) { m_pipelineNameHasBeenSet = true; m_pipelineName = std::move(value); }

    /**
     *
The name of the pipeline that contains the failed stage.

     */
    inline void SetPipelineName(const char* value) { m_pipelineNameHasBeenSet = true; m_pipelineName.assign(value); }

    /**
     *
The name of the pipeline that contains the failed stage.

     */
    inline RetryStageExecutionRequest& WithPipelineName(const Aws::String& value) { SetPipelineName(value); return *this;}

    /**
     *
The name of the pipeline that contains the failed stage.

     */
    inline RetryStageExecutionRequest& WithPipelineName(Aws::String&& value) { SetPipelineName(std::move(value)); return *this;}

    /**
     *
The name of the pipeline that contains the failed stage.

     */
    inline RetryStageExecutionRequest& WithPipelineName(const char* value) { SetPipelineName(value); return *this;}

    /**
     *
The name of the failed stage to be retried.

     */
    inline const Aws::String& GetStageName() const{ return m_stageName; }

    /**
     *
The name of the failed stage to be retried.

     */
    inline bool StageNameHasBeenSet() const { return m_stageNameHasBeenSet; }

    /**
     *
The name of the failed stage to be retried.

     */
    inline void SetStageName(const Aws::String& value) { m_stageNameHasBeenSet = true; m_stageName = value; }

    /**
     *
The name of the failed stage to be retried.

     */
    inline void SetStageName(Aws::String&& value) { m_stageNameHasBeenSet = true; m_stageName = std::move(value); }

    /**
     *
The name of the failed stage to be retried.

     */
    inline void SetStageName(const char* value) { m_stageNameHasBeenSet = true; m_stageName.assign(value); }

    /**
     *
The name of the failed stage to be retried.

     */
    inline RetryStageExecutionRequest& WithStageName(const Aws::String& value) { SetStageName(value); return *this;}

    /**
     *
The name of the failed stage to be retried.

     */
    inline RetryStageExecutionRequest& WithStageName(Aws::String&& value) { SetStageName(std::move(value)); return *this;}

    /**
     *
The name of the failed stage to be retried.

     */
    inline RetryStageExecutionRequest& WithStageName(const char* value) { SetStageName(value); return *this;}

    /**
     *
The ID of the pipeline execution in the failed stage to be retried. Use the
     * GetPipelineState action to retrieve the current pipelineExecutionId of
     * the failed stage

     */
    inline const Aws::String& GetPipelineExecutionId() const{ return m_pipelineExecutionId; }

    /**
     *
The ID of the pipeline execution in the failed stage to be retried. Use the
     * GetPipelineState action to retrieve the current pipelineExecutionId of
     * the failed stage

     */
    inline bool PipelineExecutionIdHasBeenSet() const { return m_pipelineExecutionIdHasBeenSet; }

    /**
     *
The ID of the pipeline execution in the failed stage to be retried. Use the
     * GetPipelineState action to retrieve the current pipelineExecutionId of
     * the failed stage

     */
    inline void SetPipelineExecutionId(const Aws::String& value) { m_pipelineExecutionIdHasBeenSet = true; m_pipelineExecutionId = value; }

    /**
     *
The ID of the pipeline execution in the failed stage to be retried. Use the
     * GetPipelineState action to retrieve the current pipelineExecutionId of
     * the failed stage

     */
    inline void SetPipelineExecutionId(Aws::String&& value) { m_pipelineExecutionIdHasBeenSet = true; m_pipelineExecutionId = std::move(value); }

    /**
     *
The ID of the pipeline execution in the failed stage to be retried. Use the
     * GetPipelineState action to retrieve the current pipelineExecutionId of
     * the failed stage

     */
    inline void SetPipelineExecutionId(const char* value) { m_pipelineExecutionIdHasBeenSet = true; m_pipelineExecutionId.assign(value); }

    /**
     *
The ID of the pipeline execution in the failed stage to be retried. Use the
     * GetPipelineState action to retrieve the current pipelineExecutionId of
     * the failed stage

     */
    inline RetryStageExecutionRequest& WithPipelineExecutionId(const Aws::String& value) { SetPipelineExecutionId(value); return *this;}

    /**
     *
The ID of the pipeline execution in the failed stage to be retried. Use the
     * GetPipelineState action to retrieve the current pipelineExecutionId of
     * the failed stage

     */
    inline RetryStageExecutionRequest& WithPipelineExecutionId(Aws::String&& value) { SetPipelineExecutionId(std::move(value)); return *this;}

    /**
     *
The ID of the pipeline execution in the failed stage to be retried. Use the
     * GetPipelineState action to retrieve the current pipelineExecutionId of
     * the failed stage

     */
    inline RetryStageExecutionRequest& WithPipelineExecutionId(const char* value) { SetPipelineExecutionId(value); return *this;}

    /**
     *
The scope of the retry attempt. Currently, the only supported value is
     * FAILED_ACTIONS.

     */
    inline const StageRetryMode& GetRetryMode() const{ return m_retryMode; }

    /**
     *
The scope of the retry attempt. Currently, the only supported value is
     * FAILED_ACTIONS.

     */
    inline bool RetryModeHasBeenSet() const { return m_retryModeHasBeenSet; }

    /**
     *
The scope of the retry attempt. Currently, the only supported value is
     * FAILED_ACTIONS.

     */
    inline void SetRetryMode(const StageRetryMode& value) { m_retryModeHasBeenSet = true; m_retryMode = value; }

    /**
     *
The scope of the retry attempt. Currently, the only supported value is
     * FAILED_ACTIONS.

     */
    inline void SetRetryMode(StageRetryMode&& value) { m_retryModeHasBeenSet = true; m_retryMode = std::move(value); }

    /**
     *
The scope of the retry attempt. Currently, the only supported value is
     * FAILED_ACTIONS.

     */
    inline RetryStageExecutionRequest& WithRetryMode(const StageRetryMode& value) { SetRetryMode(value); return *this;}

    /**
     *
The scope of the retry attempt. Currently, the only supported value is
     * FAILED_ACTIONS.

     */
    inline RetryStageExecutionRequest& WithRetryMode(StageRetryMode&& value) { SetRetryMode(std::move(value)); return *this;}

  private:

    Aws::String m_pipelineName;
    bool m_pipelineNameHasBeenSet;

    Aws::String m_stageName;
    bool m_stageNameHasBeenSet;

    Aws::String m_pipelineExecutionId;
    bool m_pipelineExecutionIdHasBeenSet;

    StageRetryMode m_retryMode;
    bool m_retryModeHasBeenSet;
  };

} // namespace Model
} // namespace CodePipeline
} // namespace Aws


text:
/*
 * DummyDevice.cpp
 *
 *  Created on: 28.12.2016
 *      Author: gumyns
 */

#include <WindowSensor.h>
#include <config/GPIO.h>
#include <config/EXTI.h>
#include <BlinkLed.h>
#include <stm32f0xx_conf.h>

using namespace ::gumyns::sh;

namespace {
	static inline uint8_t readValue() {
		return GPIO::A::read(GPIO::A::SENSOR0);
	}
}

WindowSensor::WindowSensor(uint8_t channel) :
		channel(channel), request(nullptr), response(nullptr) {
	NVIC_InitTypeDef nvic;
	// Enable interrupt
	nvic.NVIC_IRQChannel = EXTI0_1_IRQn;
	nvic.NVIC_IRQChannelPriority = 3;
	nvic.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&nvic);
}

WindowSensor::~WindowSensor() {
}

Frame* WindowSensor::read() {
	if(this->response) {
		Frame *ret = this->response;
		this->response = nullptr;
		return ret;
	}
	return nullptr;
}

void WindowSensor::write(::gumyns::sh::Frame* frame) {
	if (this->request) {
		delete request;
		this->request = nullptr;
	}
	this->request = frame;
}

bool WindowSensor::process() {
	Frame * frame;
	bool ret = false;
	if (this->response)
		return true;
	if(this->request) {
		switch((Order)(*this->request)[Frame::DESCRIPTOR] >> 5) {
		case IDENTIFY:
			BlinkLed::turnOn();
			frame = new Frame(IDENTIFY, 0);
			frame->push(0x00);
			frame->push(0x11);
			if (this->response) {
				delete response;
				this->response = nullptr;
			}
			ret = (response = frame);
			break;
		case READ:
		case WRITE:
			frame = new Frame(RESPONSE, 0);
			frame->push(readValue());
			if (this->response) {
				delete response;
				this->response = nullptr;
			}
			ret = (response = frame);
			break;
		default:
			delete this->request;
		}
	}
	if (this->request) {
		delete request;
		this->request = nullptr;
	}
	return ret;
}

::gumyns::sh::Socket::IRQ WindowSensor::handler() {
	Exti::init();
	return [this]() {
		Frame * frame;
		frame = new Frame(RESPONSE, 0);
		frame->push(readValue());
		if (this->response) {
			delete response;
			this->response = nullptr;
		}
		response = frame;
		Exti::clear(Exti::SENSOR0);
	};
}


text:
import express from 'express'
import path from 'path'
import { dirname } from 'path'
import { fileURLToPath } from 'url'
const app = express()
app.get('/', (request, response) => response.send('Always pass on what you have learned.'))
const __dirname = path.join(dirname(fileURLToPath(import.meta.url)), '../');
app.use(express.static(path.join(__dirname, 'public')))
export default app


text:
namespace OCIO = OCIO_NAMESPACE;

OCIO_ADD_TEST(GradingToneTransform, basic)
{
    // Create transform and validate default values for all styles.
    auto gttLin = OCIO::GradingToneTransform::Create(OCIO::GRADING_LIN);
    OCIO_CHECK_EQUAL(gttLin->getStyle(), OCIO::GRADING_LIN);

    const OCIO::GradingTone toneDefaultsLin(OCIO::GRADING_LIN);
    OCIO_CHECK_EQUAL(gttLin->getValue(), toneDefaultsLin);
    OCIO::GradingTone tone(OCIO::GRADING_LIN);
    tone.m_scontrast += 0.123;
    tone.m_blacks.m_red += 0.321;
    tone.m_blacks.m_start += 0.1;
    gttLin->setValue(tone);
    OCIO_CHECK_EQUAL(gttLin->getValue(), tone);

    OCIO_CHECK_EQUAL(gttLin->getDirection(), OCIO::TRANSFORM_DIR_FORWARD);
    gttLin->setDirection(OCIO::TRANSFORM_DIR_INVERSE);
    OCIO_CHECK_EQUAL(gttLin->getDirection(), OCIO::TRANSFORM_DIR_INVERSE);

    OCIO_CHECK_ASSERT(!gttLin->isDynamic());
    gttLin->makeDynamic();
    OCIO_CHECK_ASSERT(gttLin->isDynamic());
    gttLin->makeNonDynamic();
    OCIO_CHECK_ASSERT(!gttLin->isDynamic());

    OCIO_CHECK_NO_THROW(gttLin->validate());
    tone.m_blacks.m_width = 0.0001;
    OCIO_CHECK_THROW_WHAT(gttLin->setValue(tone), OCIO::Exception, "is below lower bound (0.01)");
    tone.m_blacks.m_width = 1.;
    tone.m_blacks.m_red = 2.1;
    OCIO_CHECK_THROW_WHAT(gttLin->setValue(tone), OCIO::Exception, "are above upper bound (1.9)");

    auto gttLog = OCIO::GradingToneTransform::Create(OCIO::GRADING_LOG);
    OCIO_CHECK_EQUAL(gttLog->getStyle(), OCIO::GRADING_LOG);
    const OCIO::GradingTone toneDefaultsLog(OCIO::GRADING_LOG);
    OCIO_CHECK_EQUAL(gttLog->getValue(), toneDefaultsLog);
    auto gttVid = OCIO::GradingToneTransform::Create(OCIO::GRADING_VIDEO);
    OCIO_CHECK_EQUAL(gttVid->getStyle(), OCIO::GRADING_VIDEO);
    const OCIO::GradingTone toneDefaultsVid(OCIO::GRADING_VIDEO);
    OCIO_CHECK_EQUAL(gttVid->getValue(), toneDefaultsVid);
}

OCIO_ADD_TEST(GradingToneTransform, serialization)
{
    // Test the serialization of the transform.

    OCIO::GradingTone data(OCIO::GRADING_LIN);
    data.m_scontrast      += 0.123;
    data.m_blacks.m_red   += 0.321;
    data.m_blacks.m_start += 0.1;

    auto tone = OCIO::GradingToneTransform::Create(OCIO::GRADING_LIN);
    tone->setValue(data);

    static constexpr char TONE_STR[]
        = "<GradingToneTransform direction=forward, style=linear, values=<"\
          "blacks=<red=1.321 green=1 blue=1 master=1 start=0.1 width=4> "\
          "shadows=<red=1 green=1 blue=1 master=1 start=2 width=-7> "\
          "midtones=<red=1 green=1 blue=1 master=1 start=0 width=8> "\
          "highlights=<red=1 green=1 blue=1 master=1 start=-2 width=9> "\
          "whites=<red=1 green=1 blue=1 master=1 start=0 width=8> s_contrast=1.123>>";

    {
        std::ostringstream oss;
        oss << *tone;

        OCIO_CHECK_EQUAL(oss.str(), TONE_STR);
    }

    OCIO::GroupTransformRcPtr grp = OCIO::GroupTransform::Create();
    grp->appendTransform(OCIO::DynamicPtrCast<OCIO::Transform>(tone));

    {
        std::ostringstream oss;
        oss << *grp;

        std::string GROUP_STR("<GroupTransform direction=forward, transforms=\n");
        GROUP_STR += "        ";
        GROUP_STR += TONE_STR;
        GROUP_STR += ">";

        OCIO_CHECK_EQUAL(oss.str(), GROUP_STR);
    }
}

OCIO_ADD_TEST(GradingToneTransform, local_bypass)
{
    // Test the local bypass behavior.

    OCIO::GradingToneTransformRcPtr transform
        = OCIO::GradingToneTransform::Create(OCIO::GRADING_LOG);

    OCIO::ConstConfigRcPtr config = OCIO::Config::CreateRaw();

    {
        // Test that the GPU is empty for an identity transform.

        OCIO::ConstProcessorRcPtr proc = config->getProcessor(transform);
        OCIO::ConstGPUProcessorRcPtr gpu = proc->getOptimizedGPUProcessor(OCIO::OPTIMIZATION_NONE);

        OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc();

        OCIO_CHECK_NO_THROW(gpu->extractGpuShaderInfo(shaderDesc));

        static const std::string gpuStr("\n"
                                        "// Declaration of the OCIO shader function\n"
                                        "\n"
                                        "vec4 OCIOMain(vec4 inPixel)\n"
                                        "{\n"
                                        "  vec4 outColor = inPixel;\n"
                                        "\n"
                                        "  return outColor;\n"
                                        "}\n");

        OCIO_CHECK_EQUAL(gpuStr, std::string(shaderDesc->getShaderText()));
    }

    {
        transform->makeDynamic();

        const auto proc = config->getProcessor(transform);
        const auto cpu = proc->getOptimizedCPUProcessor(OCIO::OPTIMIZATION_NONE);

        // Values are unchanged (to within 32f precision).

        float v1[3] {0.3f, 0.4f, 0.5f};
        cpu->applyRGB(v1);
        OCIO_CHECK_CLOSE_FROM(v1[0], 0.30000001192092896f, std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_CLOSE_FROM(v1[1], 0.4000000059604645f,  std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_EQUAL(v1[2], 0.5f);

        // Try a value > HalfMax = 65504, note it is not clamped.  Therefore localBypass is being used.

        float v2[3] {0.3f, 0.4f, 65550.0f};
        cpu->applyRGB(v2);
        OCIO_CHECK_CLOSE_FROM(v2[0], 0.30000001192092896f, std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_CLOSE_FROM(v2[1], 0.4000000059604645f,  std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_EQUAL(v2[2], 65550.0f);

        // Set the midtones control so it is no longer an identity.

        auto valst = OCIO::GradingTone(OCIO::GRADING_LOG);
        valst.m_midtones = OCIO::GradingRGBMSW(0.3, 1.0, 1.8,  1.2, 0.37, 0.6);
        auto dp = cpu->getDynamicProperty(OCIO::DYNAMIC_PROPERTY_GRADING_TONE);
        auto propGT = OCIO::DynamicPropertyValue::AsGradingTone(dp);
        OCIO_CHECK_ASSERT(propGT);
        OCIO_CHECK_NO_THROW(propGT->setValue(valst));

        // It is affecting the midtones.

        float v3[3] {0.3f, 0.4f, 0.5f};
        cpu->applyRGB(v3);
        OCIO_CHECK_CLOSE_FROM(v3[0], 0.20410963892936707f, std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_CLOSE_FROM(v3[1], 0.4343799948692322f,  std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_CLOSE_FROM(v3[2], 0.6093657612800598f,  std::numeric_limits<float>::max_digits10, __LINE__);

        // The max value is now clamped, so localBypass is not being used.

        float v4[3] {0.3f, 0.4f, 65550.0f};
        cpu->applyRGB(v4);
        OCIO_CHECK_CLOSE_FROM(v4[0], 0.20410963892936707f, std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_CLOSE_FROM(v4[1], 0.4343799948692322f,  std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_EQUAL(v4[2], 65504.0f);

        // The midtones control does not affect large values, so just clarify that large values
        // below 65504 are not affected.

        float v5[3] {0.3f, 0.4f, 65500.0f};
        cpu->applyRGB(v5);
        OCIO_CHECK_CLOSE_FROM(v5[0], 0.20410963892936707f, std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_CLOSE_FROM(v5[1], 0.4343799948692322f,  std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_EQUAL(v5[2], 65500.0f);

        // Set the midtones values back to its default.

        valst.m_midtones = OCIO::GradingRGBMSW(1., 1.0, 1.,  1., 0.4, 0.6);
        OCIO_CHECK_NO_THROW(propGT->setValue(valst));

        // The behavior is now the same as originally.

        float v6[3] {0.3f, 0.4f, 0.5f};
        cpu->applyRGB(v6);
        OCIO_CHECK_CLOSE_FROM(v6[0], 0.30000001192092896f, std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_CLOSE_FROM(v6[1], 0.4000000059604645f,  std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_EQUAL(v6[2], 0.5f);

        float v7[3] {0.3f, 0.4f, 65550.0f};
        cpu->applyRGB(v7);
        OCIO_CHECK_CLOSE_FROM(v7[0], 0.30000001192092896f, std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_CLOSE_FROM(v7[1], 0.4000000059604645f,  std::numeric_limits<float>::max_digits10, __LINE__);
        OCIO_CHECK_EQUAL(v7[2], 65550.0f);
    }
}


text:
#include "avionics/firmware/cpu/sci.h"

#include <assert.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#include "avionics/firmware/cpu/clock.h"
#include "avionics/firmware/cpu/iomm.h"
#include "avionics/firmware/cpu/peripherals.h"
#include "avionics/firmware/cpu/registers.h"
#include "avionics/firmware/cpu/vim.h"
#include "common/barrier.h"
#include "common/macros.h"

#define SCI_TALK_TIMEOUT_CYCLES CLOCK32_MSEC_TO_CYCLES(10)

// Buffer sizes divide evenly into 2^32 to ensure that indices remain
// continuous during uint32_t rollovers.
COMPILE_ASSERT(UINT32_MAX % SCI_RECEIVE_SIZE == SCI_RECEIVE_SIZE - 1,
               SCI_RECEIVE_SIZE_must_divide_evenly_into_UINT32);
COMPILE_ASSERT(UINT32_MAX % SCI_TRANSMIT_SIZE == SCI_TRANSMIT_SIZE - 1,
               SCI_TRANSMIT_SIZE_must_divide_evenly_into_UINT32);

static void InterruptHandler1(void);
static void InterruptHandler2(void);

static const SciPeripheral kSciPeripheral1 = {
  .peripheral = kPeripheralSci1,
  .registers = &SCI(1),
  .receive_buffer = (SciReceiveBuffer[1]) {},
  .receive_pinmux = {0, 0},  // Not multiplexed, mark invalid.
  .transmit_buffer = (SciTransmitBuffer[1]) {},
  .transmit_pinmux = {0, 0},  // Not multiplexed, mark invalid.
  .interrupt_function = InterruptHandler1,
  .interrupt_channel = kVimChannelSci1Level0
};

static const SciPeripheral kSciPeripheral2 = {
  .peripheral = kPeripheralSci2,
  .registers = &SCI(2),
  .receive_buffer = (SciReceiveBuffer[1]) {},
  .receive_pinmux = {7, 17},
  .transmit_buffer = (SciTransmitBuffer[1]) {},
  .transmit_pinmux = {8, 1},
  .interrupt_function = InterruptHandler2,
  .interrupt_channel = kVimChannelSci2Level0
};

static void InterruptHandler(volatile SciRegisters *reg, SciReceiveBuffer *rx,
                             SciTransmitBuffer *tx) {
  switch (reg->INTVECT0.raw) {
    case 11:  // Receive interrupt.
      rx->data[rx->head % SCI_RECEIVE_SIZE] = reg->RD.RD;
      ++rx->head;
      break;
    case 12:  // Transmit interrupt.
      if (tx->tail != tx->head) {
        reg->TD.TD = tx->data[tx->tail % SCI_TRANSMIT_SIZE];
        ++tx->tail;
      } else {
        reg->CLEARINT.raw = SCI_CLEARINT_CLR_TX_INT;
      }
      break;
    default:
      break;
  }
}

static void InterruptHandler1(void) {
  InterruptHandler(kSciPeripheral1.registers, kSciPeripheral1.receive_buffer,
                   kSciPeripheral1.transmit_buffer);
}

static void InterruptHandler2(void) {
  InterruptHandler(kSciPeripheral2.registers, kSciPeripheral2.receive_buffer,
                   kSciPeripheral2.transmit_buffer);
}

static void Init(const SciPeripheral *per, int32_t baud, SciMode mode) {
  assert(per != NULL);
  assert(baud > 0);

  // Set pinmux and enables.
  IommSetPinmuxByIndex(&per->receive_pinmux, 1, 0);
  IommSetPinmuxByIndex(&per->transmit_pinmux, 1, 0);
  PeripheralEnable(per->peripheral);

  // Reset.
  volatile SciRegisters *reg = per->registers;
  reg->GCR0.RESET = 0;
  reg->GCR0.RESET = 1;

  // Issue soft reset.
  reg->GCR1.raw = 0;

  // Disable interrupts.
  reg->CLEARINT.raw = 0xFFFFFFFF;

  // Select INT0 interrupt level.
  reg->CLEARINTLVL.raw = 0xFFFFFFFF;

  // Clear pending interrupts.
  reg->FLR.raw = 0xFFFFFFFF;
  reg->FLR.raw = 0;

  // Set receive mode.
  reg->GCR1.RXENA = 1;
  reg->PIO0.RXFUNC = 1;

  // Set transmit mode.
  reg->GCR1.TXENA = 1;
  reg->PIO0.TXFUNC = 1;

  // Set asynchronous timing.
  reg->GCR1.CLOCK = 1;
  reg->GCR1.TIMINGMODE = 1;

  // Set character length to 8 bits.
  reg->FORMAT.CHAR = 7;

  // Set baud rate.
  reg->BRS.BAUD = PeripheralGetClockPrescale(per->peripheral, 16 * baud) - 1;

  // Clear receive buffer.
  SciReceiveBuffer *receive_buffer = per->receive_buffer;
  receive_buffer->head = 0U;
  receive_buffer->tail = 0U;
  receive_buffer->is_talking = false;
  receive_buffer->timeout = 0U;

  // Clear transmit buffer.
  SciTransmitBuffer *transmit_buffer = per->transmit_buffer;
  transmit_buffer->head = 0U;
  transmit_buffer->tail = 0U;

  // Register interrupt handlers.
  if (mode == kSciModeInterrupt) {
    VimRegisterIrq(per->interrupt_channel, per->interrupt_function);
    VimEnableInterrupt(per->interrupt_channel);
  }

  // Enable interrupts.
  if (mode == kSciModeInterrupt) {
    reg->SETINT.raw = SCI_SETINT_SET_RX_INT;
  }

  // Release reset hold.
  reg->GCR1.SWNRST = 1;
}

static bool PollReceive(const SciPeripheral *per) {
  volatile SciRegisters *reg = per->registers;

  // Receive. Operation not permitted while interrupts are enabled.
  if (!reg->SETINT.SET_RX_INT && reg->FLR.RXRDY) {
    SciReceiveBuffer *read = per->receive_buffer;
    uint8_t rd = reg->RD.RD;
    if ((int32_t)(read->head - read->tail) < SCI_RECEIVE_SIZE) {
      read->data[read->head % SCI_RECEIVE_SIZE] = rd;
      ++read->head;
    }
    return true;
  }
  return false;
}

static void PollTransmit(const SciPeripheral *per) {
  volatile SciRegisters *reg = per->registers;

  // Transmit. Operation not permitted while interrupts are enabled.
  SciTransmitBuffer *write = per->transmit_buffer;
  if (!reg->SETINT.SET_TX_INT && reg->FLR.TXRDY
      && write->head != write->tail) {
    reg->TD.TD = write->data[write->tail % SCI_TRANSMIT_SIZE];
    ++write->tail;
  }
}

static bool PollAsync(const SciPeripheral *per) {
  PollTransmit(per);
  return PollReceive(per);
}

// Added for Gill Windmaster. This sensor requires half duplex operation. For
// each transmit byte, we must wait for the device to respond via a single
// character (often an echo of the character sent) or stream of characters. If
// we transmit while receiving data, the device will stop transmitting data.
static bool PollHalfDuplex(const SciPeripheral *per) {
  volatile SciRegisters *reg = per->registers;

  // Receive.
  SciReceiveBuffer *read = per->receive_buffer;
  union SCI_FLR flr = reg->FLR;
  if (flr.RXRDY) {
    uint8_t rd = reg->RD.RD;
    if ((int32_t)(read->head - read->tail) < SCI_RECEIVE_SIZE) {
      read->data[read->head % SCI_RECEIVE_SIZE] = rd;
      ++read->head;
    }
    read->is_talking = true;
    read->timeout = Clock32GetCycles() + SCI_TALK_TIMEOUT_CYCLES;
  } else if (read->is_talking && !flr.RXRDY && !flr.BUSY
             && CLOCK32_GE(Clock32GetCycles(), read->timeout)) {
    read->is_talking = false;
  }

  // Transmit only when clear to talk.
  SciTransmitBuffer *write = per->transmit_buffer;
  if (!read->is_talking && write->head != write->tail && flr.TXRDY) {
    reg->TD.TD = write->data[write->tail % SCI_TRANSMIT_SIZE];
    ++write->tail;

    // Give time for the device to respond.
    read->is_talking = true;
    read->timeout = Clock32GetCycles() + SCI_TALK_TIMEOUT_CYCLES;
  }
  return read->is_talking;
}

static int32_t ReadBlocking(const SciPeripheral *per, int32_t length,
                            uint8_t *data) {
  assert(data != NULL);

  for (int32_t i = 0; i < length; ++i) {
    volatile SciRegisters *reg = per->registers;
    while (!reg->FLR.RXRDY) {}
    data[i] = reg->RD.RD;
  }
  return length;
}

// This function may be interrupted.
static int32_t ReadAsync(const SciPeripheral *per, int32_t length,
                         uint8_t *data) {
  assert(data != NULL);

  SciReceiveBuffer *buf = per->receive_buffer;
  int32_t count = 0;
  for ( ; count < length && buf->head != buf->tail; ++count) {
    data[count] = buf->data[buf->tail % SCI_RECEIVE_SIZE];
    // Since this function may be interrupted, we need to ensure that we
    // load data from the buffer before incrementing tail. If not, the
    // interrupt function could update the data at the tail position before
    // we read.
    MemoryBarrier();
    ++buf->tail;
  }
  return count;
}

static int32_t WriteBlocking(const SciPeripheral *per, int32_t length,
                             const uint8_t *data) {
  assert(data != NULL);

  for (int32_t i = 0; i < length; ++i) {
    volatile SciRegisters *reg = per->registers;
    while (!reg->FLR.TXRDY) {}
    reg->TD.TD = data[i];
  }
  return length;
}

static int32_t WriteBuffered(const SciPeripheral *per, int32_t length,
                             const uint8_t *data) {
  assert(data != NULL);

  SciTransmitBuffer *buf = per->transmit_buffer;
  int32_t count = 0;
  for ( ; (count < length
           && (int32_t)(buf->head - buf->tail) < SCI_TRANSMIT_SIZE); ++count) {
    buf->data[buf->head % SCI_TRANSMIT_SIZE] = data[count];
    ++buf->head;
  }
  return count;
}

// This function may be interrupted.
static int32_t WriteInterrupt(const SciPeripheral *per, int32_t length,
                              const uint8_t *data) {
  assert(data != NULL);

  SciTransmitBuffer *buf = per->transmit_buffer;
  int32_t count = 0;
  for ( ; (count < length
           && (int32_t)(buf->head - buf->tail) < SCI_TRANSMIT_SIZE); ++count) {
    volatile SciRegisters *reg = per->registers;
    if (buf->head == buf->tail && reg->FLR.TXRDY) {
      reg->TD.TD = data[count];
    } else {
      buf->data[buf->head % SCI_TRANSMIT_SIZE] = data[count];
      // Since this function may be interrupted, we need to ensure that we
      // store data into the buffer before incrementing head. If not, the
      // interrupt function could transmit stale data before we update the
      // buffer.
      MemoryBarrier();
      ++buf->head;
    }
    reg->SETINT.raw = SCI_SETINT_SET_TX_INT;
  }
  return count;
}

static bool IsWriteBusy(const SciPeripheral *per) {
  volatile SciRegisters *reg = per->registers;
  const SciTransmitBuffer *buf = per->transmit_buffer;

  union SCI_FLR flr = reg->FLR;
  return !(flr.TXRDY && flr.TXEMPTY
           && !reg->SETINT.SET_TX_INT && buf->head == buf->tail);
}

static void SetBreak(const SciPeripheral *per) {
  volatile SciRegisters *reg = per->registers;

  reg->PIO0.TXFUNC = 0;
  reg->PIO1.TXDIR = 1;
  reg->PIO5.TXCLR = 1;
}

static void ClearBreak(const SciPeripheral *per) {
  volatile SciRegisters *reg = per->registers;

  reg->PIO0.TXFUNC = 1;
}

static void ClearWrite(const SciPeripheral *per) {
  volatile SciRegisters *reg = per->registers;
  SciTransmitBuffer *buf = per->transmit_buffer;

  reg->CLEARINT.raw = SCI_CLEARINT_CLR_TX_INT;
  buf->tail = buf->head;
}

// This function may be interrupted.
static void AcquireReceiveData(const SciPeripheral *per, SciData *data) {
  const SciReceiveBuffer *buf = per->receive_buffer;
  uint32_t tail = buf->tail;
  uint32_t head = buf->head;

  // Since this function may be interrupted, we must ensure consistency of the
  // head position throughout this function.
  MemoryBarrier();

  int32_t tail_wrapped = tail % SCI_RECEIVE_SIZE;
  int32_t head_wrapped = head % SCI_RECEIVE_SIZE;

  // Acquire contiguous data.
  data->data = &buf->data[tail_wrapped];
  if (head == tail) {
    data->length = 0;  // Empty buffer.
  } else if (head_wrapped > tail_wrapped) {
    data->length = head_wrapped - tail_wrapped;  // Tail to head.
  } else {
    data->length = SCI_RECEIVE_SIZE - tail_wrapped;  // Tail to end of buffer.
  }
}

static void ReleaseReceiveData(const SciPeripheral *per, SciData *data) {
  SciReceiveBuffer *buf = per->receive_buffer;

  buf->tail += data->length;
  data->length = 0;
}

// Application functions.

void SciInit(const SciDevice *dev, int32_t baud) {
  assert(dev != NULL);
  Init(dev->peripheral, baud, dev->mode);
}

bool SciPoll(const SciDevice *dev) {
  assert(dev != NULL && dev->poll != NULL);
  return dev->poll(dev->peripheral);
}

int32_t SciRead(const SciDevice *dev, int32_t length, uint8_t *data) {
  assert(dev != NULL && dev->read != NULL);
  return dev->read(dev->peripheral, length, data);
}

bool SciReadByte(const SciDevice *dev, uint8_t *data) {
  assert(dev != NULL && dev->read != NULL);
  return dev->read(dev->peripheral, 1, data) == 1;
}

int32_t SciWrite(const SciDevice *dev, int32_t length, const uint8_t *data) {
  assert(dev != NULL && dev->write != NULL);
  return dev->write(dev->peripheral, length, data);
}

bool SciWriteByte(const SciDevice *dev, const uint8_t data) {
  assert(dev != NULL && dev->write != NULL);
  return dev->write(dev->peripheral, 1, &data) == 1;
}

int32_t SciWriteString(const SciDevice *dev, const char *str) {
  assert(str != NULL);
  int32_t count = 0;
  for ( ; str[count] && SciWriteByte(dev, (const uint8_t)str[count]); ++count) {
  }
  return count;
}

bool SciIsWriteBusy(const SciDevice *dev) {
  assert(dev != NULL);
  return IsWriteBusy(dev->peripheral);
}

void SciSetBreak(const SciDevice *dev) {
  assert(dev != NULL);
  SetBreak(dev->peripheral);
}

void SciClearBreak(const SciDevice *dev) {
  assert(dev != NULL);
  ClearBreak(dev->peripheral);
}

void SciClearWrite(const SciDevice *dev) {
  assert(dev != NULL);
  ClearWrite(dev->peripheral);
}

void SciAcquireReceiveData(const SciDevice *dev, SciData *data) {
  assert(dev != NULL);
  AcquireReceiveData(dev->peripheral, data);
}

void SciReleaseReceiveData(const SciDevice *dev, SciData *data) {
  assert(dev != NULL);
  ReleaseReceiveData(dev->peripheral, data);
}

const SciDevice kSci1Blocking = {
  .poll = PollAsync,
  .read = ReadBlocking,
  .write = WriteBlocking,
  .peripheral = &kSciPeripheral1,
  .mode = kSciModePolled
};

const SciDevice kSci1Buffered = {
  .poll = PollAsync,
  .read = ReadAsync,
  .write = WriteBuffered,
  .peripheral = &kSciPeripheral1,
  .mode = kSciModePolled
};

const SciDevice kSci1BufferedHalfDuplex = {
  .poll = PollHalfDuplex,
  .read = ReadAsync,
  .write = WriteBuffered,
  .peripheral = &kSciPeripheral1,
  .mode = kSciModePolled
};

const SciDevice kSci1Interrupt = {
  .poll = PollAsync,
  .read = ReadAsync,
  .write = WriteInterrupt,
  .peripheral = &kSciPeripheral1,
  .mode = kSciModeInterrupt
};

const SciDevice kSci2Blocking = {
  .poll = PollAsync,
  .read = ReadBlocking,
  .write = WriteBlocking,
  .peripheral = &kSciPeripheral2,
  .mode = kSciModePolled
};

const SciDevice kSci2Buffered = {
  .poll = PollAsync,
  .read = ReadAsync,
  .write = WriteBuffered,
  .peripheral = &kSciPeripheral2,
  .mode = kSciModePolled
};

const SciDevice kSci2BufferedHalfDuplex = {
  .poll = PollHalfDuplex,
  .read = ReadAsync,
  .write = WriteBuffered,
  .peripheral = &kSciPeripheral2,
  .mode = kSciModePolled
};

const SciDevice kSci2Interrupt = {
  .poll = PollAsync,
  .read = ReadAsync,
  .write = WriteInterrupt,
  .peripheral = &kSciPeripheral2,
  .mode = kSciModeInterrupt
};