text:
//DocSection:Using
using System;
using System.Web.Mvc;

using CMS.Core;
using CMS.ContactManagement;
using CMS.Newsletters;
using CMS.SiteProvider;
using CMS.Helpers;

using Kentico.Newsletters;
//EndDocSection:Using

namespace LearningKit.Controllers
{
    public class NewsletterSubscriptionController : Controller
    {
        /// <summary>
        /// Provides a NewsletterSubscriptionService instance for managing newsletter subscriptions and unsubscription for all types of email feeds.
        /// For real-world projects, we recommend using a dependency injection container to initialize service instances.
        /// The recommended lifetime scope for NewsletterSubscriptionService is a shared instance (singleton).
        /// </summary>
        private INewsletterSubscriptionService SubscriptionService
        {
            get
            {
                //DocSection:SubscriptionService
                var subscriptionService = new NewsletterSubscriptionService();
                //EndDocSection:SubscriptionService

                return subscriptionService;
            }
        }

        //DocSection:Subscribe
        /// <summary>
        /// Basic action that displays the newsletter subscription form.
        /// </summary>
        public ActionResult Subscribe()
        {
            return View();
        }

        /// <summary>
        /// Handles creation of new marketing email recipients when the subscription form is submitted.
        /// Accepts an email address parameter posted from the subscription form.
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Subscribe(NewsletterSubscribeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                // If the subscription data is not valid, displays the subscription form with error messages
                return View(model);
            }

            // Gets the default Kentico contact provider
            IContactProvider contactProvider = Service.Resolve<IContactProvider>();
            // Either gets an existing contact by email or creates a new contact object with the given email
            ContactInfo contact = contactProvider.GetContactForSubscribing(model.Email);

            // Gets a newsletter
            // Fill in the code name of your newsletter object in Kentico
            NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo("SampleNewsletter", SiteContext.CurrentSiteID);

            // Prepares settings that configure the subscription behavior
            var subscriptionSettings = new NewsletterSubscriptionSettings()
            {
                RemoveAlsoUnsubscriptionFromAllNewsletters = true, // Subscription removes the given email address from the global opt-out list for all marketing emails (if present)
                SendConfirmationEmail = true, // Allows sending of confirmation emails for the subscription
                AllowOptIn = true // Allows handling of double opt-in subscription for newsletters that have it enabled
            };

            // Subscribes the contact with the specified email address to the given newsletter
            SubscriptionService.Subscribe(contact, newsletter, subscriptionSettings);

            // Passes information to the view, indicating whether the newsletter requires double opt-in for subscription
            model.RequireDoubleOptIn = newsletter.NewsletterEnableOptIn;

            // Displays a view to inform the user that the subscription was successful
            return View("SubscribeSuccess", model);
        }
        //EndDocSection:Subscribe

        //DocSection:Unsubscribe
        /// <summary>
        /// Handles marketing email unsubscription requests.
        /// </summary>
        public ActionResult Unsubscribe(MarketingEmailUnsubscribeModel model)
        {
            // Verifies that the unsubscription request contains all required parameters
            if (ModelState.IsValid)
            {
                // Confirms whether the hash in the unsubscription request is valid for the given email address
                // Provides protection against forged unsubscription requests
                if (SubscriptionService.ValidateEmail(model.Email, model.Hash))
                {
                    // Unsubscribes the specified email address (either from all marketing emails or one specific email feed)
                    if (model.UnsubscribeFromAll)
                    {
                        SubscriptionService.UnsubscribeFromAll(model.Email, model.NewsletterGuid, model.IssueGuid);
                    }
                    else
                    {
                        SubscriptionService.Unsubscribe(model.Email, model.NewsletterGuid, model.IssueGuid);
                    }

                    // Displays a view to inform the user that they were unsubscribed
                    return View("UnsubscribeSuccess");
                }
            }

            // If the unsubscription was not successful, displays a view to inform the user
            // Failure can occur if the request does not provide all required parameters or if the hash is invalid
            return View("UnsubscribeFailure");
        }
        //EndDocSection:Unsubscribe

        //DocSection:ConfirmSubscription
        /// <summary>
        /// Handles confirmation requests for newsletter subscriptions (when using double opt-in).
        /// </summary>
        public ActionResult ConfirmSubscription(NewsletterConfirmSubscriptionViewModel model)
        {
            // Verifies that the confirmation request contains the required hash parameter
            if (!ModelState.IsValid)
            {
                // If the hash is missing, returns a view informing the user that the subscription confirmation was not successful
                ModelState.AddModelError(String.Empty, "The confirmation link is invalid.");
                return View(model);
            }

            // Attempts to parse the date and time parameter from the request query string
            // Uses the date and time formats required by the Kentico API
            DateTime parsedDateTime = DateTimeHelper.ZERO_TIME;
            if (!string.IsNullOrEmpty(model.DateTime) && !DateTimeUrlFormatter.TryParse(model.DateTime, out parsedDateTime))
            {
                // Returns a view informing the user that the subscription confirmation was not successful
                ModelState.AddModelError(String.Empty, "The confirmation link is invalid.");
                return View(model);
            }

            // Attempts to confirm the subscription specified by the request's parameters
            ApprovalResult result = SubscriptionService.ConfirmSubscription(model.SubscriptionHash, false, parsedDateTime);

            switch (result)
            {
                // The confirmation was successful or the recipient was already approved
                // Displays a view informing the user that the subscription is active
                case ApprovalResult.Success:
                case ApprovalResult.AlreadyApproved:
                    return View(model);

                // The confirmation link has expired
                // Expiration occurs after a certain number of hours from the time of the original subscription
                // You can set the expiration interval in Kentico (Settings -> On‑line marketing -> Email marketing -> Double opt-in interval)
                case ApprovalResult.TimeExceeded:
                    ModelState.AddModelError(String.Empty, "Your confirmation link has expired. Please subscribe to the newsletter again.");
                    break;

                // The subscription specified in the request's parameters does not exist
                case ApprovalResult.NotFound:
                    ModelState.AddModelError(String.Empty, "The subscription that you are attempting to confirm does not exist.");
                    break;

                // The confirmation failed
                default:
                    ModelState.AddModelError(String.Empty, "The confirmation of your newsletter subscription did not succeed.");
                    break;
            }

            // If the subscription confirmation was not successful, displays a view informing the user
            return View(model);
        }
        //EndDocSection:ConfirmSubscription
    }
}


text:
<?php
/**
 * The theme footer
 *
 * @package bootstrap-basic
 */
?>

            2015 ©
            FIWARE.

            The use of FIWARE Lab services is subject to the acceptance of the
              Terms and Conditions,

              Privacy Policy
              and
              Cookies Policy.

		<?php wp_footer(); ?>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.runtime.webmonitor.handlers;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.ProgramInvocationException;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.client.JobClient;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobmaster.JobManagerGateway;
import org.apache.flink.runtime.rest.handler.legacy.JsonFactory;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonGenerator;

import java.io.File;
import java.io.StringWriter;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;

/**
 * This handler handles requests to fetch plan for a jar.
 */
public class JarRunHandler extends JarActionHandler {

	static final String JAR_RUN_REST_PATH = "/jars/:jarid/run";

	private final Time timeout;
	private final Configuration clientConfig;

	public JarRunHandler(Executor executor, File jarDirectory, Time timeout, Configuration clientConfig) {
		super(executor, jarDirectory);
		this.timeout = Preconditions.checkNotNull(timeout);
		this.clientConfig = Preconditions.checkNotNull(clientConfig);
	}

	@Override
	public String[] getPaths() {
		return new String[]{JAR_RUN_REST_PATH};
	}

	@Override
	public CompletableFuture<String> handleJsonRequest(Map<String, String> pathParams, Map<String, String> queryParams, JobManagerGateway jobManagerGateway) {
		return CompletableFuture.supplyAsync(
			() -> {
				try {
					JarActionHandlerConfig config = JarActionHandlerConfig.fromParams(pathParams, queryParams);
					Tuple2<JobGraph, ClassLoader> graph = getJobGraphAndClassLoader(config);

					try {
						JobClient.submitJobDetached(
							jobManagerGateway,
							clientConfig,
							graph.f0,
							timeout,
							graph.f1);
					} catch (JobExecutionException e) {
						throw new ProgramInvocationException("Failed to submit the job to the job manager", e);
					}

					StringWriter writer = new StringWriter();
					JsonGenerator gen = JsonFactory.JACKSON_FACTORY.createGenerator(writer);
					gen.writeStartObject();
					gen.writeStringField("jobid", graph.f0.getJobID().toString());
					gen.writeEndObject();
					gen.close();
					return writer.toString();
				} catch (Exception e) {
					throw new CompletionException(new FlinkException("Could not run the jar.", e));
				}
			},
			executor);
	}
}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}

-- | Transformations on distilled expressions. Before transforming expressions,
-- they should first be renumbered, type checked, and had their source
-- annotations deleted.
module Distill.Transform
    ( lambdaLift
    , aNormalizeExpr
    ) where

import Control.Arrow
import Control.Monad.Reader
import Control.Monad.State
import Data.Functor.Foldable hiding (Mu)
import Data.List ((\\))
import Data.Maybe (fromJust)

import Distill.Expr
import Distill.Util

-- | Lambda-lift a set of declarations into supercombinator form.
lambdaLift :: (Eq b, Pretty b) => (b -> Int -> b) -> Int -> [Decl' b] -> [Decl' b]
lambdaLift ctor start decls =
    let declTypes = map (\(Decl' x t _) -> (x, t)) decls
        state = mapM_ (lambdaLift' ctor declTypes) decls in
    snd $ snd $ runState state (start, [])

-- | Lambda-lifts a single declaration into supercombinator form.
lambdaLift' :: (Eq b, Pretty b) => (b -> Int -> b) -> [(b, Type' b)] -> Decl' b
            -> State (Int, [Decl' b]) ()
lambdaLift' ctor assumed (Decl' x t m) = do
    m' <- runReaderT (lambdaLiftOuter m) (x, assumed)
    addDecl (Decl' x t m')
    return ()
  where
    -- Lift a lambda assuming we are at the top level.
    lambdaLiftOuter = \case
        lambda@Lambda{} -> do
            let (args, body) = splitLambda lambda
            let (xs, ts) = unzip args
            ts' <- mapM lambdaLiftInner ts
            let args' = zip xs ts'
            body' <- assumeArgs args $ lambdaLiftInner body
            return (unsplitLambda args' body')
        expr -> lambdaLiftInner expr
    -- Lift a lambda assuming we are inside another expression.
    lambdaLiftInner = \case
        lambda@Lambda{} -> do
            base <- lambdaLiftOuter lambda
            freeArgs <- (freeVars base \\) <$> boundVars
            completed <- unsplitLambda <$> createArgs freeArgs <*> pure base
            type_ <- typeof completed
            name <- createName
            addDecl (Decl' name type_ completed)
            return (unsplitApply (Var name : map Var freeArgs))
        expr -> embed <$> sequence (lambdaLiftInner <$> project expr)
    -- Determine the set of variables bound by declarations.
    boundVars = map (\(Decl' x _ _) -> x) <$> snd <$> get
    -- Assume a set of arguments are a set of types in a sub-computation.
    assumeArgs args = local (second (args ++))
    -- Create a new unique name for a declaration to use.
    createName = ctor <$> (fst <$> ask) <*> (fst <$> get <* modify (first succ))
    -- Add a newly created declaration to the set of declarations.
    addDecl decl = modify (second (decl:))
    -- Creates a list of (Var, Type) pairs, used as arguments for a lambda.
    createArgs names = do
        assumed <- snd <$> ask
        return (map (id &&& fromJust . flip lookup assumed) names)
    -- Determine the type of an expression.
    typeof expr = do
        assumed <- snd <$> ask
        decls <- snd <$> get
        let assumed' = assumed ++ map (\(Decl' x t _) -> (x, t)) decls
        let defined' = map (\(Decl' x _ m) -> (x, m)) decls
        let tcm = assumesIn assumed' $ definesIn defined' $ inferType expr
        return (fromRight (runTCM undefined tcm))

-- | Translate an expression into administrative normal form.
aNormalizeExpr :: (Int -> b) -> Expr' b -> State Int (Expr' b)
aNormalizeExpr ctor = aNormalizeOuter
  where
    -- Normalize expressions to A-normal form; assumes we are not in an apply.
    aNormalizeOuter expr = do
        (lets, expr') <- aNormalizeInner expr
        return (unsplitLet lets expr')
    -- Normalize expressions to simple values; this assumes we are in an apply.
    aNormalizeInner = \case
        Var x -> return ([], Var x)
        Star -> return ([], Star)
        Let x m n -> do
            (mlets, m') <- aNormalizeInner m
            (nlets, n') <- aNormalizeInner n
            return (mlets ++ [(x, m')] ++ nlets, n')
        Forall x t s -> do
            (tlets, t') <- aNormalizeInner t
            s' <- aNormalizeOuter s
            return (tlets, Forall x t' s')
        Lambda x t m -> do
            (tlets, t') <- aNormalizeInner t
            m' <- aNormalizeOuter m
            return (tlets, Lambda x t' m')
        apply@Apply{} -> do
            let args = splitApply apply
            (lets, args') <- unzip <$> mapM aNormalizeInner args
            let apply' = unsplitApply args'
            name <- createName
            return (concat lets ++ [(name, apply')], Var name)
        Mu x t s -> do
            (tlets, t') <- aNormalizeInner t
            s' <- aNormalizeOuter s
            return (tlets, Mu x t' s')
        Fold m t -> do
            (mlets, m') <- aNormalizeInner m
            (tlets, t') <- aNormalizeInner t
            return (mlets ++ tlets, Fold m' t')
        Unfold m -> do
            (mlets, m') <- aNormalizeInner m
            return (mlets, Unfold m')
        UnitT -> return ([], UnitT)
        UnitV -> return ([], UnitV)
        Product x t s -> do
            (tlets, t') <- aNormalizeInner t
            s' <- aNormalizeOuter s
            return (tlets, Product x t' s')
        Pack x m n s -> do
            (mlets, m') <- aNormalizeInner m
            (nlets, n') <- aNormalizeInner n
            s' <- aNormalizeOuter s
            return (mlets ++ nlets, Pack x m' n' s')
        Unpack m x y n -> do
            (mlets, m') <- aNormalizeInner m
            n' <- aNormalizeOuter n
            return (mlets, Unpack m' x y n')
        Coproduct ts -> do
            (tslets, ts') <- unzip <$> mapM aNormalizeInner ts
            return (concat tslets, Coproduct ts')
        Inject m i t -> do
            (mlets, m') <- aNormalizeInner m
            (tlets, t') <- aNormalizeInner t
            return (mlets ++ tlets, Inject m' i t')
        CaseOf m cs -> do
            (mlets, m') <- aNormalizeInner m
            cs' <- forM cs $ \(x, c) -> do
                c' <- aNormalizeOuter c
                return (x, c')
            return (mlets, CaseOf m' cs')
        CaseOfFalse m t -> do
            (mlets, m') <- aNormalizeInner m
            (tlets, t') <- aNormalizeInner t
            return (mlets ++ tlets, CaseOfFalse m' t')
        AnnotSource{} -> unstrippedError
        UnknownType{} -> unstrippedError
    createName = ctor <$> (get <* modify succ)
    unstrippedError = error "Unstripped annotations while A-normalizing."


text:
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

namespace System.Runtime.DurableInstancing
{
    using System;
    using System.Runtime;
    using System.Diagnostics.CodeAnalysis;

    [SuppressMessage(FxCop.Category.Naming, FxCop.Rule.FlagsEnumsShouldHavePluralNames, Justification = "Consistency is an adjective.")]
    [Flags]
    public enum InstanceValueConsistency
    {
        None = 0,
        InDoubt = 1,
        Partial = 2,
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?><blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

 <!-- to setup camel servlet with OSGi HttpService -->
  <reference id="httpService" interface="org.osgi.service.http.HttpService"/>

  <bean class="org.apache.camel.component.servlet.osgi.OsgiServletRegisterer" destroy-method="unregister" init-method="register">
    <property name="alias" value="/rest-api"/>
    <property name="httpService" ref="httpService"/>
    <property name="servlet" ref="camelServlet"/>
  </bean>

  <bean class="org.apache.camel.component.servlet.CamelHttpTransportServlet" id="camelServlet"/>

    <camelContext xmlns="http://camel.apache.org/schema/blueprint">
		<restConfiguration bindingMode="off" component="servlet" contextPath="/rest-api" enableCORS="true"/>

		<rest path="/ping">
			<get uri="/" >
				<to uri="direct:ping" />
			</get>
		</rest>

		<rest path="/tasks">
			<get uri="/" produces="application/json">
				<to uri="direct:gettasks" />
			</get>
			<post uri="/" produces="application/json">
				<to uri="direct:createtask" />
			</post>
			<get uri="/{id}" produces="application/json">
				<to uri="direct:gettask" />
			</get>
			<delete uri="/{id}">
				<to uri="direct:deletetask" />
			</delete>
			<put uri="/{id}" produces="application/json">
				<to uri="direct:updatetask" />
			</put>
		</rest>

	  <route>
		<from uri="direct:ping" />
		<transform>
			<constant>Hello, I'm Dr ToDo Little</constant>
		</transform>
	  </route>

	  <route>
		<from uri="direct:gettask" />
		<to uri="velocity:templates/gettask.vm" />
	  </route>

	  <route>
		<from uri="direct:gettasks" />
		<to uri="velocity:templates/gettasks.vm" />
	  </route>

	  <route>
		<from uri="direct:deletetask" />
		<setHeader headerName="Exchange.HTTP_RESPONSE_CODE"><constant>204</constant></setHeader>
		<to uri="mock:templates/deletetask" />
	  </route>

	  <route>
		<from uri="direct:updatetask" />
		<to uri="velocity:templates/updatetask.vm" />
	  </route>

	  <route>
		<from uri="direct:createtask" />
		<to uri="velocity:templates/createtask.vm" />
	  </route>
    </camelContext>

</blueprint>


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="unwind">
        <note>
            Frames file for 'unwind' based on sentences in financial subcorpus.
            No Verbnet entry, comparison with 'wind'.
        </note>

        <roleset id="unwind.01" name="(cause to) be uncoiled" vncls="-">
            <roles>
                <role descr="unroller" n="0"/>
                <role descr="thing unrolled or unrolling" n="1"/>
            </roles>

            <example name="specialized financial usage">
                <inflection aspect="ns" form="full" person="ns" tense="ns" voice="ns"/>
                <text>
                    And senior officials of two U.S. securities houses say they
                    switched trades in European stocks to the London market last week
                    when they couldn't unwind positions on the Continent.
                </text>
                <arg n="0">they</arg>
                <arg f="MOD" n="M">could</arg>
                <arg f="NEG" n="M">n't</arg>
                <rel>unwind</rel>
                <arg n="1">positions on the Continent</arg>
                <note>
                    I have no idea what this means.
                </note>

            </example>

            <example name="literal, agentive">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    John unwound his giant ball of shed hair.
                </text>
                <arg n="0">John</arg>
                <rel>unwound</rel>
                <arg n="1">his giant ball of shed hair</arg>
            </example>

            <example name="literal, ergative">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    John's watch unwound quickly.
                </text>
                <arg n="1">John's watch</arg>
                <rel>unwound</rel>
                <arg f="MNR" n="m">quickly</arg>
            </example>

            <note>
            </note>

        </roleset>

        <roleset id="unwind.02" name="relax" vncls="-">
            <roles>
                <role descr="relaxer" n="1"/>
                <role descr="instrument" n="2"/>
            </roles>

            <example name="hot summer days">
                <inflection aspect="ns" form="full" person="ns" tense="ns" voice="active"/>
                <text>
                    After a long day of work, [John]-1 likes *trace*-1 to relax with a nap
                    in his hammock.
                </text>
                <arg n="1">*trace*</arg>
                <rel>relax</rel>
                <arg n="2">with a nap in his hammock</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
import CanvasWidget from './canvasWidget.js'

/**
 * A horizontal or vertical fader.
 * @module Knob
 * @augments CanvasWidget
 */

let Knob = Object.create( CanvasWidget )

Object.assign( Knob, {
  /** @lends Knob.prototype */

  /**
   * A set of default property settings for all Knob instances.
   * Defaults can be overridden by user-defined properties passed to
   * construtor.
   * @memberof Knob
   * @static
   */
  defaults: {
    __value:.5, // always 0-1, not for end-users
    value:.5,   // end-user value that may be filtered
    active: false,
    knobBuffer:20,
    usesRotation:false,
    lastPosition:0,
    isSquare:true,
    /**
     * The style property can be either 'horizontal' (the default) or 'vertical'. This
     * determines the orientation of the Knob instance.
     * @memberof Knob
     * @instance
     * @type {String}
     */
    style:  'horizontal'
  },

  /**
   * Create a new Knob instance.
   * @memberof Knob
   * @constructs
   * @param {Object} [props] - A dictionary of properties to initialize Knob with.
   * @static
   */
  create( props ) {
    let knob = Object.create( this )

    // apply Widget defaults, then overwrite (if applicable) with Knob defaults
    CanvasWidget.create.call( knob )

    // ...and then finally override with user defaults
    Object.assign( knob, Knob.defaults, props )

    // set underlying value if necessary... TODO: how should this be set given min/max?
    if( props.value ) knob.__value = props.value

    // inherits from Widget
    knob.init()

    return knob
  },

  /**
   * Draw the Knob onto its canvas context using the current .__value property.
   * @memberof Knob
   * @instance
   */
  draw() {
    // draw background
    this.ctx.fillStyle   = this.container.background
    this.ctx.strokeStyle = this.stroke
    this.ctx.lineWidth   = this.lineWidth

    this.ctx.fillRect( 0,0, this.rect.width, this.rect.height )

    let x = 0,
        y = 0,
        width = this.rect.width,
        height= this.rect.height,
        radius = width / 2

    this.ctx.fillRect( x, y, width, height )
    //this.ctx.strokeStyle = this.stroke

    this.ctx.fillStyle = this.background // draw background of widget first

    let angle0 = Math.PI * .6,
        angle1 = Math.PI * .4

    this.ctx.beginPath()
    this.ctx.arc( x + radius, y + radius, radius - this.knobBuffer,         angle0, angle1, false )
    this.ctx.arc( x + radius, y + radius, (radius - this.knobBuffer) * .5 , angle1, angle0, true  )
    this.ctx.closePath()

    this.ctx.fill()

    let angle2
    if(!this.isInverted)  {
      angle2 = Math.PI * .6 + this.__value * 1.8  * Math.PI
      if( angle2 > 2 * Math.PI) angle2 -= 2 * Math.PI
    }else{
      angle2 = Math.PI * (0.4 - (1.8 * this.__value))
    }

    this.ctx.beginPath()

    if(!this.isInverted) {
      this.ctx.arc( x + radius, y + radius, radius - this.knobBuffer, angle0, angle2, false )
      this.ctx.arc( x + radius, y + radius, (radius - this.knobBuffer) * .5, angle2, angle0, true )
    } else {
      this.ctx.arc( x + radius, y + radius, radius - this.knobBuffer, angle1, angle2 ,true )
      this.ctx.arc( x + radius, y + radius, (radius - this.knobBuffer) * .5, angle2, angle1, false )
    }

    this.ctx.closePath()

    this.ctx.fillStyle = this.fill
    this.ctx.fill()

  },

  addEvents() {
    // create event handlers bound to the current object, otherwise
    // the 'this' keyword will refer to the window object in the event handlers
    for( let key in this.events ) {
      this[ key ] = this.events[ key ].bind( this )
    }

    // only listen for mousedown intially; mousemove and mouseup are registered on mousedown
    this.element.addEventListener( 'pointerdown',  this.pointerdown )
  },

  events: {
    pointerdown( e ) {
      this.active = true
      this.pointerId = e.pointerId

      this.processPointerPosition( e ) // change knob value on click / touchdown

      window.addEventListener( 'pointermove', this.pointermove ) // only listen for up and move events after pointerdown
      window.addEventListener( 'pointerup',   this.pointerup )
    },

    pointerup( e ) {
      if( this.active && e.pointerId === this.pointerId ) {
        this.active = false
        window.removeEventListener( 'pointermove', this.pointermove )
        window.removeEventListener( 'pointerup',   this.pointerup )
      }
    },

    pointermove( e ) {
      if( this.active && e.pointerId === this.pointerId ) {
        this.processPointerPosition( e )
      }
    },
  },

  /**
   * Generates a value between 0-1 given the current pointer position in relation
   * to the Knob's position, and triggers output.
   * @instance
   * @memberof Knob
   * @param {PointerEvent} e - The pointer event to be processed.
   */

  processPointerPosition( e ) {
    let xOffset = e.clientX, yOffset = e.clientY

    let radius = this.rect.width / 2;
    this.lastValue = this.value;

    if( !this.usesRotation ) {
      if( this.lastPosition !== -1 ) {
        //this.__value -= ( yOffset - this.lastPosition ) / (radius * 2);
        this.__value = 1 - yOffset / this.rect.height
      }
    }else{
      var xdiff = radius - xOffset;
      var ydiff = radius - yOffset;
      var angle = Math.PI + Math.atan2(ydiff, xdiff);
      this.__value =  ((angle + (Math.PI * 1.5)) % (Math.PI * 2)) / (Math.PI * 2);

      if(this.lastRotationValue > .8 && this.__value < .2) {
        this.__value = 1;
      }else if(this.lastRotationValue < .2 && this.__value > .8) {
        this.__value = 0;
      }
    }

    if (this.__value > 1) this.__value = 1;
    if (this.__value < 0) this.__value = 0;

    this.lastRotationValue = this.__value;
    this.lastPosition = yOffset;

    let shouldDraw = this.output()

    if( shouldDraw ) this.draw()
  },

  //__addToPanel( panel ) {
  //  this.container = panel

  //  if( typeof this.addEvents === 'function' ) this.addEvents()

  //  // called if widget uses DOMWidget as prototype; .place inherited from DOMWidget

  //  this.place( true )

  //  if( this.label ) this.addLabel()

  //  this.draw()

  //}

})

module.exports = Knob


text:
@implementation NSOperationQueue (VRNamedBlock)
- (void)putOperationWithName:(NSString*)operationName andBlock:(void (^)(void))block;
{
    if (!block) {
        return;
    }
    NSOperation* blockOperation = [NSBlockOperation blockOperationWithBlock:block];
    if (operationName.length &&
        (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_8_0 ||
         NSFoundationVersionNumber >= NSFoundationVersionNumber10_10)) {
        blockOperation.name = operationName;
    }
    [self addOperation:blockOperation];
}
@end


text:
<template name="layout">
  {{> yield region="header"}}

            {{> yield}}

  {{> yield region="footer"}}
</template>


text:
import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {DragBox, Select} from '../src/ol/interaction.js';
import {OSM, Vector as VectorSource} from '../src/ol/source.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import {platformModifierKeyOnly} from '../src/ol/events/condition.js';

const vectorSource = new VectorSource({
  url: 'data/geojson/countries.geojson',
  format: new GeoJSON(),
});

const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
    new VectorLayer({
      source: vectorSource,
    }),
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
    constrainRotation: 16,
  }),
});

// a normal select interaction to handle click
const select = new Select();
map.addInteraction(select);

const selectedFeatures = select.getFeatures();

// a DragBox interaction used to select features by drawing boxes
const dragBox = new DragBox({
  condition: platformModifierKeyOnly,
});

map.addInteraction(dragBox);

dragBox.on('boxend', function () {
  // features that intersect the box geometry are added to the
  // collection of selected features

  // if the view is not obliquely rotated the box geometry and
  // its extent are equalivalent so intersecting features can
  // be added directly to the collection
  const rotation = map.getView().getRotation();
  const oblique = rotation % (Math.PI / 2) !== 0;
  const candidateFeatures = oblique ? [] : selectedFeatures;
  const extent = dragBox.getGeometry().getExtent();
  vectorSource.forEachFeatureIntersectingExtent(extent, function (feature) {
    candidateFeatures.push(feature);
  });

  // when the view is obliquely rotated the box extent will
  // exceed its geometry so both the box and the candidate
  // feature geometries are rotated around a common anchor
  // to confirm that, with the box geometry aligned with its
  // extent, the geometries intersect
  if (oblique) {
    const anchor = [0, 0];
    const geometry = dragBox.getGeometry().clone();
    geometry.rotate(-rotation, anchor);
    const extent = geometry.getExtent();
    candidateFeatures.forEach(function (feature) {
      const geometry = feature.getGeometry().clone();
      geometry.rotate(-rotation, anchor);
      if (geometry.intersectsExtent(extent)) {
        selectedFeatures.push(feature);
      }
    });
  }
});

// clear selection when drawing a new box and when clicking on the map
dragBox.on('boxstart', function () {
  selectedFeatures.clear();
});

const infoBox = document.getElementById('info');

selectedFeatures.on(['add', 'remove'], function () {
  const names = selectedFeatures.getArray().map(function (feature) {
    return feature.get('name');
  });
  if (names.length > 0) {
    infoBox.innerHTML = names.join(', ');
  } else {
    infoBox.innerHTML = 'No countries selected';
  }
});


text:
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.views import generic

import hashlib

from groups.mixins import FormMessageMixin
from groups.models import Group

from .models import File
from .forms import EventForm
from .mixins import EventMixin

class EventCreateView(EventMixin, generic.CreateView):
    template_name = 'agenda/event_create_form.html'

    def form_valid(self, form):
        event = form.save(commit=False)
        event.group = self.get_group()
        event.author = self.request.user
        event.save()

        # Screw heroku dude.
        # for file in self.request.FILES.getlist('files'):
        #     ext = file.name.split('.')[-1]
        #     file.name = get_hash(file)[:10] + '.' + ext.lower()
        #     if File.objects.filter(name=file.name).exists():
        #         obj = File.objects.get(name=file.name)
        #     else:
        #         obj = File.objects.create(name=file.name, file=file)
        #         obj.save()
        #     event.files.add(obj)

        messages.success(self.request, 'Awwwsome! Your event has been successfully created!')
        return super(EventCreateView, self).form_valid(form)

    def form_invalid(self, form):
        messages.error(self.request, 'Something went horribly wrong, please try again.')
        return super(EventCreateView, self).form_invalid(form)

class EventDetailView(EventMixin, generic.DetailView):
    template_name = 'agenda/event_detail.html'

# class EventListView(EventMixin, generic.DetailView):
#     model = Group
#     template_name = 'agenda/event_list.html'

class EventUpdateView(EventMixin, FormMessageMixin, generic.UpdateView):
    template_name = 'agenda/event_update_form.html'

    def form_valid(self, form):
        event = form.save()

        for file in self.request.FILES.getlist('files'):
            ext = file.name.split('.')[-1]
            file.name = get_hash(file)[:10] + '.' + ext.lower()
            if File.objects.filter(name=file.name).exists():
                obj = File.objects.get(name=file.name)
            else:
                obj = File.objects.create(name=file.name, file=file)
                obj.save()
            event.files.add(obj)

        return super(EventUpdateView, self).form_valid(form)

    def test_func(self):
        return self.request.user.is_staff or self.get_group().memberships.get(user=self.request.user).is_moderator or self.request.user == self.get_object().author

class EventDeleteView(EventMixin, generic.DeleteView):
    template_name = 'agenda/event_confirm_delete.html'

    def get_success_url(self):
        return reverse('groups:group_detail', kwargs={'slug': self.kwargs.get('slug')})

    def test_func(self):
        return self.request.user.is_staff or self.get_group().memberships.get(user=self.request.user).is_moderator or self.request.user == self.get_object().author

class EventAllView(EventMixin, generic.DetailView):
    model = Group
    template_name = 'agenda/event_all.html'

def get_hash(file):
    md5 = hashlib.md5()

    for c in file.chunks():
        md5.update(c)

    return str(md5.hexdigest())


text:
package main

import (
	"testing"

	"github.com/coreos/fleet/client"
	"github.com/coreos/fleet/job"
	"github.com/coreos/fleet/machine"
	"github.com/coreos/fleet/registry"
	"github.com/coreos/fleet/unit"
)

func newMachineState(id, ip string, md map[string]string) machine.MachineState {
	return machine.MachineState{
		ID:       id,
		PublicIP: ip,
		Metadata: md,
	}
}

func newFakeRegistryForSsh() client.API {
	// clear machineStates for every invocation
	machineStates = nil
	machines := []machine.MachineState{
		newMachineState("c31e44e1-f858-436e-933e-59c642517860", "1.2.3.4", map[string]string{"ping": "pong"}),
		newMachineState("595989bb-cbb7-49ce-8726-722d6e157b4e", "5.6.7.8", map[string]string{"foo": "bar"}),
		newMachineState("hello.service", "8.7.6.5", map[string]string{"foo": "bar"}),
	}

	jobs := []job.Job{
		job.Job{Name: "j1.service", Unit: unit.UnitFile{}, TargetMachineID: machines[0].ID},
		job.Job{Name: "j2.service", Unit: unit.UnitFile{}, TargetMachineID: machines[1].ID},
		job.Job{Name: "hello.service", Unit: unit.UnitFile{}, TargetMachineID: machines[2].ID},
	}

	states := []unit.UnitState{
		unit.UnitState{
			UnitName:    "j1.service",
			LoadState:   "loaded",
			ActiveState: "active",
			SubState:    "listening",
			MachineID:   machines[0].ID,
		},
		unit.UnitState{
			UnitName:    "j2.service",
			LoadState:   "loaded",
			ActiveState: "inactive",
			SubState:    "dead",
			MachineID:   machines[1].ID,
		},
		unit.UnitState{
			UnitName:    "hello.service",
			LoadState:   "loaded",
			ActiveState: "inactive",
			SubState:    "dead",
			MachineID:   machines[2].ID,
		},
	}

	reg := registry.NewFakeRegistry()
	reg.SetMachines(machines)
	reg.SetUnitStates(states)
	reg.SetJobs(jobs)

	return &client.RegistryClient{Registry: reg}
}

func TestSshUnknownMachine(t *testing.T) {
	cAPI = newFakeRegistryForSsh()

	_, ok, _ := findAddressInMachineList("asdf")
	if ok {
		t.Error("Expected to not find any machine with the machine ID `asdf`")
	}
}

func TestSshFindMachine(t *testing.T) {
	cAPI = newFakeRegistryForSsh()

	ip, _, _ := findAddressInMachineList("c31e44e1-f858-436e-933e-59c642517860")
	if ip != "1.2.3.4" {
		t.Errorf("Expected to return the host 1.2.3.4, but it was %s", ip)
	}
}

func TestSshFindMachineByUnknownUnitName(t *testing.T) {
	cAPI = newFakeRegistryForSsh()

	_, ok, _ := findAddressInRunningUnits("asdf")
	if ok {
		t.Error("Expected to not find any machine with the unit name `asdf`")
	}
}

func TestSshFindMachineByUnitName(t *testing.T) {
	cAPI = newFakeRegistryForSsh()

	ip, _, _ := findAddressInRunningUnits("j1")
	if ip != "1.2.3.4" {
		t.Errorf("Expected to return the host 1.2.3.4, but it was %s", ip)
	}
}

func TestGlobalLookupByUnknownArgument(t *testing.T) {
	cAPI = newFakeRegistryForSsh()

	_, err := globalMachineLookup([]string{"asdf"})
	if err == nil {
		t.Fatal("Expected to receive error, got nil")
	}
}

func TestGlobalLookupByMachineID(t *testing.T) {
	cAPI = newFakeRegistryForSsh()

	ip, err := globalMachineLookup([]string{"c31e44e1-f858-436e-933e-59c642517860"})
	if err != nil {
		t.Fatal("Expected to not find any error")
	}

	if ip != "1.2.3.4" {
		t.Errorf("Expected to return the host 1.2.3.4, but it was %s", ip)
	}
}

func TestGlobalLookupByUnitName(t *testing.T) {
	cAPI = newFakeRegistryForSsh()

	ip, err := globalMachineLookup([]string{"j1"})
	if err != nil {
		t.Fatal("Expected to not find any error")
	}

	if ip != "1.2.3.4" {
		t.Errorf("Expected to return the host 1.2.3.4, but it was %s", ip)
	}
}

func TestGlobalLookupWithAmbiguousArgument(t *testing.T) {
	cAPI = newFakeRegistryForSsh()

	_, err := globalMachineLookup([]string{"hello.service"})
	if err == nil {
		t.Fatal("Expected to find an error with an ambiguous argument")
	}
}


text:
package org.apache.samza.clustermanager;

import org.apache.samza.application.ApplicationUtil;
import org.apache.samza.application.StreamApplication;
import org.apache.samza.config.Config;
import org.apache.samza.config.JobConfig;
import org.apache.samza.config.loaders.PropertiesConfigLoaderFactory;
import org.apache.samza.util.ConfigUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({
    ApplicationUtil.class,
    ConfigUtil.class,
    JobCoordinatorLaunchUtil.class,
    ClusterBasedJobCoordinatorRunner.class})
public class TestDefaultApplicationMain {

  @Test
  public void testRun() throws Exception {
    String[] args = new String[] {
        "--config",
        JobConfig.CONFIG_LOADER_FACTORY + "=" + PropertiesConfigLoaderFactory.class.getName(),
        "--config",
        PropertiesConfigLoaderFactory.CONFIG_LOADER_PROPERTIES_PREFIX + "path=" + getClass().getResource("/test.properties").getPath()
    };

    StreamApplication mockApplication = mock(StreamApplication.class);
    Config mockConfig = mock(Config.class);
    mockStatic(JobCoordinatorLaunchUtil.class, ApplicationUtil.class, ConfigUtil.class);

    when(ApplicationUtil.fromConfig(any()))
        .thenReturn(mockApplication);
    when(ConfigUtil.loadConfig(any()))
        .thenReturn(mockConfig);
    doNothing()
        .when(JobCoordinatorLaunchUtil.class, "run",
            mockApplication, mockConfig);
    DefaultApplicationMain.run(args);

    verifyStatic(times(1));
    JobCoordinatorLaunchUtil.run(mockApplication, mockConfig);
  }
}


text:
A simple testbed for polygonal triangulation code.

## Running

This code runs inside [LÖVE](https://love2d.org/). To run it, run `love`
with this directory as its target. (In a desktop environment, drag the
folder onto your `love` executable.


text:
<?php

namespace Ivory\GoogleMap\Service\Elevation\Response;

use Ivory\GoogleMap\Base\Coordinate;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
class ElevationResult
{
    /**
     * @var Coordinate|null
     */
    private $location;

    /**
     * @var float|null
     */
    private $elevation;

    /**
     * @var float|null
     */
    private $resolution;

    /**
     * @return bool
     */
    public function hasLocation()
    {
        return $this->location !== null;
    }

    /**
     * @return Coordinate|null
     */
    public function getLocation()
    {
        return $this->location;
    }

    /**
     * @param Coordinate|null $location
     */
    public function setLocation(Coordinate $location = null)
    {
        $this->location = $location;
    }

    /**
     * @return bool
     */
    public function hasElevation()
    {
        return $this->elevation !== null;
    }

    /**
     * @return float|null
     */
    public function getElevation()
    {
        return $this->elevation;
    }

    /**
     * @param float|null $elevation
     */
    public function setElevation($elevation)
    {
        $this->elevation = $elevation;
    }

    /**
     * @return bool
     */
    public function hasResolution()
    {
        return $this->resolution !== null;
    }

    /**
     * @return float|null
     */
    public function getResolution()
    {
        return $this->resolution;
    }

    /**
     * @param float|null $resolution
     */
    public function setResolution($resolution)
    {
        $this->resolution = $resolution;
    }
}


text:
"""
Tests for the API /chassis/ methods.
"""

import datetime

import mock
from oslo.config import cfg
from oslo.utils import timeutils
from six.moves.urllib import parse as urlparse

from ironic.common import utils
from ironic.tests.api import base
from ironic.tests.api import utils as apiutils
from ironic.tests.objects import utils as obj_utils

class TestListChassis(base.FunctionalTest):

    def test_empty(self):
        data = self.get_json('/chassis')
        self.assertEqual([], data['chassis'])

    def test_one(self):
        chassis = obj_utils.create_test_chassis(self.context)
        data = self.get_json('/chassis')
        self.assertEqual(chassis.uuid, data['chassis'][0]["uuid"])
        self.assertNotIn('extra', data['chassis'][0])
        self.assertNotIn('nodes', data['chassis'][0])

    def test_get_one(self):
        chassis = obj_utils.create_test_chassis(self.context)
        data = self.get_json('/chassis/%s' % chassis['uuid'])
        self.assertEqual(chassis.uuid, data['uuid'])
        self.assertIn('extra', data)
        self.assertIn('nodes', data)

    def test_detail(self):
        chassis = obj_utils.create_test_chassis(self.context)
        data = self.get_json('/chassis/detail')
        self.assertEqual(chassis.uuid, data['chassis'][0]["uuid"])
        self.assertIn('extra', data['chassis'][0])
        self.assertIn('nodes', data['chassis'][0])

    def test_detail_against_single(self):
        chassis = obj_utils.create_test_chassis(self.context)
        response = self.get_json('/chassis/%s/detail' % chassis['uuid'],
                                 expect_errors=True)
        self.assertEqual(404, response.status_int)

    def test_many(self):
        ch_list = []
        for id_ in range(5):
            chassis = obj_utils.create_test_chassis(self.context, id=id_,
                                                    uuid=utils.generate_uuid())
            ch_list.append(chassis.uuid)
        data = self.get_json('/chassis')
        self.assertEqual(len(ch_list), len(data['chassis']))
        uuids = [n['uuid'] for n in data['chassis']]
        self.assertEqual(ch_list.sort(), uuids.sort())

    def test_links(self):
        uuid = utils.generate_uuid()
        obj_utils.create_test_chassis(self.context, id=1, uuid=uuid)
        data = self.get_json('/chassis/%s' % uuid)
        self.assertIn('links', data.keys())
        self.assertEqual(2, len(data['links']))
        self.assertIn(uuid, data['links'][0]['href'])
        for l in data['links']:
            bookmark = l['rel'] == 'bookmark'
            self.assertTrue(self.validate_link(l['href'], bookmark=bookmark))

    def test_collection_links(self):
        for id in range(5):
            obj_utils.create_test_chassis(self.context, id=id,
                                          uuid=utils.generate_uuid())
        data = self.get_json('/chassis/?limit=3')
        self.assertEqual(3, len(data['chassis']))

        next_marker = data['chassis'][-1]['uuid']
        self.assertIn(next_marker, data['next'])

    def test_collection_links_default_limit(self):
        cfg.CONF.set_override('max_limit', 3, 'api')
        for id_ in range(5):
            obj_utils.create_test_chassis(self.context, id=id_,
                                          uuid=utils.generate_uuid())
        data = self.get_json('/chassis')
        self.assertEqual(3, len(data['chassis']))

        next_marker = data['chassis'][-1]['uuid']
        self.assertIn(next_marker, data['next'])

    def test_nodes_subresource_link(self):
        chassis = obj_utils.create_test_chassis(self.context)
        data = self.get_json('/chassis/%s' % chassis.uuid)
        self.assertIn('nodes', data.keys())

    def test_nodes_subresource(self):
        chassis = obj_utils.create_test_chassis(self.context)

        for id_ in range(2):
            obj_utils.create_test_node(self.context, id=id_,
                                       chassis_id=chassis.id,
                                       uuid=utils.generate_uuid())

        data = self.get_json('/chassis/%s/nodes' % chassis.uuid)
        self.assertEqual(2, len(data['nodes']))
        self.assertNotIn('next', data.keys())

        # Test collection pagination
        data = self.get_json('/chassis/%s/nodes?limit=1' % chassis.uuid)
        self.assertEqual(1, len(data['nodes']))
        self.assertIn('next', data.keys())

    def test_nodes_subresource_no_uuid(self):
        response = self.get_json('/chassis/nodes', expect_errors=True)
        self.assertEqual(400, response.status_int)

    def test_nodes_subresource_chassis_not_found(self):
        non_existent_uuid = 'eeeeeeee-cccc-aaaa-bbbb-cccccccccccc'
        response = self.get_json('/chassis/%s/nodes' % non_existent_uuid,
                                 expect_errors=True)
        self.assertEqual(404, response.status_int)

class TestPatch(base.FunctionalTest):

    def setUp(self):
        super(TestPatch, self).setUp()
        obj_utils.create_test_chassis(self.context)

    def test_update_not_found(self):
        uuid = utils.generate_uuid()
        response = self.patch_json('/chassis/%s' % uuid,
                                   [{'path': '/extra/a', 'value': 'b',
                                     'op': 'add'}],
                                   expect_errors=True)
        self.assertEqual(404, response.status_int)
        self.assertEqual('application/json', response.content_type)
        self.assertTrue(response.json['error_message'])

    @mock.patch.object(timeutils, 'utcnow')
    def test_replace_singular(self, mock_utcnow):
        chassis = obj_utils.get_test_chassis(self.context)
        description = 'chassis-new-description'
        test_time = datetime.datetime(2000, 1, 1, 0, 0)

        mock_utcnow.return_value = test_time
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/description',
                                     'value': description, 'op': 'replace'}])
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(200, response.status_code)
        result = self.get_json('/chassis/%s' % chassis.uuid)
        self.assertEqual(description, result['description'])
        return_updated_at = timeutils.parse_isotime(
                            result['updated_at']).replace(tzinfo=None)
        self.assertEqual(test_time, return_updated_at)

    def test_replace_multi(self):
        extra = {"foo1": "bar1", "foo2": "bar2", "foo3": "bar3"}
        chassis = obj_utils.create_test_chassis(self.context, extra=extra,
                                                uuid=utils.generate_uuid(),
                                                id=1)
        new_value = 'new value'
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/extra/foo2',
                                     'value': new_value, 'op': 'replace'}])
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(200, response.status_code)
        result = self.get_json('/chassis/%s' % chassis.uuid)

        extra["foo2"] = new_value
        self.assertEqual(extra, result['extra'])

    def test_remove_singular(self):
        chassis = obj_utils.create_test_chassis(self.context, extra={'a': 'b'},
                                                uuid=utils.generate_uuid(),
                                                id=1)
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/description', 'op': 'remove'}])
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(200, response.status_code)
        result = self.get_json('/chassis/%s' % chassis.uuid)
        self.assertIsNone(result['description'])

        # Assert nothing else was changed
        self.assertEqual(chassis.uuid, result['uuid'])
        self.assertEqual(chassis.extra, result['extra'])

    def test_remove_multi(self):
        extra = {"foo1": "bar1", "foo2": "bar2", "foo3": "bar3"}
        chassis = obj_utils.create_test_chassis(self.context, extra=extra,
                                                description="foobar",
                                                uuid=utils.generate_uuid(),
                                                id=1)

        # Removing one item from the collection
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/extra/foo2', 'op': 'remove'}])
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(200, response.status_code)
        result = self.get_json('/chassis/%s' % chassis.uuid)
        extra.pop("foo2")
        self.assertEqual(extra, result['extra'])

        # Removing the collection
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/extra', 'op': 'remove'}])
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(200, response.status_code)
        result = self.get_json('/chassis/%s' % chassis.uuid)
        self.assertEqual({}, result['extra'])

        # Assert nothing else was changed
        self.assertEqual(chassis.uuid, result['uuid'])
        self.assertEqual(chassis.description, result['description'])

    def test_remove_non_existent_property_fail(self):
        chassis = obj_utils.get_test_chassis(self.context)
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                             [{'path': '/extra/non-existent', 'op': 'remove'}],
                             expect_errors=True)
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(400, response.status_code)
        self.assertTrue(response.json['error_message'])

    def test_add_root(self):
        chassis = obj_utils.get_test_chassis(self.context)
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/description', 'value': 'test',
                                     'op': 'add'}])
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(200, response.status_int)

    def test_add_root_non_existent(self):
        chassis = obj_utils.get_test_chassis(self.context)
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/foo', 'value': 'bar',
                                     'op': 'add'}],
                                   expect_errors=True)
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(400, response.status_int)
        self.assertTrue(response.json['error_message'])

    def test_add_multi(self):
        chassis = obj_utils.get_test_chassis(self.context)
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/extra/foo1', 'value': 'bar1',
                                     'op': 'add'},
                                    {'path': '/extra/foo2', 'value': 'bar2',
                                     'op': 'add'}])
        self.assertEqual('application/json', response.content_type)
        self.assertEqual(200, response.status_code)
        result = self.get_json('/chassis/%s' % chassis.uuid)
        expected = {"foo1": "bar1", "foo2": "bar2"}
        self.assertEqual(expected, result['extra'])

    def test_patch_nodes_subresource(self):
        chassis = obj_utils.get_test_chassis(self.context)
        response = self.patch_json('/chassis/%s/nodes' % chassis.uuid,
                                   [{'path': '/extra/foo', 'value': 'bar',
                                     'op': 'add'}], expect_errors=True)
        self.assertEqual(403, response.status_int)

    def test_remove_uuid(self):
        chassis = obj_utils.get_test_chassis(self.context)
        response = self.patch_json('/chassis/%s' % chassis.uuid,
                                   [{'path': '/uuid', 'op': 'remove'}],
                                   expect_errors=True)
        self.assertEqual(400, response.status_int)
        self.assertEqual('application/json', response.content_type)
        self.assertTrue(response.json['error_message'])

class TestPost(base.FunctionalTest):

    @mock.patch.object(timeutils, 'utcnow')
    def test_create_chassis(self, mock_utcnow):
        cdict = apiutils.chassis_post_data()
        test_time = datetime.datetime(2000, 1, 1, 0, 0)
        mock_utcnow.return_value = test_time

        response = self.post_json('/chassis', cdict)
        self.assertEqual(201, response.status_int)
        result = self.get_json('/chassis/%s' % cdict['uuid'])
        self.assertEqual(cdict['uuid'], result['uuid'])
        self.assertFalse(result['updated_at'])
        return_created_at = timeutils.parse_isotime(
                            result['created_at']).replace(tzinfo=None)
        self.assertEqual(test_time, return_created_at)
        # Check location header
        self.assertIsNotNone(response.location)
        expected_location = '/v1/chassis/%s' % cdict['uuid']
        self.assertEqual(urlparse.urlparse(response.location).path,
                         expected_location)

    def test_create_chassis_doesnt_contain_id(self):
        with mock.patch.object(self.dbapi, 'create_chassis',
                               wraps=self.dbapi.create_chassis) as cc_mock:
            cdict = apiutils.chassis_post_data(extra={'foo': 123})
            self.post_json('/chassis', cdict)
            result = self.get_json('/chassis/%s' % cdict['uuid'])
            self.assertEqual(cdict['extra'], result['extra'])
            cc_mock.assert_called_once_with(mock.ANY)
            # Check that 'id' is not in first arg of positional args
            self.assertNotIn('id', cc_mock.call_args[0][0])

    def test_create_chassis_generate_uuid(self):
        cdict = apiutils.chassis_post_data()
        del cdict['uuid']
        self.post_json('/chassis', cdict)
        result = self.get_json('/chassis')
        self.assertEqual(cdict['description'],
                         result['chassis'][0]['description'])
        self.assertTrue(utils.is_uuid_like(result['chassis'][0]['uuid']))

    def test_post_nodes_subresource(self):
        chassis = obj_utils.create_test_chassis(self.context)
        ndict = apiutils.node_post_data(chassis_id=None)
        ndict['chassis_uuid'] = chassis.uuid
        response = self.post_json('/chassis/nodes', ndict,
                                   expect_errors=True)
        self.assertEqual(403, response.status_int)

    def test_create_chassis_valid_extra(self):
        cdict = apiutils.chassis_post_data(extra={'foo': 123})
        self.post_json('/chassis', cdict)
        result = self.get_json('/chassis/%s' % cdict['uuid'])
        self.assertEqual(cdict['extra'], result['extra'])

    def test_create_chassis_invalid_extra(self):
        cdict = apiutils.chassis_post_data(extra={'foo': 0.123})
        response = self.post_json('/chassis', cdict, expect_errors=True)
        self.assertEqual(400, response.status_int)
        self.assertEqual('application/json', response.content_type)
        self.assertTrue(response.json['error_message'])

    def test_create_chassis_unicode_description(self):
        descr = u'\u0430\u043c\u043e'
        cdict = apiutils.chassis_post_data(description=descr)
        self.post_json('/chassis', cdict)
        result = self.get_json('/chassis/%s' % cdict['uuid'])
        self.assertEqual(descr, result['description'])

class TestDelete(base.FunctionalTest):

    def test_delete_chassis(self):
        chassis = obj_utils.create_test_chassis(self.context)
        self.delete('/chassis/%s' % chassis.uuid)
        response = self.get_json('/chassis/%s' % chassis.uuid,
                                 expect_errors=True)
        self.assertEqual(404, response.status_int)
        self.assertEqual('application/json', response.content_type)
        self.assertTrue(response.json['error_message'])

    def test_delete_chassis_with_node(self):
        chassis = obj_utils.create_test_chassis(self.context)
        obj_utils.create_test_node(self.context, chassis_id=chassis.id)
        response = self.delete('/chassis/%s' % chassis.uuid,
                               expect_errors=True)
        self.assertEqual(400, response.status_int)
        self.assertEqual('application/json', response.content_type)
        self.assertTrue(response.json['error_message'])
        self.assertIn(chassis.uuid, response.json['error_message'])

    def test_delete_chassis_not_found(self):
        uuid = utils.generate_uuid()
        response = self.delete('/chassis/%s' % uuid, expect_errors=True)
        self.assertEqual(404, response.status_int)
        self.assertEqual('application/json', response.content_type)
        self.assertTrue(response.json['error_message'])

    def test_delete_nodes_subresource(self):
        chassis = obj_utils.create_test_chassis(self.context)
        response = self.delete('/chassis/%s/nodes' % chassis.uuid,
                               expect_errors=True)
        self.assertEqual(403, response.status_int)


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\OpenApi\Factory;

use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Core\Bridge\Symfony\Routing\RouterOperationPathResolver;
use ApiPlatform\Core\DataProvider\PaginationOptions;
use ApiPlatform\Core\JsonSchema\Schema;
use ApiPlatform\Core\JsonSchema\SchemaFactory;
use ApiPlatform\Core\JsonSchema\TypeFactory;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use ApiPlatform\Core\Metadata\Property\PropertyNameCollection;
use ApiPlatform\Core\Metadata\Property\SubresourceMetadata;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
use ApiPlatform\Core\Metadata\Resource\ResourceNameCollection;
use ApiPlatform\Core\OpenApi\Factory\OpenApiFactory;
use ApiPlatform\Core\OpenApi\Model;
use ApiPlatform\Core\OpenApi\OpenApi;
use ApiPlatform\Core\OpenApi\Options;
use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactory;
use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactoryInterface;
use ApiPlatform\Core\Operation\UnderscorePathSegmentNameGenerator;
use ApiPlatform\Core\PathResolver\CustomOperationPathResolver;
use ApiPlatform\Core\PathResolver\OperationPathResolver;
use ApiPlatform\Core\Tests\Fixtures\DummyFilter;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Answer;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Question;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Psr\Container\ContainerInterface;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;

class OpenApiFactoryTest extends TestCase
{
    private const OPERATION_FORMATS = [
        'input_formats' => ['jsonld' => ['application/ld+json']],
        'output_formats' => ['jsonld' => ['application/ld+json']],
    ];

    public function testInvoke(): void
    {
        $dummyMetadata = new ResourceMetadata(
            'Dummy',
            'This is a dummy.',
            'http://schema.example.com/Dummy',
            [
                'get' => ['method' => 'GET'] + self::OPERATION_FORMATS,
                'put' => ['method' => 'PUT'] + self::OPERATION_FORMATS,
                'delete' => ['method' => 'DELETE'] + self::OPERATION_FORMATS,
                'custom' => ['method' => 'HEAD', 'path' => '/foo/{id}', 'openapi_context' => ['description' => 'Custom description']] + self::OPERATION_FORMATS,
                'formats' => ['method' => 'PUT', 'path' => '/formatted/{id}', 'output_formats' => ['json' => ['application/json'], 'csv' => ['text/csv']], 'input_formats' => ['json' => ['application/json'], 'csv' => ['text/csv']]],
            ],
            [
                'get' => ['method' => 'GET'] + self::OPERATION_FORMATS,
                'post' => ['method' => 'POST'] + self::OPERATION_FORMATS,
                'filtered' => ['method' => 'GET', 'filters' => ['f1', 'f2', 'f3', 'f4', 'f5'], 'path' => '/filtered'] + self::OPERATION_FORMATS,
                'paginated' => ['method' => 'GET', 'pagination_client_enabled' => true, 'pagination_client_items_per_page' => true, 'pagination_items_per_page' => 20, 'pagination_maximum_items_per_page' => 80, 'path' => '/paginated'] + self::OPERATION_FORMATS,
            ],
            ['pagination_client_items_per_page' => true]
        );

        $subresourceOperationFactoryProphecy = $this->prophesize(SubresourceOperationFactoryInterface::class);
        $subresourceOperationFactoryProphecy->create(Argument::any())->willReturn([]);

        $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $resourceNameCollectionFactoryProphecy->create()->shouldBeCalled()->willReturn(new ResourceNameCollection([Dummy::class]));

        $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class);
        $resourceMetadataFactoryProphecy->create(Dummy::class)->shouldBeCalled()->willReturn($dummyMetadata);

        $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
        $propertyNameCollectionFactoryProphecy->create(Dummy::class, Argument::any())->shouldBeCalled()->willReturn(new PropertyNameCollection(['id', 'name', 'description', 'dummyDate', 'enum']));

        $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'id', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_INT), 'This is an id.', true, false, null, null, null, true, null, null, null, null, null, null, null, ['minLength' => 3, 'maxLength' => 20, 'pattern' => '^dummyPattern$']));
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'name', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'This is a name.', true, true, true, true, false, false, null, null, [], null, null, null, null));
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'description', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'This is an initializable but not writable property.', true, false, true, true, false, false, null, null, [], null, true));
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'dummyDate', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_OBJECT, true, \DateTime::class), 'This is a \DateTimeInterface object.', true, true, true, true, false, false, null, null, []));
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'enum', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'This is an enum.', true, true, true, true, false, false, null, null, ['openapi_context' => ['type' => 'string', 'enum' => ['one', 'two'], 'example' => 'one']]));

        $operationPathResolver = new CustomOperationPathResolver(new OperationPathResolver(new UnderscorePathSegmentNameGenerator()));

        $filterLocatorProphecy = $this->prophesize(ContainerInterface::class);
        $filters = [
            'f1' => new DummyFilter(['name' => [
                'property' => 'name',
                'type' => 'string',
                'required' => true,
                'strategy' => 'exact',
                'openapi' => ['example' => 'bar', 'deprecated' => true, 'allowEmptyValue' => true, 'allowReserved' => true],
            ]]),
            'f2' => new DummyFilter(['ha' => [
                'property' => 'foo',
                'type' => 'int',
                'required' => false,
                'strategy' => 'partial',
            ]]),
            'f3' => new DummyFilter(['toto' => [
                'property' => 'name',
                'type' => 'array',
                'is_collection' => true,
                'required' => true,
                'strategy' => 'exact',
            ]]),
            'f4' => new DummyFilter(['order[name]' => [
                'property' => 'name',
                'type' => 'string',
                'required' => false,
                'schema' => [
                    'type' => 'string',
                    'enum' => ['asc', 'desc'],
                ],
            ]]),
        ];

        foreach ($filters as $filterId => $filter) {
            $filterLocatorProphecy->has($filterId)->willReturn(true)->shouldBeCalled();
            $filterLocatorProphecy->get($filterId)->willReturn($filter)->shouldBeCalled();
        }

        $filterLocatorProphecy->has('f5')->willReturn(false)->shouldBeCalled();

        $resourceMetadataFactory = $resourceMetadataFactoryProphecy->reveal();
        $propertyNameCollectionFactory = $propertyNameCollectionFactoryProphecy->reveal();

        $propertyMetadataFactory = $propertyMetadataFactoryProphecy->reveal();

        $typeFactory = new TypeFactory();
        $schemaFactory = new SchemaFactory($typeFactory, $resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, new CamelCaseToSnakeCaseNameConverter());
        $typeFactory->setSchemaFactory($schemaFactory);

        $identifiersExtractorProphecy = $this->prophesize(IdentifiersExtractorInterface::class);
        $identifiersExtractorProphecy->getIdentifiersFromResourceClass(Argument::type('string'))->willReturn(['id']);

        $factory = new OpenApiFactory(
            $resourceNameCollectionFactoryProphecy->reveal(),
            $resourceMetadataFactory,
            $propertyNameCollectionFactory,
            $propertyMetadataFactory,
            $schemaFactory,
            $typeFactory,
            $operationPathResolver,
            $filterLocatorProphecy->reveal(),
            $subresourceOperationFactoryProphecy->reveal(),
            $identifiersExtractorProphecy->reveal(),
            [],
            new Options('Test API', 'This is a test API.', '1.2.3', true, 'oauth2', 'authorizationCode', '/oauth/v2/token', '/oauth/v2/auth', '/oauth/v2/refresh', ['scope param'], [
                'header' => [
                    'type' => 'header',
                    'name' => 'Authorization',
                ],
                'query' => [
                    'type' => 'query',
                    'name' => 'key',
                ],
            ]),
            new PaginationOptions(true, 'page', true, 'itemsPerPage', true, 'pagination')
        );

        $dummySchema = new Schema('openapi');
        // $dummySchema = new Model\Schema(false, null, false, false, null, ['url' => 'http://schema.example.com/Dummy']);
        $dummySchema->setDefinitions(new \ArrayObject([
            'type' => 'object',
            'description' => 'This is a dummy.',
            'properties' => [
                'id' => new \ArrayObject([
                    'type' => 'integer',
                    'description' => 'This is an id.',
                    'readOnly' => true,
                    'minLength' => 3,
                    'maxLength' => 20,
                    'pattern' => '^dummyPattern$',
                ]),
                'name' => new \ArrayObject([
                    'type' => 'string',
                    'description' => 'This is a name.',
                ]),
                'description' => new \ArrayObject([
                    'type' => 'string',
                    'description' => 'This is an initializable but not writable property.',
                ]),
                'dummy_date' => new \ArrayObject([
                    'type' => 'string',
                    'description' => 'This is a \DateTimeInterface object.',
                    'format' => 'date-time',
                    'nullable' => true,
                ]),
                'enum' => new \ArrayObject([
                    'type' => 'string',
                    'enum' => ['one', 'two'],
                    'example' => 'one',
                    'description' => 'This is an enum.',
                ]),
            ],
            'externalDocs' => ['url' => 'http://schema.example.com/Dummy'],
        ]));

        $openApi = $factory(['base_url' => '/app_dev.php/']);

        $this->assertInstanceOf(OpenApi::class, $openApi);
        $this->assertEquals($openApi->getInfo(), new Model\Info('Test API', '1.2.3', 'This is a test API.'));
        $this->assertEquals($openApi->getServers(), [new Model\Server('/app_dev.php/')]);

        $components = $openApi->getComponents();
        $this->assertInstanceOf(Model\Components::class, $components);

        $this->assertEquals($components->getSchemas(), new \ArrayObject(['Dummy' => $dummySchema->getDefinitions()]));

        $this->assertEquals($components->getSecuritySchemes(), new \ArrayObject([
            'oauth' => new Model\SecurityScheme('oauth2', 'OAuth 2.0 authorization code Grant', null, null, 'oauth2', null, new Model\OAuthFlows(null, null, null, new Model\OAuthFlow('/oauth/v2/auth', '/oauth/v2/token', '/oauth/v2/refresh', new \ArrayObject(['scope param'])))),
            'header' => new Model\SecurityScheme('apiKey', 'Value for the Authorization header parameter.', 'Authorization', 'header'),
            'query' => new Model\SecurityScheme('apiKey', 'Value for the key query parameter.', 'key', 'query'),
        ]));

        $paths = $openApi->getPaths();
        $dummiesPath = $paths->getPath('/dummies');
        $this->assertNotNull($dummiesPath);
        foreach (['Put', 'Head', 'Trace', 'Delete', 'Options', 'Patch'] as $method) {
            $this->assertNull($dummiesPath->{'get'.$method}());
        }

        $this->assertEquals($dummiesPath->getGet(), new Model\Operation(
            'getDummyCollection',
            ['Dummy'],
            [
                '200' => new Model\Response('Dummy collection', new \ArrayObject([
                    'application/ld+json' => new Model\MediaType(new \ArrayObject(new \ArrayObject([
                        'type' => 'array',
                        'items' => ['$ref' => '#/components/schemas/Dummy'],
                    ]))),
                ])),
            ],
            '',
            'Retrieves the collection of Dummy resources.',
            null,
            [
                new Model\Parameter('page', 'query', 'The collection page number', false, false, true, [
                    'type' => 'integer',
                    'default' => 1,
                ]),
                new Model\Parameter('itemsPerPage', 'query', 'The number of items per page', false, false, true, [
                    'type' => 'integer',
                    'default' => 30,
                    'minimum' => 0,
                ]),
                new Model\Parameter('pagination', 'query', 'Enable or disable pagination', false, false, true, [
                    'type' => 'boolean',
                ]),
            ]
        ));

        $this->assertEquals($dummiesPath->getPost(), new Model\Operation(
            'postDummyCollection',
            ['Dummy'],
            [
                '201' => new Model\Response(
                    'Dummy resource created',
                    new \ArrayObject([
                        'application/ld+json' => new Model\MediaType(new \ArrayObject(new \ArrayObject(['$ref' => '#/components/schemas/Dummy']))),
                    ]),
                    null,
                    new \ArrayObject(['GetDummyItem' => new Model\Link('getDummyItem', new \ArrayObject(['id' => '$response.body#/id']), [], 'The `id` value returned in the response can be used as the `id` parameter in `GET /dummies/{id}`.')])
                ),
                '400' => new Model\Response('Invalid input'),
            ],
            '',
            'Creates a Dummy resource.',
            null,
            [],
            new Model\RequestBody(
                'The new Dummy resource',
                new \ArrayObject([
                    'application/ld+json' => new Model\MediaType(new \ArrayObject(new \ArrayObject(['$ref' => '#/components/schemas/Dummy']))),
                ]),
                true
            )
        ));

        $dummyPath = $paths->getPath('/dummies/{id}');
        $this->assertNotNull($dummyPath);
        foreach (['Post', 'Head', 'Trace', 'Options', 'Patch'] as $method) {
            $this->assertNull($dummyPath->{'get'.$method}());
        }

        $this->assertEquals($dummyPath->getGet(), new Model\Operation(
            'getDummyItem',
            ['Dummy'],
            [
                '200' => new Model\Response(
                    'Dummy resource',
                    new \ArrayObject([
                        'application/ld+json' => new Model\MediaType(new \ArrayObject(new \ArrayObject(['$ref' => '#/components/schemas/Dummy']))),
                    ])
                ),
                '404' => new Model\Response('Resource not found'),
            ],
            '',
            'Retrieves a Dummy resource.',
            null,
            [new Model\Parameter('id', 'path', 'Resource identifier', true, false, false, ['type' => 'string'])]
        ));

        $this->assertEquals($dummyPath->getPut(), new Model\Operation(
            'putDummyItem',
            ['Dummy'],
            [
                '200' => new Model\Response(
                    'Dummy resource updated',
                    new \ArrayObject([
                        'application/ld+json' => new Model\MediaType(new \ArrayObject(['$ref' => '#/components/schemas/Dummy'])),
                    ]),
                    null,
                    new \ArrayObject(['GetDummyItem' => new Model\Link('getDummyItem', new \ArrayObject(['id' => '$response.body#/id']), [], 'The `id` value returned in the response can be used as the `id` parameter in `GET /dummies/{id}`.')])
                ),
                '400' => new Model\Response('Invalid input'),
                '404' => new Model\Response('Resource not found'),
            ],
            '',
            'Replaces the Dummy resource.',
            null,
            [new Model\Parameter('id', 'path', 'Resource identifier', true, false, false, ['type' => 'string'])],
            new Model\RequestBody(
                'The updated Dummy resource',
                new \ArrayObject([
                    'application/ld+json' => new Model\MediaType(new \ArrayObject(['$ref' => '#/components/schemas/Dummy'])),
                ]),
                true
            )
        ));

        $this->assertEquals($dummyPath->getDelete(), new Model\Operation(
            'deleteDummyItem',
            ['Dummy'],
            [
                '204' => new Model\Response('Dummy resource deleted'),
                '404' => new Model\Response('Resource not found'),
            ],
            '',
            'Removes the Dummy resource.',
            null,
            [new Model\Parameter('id', 'path', 'Resource identifier', true, false, false, ['type' => 'string'])]
        ));

        $customPath = $paths->getPath('/foo/{id}');
        $this->assertEquals($customPath->getHead(), new Model\Operation(
            'customDummyItem',
            ['Dummy'],
            [
                '404' => new Model\Response('Resource not found'),
            ],
            '',
            'Custom description',
            null,
            [new Model\Parameter('id', 'path', 'Resource identifier', true, false, false, ['type' => 'string'])]
        ));

        $formattedPath = $paths->getPath('/formatted/{id}');
        $this->assertEquals($formattedPath->getPut(), new Model\Operation(
            'formatsDummyItem',
            ['Dummy'],
            [
                '200' => new Model\Response(
                    'Dummy resource updated',
                    new \ArrayObject([
                        'application/json' => new Model\MediaType(new \ArrayObject(['$ref' => '#/components/schemas/Dummy'])),
                        'text/csv' => new Model\MediaType(new \ArrayObject(['$ref' => '#/components/schemas/Dummy'])),
                    ]),
                    null,
                    new \ArrayObject(['GetDummyItem' => new Model\Link('getDummyItem', new \ArrayObject(['id' => '$response.body#/id']), [], 'The `id` value returned in the response can be used as the `id` parameter in `GET /dummies/{id}`.')])
                ),
                '400' => new Model\Response('Invalid input'),
                '404' => new Model\Response('Resource not found'),
            ],
            '',
            'Replaces the Dummy resource.',
            null,
            [new Model\Parameter('id', 'path', 'Resource identifier', true, false, false, ['type' => 'string'])],
            new Model\RequestBody(
                'The updated Dummy resource',
                new \ArrayObject([
                    'application/json' => new Model\MediaType(new \ArrayObject(['$ref' => '#/components/schemas/Dummy'])),
                    'text/csv' => new Model\MediaType(new \ArrayObject(['$ref' => '#/components/schemas/Dummy'])),
                ]),
                true
            )
        ));

        $filteredPath = $paths->getPath('/filtered');
        $this->assertEquals($filteredPath->getGet(), new Model\Operation(
            'filteredDummyCollection',
            ['Dummy'],
            [
                '200' => new Model\Response('Dummy collection', new \ArrayObject([
                    'application/ld+json' => new Model\MediaType(new \ArrayObject([
                        'type' => 'array',
                        'items' => ['$ref' => '#/components/schemas/Dummy'],
                    ])),
                ])),
            ],
            '',
            'Retrieves the collection of Dummy resources.',
            null,
            [
                new Model\Parameter('page', 'query', 'The collection page number', false, false, true, [
                    'type' => 'integer',
                    'default' => 1,
                ]),
                new Model\Parameter('itemsPerPage', 'query', 'The number of items per page', false, false, true, [
                    'type' => 'integer',
                    'default' => 30,
                    'minimum' => 0,
                ]),
                new Model\Parameter('pagination', 'query', 'Enable or disable pagination', false, false, true, [
                    'type' => 'boolean',
                ]),
                new Model\Parameter('name', 'query', '', true, true, true, [
                    'type' => 'string',
                ], 'form', false, true, 'bar'),
                new Model\Parameter('ha', 'query', '', false, false, true, [
                    'type' => 'integer',
                ]),
                new Model\Parameter('toto', 'query', '', true, false, true, [
                    'type' => 'array',
                    'items' => ['type' => 'string'],
                ], 'deepObject', true),
                new Model\Parameter('order[name]', 'query', '', false, false, true, [
                    'type' => 'string',
                ]),
            ]
        ));

        $paginatedPath = $paths->getPath('/paginated');
        $this->assertEquals($paginatedPath->getGet(), new Model\Operation(
            'paginatedDummyCollection',
            ['Dummy'],
            [
                '200' => new Model\Response('Dummy collection', new \ArrayObject([
                    'application/ld+json' => new Model\MediaType(new \ArrayObject([
                        'type' => 'array',
                        'items' => ['$ref' => '#/components/schemas/Dummy'],
                    ])),
                ])),
            ],
            '',
            'Retrieves the collection of Dummy resources.',
            null,
            [
                new Model\Parameter('page', 'query', 'The collection page number', false, false, true, [
                    'type' => 'integer',
                    'default' => 1,
                ]),
                new Model\Parameter('itemsPerPage', 'query', 'The number of items per page', false, false, true, [
                    'type' => 'integer',
                    'default' => 20,
                    'minimum' => 0,
                    'maximum' => 80,
                ]),
                new Model\Parameter('pagination', 'query', 'Enable or disable pagination', false, false, true, [
                    'type' => 'boolean',
                ]),
            ]
        ));
    }

    public function testOverrideDocumentation()
    {
        $defaultContext = ['base_url' => '/app_dev.php/'];

        $dummyMetadata = new ResourceMetadata(
            'Dummy',
            'This is a dummy.',
            'http://schema.example.com/Dummy',
            [
                'get' => ['method' => 'GET'] + self::OPERATION_FORMATS,
                'put' => ['method' => 'PUT'] + self::OPERATION_FORMATS,
                'delete' => ['method' => 'DELETE'] + self::OPERATION_FORMATS,
            ],
            [
                'get' => ['method' => 'GET'] + self::OPERATION_FORMATS,
                'post' => ['method' => 'POST'] + self::OPERATION_FORMATS,
            ],
            []
        );

        $subresourceOperationFactoryProphecy = $this->prophesize(SubresourceOperationFactoryInterface::class);
        $subresourceOperationFactoryProphecy->create(Argument::any())->willReturn([]);

        $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $resourceNameCollectionFactoryProphecy->create()->shouldBeCalled()->willReturn(new ResourceNameCollection([Dummy::class]));

        $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class);
        $resourceMetadataFactoryProphecy->create(Dummy::class)->shouldBeCalled()->willReturn($dummyMetadata);

        $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
        $propertyNameCollectionFactoryProphecy->create(Dummy::class, Argument::any())->shouldBeCalled()->willReturn(new PropertyNameCollection(['id', 'name', 'description', 'dummyDate']));
        $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'id', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_INT), 'This is an id.', true, false, null, null, null, true, null, null, null, null, null, null, null, ['minLength' => 3, 'maxLength' => 20, 'pattern' => '^dummyPattern$']));
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'name', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'This is a name.', true, true, true, true, false, false, null, null, [], null, null, null, null));
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'description', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'This is an initializable but not writable property.', true, false, true, true, false, false, null, null, [], null, true));
        $propertyMetadataFactoryProphecy->create(Dummy::class, 'dummyDate', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_OBJECT, true, \DateTime::class), 'This is a \DateTimeInterface object.', true, true, true, true, false, false, null, null, []));

        $operationPathResolver = new CustomOperationPathResolver(new OperationPathResolver(new UnderscorePathSegmentNameGenerator()));
        $filterLocatorProphecy = $this->prophesize(ContainerInterface::class);
        $resourceMetadataFactory = $resourceMetadataFactoryProphecy->reveal();
        $propertyNameCollectionFactory = $propertyNameCollectionFactoryProphecy->reveal();
        $propertyMetadataFactory = $propertyMetadataFactoryProphecy->reveal();

        $typeFactory = new TypeFactory();
        $schemaFactory = new SchemaFactory($typeFactory, $resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, new CamelCaseToSnakeCaseNameConverter());
        $typeFactory->setSchemaFactory($schemaFactory);

        $identifiersExtractorProphecy = $this->prophesize(IdentifiersExtractorInterface::class);
        $identifiersExtractorProphecy->getIdentifiersFromResourceClass(Argument::type('string'))->willReturn(['id']);

        $factory = new OpenApiFactory(
            $resourceNameCollectionFactoryProphecy->reveal(),
            $resourceMetadataFactory,
            $propertyNameCollectionFactory,
            $propertyMetadataFactory,
            $schemaFactory,
            $typeFactory,
            $operationPathResolver,
            $filterLocatorProphecy->reveal(),
            $subresourceOperationFactoryProphecy->reveal(),
            $identifiersExtractorProphecy->reveal(),
            [],
            new Options('Test API', 'This is a test API.', '1.2.3', true, 'oauth2', 'authorizationCode', '/oauth/v2/token', '/oauth/v2/auth', '/oauth/v2/refresh', ['scope param'], [
                'header' => [
                    'type' => 'header',
                    'name' => 'Authorization',
                ],
                'query' => [
                    'type' => 'query',
                    'name' => 'key',
                ],
            ]),
            new PaginationOptions(true, 'page', true, 'itemsPerPage', true, 'pagination')
        );

        $openApi = $factory(['base_url' => '/app_dev.php/']);

        $pathItem = $openApi->getPaths()->getPath('/dummies/{id}');
        $operation = $pathItem->getGet();

        $openApi->getPaths()->addPath('/dummies/{id}', $pathItem->withGet(
            $operation->withParameters(array_merge(
                $operation->getParameters(),
                [new Model\Parameter('fields', 'query', 'Fields to remove of the output')]
            ))
        ));

        $openApi = $openApi->withInfo((new Model\Info('New Title', 'v2', 'Description of my custom API'))->withExtensionProperty('info-key', 'Info value'));
        $openApi = $openApi->withExtensionProperty('key', 'Custom x-key value');
        $openApi = $openApi->withExtensionProperty('x-value', 'Custom x-value value');

        $this->assertEquals($openApi->getInfo()->getExtensionProperties(), ['x-info-key' => 'Info value']);
        $this->assertEquals($openApi->getExtensionProperties(), ['x-key' => 'Custom x-key value', 'x-value' => 'Custom x-value value']);
    }

    public function testSubresourceDocumentation()
    {
        $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
        $propertyNameCollectionFactoryProphecy->create(Question::class, Argument::any())->shouldBeCalled()->willReturn(new PropertyNameCollection(['answer']));
        $propertyNameCollectionFactoryProphecy->create(Answer::class, Argument::any())->shouldBeCalled()->willReturn(new PropertyNameCollection(['content']));

        $questionMetadata = new ResourceMetadata(
            'Question',
            'This is a question.',
            'http://schema.example.com/Question',
            ['get' => ['method' => 'GET', 'input_formats' => ['json' => ['application/json'], 'csv' => ['text/csv']], 'output_formats' => ['json' => ['application/json'], 'csv' => ['text/csv']]]]
        );
        $answerMetadata = new ResourceMetadata(
            'Answer',
            'This is an answer.',
            'http://schema.example.com/Answer',
            [],
            ['get' => ['method' => 'GET'] + self::OPERATION_FORMATS],
            [],
            ['get' => ['method' => 'GET', 'input_formats' => ['xml' => ['text/xml']], 'output_formats' => ['xml' => ['text/xml']]]]
        );
        $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class);
        $resourceMetadataFactoryProphecy->create(Question::class)->shouldBeCalled()->willReturn($questionMetadata);
        $resourceMetadataFactoryProphecy->create(Answer::class)->shouldBeCalled()->willReturn($answerMetadata);

        $subresourceMetadata = new SubresourceMetadata(Answer::class, false);
        $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
        $propertyMetadataFactoryProphecy->create(Question::class, 'answer', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_OBJECT, false, Question::class, true, null, new Type(Type::BUILTIN_TYPE_OBJECT, false, Answer::class)), 'This is a name.', true, true, true, true, false, false, null, null, [], $subresourceMetadata));

        $propertyMetadataFactoryProphecy->create(Answer::class, 'content', Argument::any())->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_OBJECT, false, Question::class, true, null, new Type(Type::BUILTIN_TYPE_OBJECT, false, Answer::class)), 'This is a name.', true, true, true, true, false, false, null, null, []));

        $routeCollection = new RouteCollection();
        $routeCollection->add('api_answers_get_collection', new Route('/api/answers.{_format}'));
        $routeCollection->add('api_questions_answer_get_subresource', new Route('/api/questions/{id}/answer.{_format}'));
        $routeCollection->add('api_questions_get_item', new Route('/api/questions/{id}.{_format}'));

        $routerProphecy = $this->prophesize(RouterInterface::class);
        $routerProphecy->getRouteCollection()->shouldBeCalled()->willReturn($routeCollection);

        $operationPathResolver = new RouterOperationPathResolver($routerProphecy->reveal(), new CustomOperationPathResolver(new OperationPathResolver(new UnderscorePathSegmentNameGenerator())));

        $resourceMetadataFactory = $resourceMetadataFactoryProphecy->reveal();
        $propertyNameCollectionFactory = $propertyNameCollectionFactoryProphecy->reveal();
        $propertyMetadataFactory = $propertyMetadataFactoryProphecy->reveal();

        $identifiersExtractorProphecy = $this->prophesize(IdentifiersExtractorInterface::class);
        $identifiersExtractorProphecy->getIdentifiersFromResourceClass(Argument::type('string'))->willReturn(['id']);
        $identifiersExtractor = $identifiersExtractorProphecy->reveal();

        $subresourceOperationFactory = new SubresourceOperationFactory($resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, new UnderscorePathSegmentNameGenerator(), $identifiersExtractor);

        $resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $resourceNameCollectionFactoryProphecy->create()->shouldBeCalled()->willReturn(new ResourceNameCollection([Question::class, Answer::class]));

        $typeFactory = new TypeFactory();
        $schemaFactory = new SchemaFactory($typeFactory, $resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, new CamelCaseToSnakeCaseNameConverter());
        $typeFactory->setSchemaFactory($schemaFactory);
        $filterLocatorProphecy = $this->prophesize(ContainerInterface::class);

        $factory = new OpenApiFactory(
            $resourceNameCollectionFactoryProphecy->reveal(),
            $resourceMetadataFactory,
            $propertyNameCollectionFactory,
            $propertyMetadataFactory,
            $schemaFactory,
            $typeFactory,
            $operationPathResolver,
            $filterLocatorProphecy->reveal(),
            $subresourceOperationFactory,
            $identifiersExtractor,
            ['jsonld' => ['application/ld+json']],
            new Options('Test API', 'This is a test API.', '1.2.3', true, 'oauth2', 'authorizationCode', '/oauth/v2/token', '/oauth/v2/auth', '/oauth/v2/refresh', ['scope param'], [
                'header' => [
                    'type' => 'header',
                    'name' => 'Authorization',
                ],
                'query' => [
                    'type' => 'query',
                    'name' => 'key',
                ],
            ]),
            new PaginationOptions(true, 'page', true, 'itemsPerPage', true, 'pagination')
        );

        $openApi = $factory(['base_url', '/app_dev.php/']);

        $paths = $openApi->getPaths();
        $pathItem = $paths->getPath('/questions/{id}/answer');

        $this->assertEquals($pathItem->getGet(), new Model\Operation(
            'api_questions_answer_get_subresourceQuestionSubresource',
            ['Answer', 'Question'],
            [
                '200' => new Model\Response(
                    'Question resource',
                    new \ArrayObject([
                        'application/ld+json' => new Model\MediaType(new \ArrayObject(new \ArrayObject(['$ref' => '#/components/schemas/Answer']))),
                    ])
                ),
            ],
            '',
            'Retrieves a Question resource.',
            null,
            [new Model\Parameter('id', 'path', 'Question identifier', true, false, false, ['type' => 'string'])]
        ));
    }
}


text:
class CreateFacts < ActiveRecord::Migration
  def change
    create_table :facts do |t|
      t.string :operation
      t.integer :number_1
      t.integer :number_2
      t.integer :solution
      t.timestamps null: false
    end
  end
end


text:
package com.sksamuel.elastic4s.requests.common

case class Shards(total: Int, failed: Int, successful: Int)