text:
<?php
use PhpAmqpLib\Exception\AMQPRuntimeException;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

/**
 * stub class representing AMQPQueue from pecl-amqp
 */
class AMQPQueue {

    /** @var AMQPChannel  */
    private $channel;

    private $name;
    private $flags;
    private $arguments;

    private $consumer_tag;
    private $last_envelope;

    /**
     * Create an instance of an AMQPQueue object.
     *
     * @param AMQPChannel $amqp_channel The amqp channel to use.
     *
     * @throws AMQPQueueException      When amqp_channel is not connected to a
     *                                 broker.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     */
    public function __construct(AMQPChannel $amqp_channel) {
        $this->channel = $amqp_channel;
        $this->arguments = array();
        $this->flags = AMQP_NOPARAM;
        $this->consumer_tag = null;
        $this->last_envelope = null;
    }

    /**
     * Consume messages from a queue.
     *
     * Blocking function that will retrieve the next message from the queue as
     * it becomes available and will pass it off to the callback.
     *
     * @param callable | null $callback A callback function to which the
     *                              consumed message will be passed. The
     *                              function must accept at a minimum
     *                              one parameter, an AMQPEnvelope object,
     *                              and an optional second parameter
     *                              the AMQPQueue object from which callback
     *                              was invoked. The AMQPQueue::consume() will
     *                              not return the processing thread back to
     *                              the PHP script until the callback
     *                              function returns FALSE.
     *                              If the callback is omitted or null is passed,
     *                              then the messages delivered to this client will
     *                              be made available to the first real callback
     *                              registered. That allows one to have a single
     *                              callback consuming from multiple queues.
     * @param integer $flags A bitmask of any of the flags: AMQP_AUTOACK.
     * @param string $consumer_tag A string describing this consumer. Used
     *                              for canceling subscriptions with cancel().
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return void
     */
    public function consume(callable $callback = null, $flags = AMQP_NOPARAM, $consumer_tag = null) {

        $this->last_envelope = null;

        $this->setupConsume($flags, $consumer_tag);

        while(count($this->channel->_getChannel()->callbacks) > 0){
            $this->channel->_getChannel()->wait();
            //Will unblock when there's a message
            //This handling might need to be extended to receive a batch.
            //Need to MITM the callback for the message.
            call_user_func($callback, $this->last_envelope);
        }

    }

    /**
     * Retrieve the next message from the queue.
     *
     * Retrieve the next available message from the queue. If no messages are
     * present in the queue, this function will return FALSE immediately. This
     * is a non blocking alternative to the AMQPQueue::consume() method.
     * Currently, the only supported flag for the flags parameter is
     * AMQP_AUTOACK. If this flag is passed in, then the message returned will
     * automatically be marked as acknowledged by the broker as soon as the
     * frames are sent to the client.
     *
     * @param integer $flags A bitmask of supported flags for the
     *                       method call. Currently, the only the
     *                       supported flag is AMQP_AUTOACK. If this
     *                       value is not provided, it will use the
     *                       value of ini-setting amqp.auto_ack.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return AMQPEnvelope|boolean
     */
    public function get($flags = AMQP_NOPARAM) {

        $this->last_envelope = null;

        if(!$this->isConsuming())
            $this->setupConsume($flags);

        //non-blocking read from the underlying socket.
        $read = array($this->getConnection()->_getConnection()->getSocket());
        $write = null;
        $except = null;
        if(stream_select($read, $write, $except, 0) > 0) {
            $this->channel->_getChannel()->wait();
        }

        if($this->last_envelope !== null)
            return $this->last_envelope;

        return false;

    }

    private function setupConsume($flags, $consumer_tag = null){

        $auto_ack = boolval($flags & AMQP_AUTOACK);

        if($consumer_tag === null)
            $consumer_tag = '';

        //Man-in-the-middle callback to transform response to an envelope.
        //AMQPProtocolChannelException
        $queue = $this;
        list($this->consumer_tag) = $this->channel->_getChannel()->basic_consume($this->name, $consumer_tag, $no_local = false, $auto_ack, $exclusive = false, $nowait = false,
            function(AMQPMessage $message) use($queue) {
                $queue->last_envelope = AMQPEnvelope::fromAMQPMessage($message);
            });

    }

    private function isConsuming(){
        return $this->consumer_tag !== null;
    }

    /**
     * Declare a new queue on the broker.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return integer the message count.
     */
    public function declareQueue() {

        $durable = boolval($this->flags & AMQP_DURABLE);
        $passive = boolval($this->flags & AMQP_PASSIVE);
        $exclusive = boolval($this->flags & AMQP_EXCLUSIVE);
        $auto_delete = boolval($this->flags & AMQP_AUTODELETE);

        try {
            list($this->name, $num_messages) = $this->channel->_getChannel()->queue_declare($this->name, $passive, $durable, $exclusive, $auto_delete, $nowait = false, $this->arguments);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return 0;
        }

        return $num_messages;
    }

    /**
     * Delete a queue from the broker.
     *
     * This includes its entire contents of unread or unacknowledged messages.
     *
     * @param integer $flags Optionally AMQP_IFUNUSED can be specified
     *                              to indicate the queue should not be
     *                              deleted until no clients are connected to
     *                              it.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return integer The number of deleted messages.
     */
    public function delete($flags = AMQP_NOPARAM) {

        $if_unused = boolval($flags & AMQP_IFUNUSED);

        try {
            list($num_deleted) = $this->channel->_getChannel()->queue_delete($this->name, $if_unused);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return 0;
        }

        //Will always be defined if an exception isn't thrown
        return $num_deleted;
    }

    /**
     * Get the argument associated with the given key.
     *
     * @param string $key The key to look up.
     *
     * @return string|integer|boolean The string or integer value associated
     *                                with the given key, or false if the key
     *                                is not set.
     */
    public function getArgument($key) {
        if(!isset($this->arguments[$key]))
            return false;

        return $this->arguments[$key];
    }

    /**
     * Get all set arguments as an array of key/value pairs.
     *
     * @return array An array containing all of the set key/value pairs.
     */
    public function getArguments() {
        return $this->arguments;
    }

    /**
     * Get all the flags currently set on the given queue.
     *
     * @return int An integer bitmask of all the flags currently set on this
     *             exchange object.
     */
    public function getFlags() {
        return $this->flags;
    }

    /**
     * Get the configured name.
     *
     * @return string The configured name as a string.
     */
    public function getName() {
        return $this->name;
    }

    /**
     * Acknowledge the receipt of a message.
     *
     * This method allows the acknowledgement of a message that is retrieved
     * without the AMQP_AUTOACK flag through AMQPQueue::get() or
     * AMQPQueue::consume()
     *
     * @param string $delivery_tag The message delivery tag of which to
     *                              acknowledge receipt.
     * @param integer $flags The only valid flag that can be passed is
     *                              AMQP_MULTIPLE.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function ack($delivery_tag, $flags = AMQP_NOPARAM) {

        $multiple = boolval($flags & AMQP_MULTIPLE);

        try {
            $this->channel->_getChannel()->basic_ack($delivery_tag, $multiple);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return false;
        }

        return true;

    }

    /**
     * Bind the given queue to a routing key on an exchange.
     *
     * @param string $exchange_name Name of the exchange to bind to.
     * @param string $routing_key Pattern or routing key to bind with.
     * @param array $arguments Additional binding arguments.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function bind($exchange_name, $routing_key = null, array $arguments = array()) {

        if($routing_key === null)
            $routing_key = '';

        $bind_arguments = new AMQPTable($arguments);

        try {
            $this->channel->_getChannel()->queue_bind($this->name, $exchange_name, $routing_key, $nowait = false, $bind_arguments);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return false;
        }

        return true;

    }

    /**
     * Cancel a queue that is already bound to an exchange and routing key.
     *
     * @param string $consumer_tag The queue name to cancel, if the queue
     *                             object is not already representative of
     *                             a queue.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return bool;
     */
    public function cancel($consumer_tag = '') {

        if($consumer_tag === '')
            $consumer_tag = $this->consumer_tag;

        try {
            $this->channel->_getChannel()->basic_cancel($consumer_tag);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * Mark a message as explicitly not acknowledged.
     *
     * Mark the message identified by delivery_tag as explicitly not
     * acknowledged. This method can only be called on messages that have not
     * yet been acknowledged, meaning that messages retrieved with by
     * AMQPQueue::consume() and AMQPQueue::get() and using the AMQP_AUTOACK
     * flag are not eligible. When called, the broker will immediately put the
     * message back onto the queue, instead of waiting until the connection is
     * closed. This method is only supported by the RabbitMQ broker. The
     * behavior of calling this method while connected to any other broker is
     * undefined.
     *
     * @param string $delivery_tag Delivery tag of last message to reject.
     * @param integer $flags AMQP_REQUEUE to requeue the message(s),
     *                              AMQP_MULTIPLE to nack all previous
     *                              unacked messages as well.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function nack($delivery_tag, $flags = AMQP_NOPARAM) {

        $requeue = boolval($flags & AMQP_REQUEUE);
        $multiple = boolval($flags & AMQP_MULTIPLE);

        try {
            $this->channel->_getChannel()->basic_nack($delivery_tag, $multiple, $requeue);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * Mark one message as explicitly not acknowledged.
     *
     * Mark the message identified by delivery_tag as explicitly not
     * acknowledged. This method can only be called on messages that have not
     * yet been acknowledged, meaning that messages retrieved with by
     * AMQPQueue::consume() and AMQPQueue::get() and using the AMQP_AUTOACK
     * flag are not eligible.
     *
     * @param string $delivery_tag Delivery tag of the message to reject.
     * @param integer $flags AMQP_REQUEUE to requeue the message(s).
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function reject($delivery_tag, $flags = AMQP_NOPARAM) {

        $requeue = boolval($flags & AMQP_REQUEUE);

        try {
            $this->channel->_getChannel()->basic_reject($delivery_tag, $requeue);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * Purge the contents of a queue.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function purge() {

        try {
            $this->channel->_getChannel()->queue_purge($this->name);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * Set a queue argument.
     *
     * @param string $key The key to set.
     * @param mixed $value The value to set.
     *
     * @return boolean
     */
    public function setArgument($key, $value) {
        $this->arguments[$key] = $value;
    }

    /**
     * Set all arguments on the given queue.
     *
     * All other argument settings will be wiped.
     *
     * @param array $arguments An array of key/value pairs of arguments.
     *
     * @return boolean
     */
    public function setArguments(array $arguments) {
        $this->arguments = $arguments;
        return true;
    }

    /**
     * Set the flags on the queue.
     *
     * @param integer $flags A bitmask of flags:
     *                       AMQP_DURABLE, AMQP_PASSIVE,
     *                       AMQP_EXCLUSIVE, AMQP_AUTODELETE.
     *
     * @return boolean
     */
    public function setFlags($flags) {
        if($flags !== $flags & (AMQP_DURABLE | AMQP_PASSIVE | AMQP_EXCLUSIVE | AMQP_AUTODELETE))
            return false;

        $this->flags = $flags;
        return true;
    }

    /**
     * Set the queue name.
     *
     * @param string $queue_name The name of the queue.
     *
     * @return boolean
     */
    public function setName($queue_name) {
        $this->name = $queue_name;
        return true;
    }

    /**
     * Remove a routing key binding on an exchange from the given queue.
     *
     * @param string $exchange_name The name of the exchange on which the
     *                              queue is bound.
     * @param string $routing_key The binding routing key used by the
     *                              queue.
     * @param array $arguments Additional binding arguments.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function unbind($exchange_name, $routing_key = null, array $arguments = array()) {

        if($routing_key === null)
            $routing_key = '';

        $bind_arguments = new AMQPTable($arguments);

        try {
            $this->channel->_getChannel()->queue_unbind($this->name, $exchange_name, $routing_key, $bind_arguments);
        } catch (AMQPRuntimeException $e) {
            throw new AMQPConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
        } catch (Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * Get the AMQPChannel object in use
     *
     * @return AMQPChannel
     */
    public function getChannel() {
        return $this->channel;
    }

    /**
     * Get the AMQPConnection object in use
     *
     * @return AMQPConnection
     */
    public function getConnection() {
        return $this->channel->getConnection();
    }
}


text:
package com.oce.springboot.training.d01.s02.config;

import com.oce.springboot.training.d01.s02.repository.ProductRepository;
import com.oce.springboot.training.d01.s02.service.ProductService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * A simple Spring configuration, which wires two simple {@link Bean}s
 *
 * @author bogdan.solga
 */
@Configuration
public class DomainConfig {

    @Bean
    public ProductRepository productRepository() {
        return new ProductRepository();
    }

    @Bean
    public ProductService productService() {
        final ProductService productService = new ProductService();
        productService.setProductRepository(productRepository());
        return productService;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace FControl\Parameter;

use FControl\Configuration;

class ConfirmOrder extends AbstractParameter
{
    protected $parameters = array(
        'login' => null,
        'senha' => null,
        'identificadorLojaFilho' => null,
        'codigoPedido' => null,
    );

    /**
     * @param $orderNumber
     */
    public function __construct($orderNumber)
    {
        $this->codigoPedido = $orderNumber;
    }

    /**
     * @param Configuration $configuration
     */
    public function setAuthentication(Configuration $configuration)
    {
        $this->login = $configuration->getLogin();
        $this->senha = $configuration->getPassword();
        $this->identificadorLojaFilho = $configuration->getStoreId();
    }
}


text:
<?php

namespace Liip\RMT\Tests\Unit\Information;

use Liip\RMT\Information\InformationRequest;

class InformationRequestTest extends \PHPUnit_Framework_TestCase
{
    public function testSetAndGetValue()
    {
        $ir = new InformationRequest('foo', array('type'=>'text'));
        $this->assertFalse($ir->hasValue());
        $ir->setValue('bar');
        $this->assertTrue($ir->hasValue());
        $this->assertEquals('bar', $ir->getValue());
    }

    /**
     * @dataProvider getDataForValidationSuccess
     */
    public function testValidationSuccess($options, $value, $expected=null)
    {
        if (func_num_args()==2){
            $expected = $value;
        }
        $ir = new InformationRequest('foo', $options);
        $ir->setValue($value);
        $this->assertEquals($expected, $ir->getValue());
    }
    public function getDataForValidationSuccess()
    {
        return array(
            array(array('type'=>'text'),  'string'),
            array(array('type'=>'yes-no'), 'y'),
            array(array('type'=>'yes-no'), 'n'),
            array(array('type'=>'yes-no'), 'yes', 'y'),
            array(array('type'=>'yes-no'), 'no' , 'n'),
            array(array('type'=>'choice', 'choices' => array('apple', 'banana', 'cherry')), 'apple'),
            array(array('type'=>'confirmation'), true),
            array(array('type'=>'confirmation'), false)
        );
    }

    /**
     * @dataProvider getDataForValidationFail
     * @expectedException \InvalidArgumentException
     */
    public function testValidationFail($options, $value)
    {
        $ir = new InformationRequest('foo', $options);
        $ir->setValue($value);
    }
    public function getDataForValidationFail()
    {
        $choices = array('apple', 'banana', 'cherry');
        return array(
            array(array('type'=>'text'), true),
            array(array('type'=>'text'), ''),
            array(array('type'=>'yes-no'), 'foo'),
            array(array('type'=>'yes-no'), 19),
            array(array('type'=>'choice', 'choices' => $choices), 'mango')
        );
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Common.Decomposition;
using FarseerPhysics.Common.PolygonManipulation;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;

namespace FallingBombs.Windows
{
    class PrimitiveDrawing
    {
        private static Color defaultColor = new Color(0, 0, (int)byte.MaxValue);
        private static List<VertexPositionColor> TriangleVerts = new List<VertexPositionColor>();
        private static List<VertexPositionColor> LineVerts = new List<VertexPositionColor>();
        private const int circleSideAmounts = 20;
        private static BasicEffect basicEffect;
        private static World world;
        private static VertexPositionColor firstVPC;
        private static VertexPositionColor secondVPC;
        private static VertexPositionColor thirdVPC;
        private static bool shaking;
        private static float shakeMagnitude;
        private static float shakeDuration;
        private static float shakeTimer;

        public static void SetUp(World startWorld)
        {
            PrimitiveDrawing.world = startWorld;
        }

        public static void Shake(float magnitude, float duration)
        {
            if (!PrimitiveDrawing.shaking)
            {
                PrimitiveDrawing.shaking = true;
                PrimitiveDrawing.shakeTimer = 0.0f;
                PrimitiveDrawing.shakeDuration = duration;
                PrimitiveDrawing.shakeMagnitude = magnitude;
            }
            else
                PrimitiveDrawing.shakeMagnitude += magnitude;
        }

        public static void Draw(float yPos, float worldScreenWidth, GraphicsDevice gd, Game1 game, GameTime gameTime, Random rand, Viewport viewport)
        {
            float xPosition = 0.0f;
            float yPosition = -yPos;
            float zPosition = 0.0f;
            if (PrimitiveDrawing.shaking)
            {
                PrimitiveDrawing.shakeTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if ((double)PrimitiveDrawing.shakeTimer >= (double)PrimitiveDrawing.shakeDuration)
                {
                    PrimitiveDrawing.shaking = false;
                    PrimitiveDrawing.shakeTimer = PrimitiveDrawing.shakeDuration;
                }
                float num1 = PrimitiveDrawing.shakeTimer / PrimitiveDrawing.shakeDuration;
                float num2 = PrimitiveDrawing.shakeMagnitude * (float)(1.0 - (double)num1 * (double)num1);
                xPosition = (float)(rand.NextDouble() * 2.0 - 1.0) * num2;
                yPosition += (float)(rand.NextDouble() * 2.0 - 1.0) * num2;
            }
            PrimitiveDrawing.basicEffect = new BasicEffect(gd)
            {
                Projection = Matrix.CreateOrthographic(worldScreenWidth, worldScreenWidth / gd.Viewport.AspectRatio, 0.0f, 1f),
                View = Matrix.CreateTranslation(xPosition, yPosition, zPosition),
                VertexColorEnabled = true
            };
            foreach (Body body in PrimitiveDrawing.world.BodyList)
            {
                if (body != game.highScoreLine || body.UserData == (ValueType)Mine.MineColor)
                    PrimitiveDrawing.DrawBody(body);
            }
            PrimitiveDrawing.DrawBody(game.highScoreLine);
            gd.Viewport = viewport;
            foreach (EffectPass effectPass in PrimitiveDrawing.basicEffect.CurrentTechnique.Passes)
            {
                effectPass.Apply();
                if (PrimitiveDrawing.TriangleVerts.Count > 0)
                    gd.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, PrimitiveDrawing.TriangleVerts.ToArray(), 0, PrimitiveDrawing.TriangleVerts.Count / 3);
                if (PrimitiveDrawing.LineVerts.Count > 0)
                    gd.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, PrimitiveDrawing.LineVerts.ToArray(), 0, PrimitiveDrawing.LineVerts.Count / 2);
            }
            PrimitiveDrawing.LineVerts.Clear();
            PrimitiveDrawing.TriangleVerts.Clear();
        }

        private static void DrawBody(Body body)
        {
            foreach (Fixture fixture in body.FixtureList)
            {
                Vertices vertsFromFixture = PrimitiveDrawing.GetVertsFromFixture(fixture);
                if (fixture.UserData is Color)
                    PrimitiveDrawing.DrawShape(vertsFromFixture, (Color)fixture.UserData, fixture.Body.Position, fixture.Body.Rotation, fixture.Shape.ShapeType == ShapeType.Circle);
                else if (!(fixture.UserData is Texture))
                    PrimitiveDrawing.DrawShape(vertsFromFixture, PrimitiveDrawing.defaultColor, fixture.Body.Position, fixture.Body.Rotation, fixture.Shape.ShapeType == ShapeType.Circle);
            }
        }

        public static void DrawShape(Vertices fixtureVerts, Color color, Vector2 position, float rotation, bool drawRadius)
        {
            bool flag1 = false;
            Vector2 vector1 = Vector2.Zero;
            bool flag2 = false;
            Vector2 vector2 = Vector2.Zero;
            Matrix translation = Matrix.CreateTranslation(PrimitiveDrawing.MakeVector3(position));
            Matrix rotationZ = Matrix.CreateRotationZ(rotation);
            Matrix matrix = rotationZ * translation;
            foreach (Vector2 vector3 in (List<Vector2>)fixtureVerts)
            {
                if (!flag1)
                {
                    flag1 = true;
                    vector1 = vector3;
                }
                else if (!flag2)
                {
                    flag2 = true;
                    vector2 = vector3;
                }
                else
                {
                    Vector3 vector3_1 = Vector3.Transform(PrimitiveDrawing.MakeVector3(vector1), matrix);
                    Vector3 vector3_2 = Vector3.Transform(PrimitiveDrawing.MakeVector3(vector2), matrix);
                    Vector3 vector3_3 = Vector3.Transform(PrimitiveDrawing.MakeVector3(vector3), matrix);
                    PrimitiveDrawing.firstVPC.Position = vector3_1;
                    PrimitiveDrawing.firstVPC.Color = color;
                    PrimitiveDrawing.secondVPC.Position = vector3_2;
                    PrimitiveDrawing.secondVPC.Color = color;
                    PrimitiveDrawing.thirdVPC.Position = vector3_3;
                    PrimitiveDrawing.thirdVPC.Color = color;
                    PrimitiveDrawing.TriangleVerts.Add(PrimitiveDrawing.thirdVPC);
                    PrimitiveDrawing.TriangleVerts.Add(PrimitiveDrawing.secondVPC);
                    PrimitiveDrawing.TriangleVerts.Add(PrimitiveDrawing.firstVPC);
                    vector2 = vector3;
                }
            }
            if (!drawRadius)
                return;
            Vector3 position1 = Vector3.Transform(Vector3.Transform(PrimitiveDrawing.MakeVector3(fixtureVerts[0]), rotationZ), translation);
            PrimitiveDrawing.LineVerts.Add(new VertexPositionColor(position1, Color.White));
            PrimitiveDrawing.LineVerts.Add(new VertexPositionColor(PrimitiveDrawing.MakeVector3(position), Color.White));
        }

        private static Vector3 MakeVector3(Vector2 vector)
        {
            return new Vector3(vector.X, vector.Y, 0.0f);
        }

        private static Vertices GetVertsFromFixture(Fixture fixture)
        {
            if (fixture.Shape.ShapeType == ShapeType.Circle)
                return PolygonTools.CreateCircle(fixture.Shape.Radius, 20);
            return ((PolygonShape)fixture.Shape).Vertices;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.IFC;
using Revit.IFC.Common.Utility;
using Revit.IFC.Common.Enums;
using Revit.IFC.Import.Enums;
using Revit.IFC.Import.Geometry;
using Revit.IFC.Import.Utility;

namespace Revit.IFC.Import.Data
{
    /// <summary>
    /// Class that represents an IfcCartesianPoint3D.
    /// </summary>
    public class IFCCartesianPointList3D : IFCRepresentationItem
    {
        IList<IList<double>> m_CoordList = null;

        protected IFCCartesianPointList3D()
        {
        }

        /// <summary>
        /// The list of vertices, where the vertices are represented as an IList of doubles.
        /// </summary>
        public IList<IList<double>> CoordList
        {
            get { return m_CoordList; }
            protected set { m_CoordList = value; }
        }

        /// <summary>
        /// Create IFCCartesianPointList3D instance
        /// </summary>
        /// <param name="item">The handle</param>
        protected IFCCartesianPointList3D(IFCAnyHandle item)
        {
            Process(item);
        }

        /// <summary>
        /// Process the IfcCartesianPointList3D handle.
        /// </summary>
        /// <param name="item">The handle</param>
        protected override void Process(IFCAnyHandle item)
        {
            base.Process(item);

            IList<IList<double>> coordListAttrbute = IFCImportHandleUtil.GetListOfListOfDoubleAttribute(item, "CoordList");
            if (coordListAttrbute != null)
                m_CoordList = coordListAttrbute;
        }

        /// <summary>
        /// Accept the handle for IFCCartesianPointList3D and return the instance (creating it if not yet created)
        /// </summary>
        /// <param name="ifcCartesianPointList3D">The handle.</param>
        /// <returns>The associated IFCCartesianPointList3D class.</returns>
        public static IFCCartesianPointList3D processIFCCartesianPointList3D(IFCAnyHandle ifcCartesianPointList3D)
        {
            if (IFCAnyHandleUtil.IsNullOrHasNoValue(ifcCartesianPointList3D))
            {
                Importer.TheLog.LogNullError(IFCEntityType.IfcCartesianPointList3D);
                return null;
            }

            IFCEntity cartesianPointList3D;
            if (!IFCImportFile.TheFile.EntityMap.TryGetValue(ifcCartesianPointList3D.StepId, out cartesianPointList3D))
                cartesianPointList3D = new IFCCartesianPointList3D(ifcCartesianPointList3D);
            return (cartesianPointList3D as IFCCartesianPointList3D);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.IO;

namespace Orbital7.Extensions.NETFramework
{
    public static class RegistryHelper
    {
        public static string GetLocalMachineRegistryValue(string root, string path, string name)
        {
            return GetRegistryKeyValue(GetLocalMachineRegistryKey(root, path), name);
        }

        public static RegistryKey GetLocalMachineRegistryKey(string root, string path)
        {
            return GetRegistryKey(Registry.LocalMachine, root, path);
        }

        public static string GetCurrentUserRegistryValue(string root, string path, string name)
        {
            return GetRegistryKeyValue(GetCurrentUserRegistryKey(root, path), name);
        }

        public static RegistryKey GetCurrentUserRegistryKey(string root, string path)
        {
            return GetRegistryKey(Registry.CurrentUser, root, path);
        }

        private static RegistryKey GetRegistryKey(RegistryKey home, string root, string path)
        {
            RegistryKey registryKey = home.OpenSubKey(Path.Combine(root, path));
            if (registryKey == null) registryKey = home.OpenSubKey(Path.Combine(root, "Wow6432Node", path));

            return registryKey;
        }

        private static string GetRegistryKeyValue(RegistryKey registryKey, string name)
        {
            string value = string.Empty;

            if (registryKey != null)
            {
                object oValue = registryKey.GetValue(name);
                if (oValue != null) value = oValue.ToString();
            }

            return value;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;

namespace System
{
    public static class __ArrayTypeMismatchException
    {
    }
}


text:
package org.elasticsearch.index.query.support;

import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.search.fetch.fielddata.FieldDataFieldsParseElement;
import org.elasticsearch.search.fetch.innerhits.InnerHitsSubSearchContext;
import org.elasticsearch.search.fetch.script.ScriptFieldsParseElement;
import org.elasticsearch.search.fetch.source.FetchSourceParseElement;
import org.elasticsearch.search.highlight.HighlighterParseElement;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.internal.SubSearchContext;
import org.elasticsearch.search.sort.SortParseElement;

import java.io.IOException;

public class InnerHitsQueryParserHelper {

    private final SortParseElement sortParseElement;
    private final FetchSourceParseElement sourceParseElement;
    private final HighlighterParseElement highlighterParseElement;
    private final ScriptFieldsParseElement scriptFieldsParseElement;
    private final FieldDataFieldsParseElement fieldDataFieldsParseElement;

    @Inject
    public InnerHitsQueryParserHelper(SortParseElement sortParseElement, FetchSourceParseElement sourceParseElement, HighlighterParseElement highlighterParseElement, ScriptFieldsParseElement scriptFieldsParseElement, FieldDataFieldsParseElement fieldDataFieldsParseElement) {
        this.sortParseElement = sortParseElement;
        this.sourceParseElement = sourceParseElement;
        this.highlighterParseElement = highlighterParseElement;
        this.scriptFieldsParseElement = scriptFieldsParseElement;
        this.fieldDataFieldsParseElement = fieldDataFieldsParseElement;
    }

    public InnerHitsSubSearchContext parse(XContentParser parser) throws IOException {
        String fieldName = null;
        XContentParser.Token token;
        String innerHitName = null;
        SubSearchContext subSearchContext = new SubSearchContext(SearchContext.current());
        try {
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    fieldName = parser.currentName();
                } else if (token.isValue()) {
                    if ("name".equals(fieldName)) {
                        innerHitName = parser.textOrNull();
                    } else {
                        parseCommonInnerHitOptions(parser, token, fieldName, subSearchContext, sortParseElement, sourceParseElement, highlighterParseElement, scriptFieldsParseElement, fieldDataFieldsParseElement);
                    }
                } else {
                    parseCommonInnerHitOptions(parser, token, fieldName, subSearchContext, sortParseElement, sourceParseElement, highlighterParseElement, scriptFieldsParseElement, fieldDataFieldsParseElement);
                }
            }
        } catch (Exception e) {
            throw new IOException("Failed to parse [_inner_hits]", e);
        }
        return new InnerHitsSubSearchContext(innerHitName, subSearchContext);
    }

    public static void parseCommonInnerHitOptions(XContentParser parser, XContentParser.Token token, String fieldName, SubSearchContext subSearchContext,
                                                  SortParseElement sortParseElement, FetchSourceParseElement sourceParseElement, HighlighterParseElement highlighterParseElement,
                                                  ScriptFieldsParseElement scriptFieldsParseElement, FieldDataFieldsParseElement fieldDataFieldsParseElement) throws Exception {
        if ("sort".equals(fieldName)) {
            sortParseElement.parse(parser, subSearchContext);
        } else if ("_source".equals(fieldName)) {
            sourceParseElement.parse(parser, subSearchContext);
        } else if (token == XContentParser.Token.START_OBJECT) {
            switch (fieldName) {
                case "highlight":
                    highlighterParseElement.parse(parser, subSearchContext);
                    break;
                case "scriptFields":
                case "script_fields":
                    scriptFieldsParseElement.parse(parser, subSearchContext);
                    break;
                default:
                    throw new IllegalArgumentException("Unknown key for a " + token + " for nested query: [" + fieldName + "].");
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            switch (fieldName) {
                case "fielddataFields":
                case "fielddata_fields":
                    fieldDataFieldsParseElement.parse(parser, subSearchContext);
                    break;
                case "fields":
                    boolean added = false;
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        String name = parser.text();
                        added = true;
                        subSearchContext.fieldNames().add(name);
                    }
                    if (!added) {
                        subSearchContext.emptyFieldNames();
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Unknown key for a " + token + " for nested query: [" + fieldName + "].");
            }
        } else if (token.isValue()) {
            switch (fieldName) {
                case "from":
                    subSearchContext.from(parser.intValue());
                    break;
                case "size":
                    subSearchContext.size(parser.intValue());
                    break;
                case "track_scores":
                case "trackScores":
                    subSearchContext.trackScores(parser.booleanValue());
                    break;
                case "version":
                    subSearchContext.version(parser.booleanValue());
                    break;
                case "explain":
                    subSearchContext.explain(parser.booleanValue());
                    break;
                case "fields":
                    subSearchContext.fieldNames().add(parser.text());
                    break;
                default:
                    throw new IllegalArgumentException("Unknown key for a " + token + " for nested query: [" + fieldName + "].");
            }
        }
    }
}


text:
title: "tinted.xyz"
layout: post
description: tinting glass guide
category: item
img: img/tinted.xyz.png
redirect: http://tinted.xyz
---


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TokenKind = undefined;
exports.createLexer = createLexer;
exports.getTokenDesc = getTokenDesc;

var _error = require('../error');

var _blockStringValue = require('./blockStringValue');

var _blockStringValue2 = _interopRequireDefault(_blockStringValue);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Given a Source object, this returns a Lexer for that source.
 * A Lexer is a stateful stream generator in that every time
 * it is advanced, it returns the next token in the Source. Assuming the
 * source lexes, the final Token emitted by the lexer will be of kind
 * EOF, after which the lexer will repeatedly return the same EOF token
 * whenever called.
 */
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 *  strict
 */

function createLexer(source, options) {
  var startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null);
  var lexer = {
    source: source,
    options: options,
    lastToken: startOfFileToken,
    token: startOfFileToken,
    line: 1,
    lineStart: 0,
    advance: advanceLexer,
    lookahead: lookahead
  };
  return lexer;
}

function advanceLexer() {
  this.lastToken = this.token;
  var token = this.token = this.lookahead();
  return token;
}

function lookahead() {
  var token = this.token;
  if (token.kind !== TokenKind.EOF) {
    do {
      // Note: next is only mutable during parsing, so we cast to allow this.
      token = token.next || (token.next = readToken(this, token));
    } while (token.kind === TokenKind.COMMENT);
  }
  return token;
}

/**
 * The return type of createLexer.
 */

/**
 * An exported enum describing the different kinds of tokens that the
 * lexer emits.
 */
var TokenKind = exports.TokenKind = Object.freeze({
  SOF: '<SOF>',
  EOF: '<EOF>',
  BANG: '!',
  DOLLAR: '$',
  AMP: '&',
  PAREN_L: '(',
  PAREN_R: ')',
  SPREAD: '...',
  COLON: ':',
  EQUALS: '=',
  AT: '@',
  BRACKET_L: '[',
  BRACKET_R: ']',
  BRACE_L: '{',
  PIPE: '|',
  BRACE_R: '}',
  NAME: 'Name',
  INT: 'Int',
  FLOAT: 'Float',
  STRING: 'String',
  BLOCK_STRING: 'BlockString',
  COMMENT: 'Comment'
});

/**
 * The enum type representing the token kinds values.
 */

/**
 * A helper function to describe a token as a string for debugging
 */
function getTokenDesc(token) {
  var value = token.value;
  return value ? token.kind + ' "' + value + '"' : token.kind;
}

var charCodeAt = String.prototype.charCodeAt;
var slice = String.prototype.slice;

/**
 * Helper function for constructing the Token object.
 */
function Tok(kind, start, end, line, column, prev, value) {
  this.kind = kind;
  this.start = start;
  this.end = end;
  this.line = line;
  this.column = column;
  this.value = value;
  this.prev = prev;
  this.next = null;
}

// Print a simplified form when appearing in JSON/util.inspect.
Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() {
  return {
    kind: this.kind,
    value: this.value,
    line: this.line,
    column: this.column
  };
};

function printCharCode(code) {
  return (
    // NaN/undefined represents access beyond the end of the file.
    isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.
    code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.
    '"\\u' + ('00' + code.toString(16).toUpperCase()).slice(-4) + '"'
  );
}

/**
 * Gets the next token from the source starting at the given position.
 *
 * This skips over whitespace and comments until it finds the next lexable
 * token, then lexes punctuators immediately or calls the appropriate helper
 * function for more complicated tokens.
 */
function readToken(lexer, prev) {
  var source = lexer.source;
  var body = source.body;
  var bodyLength = body.length;

  var pos = positionAfterWhitespace(body, prev.end, lexer);
  var line = lexer.line;
  var col = 1 + pos - lexer.lineStart;

  if (pos >= bodyLength) {
    return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);
  }

  var code = charCodeAt.call(body, pos);

  // SourceCharacter
  if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
    throw (0, _error.syntaxError)(source, pos, 'Cannot contain the invalid character ' + printCharCode(code) + '.');
  }

  switch (code) {
    // !
    case 33:
      return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev);
    // #
    case 35:
      return readComment(source, pos, line, col, prev);
    // $
    case 36:
      return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev);
    // &
    case 38:
      return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev);
    // (
    case 40:
      return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev);
    // )
    case 41:
      return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev);
    // .
    case 46:
      if (charCodeAt.call(body, pos + 1) === 46 && charCodeAt.call(body, pos + 2) === 46) {
        return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev);
      }
      break;
    // :
    case 58:
      return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev);
    // =
    case 61:
      return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev);
    // @
    case 64:
      return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev);
    // [
    case 91:
      return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev);
    // ]
    case 93:
      return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev);
    // {
    case 123:
      return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev);
    // |
    case 124:
      return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev);
    // }
    case 125:
      return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev);
    // A-Z _ a-z
    case 65:
    case 66:
    case 67:
    case 68:
    case 69:
    case 70:
    case 71:
    case 72:
    case 73:
    case 74:
    case 75:
    case 76:
    case 77:
    case 78:
    case 79:
    case 80:
    case 81:
    case 82:
    case 83:
    case 84:
    case 85:
    case 86:
    case 87:
    case 88:
    case 89:
    case 90:
    case 95:
    case 97:
    case 98:
    case 99:
    case 100:
    case 101:
    case 102:
    case 103:
    case 104:
    case 105:
    case 106:
    case 107:
    case 108:
    case 109:
    case 110:
    case 111:
    case 112:
    case 113:
    case 114:
    case 115:
    case 116:
    case 117:
    case 118:
    case 119:
    case 120:
    case 121:
    case 122:
      return readName(source, pos, line, col, prev);
    // - 0-9
    case 45:
    case 48:
    case 49:
    case 50:
    case 51:
    case 52:
    case 53:
    case 54:
    case 55:
    case 56:
    case 57:
      return readNumber(source, pos, code, line, col, prev);
    // "
    case 34:
      if (charCodeAt.call(body, pos + 1) === 34 && charCodeAt.call(body, pos + 2) === 34) {
        return readBlockString(source, pos, line, col, prev);
      }
      return readString(source, pos, line, col, prev);
  }

  throw (0, _error.syntaxError)(source, pos, unexpectedCharacterMessage(code));
}

/**
 * Report a message that an unexpected character was encountered.
 */
function unexpectedCharacterMessage(code) {
  if (code === 39) {
    // '
    return "Unexpected single quote character ('), did you mean to use " + 'a double quote (")?';
  }

  return 'Cannot parse the unexpected character ' + printCharCode(code) + '.';
}

/**
 * Reads from body starting at startPosition until it finds a non-whitespace
 * or commented character, then returns the position of that character for
 * lexing.
 */
function positionAfterWhitespace(body, startPosition, lexer) {
  var bodyLength = body.length;
  var position = startPosition;
  while (position < bodyLength) {
    var code = charCodeAt.call(body, position);
    // tab | space | comma | BOM
    if (code === 9 || code === 32 || code === 44 || code === 0xfeff) {
      ++position;
    } else if (code === 10) {
      // new line
      ++position;
      ++lexer.line;
      lexer.lineStart = position;
    } else if (code === 13) {
      // carriage return
      if (charCodeAt.call(body, position + 1) === 10) {
        position += 2;
      } else {
        ++position;
      }
      ++lexer.line;
      lexer.lineStart = position;
    } else {
      break;
    }
  }
  return position;
}

/**
 * Reads a comment token from the source file.
 *
 * #[\u0009\u0020-\uFFFF]*
 */
function readComment(source, start, line, col, prev) {
  var body = source.body;
  var code = void 0;
  var position = start;

  do {
    code = charCodeAt.call(body, ++position);
  } while (code !== null && (
  // SourceCharacter but not LineTerminator
  code > 0x001f || code === 0x0009));

  return new Tok(TokenKind.COMMENT, start, position, line, col, prev, slice.call(body, start + 1, position));
}

/**
 * Reads a number token from the source file, either a float
 * or an int depending on whether a decimal point appears.
 *
 * Int:   -?(0|[1-9][0-9]*)
 * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?
 */
function readNumber(source, start, firstCode, line, col, prev) {
  var body = source.body;
  var code = firstCode;
  var position = start;
  var isFloat = false;

  if (code === 45) {
    // -
    code = charCodeAt.call(body, ++position);
  }

  if (code === 48) {
    // 0
    code = charCodeAt.call(body, ++position);
    if (code >= 48 && code <= 57) {
      throw (0, _error.syntaxError)(source, position, 'Invalid number, unexpected digit after 0: ' + printCharCode(code) + '.');
    }
  } else {
    position = readDigits(source, position, code);
    code = charCodeAt.call(body, position);
  }

  if (code === 46) {
    // .
    isFloat = true;

    code = charCodeAt.call(body, ++position);
    position = readDigits(source, position, code);
    code = charCodeAt.call(body, position);
  }

  if (code === 69 || code === 101) {
    // E e
    isFloat = true;

    code = charCodeAt.call(body, ++position);
    if (code === 43 || code === 45) {
      // + -
      code = charCodeAt.call(body, ++position);
    }
    position = readDigits(source, position, code);
  }

  return new Tok(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, slice.call(body, start, position));
}

/**
 * Returns the new position in the source after reading digits.
 */
function readDigits(source, start, firstCode) {
  var body = source.body;
  var position = start;
  var code = firstCode;
  if (code >= 48 && code <= 57) {
    // 0 - 9
    do {
      code = charCodeAt.call(body, ++position);
    } while (code >= 48 && code <= 57); // 0 - 9
    return position;
  }
  throw (0, _error.syntaxError)(source, position, 'Invalid number, expected digit but got: ' + printCharCode(code) + '.');
}

/**
 * Reads a string token from the source file.
 *
 * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
 */
function readString(source, start, line, col, prev) {
  var body = source.body;
  var position = start + 1;
  var chunkStart = position;
  var code = 0;
  var value = '';

  while (position < body.length && (code = charCodeAt.call(body, position)) !== null &&
  // not LineTerminator
  code !== 0x000a && code !== 0x000d) {
    // Closing Quote (")
    if (code === 34) {
      value += slice.call(body, chunkStart, position);
      return new Tok(TokenKind.STRING, start, position + 1, line, col, prev, value);
    }

    // SourceCharacter
    if (code < 0x0020 && code !== 0x0009) {
      throw (0, _error.syntaxError)(source, position, 'Invalid character within String: ' + printCharCode(code) + '.');
    }

    ++position;
    if (code === 92) {
      // \
      value += slice.call(body, chunkStart, position - 1);
      code = charCodeAt.call(body, position);
      switch (code) {
        case 34:
          value += '"';
          break;
        case 47:
          value += '/';
          break;
        case 92:
          value += '\\';
          break;
        case 98:
          value += '\b';
          break;
        case 102:
          value += '\f';
          break;
        case 110:
          value += '\n';
          break;
        case 114:
          value += '\r';
          break;
        case 116:
          value += '\t';
          break;
        case 117:
          // u
          var charCode = uniCharCode(charCodeAt.call(body, position + 1), charCodeAt.call(body, position + 2), charCodeAt.call(body, position + 3), charCodeAt.call(body, position + 4));
          if (charCode < 0) {
            throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: ' + ('\\u' + body.slice(position + 1, position + 5) + '.'));
          }
          value += String.fromCharCode(charCode);
          position += 4;
          break;
        default:
          throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: \\' + String.fromCharCode(code) + '.');
      }
      ++position;
      chunkStart = position;
    }
  }

  throw (0, _error.syntaxError)(source, position, 'Unterminated string.');
}

/**
 * Reads a block string token from the source file.
 *
 * """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""
 */
function readBlockString(source, start, line, col, prev) {
  var body = source.body;
  var position = start + 3;
  var chunkStart = position;
  var code = 0;
  var rawValue = '';

  while (position < body.length && (code = charCodeAt.call(body, position)) !== null) {
    // Closing Triple-Quote (""")
    if (code === 34 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34) {
      rawValue += slice.call(body, chunkStart, position);
      return new Tok(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, (0, _blockStringValue2.default)(rawValue));
    }

    // SourceCharacter
    if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
      throw (0, _error.syntaxError)(source, position, 'Invalid character within String: ' + printCharCode(code) + '.');
    }

    // Escape Triple-Quote (\""")
    if (code === 92 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34 && charCodeAt.call(body, position + 3) === 34) {
      rawValue += slice.call(body, chunkStart, position) + '"""';
      position += 4;
      chunkStart = position;
    } else {
      ++position;
    }
  }

  throw (0, _error.syntaxError)(source, position, 'Unterminated string.');
}

/**
 * Converts four hexidecimal chars to the integer that the
 * string represents. For example, uniCharCode('0','0','0','f')
 * will return 15, and uniCharCode('0','0','f','f') returns 255.
 *
 * Returns a negative number on error, if a char was invalid.
 *
 * This is implemented by noting that char2hex() returns -1 on error,
 * which means the result of ORing the char2hex() will also be negative.
 */
function uniCharCode(a, b, c, d) {
  return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);
}

/**
 * Converts a hex character to its integer value.
 * '0' becomes 0, '9' becomes 9
 * 'A' becomes 10, 'F' becomes 15
 * 'a' becomes 10, 'f' becomes 15
 *
 * Returns -1 on error.
 */
function char2hex(a) {
  return a >= 48 && a <= 57 ? a - 48 // 0-9
  : a >= 65 && a <= 70 ? a - 55 // A-F
  : a >= 97 && a <= 102 ? a - 87 // a-f
  : -1;
}

/**
 * Reads an alphanumeric + underscore name from the source.
 *
 * [_A-Za-z][_0-9A-Za-z]*
 */
function readName(source, start, line, col, prev) {
  var body = source.body;
  var bodyLength = body.length;
  var position = start + 1;
  var code = 0;
  while (position !== bodyLength && (code = charCodeAt.call(body, position)) !== null && (code === 95 || // _
  code >= 48 && code <= 57 || // 0-9
  code >= 65 && code <= 90 || // A-Z
  code >= 97 && code <= 122) // a-z
  ) {
    ++position;
  }
  return new Tok(TokenKind.NAME, start, position, line, col, prev, slice.call(body, start, position));
}


text:
<!doctype html>

 <meta charset='UTF-8'>
 <meta name="keywords" content="astronomy">
 <meta name="description" content="Generate SELECT items for UK weather sites">
 <meta name="viewport" content="width=device-width">

 <title>Generate SELECT items for UK weather sites</title>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--  Copyright (C) 2010 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
 -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="app_label" msgid="3070921713463294774">"Mga Download"</string>
    <string name="download_title_sorted_by_date" msgid="5898014492155434221">"Mga download - Inuri-uri ayon sa petsa"</string>
    <string name="download_title_sorted_by_size" msgid="1417193166677094813">"Mga download - Inuri-uri ayon sa laki"</string>
    <string name="no_downloads" msgid="1029667411186146836">"Walang mga pag-download."</string>
    <string name="missing_title" msgid="830115697868833773">"<Hindi Kilala>"</string>
    <string name="button_sort_by_size" msgid="7331549713691146251">"Pag-uri-uriin sa laki"</string>
    <string name="button_sort_by_date" msgid="8800842892684101528">"Pag-uri-uriin sa petsa"</string>
    <string name="download_queued" msgid="104973307780629904">"Naka-queue"</string>
    <string name="download_running" msgid="4656462962155580641">"Isinasagawa"</string>
    <string name="download_success" msgid="7006048006543495236">"Kumpleto"</string>
    <string name="download_error" msgid="8081329546008568251">"Hindi matagumpay"</string>
    <string name="dialog_title_not_available" msgid="5746317632356158515">"Hindi ma-download"</string>
    <string name="dialog_failed_body" msgid="587545111677064427">"Gusto mo bang subukang muling i-download ang file sa ibang pagkakataon o alisin ito mula sa queue?"</string>
    <string name="dialog_title_queued_body" msgid="6760681913815015219">"File sa queue"</string>
    <string name="dialog_queued_body" msgid="708552801635572720">"Ang file na ito ay naka-queue para sa pag-download sa hinaharap kaya hindi pa available."</string>
    <string name="dialog_file_missing_body" msgid="3223012612774276284">"Hindi matagpuan ang na-download na file."</string>
    <string name="dialog_insufficient_space_on_external" msgid="8692452156251449195">"Hindi matapos ang pag-download. Walang sapat na puwang sa panlabas na storage."</string>
    <string name="dialog_insufficient_space_on_cache" msgid="6313630206163908994">"Hindi matapos ang pag-download. Walang sapat na puwang sa panloob na storage ng pag-download."</string>
    <string name="dialog_cannot_resume" msgid="8664509751358983543">"Naantala ang pag-download at hindi maipagpapatuloy."</string>
    <string name="dialog_file_already_exists" msgid="8308563940663449590">"Hindi ma-download. Umiiral na ang destination file."</string>
    <string name="dialog_media_not_found" msgid="4468088418758018765">"Hindi makapag-download. Hindi available ang panlabas na media."</string>
    <string name="download_no_application_title" msgid="7024782176657362251">"Hindi mabuksan ang file"</string>
    <string name="remove_download" msgid="6372920256257247857">"Alisin"</string>
    <string name="delete_download" msgid="76629022653866471">"Tanggalin"</string>
    <string name="keep_queued_download" msgid="5144882786014818569">"Panatilihin"</string>
    <string name="cancel_running_download" msgid="5232704030969221112">"Kanselahin"</string>
    <string name="retry_download" msgid="7617100787922717912">"Subukang muli"</string>
    <string name="deselect_all" msgid="6348198946254776764">"Alisin sa pagkakapili lahat"</string>
    <string name="select_all" msgid="634074918366265804">"Piliin lahat"</string>
    <string name="selected_count" msgid="2101564570019753277">"Pinili <xliff:g id="NUMBER">%1$d</xliff:g> sa <xliff:g id="TOTAL">%2$d</xliff:g>"</string>
    <string name="download_share_dialog" msgid="3355867339806448955">"Ibahagi gamit ang"</string>
</resources>


text:
var assert = require('assert');
var expect = require('chai').expect;
var halson = require('./index');
var nodePkg = require('./package.json');
var bowerPkg = require('./bower.json');

var example = {
    _links: {
        self: {
            href: "/hajovsky",
        },
        avatar: {
            href: "https://avatars0.githubusercontent.com/u/113901?s=460",
            type: "image/jpeg"
        },
        related: [{
            href: "http://hajovsky.sk",
            name: "homepage"
        }, {
            href: "https://twitter.com/hajovsky",
            name: "twitter"
        }]
    },
    title: "Juraj Hájovský",
    username: "hajovsky",
    emails: [
        "juraj.hajovsky@example.com",
        "hajovsky@example.com"
    ],
    stats: {
        starred: 3,
        followers: 0,
        following: 0

    },
    joined: "2009-08-10T00:00:00.000Z",
    _embedded: {
        starred: [
            {
                _links: {
                    self: {
                        href: "/joyent/node"
                    },
                    related: {
                        href: "http://nodejs.org/",
                        title: "nodejs.org",
                        name: "website"
                    },
                    author: {
                        href: "/joyent",
                        title: "Joyent"
                    }
                },
                title: "joyent / node",
                description: "evented I/O for v8 javascript",
                stats: {
                    watched: 2092,
                    starred: 28426,
                    forked: 5962
                }
            },
            {
                _links: {
                    self: {
                        href: "/koajs/koa"
                    },
                    related: {
                        href: "http://koajs.com",
                        title: "koajs.com",
                        name: "website"
                    },
                    author: {
                        href: "/koajs",
                        title: "koajs"
                    }
                },
                title: "koajs / koa",
                description: "Expressive middleware for node.js using generators",
                stats: {
                    watched: 238,
                    starred: 3193,
                    forked: 180
                }
            },
            {
                _links: {
                    self: {
                        href: "/pgte/nock"
                    },
                    author: {
                        href: "/pgte",
                        title: "Pedro Teixeira"
                    }
                },
                title: "pgte / nock",
                description: "HTTP mocking and expectations library",
                stats: {
                    watched: 22,
                    starred: 803,
                    forked: 77
                }
            }
        ]
    }
};

function clone(data) {
    return JSON.parse(JSON.stringify(data));
}

function dump(obj) {
    console.log(JSON.stringify(obj, null, "  "));
}

describe('halson', function() {
    describe('metadata', function() {
        it('bower.json vs. package.json', function() {
            assert.equal(nodePkg.name, bowerPkg.name);
            assert.equal(nodePkg.version, bowerPkg.version);
            assert.equal(nodePkg.description, bowerPkg.description);
            assert.equal(nodePkg.license, bowerPkg.license);
            assert.equal(nodePkg.main, bowerPkg.main);
        });
    });

    describe('factory', function() {
        it('create without data', function() {
            var res = halson();
            var expected = {};
            expect(res.className).to.be.a('string');
            expect(res.className).to.be.equal(halson.Resource.prototype.className);
            assert.deepEqual(res, expected);
        });

        it('create with object', function() {
            var res = halson(clone(example));
            var expected = clone(example);
            assert.deepEqual(res, expected);
        });

        it('ignore prototype of data', function() {
            function X() {
                this.dolor = 'sit';
            }
            X.prototype.lorem = 'ipsum';
            var data = new X();
            var res = halson(data);
            expect(res.lorem).to.be.an('undefined');
            expect(res.dolor).to.be.equal('sit');
        });

        it('create with serialized object', function() {
            var res = halson(JSON.stringify(clone(example)));
            var expected = clone(example);
            assert.deepEqual(res, expected);
        });

        it('prevent double conversion', function() {
            var data = { title: "Untitled"};
            var res1 = halson(data);
            var res2 = halson(res1);
            expect(res1).to.be.equal(res2);
        });
    });

    describe('listLinkRels()', function() {
        it('return empty list', function() {
            var res = halson().listLinkRels();
            var expected = [];
            assert.deepEqual(res, expected);
        });

        it('return existing rels', function() {
            var res = halson(clone(example)).listLinkRels();
            var expected = ['self', 'avatar', 'related'];
            assert.deepEqual(res, expected);
        });
    });

    describe('listEmbedRels()', function() {
        it('return empty list', function() {
            var res = halson().listEmbedRels();
            var expected = [];
            assert.deepEqual(res, expected);
        });

        it('return existing rels', function() {
            var res = halson(clone(example)).listEmbedRels();
            var expected = ['starred'];
            assert.deepEqual(res, expected);
        });
    });

    describe('getLinks()', function() {
        it('return empty list', function() {
            var expected = [];

            var res = halson().getLinks('self');
            assert.deepEqual(res, expected);

            res = halson(clone(example)).getLinks('selfX');
            assert.deepEqual(res, expected);
        });

        it('return links by rel', function() {
            var res = halson(clone(example)).getLinks('avatar');
            assert.deepEqual(res, [example._links.avatar]);

            res = halson(clone(example)).getLinks('related');
            assert.deepEqual(res, example._links.related);
        });

        it('use filterCallback', function() {
            var expected = [{
                href: 'https://twitter.com/hajovsky',
                name: 'twitter'
            }];

            var res = halson(clone(example));
            var links = res.getLinks('related', function(item) {
                return item.name === 'twitter';
            });
            assert.deepEqual(links, expected);

            links = res.getLinks('related', function(item) {
                return Boolean(item.href);
            });
            assert.deepEqual(links, example._links.related);
        });

        it('use begin/end', function() {
            var res = halson(clone(example));
            var links = res.getLinks('related', null, 0);
            assert.deepEqual(links, example._links.related);

            links = res.getLinks('related', null, 1);
            assert.deepEqual(links, example._links.related.slice(1));

            links = res.getLinks('related', null, 0, 1);
            assert.deepEqual(links, example._links.related.slice(0, 1));
        });
    });

    describe('getLink()', function() {
        it('return undefined', function() {
            var res = halson().getLink('selfX');
            expect(res).to.be.an('undefined');

            res = halson(clone(example)).getLink('selfX');
            expect(res).to.be.an('undefined');
        });

        it('return default value', function(){
            var def = {title: "Untitled"};
            var res = halson().getLink('selfX', def);
            assert.deepEqual(res, def);
        });

        it('return link by rel', function() {
            var res = halson(clone(example));

            assert.deepEqual(res.getLink('avatar'), example._links.avatar);
            assert.deepEqual(res.getLink('related'), example._links.related[0]);
        });

        it('use filterCallback', function() {
            var res = halson(clone(example));

            assert.deepEqual(res.getLink('avatar', function(item) {
                return true;
            }), example._links.avatar);

            assert.deepEqual(res.getLink('related', function(item) {
                return item.name === 'twitter';
            }), example._links.related[1]);

            assert.deepEqual(res.getLink('related', function(item) {
                return true;
            }), example._links.related[0]);
        });

        it('use filterCallback w/ default value', function(){
            var res = halson(clone(example));
            var def = {title: "Untitled"};
            assert.deepEqual(res.getLink('related', function(item) {
                return item.name === 'not exists';
            }, def), def);
        });
    });

    describe('getEmbeds()', function() {
        it('return empty list', function() {
            var res = halson();
            assert.deepEqual(res.getEmbeds('asdf'), []);

            res = halson(clone(example));
            assert.deepEqual(res.getEmbeds('asdf'), []);
        });

        it('return embedded as HALSON Resources', function() {
            var res = halson(clone(example));
            var expected = example._embedded.starred.map(function(item) {
                return halson(item);
            });

            var ret = res.getEmbeds('starred');
            assert.deepEqual(ret, expected);
            expect(ret[0].className).to.be.equal(halson.Resource.prototype.className);
        });

        it('user filterCallback', function() {
            var res = halson(clone(example));
            var expected = [halson(example._embedded.starred[1])];
            var embeds = res.getEmbeds('starred', function(item) {
                return item._links.self.href === '/koajs/koa';
            });
            assert.deepEqual(embeds, expected);

            expected = example._embedded.starred.map(function(item) {
                return halson(item);
            });
            embeds = res.getEmbeds('starred', function(item) {
                return true;
            });
            assert.deepEqual(embeds, expected);

            embeds = res.getEmbeds('starred', function(item) {
                return false;
            });
            assert.deepEqual(embeds, []);
        });

        it('use begin/end', function() {
            var res = halson(clone(example));
            var expected = example._embedded.starred.map(function(item) {
                return halson(item);
            });

            var embeds = res.getEmbeds('starred', null, 0);
            assert.deepEqual(embeds, expected);

            embeds = res.getEmbeds('starred', null, 1);
            assert.deepEqual(embeds, expected.slice(1));

            embeds = res.getEmbeds('starred', null, 0, 1);
            assert.deepEqual(embeds, expected.slice(0, 1));
        });
    });

    describe('getEmbed()', function() {
        it('return undefined', function() {
            var res = halson();
            assert.strictEqual(res.getEmbed('item'), undefined);
        });

        it('return default value', function() {
            var res = halson();
            var def = {title: "Untitled"};
            assert.deepEqual(res.getEmbed('item', def), def);
        });

        it('return embed by rel', function() {
            var res = halson(clone(example));
            var expected = halson(example._embedded.starred[0]);
            assert.deepEqual(res.getEmbed('starred'), expected);
        });

        it('use filterCallback', function() {
            var res = halson(clone(example));
            var expected = halson(example._embedded.starred[1]);
            assert.deepEqual(res.getEmbed('starred', function(item) {
                return item.title === 'koajs / koa';
            }), expected);
        });

        it('use filterCallback w/ default value', function() {
            var res = halson(clone(example));
            var def = {title: "Untitled"};
            assert.deepEqual(res.getEmbed('starred', function(item) {
                return item.title === 'not exists';
            }, def), def);
        });
    });

    describe('addLink()', function() {
        it('return this', function() {
            var res = halson();
            var ret = res.addLink('self', '/hajovsky');
            expect(ret).to.be.equal(res);
        });

        it('add first link (Object)', function() {
            var res = halson();
            var link = {href: "/hajovsky"};

            res.addLink('self', link);
            assert.deepEqual(res.getLink('self'), link);
        });

        it('add first link (string)', function() {
            var res = halson();
            var link = {href: "/hajovsky"};

            res.addLink('self', link.href);
            assert.deepEqual(res.getLink('self'), link);
        });

        it('add second link', function() {
            var res = halson()
                .addLink('related', example._links.related[0])
                .addLink('related', example._links.related[1]);

            assert.deepEqual(res.getLinks('related'), example._links.related);
        });
    });

    describe('addEmbed()', function() {
        it('return this', function(){
            var res = halson();
            expect(res).to.be.equal(res.addEmbed('starred', {title: 'Untitled'}));
        });

        it('add first embed', function() {
            var res = halson();
            var embed = {title: "Untitled"};
            var expected = {
                _embedded: {
                    item: {
                        title: "Untitled"
                    }
                }
            };

            res.addEmbed('item', embed);
            assert.deepEqual(res, expected);
        });

        it('add first embed array', function() {
            var res = halson();
            var embed = [{title: "Untitled"}];
            var expected = {
                _embedded: {
                    item: [{
                        title: "Untitled"
                    }]
                }
            };

            res.addEmbed('item', embed);
            assert.deepEqual(res, expected);
        });

        it('add second embed', function() {
            var res = halson();
            var embed1 = {title: "Untitled1"};
            var embed2 = [{title: "Untitled2"}];
            var expected = {
                _embedded: {
                    item: [{
                        title: "Untitled1"
                    }, {
                        title: "Untitled2"
                    }]
                }
            };

            res.addEmbed('item', embed1);
            res.addEmbed('item', embed2);
            assert.deepEqual(res, expected);
        });

        it('add first embed array', function() {
            var res = halson();
            var embed = [{title: "Untitled1"}, {title: "Untitled2"}];
            var expected = {
                _embedded: {
                    item: [
                        {
                            title: "Untitled1"
                        },
                        {
                            title: "Untitled2"
                        }
                    ]
                }
            };

            res.addEmbed('item', embed);
            assert.deepEqual(res, expected);
        });

        it('add second embed array', function() {
            var res = halson();
            var embed1 = [{title: "Untitled1"}, {title: "Untitled2"}];
            var embed2 = [{title: "Untitled3"}, {title: "Untitled4"}];
            var expected = {
                _embedded: {
                    item: [
                        {
                            title: "Untitled1"
                        },
                        {
                            title: "Untitled2"
                        },
                        {
                            title: "Untitled3"
                        },
                        {
                            title: "Untitled4"
                        }
                    ]
                }
            };

            res.addEmbed('item', embed1);
            res.addEmbed('item', embed2);
            assert.deepEqual(res, expected);
        });

        it('add first embed as array second as object', function() {
            var res = halson();
            var embed1 = [{title: "Untitled1"}, {title: "Untitled2"}];
            var embed2 = {title: "Untitled3"};
            var expected = {
                _embedded: {
                    item: [
                        {
                            title: "Untitled1"
                        },
                        {
                            title: "Untitled2"
                        },
                        {
                            title: "Untitled3"
                        }
                    ]
                }
            };

            res.addEmbed('item', embed1);
            res.addEmbed('item', embed2);
            assert.deepEqual(res, expected);
        });

    });

    describe('insertEmbed()', function() {
        it('return this', function(){
            var res = halson();
            expect(res).to.be.equal(res.addEmbed('starred', {title: 'Untitled'}));
        });

        it('add first embed', function() {
            var res = halson();
            var embed = {title: "Untitled"};
            var expected = {
                _embedded: {
                    item: {
                        title: "Untitled"
                    }
                }
            };

            res.insertEmbed('item', -1, embed);
            assert.deepEqual(res, expected);
        });

        it('add second embed before first embed', function() {
            var res = halson();
            var embed1 = {title: "Untitled1"};
            var embed2 = {title: "Untitled2"};
            var expected = {
                _embedded: {
                    item: [{
                        title: "Untitled2"
                    }, {
                        title: "Untitled1"
                    }]
                }
            };

            res.insertEmbed('item', -1, embed1);
            res.insertEmbed('item', 0, embed2);
            assert.deepEqual(res, expected);
        });

        it('add third embed before second', function() {
            var res = halson();
            var embed1 = {title: "Untitled1"};
            var embed2 = {title: "Untitled2"};
            var embed3 = {title: "Untitled3"};
            var expected = {
                _embedded: {
                    item: [{
                        title: "Untitled1"
                    },{
                        title: "Untitled3"
                    },{
                        title: "Untitled2"
                    }]
                }
            };

            res.insertEmbed('item', -1, embed1);
            res.insertEmbed('item', -1, embed2);
            res.insertEmbed('item', 1, embed3);
            assert.deepEqual(res, expected);
        });

        it('add third embed (as an array) before second', function() {
            var res = halson();
            var embed1 = {title: "Untitled1"};
            var embed2 = {title: "Untitled2"};
            var embed3 = [
                {title: "Untitled3a"},
                {title: "Untitled3b"},
            ];
            var expected = {
                _embedded: {
                    item: [{
                        title: "Untitled1"
                    },{
                        title: "Untitled3a"
                    },{
                        title: "Untitled3b"
                    },{
                        title: "Untitled2"
                    }]
                }
            };

            res.insertEmbed('item', -1, embed1);
            res.insertEmbed('item', -1, embed2);
            res.insertEmbed('item', 1, embed3);
            assert.deepEqual(res, expected);
        });
    });

    describe('removeLinks()', function() {
        it('remove all links by rel', function() {
            var res = halson(clone(example));
            var expected = clone(example._links);
            delete(expected.related);
            res.removeLinks('related');
            assert.deepEqual(res._links, expected);
        });

        it('ignore missing links', function() {
            var res = halson(clone(example));
            var expected = clone(example._links);
            res.removeLinks('relatedX');
            assert.deepEqual(res._links, expected);
        });

        it('use filterCallback', function() {
            var res = halson(clone(example));
            res.removeLinks('related', function(item) {
                return item.name === 'twitter';
            });
            var expected = clone(example._links);
            expected.related = [expected.related[0]];
            assert.deepEqual(res._links, expected);
        });
    });

    describe('removeEmbeds()', function() {
        it('remove all embeds by rel', function() {
            var res = halson(clone(example));
            res.removeEmbeds('starred');
            assert.deepEqual(res._embedded, {});
            expect(res._embedded.starred).to.be.an('undefined');
        });

        it('ignore missing embeds', function() {
            var expected = clone(example)._embedded;
            var res = halson(clone(example));
            res.removeEmbeds('starredX');
            assert.deepEqual(res._embedded, expected);
        });

        it('use filterCallback', function() {
            var res = halson(clone(example));
            res.removeEmbeds('starred', function(item){
                return item.title === 'koajs / koa';
            });
            var embeds = res.getEmbeds('starred');

            var expected = halson(clone(example)).getEmbeds('starred');
            expected = [expected[0], expected[2]];

            assert.deepEqual(embeds, expected);
        });
    });
});


text:
package com.linecorp.armeria.common.stream;

import static java.util.Objects.requireNonNull;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

/**
 * A {@link StreamMessage} that filters objects as they are published. The filtering
 * will happen from an I/O thread, meaning the order of the filtering will match the
 * order that the {@code delegate} processes the objects in.
 */
public abstract class FilteredStreamMessage<T, U> implements StreamMessage<U> {

    private final StreamMessage<T> delegate;

    /**
     * Creates a new {@link FilteredStreamMessage} that filters objects published by {@code delegate}
     * before passing to a subscriber.
     */
    protected FilteredStreamMessage(StreamMessage<T> delegate) {
        requireNonNull(delegate, "delegate");
        this.delegate = delegate;
    }

    /**
     * The filter to apply to published objects. The result of the filter is passed on
     * to the delegate subscriber.
     */
    protected abstract U filter(T obj);

    /**
     * A callback executed just before calling {@link Subscriber#onSubscribe(Subscription)} on
     * {@code subscriber}. Override this method to execute any initialization logic that may be needed.
     */
    protected void beforeSubscribe(Subscriber<? super U> subscriber, Subscription subscription) {}

    /**
     * A callback executed just before calling {@link Subscriber#onComplete()} on {@code subscriber}.
     * Override this method to execute any cleanup logic that may be needed before completing the
     * subscription.
     */
    protected void beforeComplete(Subscriber<? super U> subscriber) {}

    /**
     * A callback executed just before calling {@link Subscriber#onError(Throwable)} on {@code subscriber}.
     * Override this method to execute any cleanup logic that may be needed before failing the
     * subscription.
     */
    protected void beforeError(Subscriber<? super U> subscriber, Throwable cause) {}

    @Override
    public boolean isOpen() {
        return delegate.isOpen();
    }

    @Override
    public boolean isEmpty() {
        return delegate.isEmpty();
    }

    @Override
    public CompletableFuture<Void> closeFuture() {
        return delegate.closeFuture();
    }

    @Override
    public void subscribe(Subscriber<? super U> subscriber) {
        requireNonNull(subscriber, "subscriber");
        delegate.subscribe(new FilteringSubscriber(subscriber));
    }

    @Override
    public void subscribe(Subscriber<? super U> subscriber, Executor executor) {
        requireNonNull(subscriber, "subscriber");
        delegate.subscribe(new FilteringSubscriber(subscriber), executor);
    }

    @Override
    public void abort() {
        delegate.abort();
    }

    private final class FilteringSubscriber implements Subscriber<T> {

        private final Subscriber<? super U> delegate;

        FilteringSubscriber(Subscriber<? super U> delegate) {
            requireNonNull(delegate, "delegate");
            this.delegate = delegate;
        }

        @Override
        public void onSubscribe(Subscription s) {
            beforeSubscribe(delegate, s);
            delegate.onSubscribe(s);
        }

        @Override
        public void onNext(T t) {
            delegate.onNext(filter(t));
        }

        @Override
        public void onError(Throwable t) {
            beforeError(delegate, t);
            delegate.onError(t);
        }

        @Override
        public void onComplete() {
            beforeComplete(delegate);
            delegate.onComplete();
        }
    }
}


text:
// Generated by CoffeeScript 1.7.1

(function() {
  var Constants, Glass, Glassscript, Javascript, Utility, exports, _instance, _ref,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  Glass = require('glass-script');

  Constants = require('goatee/Core/Constants').Constants;

  Utility = require('goatee/Core/Utility').Utility;

  Javascript = require('goatee/Action/Expression/Javascript').Javascript;

  exports = (_ref = typeof module !== "undefined" && module !== null ? module.exports : void 0) != null ? _ref : this;

  /*
  Glassscript

  @class
  @namespace goatee.Action.Expression
   */

  exports.Glassscript = Glassscript = (function(_super) {
    var _expressionCache;

    __extends(Glassscript, _super);

    function Glassscript() {
      return Glassscript.__super__.constructor.apply(this, arguments);
    }

    _expressionCache = {};

    Glassscript.prototype.evaluateExpression = function(expression) {
      var js;
      ((js = _expressionCache[expression]) != null) || (js = _expressionCache[expression] = Glass.parse(expression));
      return Glassscript.__super__.evaluateExpression.call(this, js);
    };

    return Glassscript;

  })(Javascript);

  _instance = Glassscript.instance = null;

  Glassscript.get = function() {
    return _instance != null ? _instance : (_instance = new Glassscript);
  };

}).call(this);

//# sourceMappingURL=Glassscript.map