text:
/*
 * Do not modify this file. This file is generated from the cognito-identity-2014-06-30.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.CognitoIdentity.Model
{
    ///
    /// Returned in response to a successful GetOpenIdTokenForDeveloperIdentity
    /// request.
    ///
    public partial class GetOpenIdTokenForDeveloperIdentityResponse : AmazonWebServiceResponse
    {
        private string _identityId;
        private string _token;

        ///
        /// Gets and sets the property IdentityId.
        /// <para>
        /// A unique identifier in the format REGION:GUID.
        /// </para>
        ///
        public string IdentityId
        {
            get { return this._identityId; }
            set { this._identityId = value; }
        }

        // Check to see if IdentityId property is set
        internal bool IsSetIdentityId()
        {
            return this._identityId != null;
        }

        ///
        /// Gets and sets the property Token.
        /// <para>
        /// An OpenID token.
        /// </para>
        ///
        public string Token
        {
            get { return this._token; }
            set { this._token = value; }
        }

        // Check to see if Token property is set
        internal bool IsSetToken()
        {
            return this._token != null;
        }

    }
}


text:
package io.udash
package rest.raw

import com.avsystem.commons.misc.ImplicitNotFound
import com.avsystem.commons.rpc.{AsRaw, AsRawReal, AsReal}
import com.avsystem.commons.serialization.GenCodec.ReadFailure
import com.avsystem.commons.serialization.json.{JsonReader, JsonStringInput, JsonStringOutput}
import com.avsystem.commons.{JStringBuilder, Opt, OptArg, _}

import scala.annotation.implicitNotFound
import scala.util.hashing.MurmurHash3

/**
  * Value used to represent HTTP body. Also used as direct encoding of [[io.udash.rest.Body Body]] parameter in
  * [[io.udash.rest.CustomBody CustomBody]] methods.
  * Types that have encoding to [[io.udash.rest.raw.JsonValue JsonValue]] automatically have encoding to
  * [[io.udash.rest.raw.HttpBody HttpBody]] with `application/json` media type.
  * There is also a specialized encoding provided for `Unit` which returns empty HTTP body when writing and ignores
  * the body when reading.
  */
sealed trait HttpBody {
  def nonEmptyOpt: Opt[HttpBody.NonEmpty] = this match {
    case ne: HttpBody.NonEmpty => Opt(ne)
    case _ => Opt.Empty
  }

  final def textualContentOpt: Opt[String] =
    nonEmptyOpt.map(_.readText())

  final def readJson(defaultCharset: String = HttpBody.Utf8Charset): JsonValue =
    JsonValue(readText(HttpBody.JsonType, defaultCharset))

  final def readForm(defaultCharset: String = HttpBody.Utf8Charset): String =
    readText(HttpBody.FormType, defaultCharset)

  final def readText(requiredMediaType: OptArg[String] = OptArg.Empty, defaultCharset: String = HttpBody.Utf8Charset): String = this match {
    case HttpBody.Empty =>
      throw new ReadFailure("Expected non-empty textual body")
    case ne: HttpBody.NonEmpty if requiredMediaType.forall(_ == ne.mediaType) =>
      ne.text(defaultCharset)
    case ne: HttpBody.NonEmpty =>
      throw new ReadFailure(s"Expected non-empty textual body" +
        requiredMediaType.fold("")(mt => s" with media type $mt") +
        s" but got body with content type ${ne.contentType}")
  }

  final def readBytes(requiredMediaType: OptArg[String] = OptArg.Empty): Array[Byte] = this match {
    case HttpBody.Empty => throw new ReadFailure("Expected non-empty body")
    case ne: HttpBody.NonEmpty if requiredMediaType.forall(_ == ne.mediaType) => ne.bytes
    case ne: HttpBody.NonEmpty =>
      throw new ReadFailure(s"Expected non-empty body" +
        requiredMediaType.fold("")(mt => s" with media type $mt") +
        s" but got body with content type ${ne.contentType}")
  }

  final def defaultStatus: Int = this match {
    case HttpBody.Empty => 204
    case _ => 200
  }

  final def defaultResponse: RestResponse =
    RestResponse(defaultStatus, IMapping.empty, this)
}
object HttpBody extends HttpBodyLowPrio {
  case object Empty extends HttpBody

  /**
    * Non empty body can be either textual or binary. This is mostly an optimization to avoid unnecessary conversions
    * between strings and byte arrays. Both [[Binary]] and [[Textual]] can be read as text and as raw bytes.
    */
  sealed trait NonEmpty extends HttpBody {
    def mediaType: String
    def contentType: String
    def text(defaultCharset: String = Utf8Charset): String
    def bytes: Array[Byte]
  }

  /**
    * Represents textual HTTP body. A body is considered textual if `Content-Type` has `charset` defined.
    */
  final case class Textual(content: String, mediaType: String, charset: String) extends NonEmpty {
    def contentType: String = s"$mediaType;charset=$charset"
    def text(defaultCharset: String): String = content
    lazy val bytes: Array[Byte] = content.getBytes(charset)
  }

  /**
    * Represents binary HTTP body. A body is considered binary if `Content-Type` does not have `charset` defined.
    */
  final case class Binary(bytes: Array[Byte], contentType: String) extends NonEmpty {
    def mediaType: String = mediaTypeOf(contentType)
    def text(defaultCharset: String): String = defaultCharset match {
      case Utf8Charset => utf8text
      case _ => new String(bytes, defaultCharset)
    }
    lazy val utf8text: String = new String(bytes, Utf8Charset)

    override def hashCode(): Int =
      MurmurHash3.mixLast(MurmurHash3.bytesHash(bytes), MurmurHash3.stringHash(contentType))

    override def equals(obj: Any): Boolean = obj match {
      case Binary(otherBytes, otherContentType) =>
        java.util.Arrays.equals(bytes, otherBytes) && contentType == otherContentType
      case _ => false
    }

    override def toString: String =
      s"Binary(${bytes.iterator.map(b => f"$b%02X").mkString},$contentType)"
  }

  def empty: HttpBody = Empty

  def textual(content: String, mediaType: String = PlainType, charset: String = Utf8Charset): HttpBody =
    Textual(content, mediaType, charset)

  def binary(bytes: Array[Byte], contentType: String = OctetStreamType): HttpBody =
    Binary(bytes, contentType)

  final val PlainType = "text/plain"
  final val JsonType = "application/json"
  final val FormType = "application/x-www-form-urlencoded"
  final val OctetStreamType = "application/octet-stream"

  final val CharsetParamRegex = """;\s*charset=([^;]*)""".r

  final val Utf8Charset = "utf-8"

  def mediaTypeOf(contentType: String): String =
    contentType.indexOf(';') match {
      case -1 => contentType.trim
      case idx => contentType.substring(0, idx).trim
    }

  def charsetOf(contentType: String): Opt[String] =
    CharsetParamRegex.findFirstMatchIn(contentType)
      .toOpt.map(_.group(1).trim)
      .map { charset =>
        if (charset.startsWith("\"") && charset.endsWith("\""))
          charset.substring(1, charset.length - 1)
        else charset
      }

  def plain(content: OptArg[String] = OptArg.Empty): HttpBody =
    content.toOpt.map(textual(_, PlainType)).getOrElse(Empty)

  def json(json: JsonValue): HttpBody = textual(json.value, JsonType)

  def createFormBody(values: Mapping[PlainValue]): HttpBody =
    if (values.isEmpty) HttpBody.Empty else textual(PlainValue.encodeQuery(values), FormType)

  def parseFormBody(body: HttpBody): Mapping[PlainValue] = body match {
    case HttpBody.Empty => Mapping.empty[PlainValue]
    case _ => PlainValue.decodeQuery(body.readForm())
  }

  def createJsonBody(fields: Mapping[JsonValue]): HttpBody =
    if (fields.isEmpty) HttpBody.Empty else {
      val sb = new JStringBuilder
      val oo = new JsonStringOutput(sb).writeObject()
      fields.entries.foreach {
        case (key, JsonValue(json)) =>
          oo.writeField(key).writeRawJson(json)
      }
      oo.finish()
      HttpBody.json(JsonValue(sb.toString))
    }

  def parseJsonBody(body: HttpBody): Mapping[JsonValue] = body match {
    case HttpBody.Empty => Mapping.empty
    case _ =>
      val oi = new JsonStringInput(new JsonReader(body.readJson().value)).readObject()
      val builder = Mapping.newBuilder[JsonValue]
      while (oi.hasNext) {
        val fi = oi.nextField()
        builder += ((fi.fieldName, JsonValue(fi.readRawJson())))
      }
      builder.result()
  }

  implicit val emptyBodyForUnit: AsRawReal[HttpBody, Unit] =
    AsRawReal.create(_ => HttpBody.Empty, _ => ())

  implicit val octetStreamBodyForByteArray: AsRawReal[HttpBody, Array[Byte]] =
    AsRawReal.create(binary(_), body => body.readBytes(OctetStreamType))
}
trait HttpBodyLowPrio { this: HttpBody.type =>
  implicit def httpBodyJsonAsRaw[T](implicit jsonAsRaw: AsRaw[JsonValue, T]): AsRaw[HttpBody, T] =
    v => HttpBody.json(jsonAsRaw.asRaw(v))
  implicit def httpBodyJsonAsReal[T](implicit jsonAsReal: AsReal[JsonValue, T]): AsReal[HttpBody, T] =
    v => jsonAsReal.asReal(v.readJson())

  @implicitNotFound("Cannot deserialize ${T} from HttpBody, because:\n#{forJson}")
  implicit def asRealNotFound[T](
    implicit forJson: ImplicitNotFound[AsReal[JsonValue, T]]
  ): ImplicitNotFound[AsReal[HttpBody, T]] = ImplicitNotFound()

  @implicitNotFound("Cannot serialize ${T} into HttpBody, because:\n#{forJson}")
  implicit def asRawNotFound[T](
    implicit forJson: ImplicitNotFound[AsRaw[JsonValue, T]]
  ): ImplicitNotFound[AsRaw[HttpBody, T]] = ImplicitNotFound()
}

redpajama_set_name: RedPajamaGithub


text:
package com.drew.lang;

import org.junit.Test;

/**
 * @author Drew Noakes https://drewnoakes.com
 */
public class SequentialByteArrayReaderTest extends SequentialAccessTestBase
{
    @SuppressWarnings({"ConstantConditions"})
    @Test(expected = NullPointerException.class)
    public void testConstructWithNullStreamThrows()
    {
        new SequentialByteArrayReader(null);
    }

    @Override
    protected SequentialReader createReader(byte[] bytes)
    {
        return new SequentialByteArrayReader(bytes);
    }
}


text:
"""Ce module contient la classe Affection, détaillée plus bas."""

from abstraits.obase import BaseObj

class Affection(BaseObj):

    """Affection concrète, affectant un subissant (personnage, salle...).

    Quand un subissant est affecté (la neige tombe dans une salle, par exemple), si l'affection n'est pas présente un objet de cette classe est créé. Il contient :
        L'objet indirectement hérité de AffectionAbstraite (Neige ici)
        Des valeurs propres à cette affection (sa durée restante, sa forcce)

    """

    def __init__(self, affection, affecte, duree, force):
        BaseObj.__init__(self)
        self.affecte = affecte
        self.affection = affection
        self.age = 0
        self.duree = duree
        self.force = force
        self._construire()
        if affection:
            affection.initialiser(self)

    def __getnewargs__(self):
        return (None, None, 0, 0)

    def __repr__(self):
        return "<affection de {} par {} (force={}, duree={})>".format(
                self.nom_affecte, self.cle_affection, self.force, self.duree)

    def __setstate__(self, dico_attrs):
        """Méthode appelée à la récfupération de l'objet."""
        BaseObj.__setstate__(self, dico_attrs)
        self.prevoir_tick()

    @property
    def nom_affecte(self):
        return self.affecte and self.affecte.nom_unique or "inconnu"

    @property
    def cle_affection(self):
        return self.affection and self.affection.cle or "aucune"

    def detruire(self):
        """Destruction de l'affection."""
        self.affection.programmer_destruction(self)
        BaseObj.detruire(self)

    def prevoir_tick(self):
        """Ajoute l'action à exécuter dans diffact."""
        if self.affection.tick_actif:
            importeur.diffact.ajouter_action("aff_" + str(id(self)),
                    self.affection.duree_tick, self.affection.tick, self)


text:
package boofcv.alg.geo.bundle;

import boofcv.alg.geo.RodriguesRotationJacobian;
import georegression.geometry.GeometryMath_F64;
import georegression.geometry.RotationMatrixGenerator;
import georegression.struct.point.Point3D_F64;
import georegression.struct.point.Vector3D_F64;
import georegression.struct.se.Se3_F64;
import georegression.struct.so.Rodrigues_F64;
import org.ddogleg.optimization.functions.FunctionNtoMxN;
import org.ejml.data.DenseMatrix64F;

import java.util.Arrays;
import java.util.List;

/**
 * Computes the Jacobian for {@link CalibPoseAndPointResiduals}.
 *
 * @author Peter Abeles
 */
public class CalibPoseAndPointRodriguesJacobian implements FunctionNtoMxN {

	// if the extrinsic parameters are known, specify them here
	Se3_F64 extrinsic[];
	// observed location of features in each view
	List<ViewPointObservations> observations;

	// number of camera views
	int numViews;
	// number of points in world coordinates
	int numPoints;
	// number of views with unknown extrinsic parameters
	int numViewsUnknown;
	// number of observations across all views
	int numObservations;
	// total number of parameters being optimized
	int numParameters;

	// used to compute the Jacobian from Rodrigues coordinates
	RodriguesRotationJacobian rodJacobian = new RodriguesRotationJacobian();

	// local variable which stores the predicted location of the feature in the camera frame
	Rodrigues_F64 rodrigues = new Rodrigues_F64();
	// rotation matrix
	DenseMatrix64F R = new DenseMatrix64F(3,3);
	// translation vector
	Vector3D_F64 T = new Vector3D_F64();
	// feature location in world coordinates
	Point3D_F64 worldPt = new Point3D_F64();
	// feature location in camera coordinates
	Point3D_F64 cameraPt = new Point3D_F64();

	// index in parameters of the first point
	int indexFirstPoint;
	// how many point observations have been processed
	int countPointObs;

	// Jacobian matrix index of x and y partial
	int indexX;
	int indexY;

	// reference to output Jacobian matrix
	double[] output;

	public void configure( List<ViewPointObservations> observations , int numPoints , Se3_F64 ...extrinsic) {
		if( extrinsic.length < observations.size() )
			throw new RuntimeException("knownExtrinsic length is less than the number of views in 'observations'");

		this.observations = observations;
		this.extrinsic = extrinsic;
		this.numViews = observations.size();
		this.numPoints = numPoints;

		numViewsUnknown = 0;
		numObservations = 0;
		for( int i = 0; i < numViews; i++ ) {
			if( extrinsic[i] == null )
				numViewsUnknown++;
			numObservations += observations.get(i).points.size;
		}

		indexFirstPoint = numViewsUnknown*6;
		numParameters = numViewsUnknown*6 + numPoints*3;
	}

	@Override
	public int getNumOfInputsN() {
		return numParameters;
	}

	@Override
	public int getNumOfOutputsM() {
		return numObservations*2;
	}

	@Override
	public void process(double[] input, double[] output) {
		this.output = output;
		int paramIndex = 0;
		countPointObs = 0;

		Arrays.fill(output,0);

		// first decode the transformation
		for( int i = 0; i < numViews; i++ ) {
			if( extrinsic[i] == null ) {
				double rodX = input[paramIndex++];
				double rodY = input[paramIndex++];
				double rodZ = input[paramIndex++];

				T.x = input[paramIndex++];
				T.y = input[paramIndex++];
				T.z = input[paramIndex++];

				rodrigues.setParamVector(rodX,rodY,rodZ);
				rodJacobian.process(rodX,rodY,rodZ);

				RotationMatrixGenerator.rodriguesToMatrix(rodrigues,R);
				ViewPointObservations obs = observations.get(i);
				gradientViewMotionAndPoint(input, paramIndex-6, obs);
			} else {
				T.set( extrinsic[i].getT());
				R.set( extrinsic[i].getR());

				ViewPointObservations obs = observations.get(i);
				gradientViewPoint(input, obs);
			}
		}
	}

	/**
	 * Computes the partials for the pose and observed points at this view
	 */
	private void gradientViewMotionAndPoint(double[] input,
											int extrinsicParamStart,
											ViewPointObservations obs)
	{
		for( int j = 0; j < obs.points.size; j++ , countPointObs++ ) {
			PointIndexObservation o = obs.points.get(j);
			int indexParamWorld = indexFirstPoint+o.pointIndex*3;

			// extract location of world point
			worldPt.x = input[indexParamWorld++];
			worldPt.y = input[indexParamWorld++];
			worldPt.z = input[indexParamWorld];

			// compute the index in output matrix for derivatives
			indexX = numParameters*countPointObs*2 + extrinsicParamStart;
			indexY = indexX + numParameters;

			// location of point in camera view
			GeometryMath_F64.mult(R, worldPt, cameraPt);
			cameraPt.x += T.x;
			cameraPt.y += T.y;
			cameraPt.z += T.z;

			// add gradient from rotation
			addRodriguesJacobian(rodJacobian.Rx,worldPt);
			addRodriguesJacobian(rodJacobian.Ry,worldPt);
			addRodriguesJacobian(rodJacobian.Rz,worldPt);

			// add gradient from translation
			addTranslationJacobian();

			// add gradient for the point in this view
			indexX = numParameters*countPointObs*2 + indexFirstPoint+o.pointIndex*3;
			indexY = indexX + numParameters;
			addWorldPointGradient(R);
		}
	}

	/**
	 * Computes the partials for observed points at this view
	 */
	private void gradientViewPoint(double[] input,
								   ViewPointObservations obs)
	{
		for( int j = 0; j < obs.points.size; j++, countPointObs++ ) {
			PointIndexObservation o = obs.points.get(j);
			int indexParamWorld = indexFirstPoint+o.pointIndex*3;

			// extract location of world point
			worldPt.x = input[indexParamWorld];
			worldPt.y = input[indexParamWorld+1];
			worldPt.z = input[indexParamWorld+2];

			// location of point in camera view
			GeometryMath_F64.mult(R, worldPt, cameraPt);
			cameraPt.x += T.x;
			cameraPt.y += T.y;
			cameraPt.z += T.z;

			// add gradient for the point in this view
			indexX = numParameters*countPointObs*2 + indexFirstPoint+o.pointIndex*3;
			indexY = indexX + numParameters;
			addWorldPointGradient(R);
		}
	}

	/**
	 * Adds to the Jacobian matrix using the derivative from a Rodrigues parameter.
	 *
	 * deriv [x,y] = -dot(z)/(z^2)*(R*X+T) + (1/z)*dot(R)*X
	 *
	 * where R is rotation matrix, T is translation, z = z-coordinate of point in camera frame
	 *
	 * @param Rj Jacobian for Rodrigues
	 * @param worldPt Location of point in world coordinates
	 */
	private void addRodriguesJacobian( DenseMatrix64F Rj , Point3D_F64 worldPt )
	{
		// (1/z)*dot(R)*X
		double Rx = (Rj.data[0]*worldPt.x + Rj.data[1]*worldPt.y + Rj.data[2]*worldPt.z)/cameraPt.z;
		double Ry = (Rj.data[3]*worldPt.x + Rj.data[4]*worldPt.y + Rj.data[5]*worldPt.z)/cameraPt.z;

		// dot(z)/(z^2)
		double zDot_div_z2 = (Rj.data[6]*worldPt.x + Rj.data[7]*worldPt.y + Rj.data[8]*worldPt.z)/
				(cameraPt.z*cameraPt.z);

		output[indexX++] = -zDot_div_z2*cameraPt.x + Rx;
		output[indexY++] = -zDot_div_z2*cameraPt.y + Ry;
	}

	/**
	 * Derivative for translation element
	 *
	 * deriv [x,y] = -dot(z)*T/(z^2) + dot(T)/z
	 *
	 * where T is translation, z = z-coordinate of point in camera frame
	 */
	private void addTranslationJacobian()
	{
		double divZ = 1.0/cameraPt.z;
		double divZ2 = 1.0/(cameraPt.z*cameraPt.z);

		// partial T.x
		output[indexX++] = divZ;
		output[indexY++] = 0;
		// partial T.y
		output[indexX++] = 0;
		output[indexY++] = divZ;
		// partial T.z
		output[indexX++] = -cameraPt.x*divZ2;
		output[indexY++] = -cameraPt.y*divZ2;
	}

	/**
	 * Gradient of the feature's 3D location
	 *
	 * deriv [x,y] = -dot(z)*(R*X+T)/(z^2) + R*dot(X)/z
	 *
	 * @param R rotation matrix
	 */
	private void addWorldPointGradient( DenseMatrix64F R ) {
		double divZ2 = 1.0/(cameraPt.z*cameraPt.z);

		// partial P.x
		output[indexX++] = -R.data[6]*divZ2*cameraPt.x + R.data[0]/cameraPt.z;
		output[indexY++] = -R.data[6]*divZ2*cameraPt.y + R.data[3]/cameraPt.z;
		// partial P.y
		output[indexX++] = -R.data[7]*divZ2*cameraPt.x + R.data[1]/cameraPt.z;
		output[indexY++] = -R.data[7]*divZ2*cameraPt.y + R.data[4]/cameraPt.z;
		// partial P.z
		output[indexX++] = -R.data[8]*divZ2*cameraPt.x + R.data[2]/cameraPt.z;
		output[indexY++] = -R.data[8]*divZ2*cameraPt.y + R.data[5]/cameraPt.z;
	}
}


text:
var { View, PropTypes, requireNativeComponent } = require('react-native');

var iface = {
  name: 'RCTBaiduMap',
  propTypes: {
    ...View.propTypes,
    mode: PropTypes.number,
    trafficEnabled: PropTypes.bool,
    heatMapEnabled: PropTypes.bool,
    marker:PropTypes.array
  }
}

module.exports = requireNativeComponent('RCTBaiduMap', iface);


text:
using System.Collections.Generic;

namespace PathsToTree
{
    public class TreeElement
    {
        public string Name { get; set; }
        public IList<TreeElement> Children { get; set; } = new List<TreeElement>();
    }
}


text:
.uiSelectMenuPanel .uiMenuPanel-label {
	margin-left: 1em;
	padding-left: 4px;
}

.uiSelectMenuPanel .uiMenuPanel-item.selected .uiMenuPanel-label:before {
	content: "\2713";
	width: 12px;
	margin-left: -12px;
	display: inline-block;
}


text:
package awsxrayreceiver

import (
	"context"
	"errors"
	"fmt"
	"net"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/component/componenttest"
	"go.opentelemetry.io/collector/config"
	"go.opentelemetry.io/collector/config/confignet"
	"go.opentelemetry.io/collector/consumer"
	"go.opentelemetry.io/collector/consumer/consumertest"
	"go.opentelemetry.io/collector/obsreport/obsreporttest"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"go.uber.org/zap/zaptest/observer"

	"github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/proxy"
	"github.com/open-telemetry/opentelemetry-collector-contrib/internal/common/testutil"
	"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/awsxrayreceiver/internal/udppoller"
)

const (
	segmentHeader        = "{\"format\": \"json\", \"version\": 1}\n"
	defaultRegionEnvName = "AWS_DEFAULT_REGION"
	mockRegion           = "us-west-2"
)

func TestConsumerCantBeNil(t *testing.T) {
	addr, err := net.ResolveUDPAddr(udppoller.Transport, "localhost:0")
	assert.NoError(t, err, "should resolve UDP address")

	sock, err := net.ListenUDP(udppoller.Transport, addr)
	assert.NoError(t, err, "should be able to listen")
	defer sock.Close()
	address := sock.LocalAddr().String()

	_, err = newReceiver(
		&Config{
			NetAddr: confignet.NetAddr{
				Endpoint:  address,
				Transport: udppoller.Transport,
			},
		},
		nil,
		componenttest.NewNopReceiverCreateSettings(),
	)
	assert.True(t, errors.Is(err, component.ErrNilNextConsumer), "consumer is nil should be detected")
}

func TestProxyCreationFailed(t *testing.T) {
	addr, err := findAvailableUDPAddress()
	assert.NoError(t, err, "there should be address available")

	sink := new(consumertest.TracesSink)
	_, err = newReceiver(
		&Config{
			NetAddr: confignet.NetAddr{
				Endpoint:  addr,
				Transport: udppoller.Transport,
			},
			ProxyServer: &proxy.Config{
				TCPAddr: confignet.TCPAddr{
					Endpoint: "invalidEndpoint",
				},
			},
		},
		sink,
		componenttest.NewNopReceiverCreateSettings(),
	)
	assert.Error(t, err, "receiver creation should fail due to failure to create TCP proxy")
}

func TestPollerCreationFailed(t *testing.T) {
	sink := new(consumertest.TracesSink)
	_, err := newReceiver(
		&Config{
			NetAddr: confignet.NetAddr{
				Endpoint:  "dontCare",
				Transport: "tcp",
			},
		},
		sink,
		componenttest.NewNopReceiverCreateSettings(),
	)
	assert.Error(t, err, "receiver creation should fail due to failure to create UCP poller")
}

// TODO: Update this test to assert on the format of traces
// once the transformation from X-Ray segments -> OTLP is done.
func TestSegmentsPassedToConsumer(t *testing.T) {
	if runtime.GOOS == "darwin" {
		t.Skip("skipping test on darwin")
	}
	t.Skip("Flaky Test - See https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/10596")

	tt, err := obsreporttest.SetupTelemetry()
	assert.NoError(t, err, "SetupTelemetry should succeed")
	defer func() {
		assert.NoError(t, tt.Shutdown(context.Background()))
	}()

	t.Setenv(defaultRegionEnvName, mockRegion)

	receiverID := component.NewID("TestSegmentsPassedToConsumer")

	addr, rcvr, _ := createAndOptionallyStartReceiver(t, receiverID, nil, true, tt.ToReceiverCreateSettings())
	defer func() {
		assert.NoError(t, rcvr.Shutdown(context.Background()))
	}()

	content, err := os.ReadFile(filepath.Join("../../internal/aws/xray", "testdata", "ddbSample.txt"))
	assert.NoError(t, err, "can not read raw segment")

	err = writePacket(t, addr, segmentHeader+string(content))
	assert.NoError(t, err, "can not write packet in the happy case")

	sink := rcvr.(*xrayReceiver).consumer.(*consumertest.TracesSink)

	assert.Eventuallyf(t, func() bool {
		got := sink.AllTraces()
		return len(got) == 1
	}, 10*time.Second, 5*time.Millisecond, "consumer should eventually get the X-Ray span")

	assert.NoError(t, obsreporttest.CheckReceiverTraces(tt, receiverID, udppoller.Transport, 18, 0))
}

func TestTranslatorErrorsOut(t *testing.T) {
	tt, err := obsreporttest.SetupTelemetry()
	assert.NoError(t, err, "SetupTelemetry should succeed")
	defer func() {
		assert.NoError(t, tt.Shutdown(context.Background()))
	}()

	t.Setenv(defaultRegionEnvName, mockRegion)

	receiverID := component.NewID("TestTranslatorErrorsOut")

	addr, rcvr, recordedLogs := createAndOptionallyStartReceiver(t, receiverID, nil, true, tt.ToReceiverCreateSettings())
	defer func() {
		assert.NoError(t, rcvr.Shutdown(context.Background()))
	}()

	err = writePacket(t, addr, segmentHeader+"invalidSegment")
	assert.NoError(t, err, "can not write packet in the "+receiverID.String()+" case")

	assert.Eventuallyf(t, func() bool {
		logs := recordedLogs.All()
		return len(logs) > 0 && strings.Contains(logs[len(logs)-1].Message,
			"X-Ray segment to OT traces conversion failed")
	}, 10*time.Second, 5*time.Millisecond, "poller should log warning because consumer errored out")

	assert.NoError(t, obsreporttest.CheckReceiverTraces(tt, receiverID, udppoller.Transport, 1, 1))
}

func TestSegmentsConsumerErrorsOut(t *testing.T) {
	tt, err := obsreporttest.SetupTelemetry()
	assert.NoError(t, err, "SetupTelemetry should succeed")
	defer func() {
		assert.NoError(t, tt.Shutdown(context.Background()))
	}()

	t.Setenv(defaultRegionEnvName, mockRegion)

	receiverID := component.NewID("TestSegmentsConsumerErrorsOut")

	addr, rcvr, recordedLogs := createAndOptionallyStartReceiver(t, receiverID,
		consumertest.NewErr(errors.New("can't consume traces")), true, tt.ToReceiverCreateSettings())
	defer func() {
		assert.NoError(t, rcvr.Shutdown(context.Background()))
	}()

	content, err := os.ReadFile(filepath.Join("../../internal/aws/xray", "testdata", "serverSample.txt"))
	assert.NoError(t, err, "can not read raw segment")

	err = writePacket(t, addr, segmentHeader+string(content))
	assert.NoError(t, err, "can not write packet")

	assert.Eventuallyf(t, func() bool {
		logs := recordedLogs.All()
		return len(logs) > 0 && strings.Contains(logs[len(logs)-1].Message,
			"Trace consumer errored out")
	}, 10*time.Second, 5*time.Millisecond, "poller should log warning because consumer errored out")

	assert.NoError(t, obsreporttest.CheckReceiverTraces(tt, receiverID, udppoller.Transport, 1, 1))
}

func TestPollerCloseError(t *testing.T) {
	tt, err := obsreporttest.SetupTelemetry()
	assert.NoError(t, err, "SetupTelemetry should succeed")
	defer func() {
		assert.NoError(t, tt.Shutdown(context.Background()))
	}()

	t.Setenv(defaultRegionEnvName, mockRegion)

	_, rcvr, _ := createAndOptionallyStartReceiver(t, component.NewID("TestPollerCloseError"), nil, false, tt.ToReceiverCreateSettings())
	mPoller := &mockPoller{closeErr: errors.New("mockPollerCloseErr")}
	rcvr.(*xrayReceiver).poller = mPoller
	rcvr.(*xrayReceiver).server = &mockProxy{}
	err = rcvr.Shutdown(context.Background())
	assert.ErrorIs(t, err, mPoller.closeErr, "expected error")
}

func TestProxyCloseError(t *testing.T) {
	tt, err := obsreporttest.SetupTelemetry()
	assert.NoError(t, err, "SetupTelemetry should succeed")
	defer func() {
		assert.NoError(t, tt.Shutdown(context.Background()))
	}()

	t.Setenv(defaultRegionEnvName, mockRegion)

	_, rcvr, _ := createAndOptionallyStartReceiver(t, component.NewID("TestPollerCloseError"), nil, false, tt.ToReceiverCreateSettings())
	mProxy := &mockProxy{closeErr: errors.New("mockProxyCloseErr")}
	rcvr.(*xrayReceiver).poller = &mockPoller{}
	rcvr.(*xrayReceiver).server = mProxy
	err = rcvr.Shutdown(context.Background())
	assert.ErrorIs(t, err, mProxy.closeErr, "expected error")
}

func TestBothPollerAndProxyCloseError(t *testing.T) {
	tt, err := obsreporttest.SetupTelemetry()
	assert.NoError(t, err, "SetupTelemetry should succeed")
	defer func() {
		assert.NoError(t, tt.Shutdown(context.Background()))
	}()

	t.Setenv(defaultRegionEnvName, mockRegion)

	_, rcvr, _ := createAndOptionallyStartReceiver(t, component.NewID("TestBothPollerAndProxyCloseError"), nil, false, tt.ToReceiverCreateSettings())
	mPoller := &mockPoller{closeErr: errors.New("mockPollerCloseErr")}
	mProxy := &mockProxy{closeErr: errors.New("mockProxyCloseErr")}
	rcvr.(*xrayReceiver).poller = mPoller
	rcvr.(*xrayReceiver).server = mProxy
	err = rcvr.Shutdown(context.Background())
	assert.ErrorIs(t, err, mPoller.closeErr, "expected error")
	assert.ErrorIs(t, err, mProxy.closeErr, "expected error")
}

type mockPoller struct {
	closeErr error
}

func (m *mockPoller) SegmentsChan() <-chan udppoller.RawSegment {
	return make(chan udppoller.RawSegment, 1)
}

func (m *mockPoller) Start(ctx context.Context) {}

func (m *mockPoller) Close() error {
	if m.closeErr != nil {
		return m.closeErr
	}
	return nil
}

type mockProxy struct {
	closeErr error
}

func (m *mockProxy) ListenAndServe() error {
	return errors.New("returning from ListenAndServe() always errors out")
}

func (m *mockProxy) Shutdown(ctx context.Context) error {
	if m.closeErr != nil {
		return m.closeErr
	}
	return nil
}

func createAndOptionallyStartReceiver(
	t *testing.T,
	receiverID component.ID,
	csu consumer.Traces,
	start bool,
	set component.ReceiverCreateSettings) (string, component.TracesReceiver, *observer.ObservedLogs) {
	addr, err := findAvailableUDPAddress()
	assert.NoError(t, err, "there should be address available")
	tcpAddr := testutil.GetAvailableLocalAddress(t)

	var sink consumer.Traces
	if csu == nil {
		sink = new(consumertest.TracesSink)
	} else {
		sink = csu
	}

	logger, recorded := logSetup()
	set.Logger = logger
	rcvr, err := newReceiver(
		&Config{
			ReceiverSettings: config.NewReceiverSettings(receiverID),
			NetAddr: confignet.NetAddr{
				Endpoint:  addr,
				Transport: udppoller.Transport,
			},
			ProxyServer: &proxy.Config{
				TCPAddr: confignet.TCPAddr{
					Endpoint: tcpAddr,
				},
			},
		},
		sink,
		set,
	)
	assert.NoError(t, err, "receiver should be created")

	if start {
		err = rcvr.Start(context.Background(), componenttest.NewNopHost())
		assert.NoError(t, err, "receiver should be started")
	}
	return addr, rcvr, recorded
}

// findAvailableUDPAddress finds an available local address+port and returns it.
// There might be race condition on the address returned by this function if
// there's some other code that grab the address before we can listen on it.
func findAvailableUDPAddress() (string, error) {
	addr, err := net.ResolveUDPAddr(udppoller.Transport, "localhost:0")
	if err != nil {
		return "", err
	}

	sock, err := net.ListenUDP(udppoller.Transport, addr)
	if err != nil {
		return "", err
	}
	defer sock.Close()
	return sock.LocalAddr().String(), nil
}

func writePacket(t *testing.T, addr, toWrite string) error {
	conn, err := net.Dial(udppoller.Transport, addr)
	if err != nil {
		return err
	}
	defer conn.Close()

	n, err := fmt.Fprint(conn, toWrite)
	if err != nil {
		return err
	}
	assert.Equal(t, len(toWrite), n, "unexpected number of bytes written")
	return nil
}

func logSetup() (*zap.Logger, *observer.ObservedLogs) {
	core, recorded := observer.New(zapcore.InfoLevel)
	return zap.New(core), recorded
}


text:
[jvm]
Content
open override val [methodRef](method-ref.md): [MethodInvokeSpec](../../../com.github.jonathanxd.kores.common/-method-invoke-spec/index.md)
More info

Method reference to invoke


text:
#include "2d/actions/CCActionCatmullRom.h"

using namespace std;

NS_CC_BEGIN;

/*
 *  Implementation of PointArray
 */

PointArray* PointArray::create(unsigned int capacity)
{
    PointArray* pointArray = new PointArray();
    if (pointArray)
    {
        if (pointArray->initWithCapacity(capacity))
        {
            pointArray->autorelease();
        }
        else
        {
            delete pointArray;
            pointArray = nullptr;
        }
    }

    return pointArray;
}

bool PointArray::initWithCapacity(unsigned int capacity)
{
    m_pControlPoints = new vector<Point*>();

    return true;
}

PointArray* PointArray::clone() const
{
    vector<Point*> *newArray = new vector<Point*>();
    vector<Point*>::iterator iter;
    for (iter = m_pControlPoints->begin(); iter != m_pControlPoints->end(); ++iter)
    {
        newArray->push_back(new Point((*iter)->x, (*iter)->y));
    }

    PointArray *points = new PointArray();
    points->initWithCapacity(10);
    points->setControlPoints(newArray);

    points->autorelease();
    return points;
}

PointArray::~PointArray()
{
    CCLOGINFO("deallocing PointArray: %p", this);

    vector<Point*>::iterator iter;
    for (iter = m_pControlPoints->begin(); iter != m_pControlPoints->end(); ++iter)
    {
        delete *iter;
    }
    delete m_pControlPoints;
}

PointArray::PointArray() :m_pControlPoints(nullptr){}

const std::vector<Point*>* PointArray::getControlPoints() const
{
    return m_pControlPoints;
}

void PointArray::setControlPoints(vector<Point*> *controlPoints)
{
    CCASSERT(controlPoints != nullptr, "control points should not be nullptr");

    // delete old points
    vector<Point*>::iterator iter;
    for (iter = m_pControlPoints->begin(); iter != m_pControlPoints->end(); ++iter)
    {
        delete *iter;
    }
    delete m_pControlPoints;

    m_pControlPoints = controlPoints;
}

void PointArray::addControlPoint(Point controlPoint)
{
    m_pControlPoints->push_back(new Point(controlPoint.x, controlPoint.y));
}

KDvoid PointArray::insertControlPoint ( const Point& tControlPoint, KDuint uIndex )
{
    Point*		pTemp = new Point ( tControlPoint.x, tControlPoint.y );
    m_pControlPoints->insert ( m_pControlPoints->begin ( ) + uIndex, pTemp );
}

Point PointArray::getControlPointAtIndex(unsigned int index)
{
    index = KD_MIN(m_pControlPoints->size()-1, KD_MAX(index, 0));
    return *(m_pControlPoints->at(index));
}

KDvoid PointArray::replaceControlPoint ( const Point& tControlPoint, KDuint uIndex )
{
    Point*		pTemp = m_pControlPoints->at ( uIndex );
    pTemp->x = tControlPoint.x;
    pTemp->y = tControlPoint.y;
}

void PointArray::removeControlPointAtIndex(unsigned int index)
{
    vector<Point*>::iterator iter = m_pControlPoints->begin() + index;
    Point* pRemovedPoint = *iter;
    m_pControlPoints->erase(iter);
    delete pRemovedPoint;
}

unsigned int PointArray::count() const
{
    return m_pControlPoints->size();
}

PointArray* PointArray::reverse() const
{
    vector<Point*> *newArray = new vector<Point*>();
    vector<Point*>::reverse_iterator iter;
    Point *point = nullptr;
    for (iter = m_pControlPoints->rbegin(); iter != m_pControlPoints->rend(); ++iter)
    {
        point = *iter;
        newArray->push_back(new Point(point->x, point->y));
    }
    PointArray *config = PointArray::create(0);
    config->setControlPoints(newArray);

    return config;
}

void PointArray::reverseInline()
{
    unsigned long l = m_pControlPoints->size();
    Point *p1 = nullptr;
    Point *p2 = nullptr;
    int x, y;
    for (unsigned int i = 0; i < l/2; ++i)
    {
        p1 = m_pControlPoints->at(i);
        p2 = m_pControlPoints->at(l-i-1);

        x = p1->x;
        y = p1->y;

        p1->x = p2->x;
        p1->y = p2->y;

        p2->x = x;
        p2->y = y;
    }
}

// CatmullRom Spline formula:
Point ccCardinalSplineAt(Point &p0, Point &p1, Point &p2, Point &p3, float tension, float t)
{
    float t2 = t * t;
    float t3 = t2 * t;

	/*
	 * Formula: s(-ttt + 2tt - t)P1 + s(-ttt + tt)P2 + (2ttt - 3tt + 1)P2 + s(ttt - 2tt + t)P3 + (-2ttt + 3tt)P3 + s(ttt - tt)P4
	 */
    float s = (1 - tension) / 2;

    float b1 = s * ((-t3 + (2 * t2)) - t);                      // s(-t3 + 2 t2 - t)P1
    float b2 = s * (-t3 + t2) + (2 * t3 - 3 * t2 + 1);          // s(-t3 + t2)P2 + (2 t3 - 3 t2 + 1)P2
    float b3 = s * (t3 - 2 * t2 + t) + (-2 * t3 + 3 * t2);      // s(t3 - 2 t2 + t)P3 + (-2 t3 + 3 t2)P3
    float b4 = s * (t3 - t2);                                   // s(t3 - t2)P4

    float x = (p0.x*b1 + p1.x*b2 + p2.x*b3 + p3.x*b4);
    float y = (p0.y*b1 + p1.y*b2 + p2.y*b3 + p3.y*b4);

	return Point(x,y);
}

/* Implementation of CardinalSplineTo
 */

CardinalSplineTo* CardinalSplineTo::create(float duration, cocos2d::PointArray *points, float tension)
{
    CardinalSplineTo *ret = new CardinalSplineTo();
    if (ret)
    {
        if (ret->initWithDuration(duration, points, tension))
        {
            ret->autorelease();
        }
        else
        {
            CC_SAFE_RELEASE(ret);
        }
    }

    return ret;
}

bool CardinalSplineTo::initWithDuration(float duration, cocos2d::PointArray *points, float tension)
{
    CCASSERT(points->count() > 0, "Invalid configuration. It must at least have one control point");

    if (ActionInterval::initWithDuration(duration))
    {
        this->setPoints(points);
        this->m_tTension = tension;

        return true;
    }

    return false;
}

CardinalSplineTo::~CardinalSplineTo()
{
    CC_SAFE_RELEASE(m_pPoints);
}

CardinalSplineTo::CardinalSplineTo()
: m_pPoints(nullptr)
, m_tDeltaT(0.f)
, m_tTension(0.f)
{
}

void CardinalSplineTo::startWithTarget(cocos2d::Node *target)
{
    ActionInterval::startWithTarget(target);

//    _deltaT = (float) 1 / _points->count();

    // Issue #1441
    m_tDeltaT = (float) 1 / (m_pPoints->count() - 1);

    m_tPreviousPosition = target->getPosition();
    m_tAccumulatedDiff = Point::ZERO;
}

CardinalSplineTo* CardinalSplineTo::clone() const
{
	// no copy constructor
	auto a = new CardinalSplineTo();
	a->initWithDuration(this->m_fDuration, this->m_pPoints->clone(), this->m_tTension);
	a->autorelease();
	return a;
}

void CardinalSplineTo::update(float time)
{
    unsigned int p;
    float lt;

	// eg.
	// p..p..p..p..p..p..p
	// 1..2..3..4..5..6..7
	// want p to be 1, 2, 3, 4, 5, 6
    if (time == 1)
    {
        p = m_pPoints->count() - 1;
        lt = 1;
    }
    else
    {
        p = time / m_tDeltaT;
        lt = (time - m_tDeltaT * (float)p) / m_tDeltaT;
    }

	// Interpolate
    Point pp0 = m_pPoints->getControlPointAtIndex(p-1);
    Point pp1 = m_pPoints->getControlPointAtIndex(p+0);
    Point pp2 = m_pPoints->getControlPointAtIndex(p+1);
    Point pp3 = m_pPoints->getControlPointAtIndex(p+2);

    Point newPos = ccCardinalSplineAt(pp0, pp1, pp2, pp3, m_tTension, lt);

#if CC_ENABLE_STACKABLE_ACTIONS
    // Support for stacked actions
    Node *node = m_pTarget;
    Point diff = node->getPosition() - m_tPreviousPosition;
    if( diff.x !=0 || diff.y != 0 ) {
        m_tAccumulatedDiff = m_tAccumulatedDiff + diff;
        newPos = newPos + m_tAccumulatedDiff;
    }
#endif

    this->updatePosition(newPos);
}

void CardinalSplineTo::updatePosition(cocos2d::Point &newPos)
{
    m_pTarget->setPosition(newPos);
    m_tPreviousPosition = newPos;
}

CardinalSplineTo* CardinalSplineTo::reverse() const
{
    PointArray *pReverse = m_pPoints->reverse();

    return CardinalSplineTo::create(m_fDuration, pReverse, m_tTension);
}

/* CardinalSplineBy
 */

CardinalSplineBy* CardinalSplineBy::create(float duration, cocos2d::PointArray *points, float tension)
{
    CardinalSplineBy *ret = new CardinalSplineBy();
    if (ret)
    {
        if (ret->initWithDuration(duration, points, tension))
        {
            ret->autorelease();
        }
        else
        {
            CC_SAFE_RELEASE(ret);
        }
    }

    return ret;
}

CardinalSplineBy::CardinalSplineBy() : m_tStartPosition(0,0)
{
}

void CardinalSplineBy::updatePosition(cocos2d::Point &newPos)
{
    Point p = newPos + m_tStartPosition;
    m_pTarget->setPosition(p);
    m_tPreviousPosition = p;
}

CardinalSplineBy* CardinalSplineBy::reverse() const
{
    PointArray *copyConfig = m_pPoints->clone();

	//
	// convert "absolutes" to "diffs"
	//
    Point p = copyConfig->getControlPointAtIndex(0);
    for (unsigned int i = 1; i < copyConfig->count(); ++i)
    {
        Point current = copyConfig->getControlPointAtIndex(i);
        Point diff = current - p;
        copyConfig->replaceControlPoint(diff, i);

        p = current;
    }

	// convert to "diffs" to "reverse absolute"

    PointArray *pReverse = copyConfig->reverse();

	// 1st element (which should be 0,0) should be here too

    p = pReverse->getControlPointAtIndex(pReverse->count()-1);
    pReverse->removeControlPointAtIndex(pReverse->count()-1);

    p = -p;
    pReverse->insertControlPoint(p, 0);

    for (unsigned int i = 1; i < pReverse->count(); ++i)
    {
        Point current = pReverse->getControlPointAtIndex(i);
        current = -current;
        Point abs = current + p;
        pReverse->replaceControlPoint(abs, i);

        p = abs;
    }

    return CardinalSplineBy::create(m_fDuration, pReverse, m_tTension);
}

void CardinalSplineBy::startWithTarget(cocos2d::Node *target)
{
    CardinalSplineTo::startWithTarget(target);
    m_tStartPosition = target->getPosition();
}

CardinalSplineBy* CardinalSplineBy::clone() const
{
	// no copy constructor
	auto a = new CardinalSplineBy();
	a->initWithDuration(this->m_fDuration, this->m_pPoints->clone(), this->m_tTension);
	a->autorelease();
	return a;
}

/* CatmullRomTo
 */

CatmullRomTo* CatmullRomTo::create(float dt, cocos2d::PointArray *points)
{
    CatmullRomTo *ret = new CatmullRomTo();
    if (ret)
    {
        if (ret->initWithDuration(dt, points))
        {
            ret->autorelease();
        }
        else
        {
            CC_SAFE_RELEASE(ret);
        }
    }

    return ret;
}

bool CatmullRomTo::initWithDuration(float dt, cocos2d::PointArray *points)
{
    if (CardinalSplineTo::initWithDuration(dt, points, 0.5f))
    {
        return true;
    }

    return false;
}

CatmullRomTo* CatmullRomTo::clone() const
{
	// no copy constructor
	auto a = new CatmullRomTo();
	a->initWithDuration(this->m_fDuration, this->m_pPoints->clone());
	a->autorelease();
	return a;
}

CatmullRomTo* CatmullRomTo::reverse() const
{
    PointArray *pReverse = m_pPoints->reverse();
    return CatmullRomTo::create(m_fDuration, pReverse);
}

/* CatmullRomBy
 */

CatmullRomBy* CatmullRomBy::create(float dt, cocos2d::PointArray *points)
{
    CatmullRomBy *ret = new CatmullRomBy();
    if (ret)
    {
        if (ret->initWithDuration(dt, points))
        {
            ret->autorelease();
        }
        else
        {
            CC_SAFE_RELEASE(ret);
        }
    }

    return ret;
}

bool CatmullRomBy::initWithDuration(float dt, cocos2d::PointArray *points)
{
    if (CardinalSplineTo::initWithDuration(dt, points, 0.5f))
    {
        return true;
    }

    return false;
}

CatmullRomBy* CatmullRomBy::clone() const
{
	// no copy constructor
	auto a = new CatmullRomBy();
	a->initWithDuration(this->m_fDuration, this->m_pPoints->clone());
	a->autorelease();
	return a;
}

CatmullRomBy* CatmullRomBy::reverse() const
{
    PointArray *copyConfig = m_pPoints->clone();

	//
	// convert "absolutes" to "diffs"
	//
    Point p = copyConfig->getControlPointAtIndex(0);
    for (unsigned int i = 1; i < copyConfig->count(); ++i)
    {
        Point current = copyConfig->getControlPointAtIndex(i);
        Point diff = current - p;
        copyConfig->replaceControlPoint(diff, i);

        p = current;
    }

	// convert to "diffs" to "reverse absolute"

    PointArray *reverse = copyConfig->reverse();

	// 1st element (which should be 0,0) should be here too

    p = reverse->getControlPointAtIndex(reverse->count()-1);
    reverse->removeControlPointAtIndex(reverse->count()-1);

    p = -p;
    reverse->insertControlPoint(p, 0);

    for (unsigned int i = 1; i < reverse->count(); ++i)
    {
        Point current = reverse->getControlPointAtIndex(i);
        current = -current;
        Point abs = current + p;
        reverse->replaceControlPoint(abs, i);

        p = abs;
    }

    return CatmullRomBy::create(m_fDuration, reverse);
}

NS_CC_END;


text:
/* @flow */

import type {ReporterSpinner} from '../reporters/types.js';
import type Config from '../config.js';
import {MessageError, SpawnError} from '../errors.js';
import * as constants from '../constants.js';
import * as child from './child.js';
import {registries} from '../resolvers/index.js';
import {fixCmdWinSlashes} from './fix-cmd-win-slashes.js';

const path = require('path');

export type LifecycleReturn = Promise<{
  cwd: string,
  command: string,
  stdout: string,
}>;

const IGNORE_MANIFEST_KEYS = ['readme'];

// We treat these configs as internal, thus not expose them to process.env.
// This helps us avoid some gyp issues when building native modules.
// See https://github.com/yarnpkg/yarn/issues/2286.
const IGNORE_CONFIG_KEYS = ['lastUpdateCheck'];

async function makeEnv(stage: string, cwd: string, config: Config): {
  [key: string]: string
} {
  const env = Object.assign({}, process.env);

  env.npm_lifecycle_event = stage;
  env.npm_node_execpath = env.NODE || process.execPath;
  env.npm_execpath = env.npm_execpath || process.mainModule.filename;

  // Set the env to production for npm compat if production mode.
  // https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336
  if (config.production) {
    env.NODE_ENV = 'production';
  }

  // Note: npm_config_argv environment variable contains output of nopt - command-line
  // parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684)
  env.npm_config_argv = JSON.stringify({remain:[], cooked: [config.commandName], original: [config.commandName]});

  // add npm_package_*
  const manifest = await config.maybeReadManifest(cwd);
  if (manifest) {
    const queue = [['', manifest]];
    while (queue.length) {
      const [key, val] = queue.pop();
      if (key[0] === '_') {
        continue;
      }

      if (typeof val === 'object') {
        for (const subKey in val) {
          const completeKey = [key, subKey]
            .filter((part: ?string): boolean => !!part)
            .join('_');
          queue.push([completeKey, val[subKey]]);
        }
      } else if (IGNORE_MANIFEST_KEYS.indexOf(key) < 0) {
        let cleanVal = String(val);
        if (cleanVal.indexOf('\n') >= 0) {
          cleanVal = JSON.stringify(cleanVal);
        }
        env[`npm_package_${key}`] = cleanVal;
      }
    }
  }

  // add npm_config_*
  const keys: Set<string> = new Set([
    ...Object.keys(config.registries.yarn.config),
    ...Object.keys(config.registries.npm.config),
  ]);
  for (const key of keys) {
    if (key.match(/:_/) || IGNORE_CONFIG_KEYS.indexOf(key) >= 0) {
      continue;
    }

    let val = config.getOption(key);

    if (!val) {
      val = '';
    } else if (typeof val === 'number') {
      val = '' + val;
    } else if (typeof val !== 'string') {
      val = JSON.stringify(val);
    }

    if (val.indexOf('\n') >= 0) {
      val = JSON.stringify(val);
    }

    const cleanKey = key.replace(/^_+/, '');
    const envKey = `npm_config_${cleanKey}`.replace(/[^a-zA-Z0-9_]/g, '_');
    env[envKey] = val;
  }

  return env;
}

export async function executeLifecycleScript(
  stage: string,
  config: Config,
  cwd: string,
  cmd: string,
  spinner?: ReporterSpinner,
): LifecycleReturn {
  // if we don't have a spinner then pipe everything to the terminal
  const stdio = spinner ? undefined : 'inherit';

  const env = await makeEnv(stage, cwd, config);

  // split up the path
  const pathParts = (env[constants.ENV_PATH_KEY] || '').split(path.delimiter);

  // add node-gyp
  pathParts.unshift(path.join(__dirname, '..', '..', 'bin', 'node-gyp-bin'));

  // add .bin folders to PATH
  for (const registry of Object.keys(registries)) {
    const binFolder = path.join(config.registries[registry].folder, '.bin');
    pathParts.unshift(path.join(config.linkFolder, binFolder));
    pathParts.unshift(path.join(cwd, binFolder));
  }

  // join path back together
  env[constants.ENV_PATH_KEY] = pathParts.join(path.delimiter);

  // get shell
  const conf = {windowsVerbatimArguments: false};
  let sh = 'sh';
  let shFlag = '-c';
  if (process.platform === 'win32') {
    // cmd or command.com
    sh = process.env.comspec || 'cmd';

    // d - Ignore registry AutoRun commands
    // s - Strip " quote characters from command.
    // c - Run Command and then terminate
    shFlag = '/d /s /c';

    // handle windows run scripts starting with a relative path
    cmd = fixCmdWinSlashes(cmd);

    // handle quotes properly in windows environments - https://github.com/nodejs/node/issues/5060
    conf.windowsVerbatimArguments = true;
  }

  const stdout = await child.spawn(sh, [shFlag, cmd], {cwd, env, stdio, ...conf}, (data) => {
    if (spinner) {
      const line = data.toString() // turn buffer into string
        .trim() // trim whitespace
        .split('\n') // split into lines
        .pop() // use only the last line
        .replace(/\t/g, ' '); // change tabs to spaces as they can interfere with the console

      if (line) {
        spinner.tick(line);
      }
    }
  });

  return {cwd, command: cmd, stdout};
}

export default executeLifecycleScript;

export async function execFromManifest(config: Config, commandName: string, cwd: string): Promise<void> {
  const pkg = await config.maybeReadManifest(cwd);
  if (!pkg || !pkg.scripts) {
    return;
  }

  const cmd: ?string = pkg.scripts[commandName];
  if (cmd) {
    await execCommand(commandName, config, cmd, cwd);
  }
}

export async function execCommand(stage: string, config: Config, cmd: string, cwd: string): Promise<void> {
  const {reporter} = config;
  try {
    reporter.command(cmd);
    await executeLifecycleScript(stage, config, cwd, cmd);
    return Promise.resolve();
  } catch (err) {
    if (err instanceof SpawnError) {
      throw new MessageError(reporter.lang('commandFailed', err.EXIT_CODE));
    } else {
      throw err;
    }
  }
}


text:
<?php

/**
 * Clase base para componentes de cacheo
 *
 * @category   Kumbia
 * @package    Cache
 */
abstract class Cache
{

    /**
     * Pool de drivers para cache
     *
     * @var array
     * */
    protected static $_drivers = array();
    /**
     * Driver por defecto
     *
     * @var string
     * */
    protected static $_default_driver = 'file';
    /**
     * Id de ultimo elemento solicitado
     *
     * @var string
     */
    protected $_id = null;
    /**
     * Grupo de ultimo elemento solicitado
     *
     * @var string
     */
    protected $_group = 'default';
    /**
     * Tiempo de vida
     *
     * @var string
     */
    protected $_lifetime = '';

    /**
     * Carga un elemento cacheado
     *
     * @param string $id
     * @param string $group
     * @return string
     */
    public abstract function get($id, $group = 'default');

    /**
     * Guarda un elemento en la cache con nombre $id y valor $value
     *
     * @param string $value
     * @param string $lifetime tiempo de vida con formato strtotime, utilizado para cache
     * @param string $id
     * @param string $group
     * @return boolean
     */
    public abstract function save($value, $lifetime = '', $id = FALSE, $group = 'default');

    /**
     * Limpia la cache
     *
     * @param string $group
     * @return boolean
     */
    public abstract function clean($group=false);

    /**
     * Elimina un elemento de la cache
     *
     * @param string $id
     * @param string $group
     * @return boolean
     */
    public abstract function remove($id, $group = 'default');

    /**
     * Inicia el cacheo del buffer de salida hasta que se llame a end
     *
     * @param string $lifetime tiempo de vida con formato strtotime, utilizado para cache
     * @param string $id
     * @param string $group
     * @return boolean
     */
    public function start($lifetime, $id, $group = 'default')
    {
        if ($data = $this->get($id, $group)) {
            echo $data;

            // No es necesario cachear
            return FALSE;
        }
        $this->_lifetime = $lifetime;

        // inicia la captura del buffer
        ob_start();

        // Inicia cacheo
        return TRUE;
    }

    /**
     * Termina el buffer de salida
     *
     * @param boolean $save indica si al terminar guarda la cache
     * @return boolean
     */
    public function end($save = TRUE)
    {
        if (!$save) {
            ob_end_flush();
            return FALSE;
        }

        // obtiene el contenido del buffer
        $value = ob_get_contents();

        // libera el buffer
        ob_end_flush();

        return $this->save($value, $this->_lifetime, $this->_id, $this->_group);
    }

    /**
     * Obtiene el driver de cache indicado
     *
     * @param string $driver (file, sqlite, memsqlite, APC)
     * */
    public static function driver($driver = '')
    {
        if (!$driver) {
            $driver = self::$_default_driver;
        }

        if (!isset(self::$_drivers[$driver])) {
            require_once CORE_PATH . "libs/cache/drivers/{$driver}_cache.php";
            $class = $driver . 'cache';
            self::$_drivers[$driver] = new $class();
        }

        return self::$_drivers[$driver];
    }

    /**
     * Cambia el driver por defecto
     *
     * @param string $driver nombre del driver por defecto
     */
    public static function setDefault($driver = 'file')
    {
        self::$_default_driver = $driver;
    }

}


text:
<?php

namespace Oro\Bundle\SyncBundle\EventListener;

use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Oro\Bundle\SyncBundle\Content\DataUpdateTopicSender;
use Oro\Bundle\SyncBundle\Content\TagGeneratorInterface;

/**
 * Collects changes in entities and sends tags to websocket server using DataUpdateTopicSender.
 */
class DoctrineTagEventListener
{
    /**
     * @var bool
     */
    private $enabled = true;

    /**
     * @var bool
     */
    private $isApplicationInstalled;

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

    /**
     * @var DataUpdateTopicSender
     */
    private $dataUpdateTopicSender;

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

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

    /**
     * @var TagGeneratorInterface
     */
    private $tagGenerator;

    /**
     * @param DataUpdateTopicSender $dataUpdateTopicSender
     * @param TagGeneratorInterface $tagGenerator
     * @param bool|string|null      $isApplicationInstalled
     */
    public function __construct(
        DataUpdateTopicSender $dataUpdateTopicSender,
        TagGeneratorInterface $tagGenerator,
        $isApplicationInstalled
    ) {
        $this->dataUpdateTopicSender = $dataUpdateTopicSender;
        $this->isApplicationInstalled = !empty($isApplicationInstalled);
        $this->tagGenerator = $tagGenerator;
    }

    /**
     * Enables or disables the listener.
     *
     * @param bool $enabled
     */
    public function setEnabled($enabled = true)
    {
        $this->enabled = $enabled;
    }

    /**
     * Collect changes that were done
     * Generates tags and store in protected variable
     *
     * @param OnFlushEventArgs $event
     */
    public function onFlush(OnFlushEventArgs $event)
    {
        if (!$this->enabled || !$this->isApplicationInstalled) {
            return;
        }

        $uow = $event->getEntityManager()->getUnitOfWork();

        foreach ($uow->getScheduledEntityInsertions() as $entity) {
            $this->addEntityTags($entity, true);
        }
        foreach ($uow->getScheduledEntityDeletions() as $entity) {
            $this->addEntityTags($entity, true);
        }
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
            $this->addEntityTags($entity);
        }
        foreach ($uow->getScheduledCollectionDeletions() as $collection) {
            $this->addEntityTags($collection->getOwner());
        }
        foreach ($uow->getScheduledCollectionUpdates() as $collection) {
            $this->addEntityTags($collection->getOwner());
        }
    }

    /**
     * Send collected tags to publisher
     *
     * @param PostFlushEventArgs $event
     */
    public function postFlush(PostFlushEventArgs $event)
    {
        $this->dataUpdateTopicSender->send(array_unique($this->collectedTags));
        $this->collectedTags = [];
        $this->processedEntities = [];
    }

    /**
     * Add this method call to service declaration in case when you need
     * to do not send update tags whenever your entity modified
     *
     * @param string $className The FQCN of an entity to be skipped
     *
     * @throws \InvalidArgumentException
     */
    public function markSkipped($className)
    {
        if (!class_exists($className)) {
            throw new \InvalidArgumentException(
                sprintf('The class "%s" does not exist.', $className)
            );
        }

        $this->skipTrackingFor[$className] = true;
    }

    /**
     * @param object $entity
     * @param bool   $includeCollectionTag
     */
    private function addEntityTags($entity, $includeCollectionTag = false)
    {
        $hash = spl_object_hash($entity);
        if (!isset($this->processedEntities[$hash])
            && !isset($this->skipTrackingFor[ClassUtils::getClass($entity)])
        ) {
            $this->collectedTags = array_merge(
                $this->collectedTags,
                $this->tagGenerator->generate($entity, $includeCollectionTag)
            );
            $this->processedEntities[$hash] = true;
        }
    }
}