text:
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Regalo.Testing;

namespace Regalo.Core.Tests.Unit
{
    [TestFixture]
    public class CommandProcessorTests
    {
        private ObjectCommandHandler _objectCommandHandler;
        private CommandHandlerA _commandHandlerA;
        private CommandHandlerB _commandHandlerB;

        [SetUp]
        public void SetUp()
        {
            _objectCommandHandler = new ObjectCommandHandler();
            _commandHandlerA = new CommandHandlerA();
            _commandHandlerB = new CommandHandlerB();
            Resolver.SetResolvers(type => null, LocateAllCommandHandlers);
        }

        private IEnumerable<object> LocateAllCommandHandlers(Type type)
        {
            return new object[] { _objectCommandHandler, _commandHandlerA, _commandHandlerB }
                .Where(x => type.IsAssignableFrom(x.GetType()));
        }

        [TearDown]
        public void TearDown()
        {
            Resolver.ClearResolvers();
        }

        [Test]
        public void GivenAMessage_WhenAskedToProcess_ShouldTryToFindHandlersForMessageTypeHierarchy()
        {
            var expected = new[]
            {
                typeof(ICommandHandler<object>),
                typeof(ICommandHandler<SimpleCommandBase>),
                typeof(ICommandHandler<SimpleCommand>),
            };

            var result = new List<Type>();
            Resolver.ClearResolvers();
            Resolver.SetResolvers(
                type => null,
                type =>
                {
                    result.Add(type);
                    return LocateAllCommandHandlers(type);
                });

            var processor = new CommandProcessor(new NullLogger());

            processor.Process(new SimpleCommand());

            CollectionAssert.AreEqual(expected, result);
        }

        [Test]
        public void GivenAMessage_WhenAskedToProcess_ShouldInvokeCommandHandlersInCorrectSequence()
        {
            var expected = new[]
            {
                typeof(object),
                typeof(SimpleCommandBase),
                typeof(SimpleCommand),
            };

            var processor = new CommandProcessor(new NullLogger());

            processor.Process(new SimpleCommand());

            _objectCommandHandler.Messages.ToList().ForEach(Console.WriteLine);

            CollectionAssert.AreEqual(expected, _objectCommandHandler.Messages);
        }

        [Test]
        public void GivenAMessageHandledMultipleHandlers_WhenAskedToProcess_ShouldInvokeAllCommandHandlersInCorrectSequence()
        {
            var processor = new CommandProcessor(new NullLogger());

            processor.Process(new CommandHandledByMultipleHandlers());

            CollectionAssert.AreEqual(new [] { typeof(object) }, _objectCommandHandler.Messages);
            CollectionAssert.AreEqual(new [] { typeof(CommandHandledByMultipleHandlers) }, _commandHandlerA.Messages);
            CollectionAssert.AreEqual(new [] { typeof(CommandHandledByMultipleHandlers) }, _commandHandlerB.Messages);
        }
    }

    public class CommandHandledByMultipleHandlers
    {
    }

    public class CommandHandlerA : ICommandHandler<CommandHandledByMultipleHandlers>
    {
        public readonly IList<Type> Messages = new List<Type>();

        public void Handle(CommandHandledByMultipleHandlers command)
        {
            Messages.Add(typeof(CommandHandledByMultipleHandlers));
        }
    }

    public class CommandHandlerB : ICommandHandler<CommandHandledByMultipleHandlers>
    {
        public readonly IList<Type> Messages = new List<Type>();

        public void Handle(CommandHandledByMultipleHandlers command)
        {
            Messages.Add(typeof(CommandHandledByMultipleHandlers));
        }
    }

    public class SimpleCommand : SimpleCommandBase
    {
    }

    public class SimpleCommandBase // Remember this inherits from object...
    {
    }

    public class ObjectCommandHandler
        : ICommandHandler<object>,
        ICommandHandler<SimpleCommandBase>,
        ICommandHandler<SimpleCommand>
    {
        public readonly IList<Type> Messages = new List<Type>();

        public void Handle(object command)
        {
            Messages.Add(typeof(object));
        }

        void ICommandHandler<SimpleCommandBase>.Handle(SimpleCommandBase command)
        {
            Messages.Add(typeof(SimpleCommandBase));
        }

        public void Handle(SimpleCommand command)
        {
            Messages.Add(typeof(SimpleCommand));
        }
    }
}


text:
<?php

namespace Magento\Sales\Test\Unit\Model;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory as HistoryCollectionFactory;
use Magento\Sales\Model\ResourceModel\Order\Item;

/**
 * Test class for \Magento\Sales\Model\Order
 */
class OrderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $paymentCollectionFactoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $orderItemCollectionFactoryMock;

    /**
     * @var \Magento\Sales\Model\Order
     */
    protected $order;

    /**
     * @var \Magento\Framework\Event\Manager | \PHPUnit_Framework_MockObject_MockObject
     */
    protected $eventManager;

    /**
     * @var string
     */
    protected $incrementId;

    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\Item | \PHPUnit_Framework_MockObject_MockObject
     */
    protected $item;

    /**
     * @var HistoryCollectionFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $historyCollectionFactoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject | \Magento\Framework\Pricing\PriceCurrencyInterface
     */
    protected $priceCurrency;

    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $salesOrderCollectionFactoryMock;

    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\Collection|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $salesOrderCollectionMock;

    /**
     * @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private $productRepository;

    protected function setUp()
    {
        $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->paymentCollectionFactoryMock = $this->getMock(
            'Magento\Sales\Model\ResourceModel\Order\Payment\CollectionFactory',
            ['create'],
            [],
            '',
            false
        );
        $this->orderItemCollectionFactoryMock = $this->getMock(
            'Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory',
            ['create'],
            [],
            '',
            false
        );
        $this->historyCollectionFactoryMock = $this->getMock(
            'Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory',
            ['create'],
            [],
            '',
            false
        );
        $this->salesOrderCollectionFactoryMock = $this->getMock(
            'Magento\Sales\Model\ResourceModel\Order\CollectionFactory',
            ['create'],
            [],
            '',
            false
        );
        $this->item = $this->getMock(
            'Magento\Sales\Model\ResourceModel\Order\Item',
            ['isDeleted', 'getQtyToInvoice', 'getParentItemId', 'getQuoteItemId', 'getLockedDoInvoice'],
            [],
            '',
            false
        );
        $this->item = $this->getMockBuilder(Item::class)
            ->disableOriginalConstructor()
            ->setMethods([
                'isDeleted',
                'getQtyToInvoice',
                'getParentItemId',
                'getQuoteItemId',
                'getLockedDoInvoice',
                'getProductId'
            ])
            ->getMock();
        $this->salesOrderCollectionMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Collection')
            ->disableOriginalConstructor()
            ->setMethods(['addFieldToFilter', 'load', 'getFirstItem'])
            ->getMock();
        $collection = $this->getMock('Magento\Sales\Model\ResourceModel\Order\Item\Collection', [], [], '', false);
        $collection->expects($this->any())
            ->method('setOrderFilter')
            ->willReturnSelf();
        $collection->expects($this->any())
            ->method('getItems')
            ->willReturn([$this->item]);
        $collection->expects(self::any())
            ->method('getIterator')
            ->willReturn(new \ArrayIterator([$this->item]));
        $this->orderItemCollectionFactoryMock->expects($this->any())
            ->method('create')
            ->willReturn($collection);

        $this->priceCurrency = $this->getMockForAbstractClass(
            'Magento\Framework\Pricing\PriceCurrencyInterface',
            [],
            '',
            false,
            false,
            true,
            ['round']
        );

        $this->productRepository = $this->getMockBuilder(ProductRepositoryInterface::class)
            ->getMockForAbstractClass();

        $this->incrementId = '#00000001';
        $this->eventManager = $this->getMock('Magento\Framework\Event\Manager', [], [], '', false);
        $context = $this->getMock('Magento\Framework\Model\Context', ['getEventDispatcher'], [], '', false);
        $context->expects($this->any())
            ->method('getEventDispatcher')
            ->willReturn($this->eventManager);

        $this->order = $helper->getObject(
            'Magento\Sales\Model\Order',
            [
                'paymentCollectionFactory' => $this->paymentCollectionFactoryMock,
                'orderItemCollectionFactory' => $this->orderItemCollectionFactoryMock,
                'data' => ['increment_id' => $this->incrementId],
                'context' => $context,
                'historyCollectionFactory' => $this->historyCollectionFactoryMock,
                'salesOrderCollectionFactory' => $this->salesOrderCollectionFactoryMock,
                'priceCurrency' => $this->priceCurrency,
                'productRepository' => $this->productRepository
            ]
        );
    }

    public function testGetItemById()
    {
        $realOrderItemId = 1;
        $fakeOrderItemId = 2;

        $orderItem = $this->getMock(
            'Magento\Sales\Model\Order\Item',
            [],
            [],
            '',
            false
        );

        $this->order->setData(
            \Magento\Sales\Api\Data\OrderInterface::ITEMS,
            [
                $realOrderItemId => $orderItem
            ]
        );

        $this->assertEquals($orderItem, $this->order->getItemById($realOrderItemId));
        $this->assertEquals(null, $this->order->getItemById($fakeOrderItemId));
    }

    /**
     * @param int|null $gettingQuoteItemId
     * @param int|null $quoteItemId
     * @param string|null $result
     *
     * @dataProvider dataProviderGetItemByQuoteItemId
     */
    public function testGetItemByQuoteItemId($gettingQuoteItemId, $quoteItemId, $result)
    {
        $this->item->expects($this->any())
            ->method('getQuoteItemId')
            ->willReturn($gettingQuoteItemId);

        if ($result !== null) {
            $result = $this->item;
        }

        $this->assertEquals($result, $this->order->getItemByQuoteItemId($quoteItemId));
    }

    /**
     * @return array
     */
    public function dataProviderGetItemByQuoteItemId()
    {
        return [
            [10, 10, 'replace-me'],
            [10, 88, null],
            [88, 10, null],
        ];
    }

    /**
     * @param bool $isDeleted
     * @param int|null $parentItemId
     * @param array $result
     *
     * @dataProvider dataProviderGetAllVisibleItems
     */
    public function testGetAllVisibleItems($isDeleted, $parentItemId, array $result)
    {
        $this->item->expects($this->once())
            ->method('isDeleted')
            ->willReturn($isDeleted);

        $this->item->expects($this->any())
            ->method('getParentItemId')
            ->willReturn($parentItemId);

        if (!empty($result)) {
            $result = [$this->item];
        }

        $this->assertEquals($result, $this->order->getAllVisibleItems());
    }

    /**
     * @return array
     */
    public function dataProviderGetAllVisibleItems()
    {
        return [
            [false, null, ['replace-me']],
            [true, null, []],
            [true, 10, []],
            [false, 10, []],
            [true, null, []],
        ];
    }

    public function testCanCancelCanUnhold()
    {
        $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, true);
        $this->order->setState(\Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW);
        $this->assertFalse($this->order->canCancel());
    }

    public function testCanCancelIsPaymentReview()
    {
        $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, false);
        $this->order->setState(\Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW);
        $this->assertFalse($this->order->canCancel());
    }

    public function testCanInvoice()
    {
        $this->item->expects($this->any())
            ->method('getQtyToInvoice')
            ->willReturn(42);
        $this->item->expects($this->any())
            ->method('getLockedDoInvoice')
            ->willReturn(false);

        $this->assertTrue($this->order->canInvoice());
    }

    /**
     * @param string $status
     *
     * @dataProvider notInvoicingStatesProvider
     */
    public function testCanNotInvoiceInSomeStates($status)
    {
        $this->item->expects($this->any())
            ->method('getQtyToInvoice')
            ->willReturn(42);
        $this->item->expects($this->any())
            ->method('getLockedDoInvoice')
            ->willReturn(false);
        $this->order->setData('state', $status);
        $this->assertFalse($this->order->canInvoice());
    }

    public function testCanNotInvoiceWhenActionInvoiceFlagIsFalse()
    {
        $this->item->expects($this->any())
            ->method('getQtyToInvoice')
            ->willReturn(42);
        $this->item->expects($this->any())
            ->method('getLockedDoInvoice')
            ->willReturn(false);
        $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_INVOICE, false);
        $this->assertFalse($this->order->canInvoice());
    }

    public function testCanNotInvoiceWhenLockedInvoice()
    {
        $this->item->expects($this->any())
            ->method('getQtyToInvoice')
            ->willReturn(42);
        $this->item->expects($this->any())
            ->method('getLockedDoInvoice')
            ->willReturn(true);
        $this->assertFalse($this->order->canInvoice());
    }

    public function testCanNotInvoiceWhenDidNotHaveQtyToInvoice()
    {
        $this->item->expects($this->any())
            ->method('getQtyToInvoice')
            ->willReturn(0);
        $this->item->expects($this->any())
            ->method('getLockedDoInvoice')
            ->willReturn(false);
        $this->assertFalse($this->order->canInvoice());
    }

    public function testCanCreditMemo()
    {
        $totalPaid = 10;
        $this->order->setTotalPaid($totalPaid);
        $this->priceCurrency->expects($this->once())->method('round')->with($totalPaid)->willReturnArgument(0);
        $this->assertTrue($this->order->canCreditmemo());
    }

    public function testCanNotCreditMemoWithTotalNull()
    {
        $totalPaid = 0;
        $this->order->setTotalPaid($totalPaid);
        $this->priceCurrency->expects($this->once())->method('round')->with($totalPaid)->willReturnArgument(0);
        $this->assertFalse($this->order->canCreditmemo());
    }

    /**
     * @param string $state
     *
     * @dataProvider canNotCreditMemoStatesProvider
     */
    public function testCanNotCreditMemoWithSomeStates($state)
    {
        $this->order->setData('state', $state);
        $this->assertFalse($this->order->canCreditmemo());
    }

    public function testCanNotCreditMemoWithForced()
    {
        $this->order->setData('forced_can_creditmemo', true);
        $this->assertTrue($this->order->canCreditmemo());
    }

    public function testCanEditIfHasInvoices()
    {
        $invoiceCollection = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Invoice\Collection')
            ->disableOriginalConstructor()
            ->setMethods(['count'])
            ->getMock();

        $invoiceCollection->expects($this->once())
            ->method('count')
            ->willReturn(2);

        $this->order->setInvoiceCollection($invoiceCollection);
        $this->order->setState(\Magento\Sales\Model\Order::STATE_PROCESSING);

        $this->assertFalse($this->order->canEdit());
    }

    /**
     * @covers \Magento\Sales\Model\Order::canReorder
     */
    public function testCanReorder()
    {
        $productId = 1;

        $this->order->setState(Order::STATE_PROCESSING);
        $this->order->setActionFlag(Order::ACTION_FLAG_REORDER, true);

        $this->item->expects(static::once())
            ->method('getProductId')
            ->willReturn($productId);

        $product = $this->getMockBuilder(ProductInterface::class)
            ->setMethods(['isSalable'])
            ->getMockForAbstractClass();
        $product->expects(static::once())
            ->method('isSalable')
            ->willReturn(true);

        $this->productRepository->expects(static::once())
            ->method('getById')
            ->with($productId, false)
            ->willReturn($product);

        $this->assertTrue($this->order->canReorder());
    }

    /**
     * @covers \Magento\Sales\Model\Order::canReorder
     */
    public function testCanReorderIsPaymentReview()
    {
        $this->order->setState(Order::STATE_PAYMENT_REVIEW);

        $this->assertFalse($this->order->canReorder());
    }

    /**
     * @covers \Magento\Sales\Model\Order::canReorder
     */
    public function testCanReorderFlagReorderFalse()
    {
        $this->order->setState(Order::STATE_PROCESSING);
        $this->order->setActionFlag(Order::ACTION_FLAG_REORDER, false);

        $this->assertFalse($this->order->canReorder());
    }

    /**
     * @covers \Magento\Sales\Model\Order::canReorder
     */
    public function testCanReorderProductNotExists()
    {
        $productId = 1;

        $this->order->setState(Order::STATE_PROCESSING);
        $this->order->setActionFlag(Order::ACTION_FLAG_REORDER, true);

        $this->item->expects(static::once())
            ->method('getProductId')
            ->willReturn($productId);

        $product = $this->getMockBuilder(ProductInterface::class)
            ->setMethods(['isSalable'])
            ->getMockForAbstractClass();
        $product->expects(static::never())
            ->method('isSalable');

        $this->productRepository->expects(static::once())
            ->method('getById')
            ->with($productId, false)
            ->willThrowException(new NoSuchEntityException(__('Requested product doesn\'t exist')));

        $this->assertFalse($this->order->canReorder());
    }

    /**
     * @covers \Magento\Sales\Model\Order::canReorder
     */
    public function testCanReorderProductNotSalable()
    {
        $productId = 1;

        $this->order->setState(Order::STATE_PROCESSING);
        $this->order->setActionFlag(Order::ACTION_FLAG_REORDER, true);

        $this->item->expects(static::once())
            ->method('getProductId')
            ->willReturn($productId);

        $product = $this->getMockBuilder(ProductInterface::class)
            ->setMethods(['isSalable'])
            ->getMockForAbstractClass();
        $product->expects(static::once())
            ->method('isSalable')
            ->willReturn(false);

        $this->productRepository->expects(static::once())
            ->method('getById')
            ->with($productId, false)
            ->willReturn($product);

        $this->assertFalse($this->order->canReorder());
    }

    public function testCanCancelCanReviewPayment()
    {
        $paymentMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Payment')
            ->disableOriginalConstructor()
            ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo', '__wakeUp'])
            ->getMock();
        $paymentMock->expects($this->any())
            ->method('canReviewPayment')
            ->will($this->returnValue(false));
        $paymentMock->expects($this->any())
            ->method('canFetchTransactionInfo')
            ->will($this->returnValue(true));
        $this->preparePaymentMock($paymentMock);
        $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, false);
        $this->order->setState(\Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW);
        $this->assertFalse($this->order->canCancel());
    }

    public function testCanCancelAllInvoiced()
    {
        $paymentMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Payment')
            ->disableOriginalConstructor()
            ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo', '__wakeUp'])
            ->getMock();
        $paymentMock->expects($this->any())
            ->method('canReviewPayment')
            ->will($this->returnValue(false));
        $paymentMock->expects($this->any())
            ->method('canFetchTransactionInfo')
            ->will($this->returnValue(false));
        $collectionMock = $this->getMock(
            'Magento\Sales\Model\ResourceModel\Order\Item\Collection',
            ['getItems', 'setOrderFilter'],
            [],
            '',
            false
        );
        $this->orderItemCollectionFactoryMock->expects($this->any())
            ->method('create')
            ->will($this->returnValue($collectionMock));
        $collectionMock->expects($this->any())
            ->method('setOrderFilter')
            ->willReturnSelf();
        $this->preparePaymentMock($paymentMock);

        $this->prepareItemMock(0);

        $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, false);
        $this->order->setState(\Magento\Sales\Model\Order::STATE_NEW);

        $this->item->expects($this->any())
            ->method('isDeleted')
            ->willReturn(false);
        $this->item->expects($this->any())
            ->method('getQtyToInvoice')
            ->willReturn(0);

        $this->assertFalse($this->order->canCancel());
    }

    public function testCanCancelState()
    {
        $paymentMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Payment')
            ->disableOriginalConstructor()
            ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo', '__wakeUp'])
            ->getMock();
        $paymentMock->expects($this->any())
            ->method('canReviewPayment')
            ->will($this->returnValue(false));
        $paymentMock->expects($this->any())
            ->method('canFetchTransactionInfo')
            ->will($this->returnValue(false));

        $this->preparePaymentMock($paymentMock);

        $this->prepareItemMock(1);
        $this->order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD, false);
        $this->order->setState(\Magento\Sales\Model\Order::STATE_CANCELED);
        $this->assertFalse($this->order->canCancel());
    }

    /**
     * @param bool $cancelActionFlag
     * @dataProvider dataProviderActionFlag
     */
    public function testCanCancelActionFlag($cancelActionFlag)
    {
        $paymentMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Payment')
            ->disableOriginalConstructor()
            ->setMethods(['isDeleted', 'canReviewPayment', 'canFetchTransactionInfo', '__wakeUp'])
            ->getMock();
        $paymentMock->expects($this->any())
            ->method('canReviewPayment')
            ->will($this->returnValue(false));
        $paymentMock->expects($this->any())
            ->method('canFetchTransactionInfo')
            ->will($this->returnValue(false));

        $this->preparePaymentMock($paymentMock);

        $this->prepareItemMock(1);

        $actionFlags = [
            \Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD => false,
            \Magento\Sales\Model\Order::ACTION_FLAG_CANCEL => $cancelActionFlag,
        ];
        foreach ($actionFlags as $action => $flag) {
            $this->order->setActionFlag($action, $flag);
        }
        $this->order->setData('state', \Magento\Sales\Model\Order::STATE_NEW);

        $this->item->expects($this->any())
            ->method('isDeleted')
            ->willReturn(false);
        $this->item->expects($this->any())
            ->method('getQtyToInvoice')
            ->willReturn(42);

        $this->assertEquals($cancelActionFlag, $this->order->canCancel());
    }

    /**
     * @param array $actionFlags
     * @param string $orderState
     * @dataProvider canVoidPaymentDataProvider
     */
    public function testCanVoidPayment($actionFlags, $orderState)
    {
        $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        /** @var Order $order */
        $order = $helper->getObject('Magento\Sales\Model\Order');
        foreach ($actionFlags as $action => $flag) {
            $order->setActionFlag($action, $flag);
        }
        $order->setData('state', $orderState);
        $payment = $this->_prepareOrderPayment($order);
        $canVoidOrder = true;

        if ($orderState == \Magento\Sales\Model\Order::STATE_CANCELED) {
            $canVoidOrder = false;
        }

        if ($orderState == \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW) {
            $canVoidOrder = false;
        }
        if ($orderState == \Magento\Sales\Model\Order::STATE_HOLDED && (!isset(
                    $actionFlags[\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD]
                ) || $actionFlags[\Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD] !== false)
        ) {
            $canVoidOrder = false;
        }

        $expected = false;
        if ($canVoidOrder) {
            $expected = 'some value';
            $payment->expects(
                $this->any()
            )->method(
                'canVoid'
            )->will(
                $this->returnValue($expected)
            );
        } else {
            $payment->expects($this->never())->method('canVoid');
        }
        $this->assertEquals($expected, $order->canVoidPayment());
    }

    /**
     * @param $paymentMock
     */
    protected function preparePaymentMock($paymentMock)
    {
        $iterator = new \ArrayIterator([$paymentMock]);

        $collectionMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Payment\Collection')
            ->disableOriginalConstructor()
            ->setMethods(['setOrderFilter', 'getIterator'])
            ->getMock();
        $collectionMock->expects($this->any())
            ->method('getIterator')
            ->will($this->returnValue($iterator));
        $collectionMock->expects($this->any())
            ->method('setOrderFilter')
            ->will($this->returnSelf());

        $this->paymentCollectionFactoryMock->expects($this->any())
            ->method('create')
            ->will($this->returnValue($collectionMock));
    }

    /**
     * Prepare payment for the order
     *
     * @param \Magento\Sales\Model\Order|\PHPUnit_Framework_MockObject_MockObject $order
     * @param array $mockedMethods
     * @return \Magento\Sales\Model\Order\Payment|\PHPUnit_Framework_MockObject_MockObject
     */
    protected function _prepareOrderPayment($order, $mockedMethods = [])
    {
        $payment = $this->getMockBuilder('Magento\Sales\Model\Order\Payment')->disableOriginalConstructor()->getMock();
        foreach ($mockedMethods as $method => $value) {
            $payment->expects($this->any())->method($method)->will($this->returnValue($value));
        }
        $payment->expects($this->any())->method('isDeleted')->will($this->returnValue(false));

        $order->setData(\Magento\Sales\Api\Data\OrderInterface::PAYMENT, $payment);

        return $payment;
    }

    /**
     * Get action flags
     *
     */
    protected function _getActionFlagsValues()
    {
        return [
            [],
            [
                \Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD => false,
                \Magento\Sales\Model\Order::ACTION_FLAG_CANCEL => false
            ],
            [
                \Magento\Sales\Model\Order::ACTION_FLAG_UNHOLD => false,
                \Magento\Sales\Model\Order::ACTION_FLAG_CANCEL => true
            ]
        ];
    }

    /**
     * Get order statuses
     *
     * @return array
     */
    protected function _getOrderStatuses()
    {
        return [
            \Magento\Sales\Model\Order::STATE_HOLDED,
            \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW,
            \Magento\Sales\Model\Order::STATE_CANCELED,
            \Magento\Sales\Model\Order::STATE_COMPLETE,
            \Magento\Sales\Model\Order::STATE_CLOSED,
            \Magento\Sales\Model\Order::STATE_PROCESSING
        ];
    }

    /**
     * @param int $qtyInvoiced
     * @return void
     */
    protected function prepareItemMock($qtyInvoiced)
    {
        $itemMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Item')
            ->disableOriginalConstructor()
            ->setMethods(['isDeleted', 'filterByTypes', 'filterByParent', 'getQtyToInvoice', '__wakeUp'])
            ->getMock();

        $itemMock->expects($this->any())
            ->method('getQtyToInvoice')
            ->will($this->returnValue($qtyInvoiced));

        $iterator = new \ArrayIterator([$itemMock]);

        $itemCollectionMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Item\Collection')
            ->disableOriginalConstructor()
            ->setMethods(['setOrderFilter', 'getIterator', 'getItems'])
            ->getMock();
        $itemCollectionMock->expects($this->any())
            ->method('getIterator')
            ->will($this->returnValue($iterator));
        $itemCollectionMock->expects($this->any())
            ->method('setOrderFilter')
            ->will($this->returnSelf());

        $this->orderItemCollectionFactoryMock->expects($this->any())
            ->method('create')
            ->will($this->returnValue($itemCollectionMock));
    }

    public function canVoidPaymentDataProvider()
    {
        $data = [];
        foreach ($this->_getActionFlagsValues() as $actionFlags) {
            foreach ($this->_getOrderStatuses() as $status) {
                $data[] = [$actionFlags, $status];
            }
        }
        return $data;
    }

    public function dataProviderActionFlag()
    {
        return [
            [false],
            [true]
        ];
    }

    /**
     * test method getIncrementId()
     */
    public function testGetIncrementId()
    {
        $this->assertEquals($this->incrementId, $this->order->getIncrementId());
    }

    public function testGetEntityType()
    {
        $this->assertEquals('order', $this->order->getEntityType());
    }

    /**
     * Run test getStatusHistories method
     *
     * @return void
     */
    public function testGetStatusHistories()
    {
        $itemMock = $this->getMockForAbstractClass(
            'Magento\Sales\Api\Data\OrderStatusHistoryInterface',
            [],
            '',
            false,
            true,
            true,
            ['setOrder']
        );
        $dbMock = $this->getMockBuilder('Magento\Framework\Data\Collection\AbstractDb')
            ->setMethods(['setOrder'])
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
        $collectionMock = $this->getMock(
            'Magento\Sales\Model\ResourceModel\Order\Status\History\Collection',
            [
                'setOrderFilter',
                'setOrder',
                'getItems',
                'getIterator',
                'toOptionArray',
                'count',
                'load'
            ],
            [],
            '',
            false
        );

        $collectionItems = [$itemMock];

        $collectionMock->expects($this->once())
            ->method('setOrderFilter')
            ->with($this->order)
            ->willReturnSelf();
        $collectionMock->expects($this->once())
            ->method('setOrder')
            ->with('created_at', 'desc')
            ->willReturn($dbMock);
        $dbMock->expects($this->once())
            ->method('setOrder')
            ->with('entity_id', 'desc')
            ->willReturn($collectionMock);
        $collectionMock->expects($this->once())
            ->method('getItems')
            ->willReturn($collectionItems);

        $this->historyCollectionFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($collectionMock);

        for ($i = 10; --$i;) {
            $this->assertEquals($collectionItems, $this->order->getStatusHistories());
        }
    }

    public function testLoadByIncrementIdAndStoreId()
    {
        $incrementId = '000000001';
        $storeId = '2';
        $this->salesOrderCollectionFactoryMock
            ->expects($this->once())
            ->method('create')
            ->willReturn($this->salesOrderCollectionMock);
        $this->salesOrderCollectionMock->expects($this->any())->method('addFieldToFilter')->willReturnSelf();
        $this->salesOrderCollectionMock->expects($this->once())->method('load')->willReturnSelf();
        $this->salesOrderCollectionMock->expects($this->once())->method('getFirstItem')->willReturn($this->order);
        $this->assertSame($this->order, $this->order->loadByIncrementIdAndStoreId($incrementId, $storeId));
    }

    public function notInvoicingStatesProvider()
    {
        return [
            [\Magento\Sales\Model\Order::STATE_COMPLETE],
            [\Magento\Sales\Model\Order::STATE_CANCELED],
            [\Magento\Sales\Model\Order::STATE_CLOSED]
        ];
    }

    public function canNotCreditMemoStatesProvider()
    {
        return [
            [\Magento\Sales\Model\Order::STATE_HOLDED],
            [\Magento\Sales\Model\Order::STATE_CANCELED],
            [\Magento\Sales\Model\Order::STATE_CLOSED],
            [\Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW]
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
import assert from 'assert';
import translateElement from '../src/overlay';
import {elem} from './index';

suite('Text-semantic argument elements', function() {
  test('without data-l10n-name', function() {
    const element = elem('div')`
      `;
    const translation = {
      value: 'FOO',
      attributes: null
    };

    translateElement(element, translation);
    assert.strictEqual(
      element.innerHTML,
      'FOO'
    );
  });

  test('mismatched types', function() {
    const element = elem('div')`
      <button data-l10n-name="foo"></button>`;
    const translation = {
      value: 'FOO',
      attributes: null
    };

    translateElement(element, translation);
    assert.strictEqual(
      element.innerHTML,
      'FOO'
    );
  });

  test('types and names match', function() {
    const element = elem('div')`
      `;
    const translation = {
      value: 'FOO',
      attributes: null
    };

    translateElement(element, translation);
    assert.strictEqual(
      element.innerHTML,
      'FOO'
    );
  });
});


text:
<?php

namespace Jackweinbender\LaravelJsonapi;

use Illuminate\Database\Eloquent\Model;
use \ReflectionClass;

abstract class JsonApiModelAbstract extends Model implements JsonApiModelInterface
{

  /**
   * The 'type' property for the JSON API response object. According to
   * the spec, all objects need them. You can set this manually, or
   * use the sensible default of a lowercase version of the
   * class name in lowercase
   *
   * @var String
   */
  protected $modelType;
  protected $modelId;
  /**
   * Returns attribute array from parent getAttribute function
   * Child class should override to include cast properties
   *
   * @return Array of attributes
   */
  public function attributes(){

    return $this->getAttributes();

  }

  /**
   * Returns the Model as a resource Object.
   *
   * @return Array
   */
  public function resourceObject(){
    return array(
      'id' => $this->getModelId(),
      'type' => $this->getModelType(),
      'attributes' => $this->attributes(),
    );
  }

  public function getModelId(){

    if(isset($this->modelId)){
      $id = $this->modelId;
      return $this->$id;
    }

    return $this->id;

  }
  /**
   * Returns the a reference ID object for the model
   *
   * @return Array
   */
  public function rid(){
    return array(
      'type' => $this->getModelType(),
      'id' => $this->getModelId(),
    );
  }

  /**
   * Returns an object
   * @return [type] [description]
   */
  public function includedObject(){
    return array(
       $this->getUniqueKey() => $this->resourceObject(),
    );
  }

  /**
   * Generates a unique ID based on the model type and its DB key
   * This allows multiple models to reference the same related
   * obect without duplicating it in the payload.
   *
   * @return String
   */
  public function getUniqueKey(){
    return $this->getmodelType() . $this->getModelId();
  }

  /**
   * Returns the modelType if already set, otherwise sets
   * the proerty and returns it
   *
   * @return String the class name as in lowercase
   */
  public function getModelType(){

    if(isset($this->modelType)){
      return $this->modelType;
    }

    return $this->setModelType();
  }

  /**
   * Sets the modelType property and returns its new value
   *
   * @return String the class name as in lowercase
   */
  protected function setModelType(){

    $this->modelType = $this->getClassName() . 's';

    return $this->modelType;

  }

  /**
   * Gets the class name via ReflectionClass::getShortName
   *
   * @return String the class name as in lowercase
   */
  protected function getClassName(){

    $modelClass = new ReflectionClass($this);

    return strtolower($modelClass->getShortName());
  }

}


text:
package serial.algo.design.scratch;
/**
 * Simple Professor abstraction.
 */
public class Professor {
    private final int professorId;
    private final String professorName;

    /**
     * Initalize new Professor
     *
     * @param professorId The ID for this professor
     * @param professorName The name of this professor
     */
    public Professor(int professorId, String professorName){
        this.professorId = professorId;
        this.professorName = professorName;
    }

    /**
     * Get professorId
     *
     * @return professorId
     */
    public int getProfessorId(){
        return this.professorId;
    }

    /**
     * Get professor's name
     *
     * @return professorName
     */
    public String getProfessorName(){
        return this.professorName;
    }
}


text:
#include <iostream>
#include "Game.h"

Game::Game(const std::string &title, uint32_t width, uint32_t height,
        uint32_t framesPerSecond)
: m_state(GS_RUNNING),
  m_title(title),
  m_width(width),
  m_height(height),
  m_framesPerSecond(framesPerSecond),
  m_timePerFrame(1000 / framesPerSecond), // milliseconds
  m_window(NULL)
{

}

Game::~Game()
{

}

bool Game::Init()
{
    //
    // INITIALIZE SDL
    //
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        std::cerr << "ERROR: Initializing SDL." << '\n';
        return false;
    }

    //
    // GL CONTEXT ATTRIBUTES
    //
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    //
    // CREATING WINDOW
    //
    m_window = SDL_CreateWindow(
        m_title.c_str(),
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        m_width,
        m_height,
        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
    );

    if(m_window == NULL)
    {
        std::cerr << "ERROR: Creating the SDL Window." << '\n';
        return false;
    }

    //
    // CREATING GL CONTEXT
    //
    m_glContext = SDL_GL_CreateContext(m_window);
    SDL_GL_MakeCurrent(m_window, m_glContext);

    //  0 - for immediate updates,
    //  1 - for updates synchronized with the vertical retrace,
    // -1 - for late swap tearing
    SDL_GL_SetSwapInterval(1);

    //
    // GL ORTHOGRAPHIC PROJECTION
    //
    float left = 0;
    float right = m_width;
    float bottom = m_height;
    float top = 0;

    glViewport(0, 0, m_width, m_height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(left, right, bottom, top, -1.0, 1.0);
    glMatrixMode( GL_MODELVIEW );
    glClearColor(0.f, 0.f, 0.f, 1.f);

    //
    // GL TEXTURE
    //
    glEnable(GL_TEXTURE_2D);

    //
    // GL BLEND
    //
    glEnable (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_ALPHA_TEST);

    //
    // INITIALIZE DEVIL AND DEVILU
    //
    ilInit();
    iluInit();
    ilClearColour(0, 0, 0, 0);

    ILenum ilError = ilGetError();
    if(ilError != IL_NO_ERROR)
    {
        printf("Error initializing DevIL! %s\n", iluErrorString(ilError));
        return false;
    }

    OnInit();

    return true;
}

void Game::OnInit()
{
    // override
}

void Game::Render()
{
    // FIXME: (Pavel) Clear color should be a setting
    glClearColor(0.f, 0.f, 0.f, 1.f);
    glClear(GL_COLOR_BUFFER_BIT);

    OnRender();

    SDL_GL_SwapWindow(m_window);
}

void Game::Update()
{
    OnUpdate();
}

bool Game::Run()
{
    if(!Init())
    {
        std::cerr << "ERROR: Initializing the Game." << '\n';
        return false;
    }

    SDL_Event event;

    while(m_state == GS_RUNNING)
    {
        Uint32 start = SDL_GetTicks();

        HandleEvent(event);
        Update();
        Render();

        Uint32 elapsedTime = SDL_GetTicks() - start;
        if(m_timePerFrame > elapsedTime)
        {
            SDL_Delay(m_timePerFrame - elapsedTime);
        }
    }

    Cleanup();
    return true;
}

void Game::HandleEvent(SDL_Event &event)
{
    //
    // EVENTS
    //
    while(SDL_PollEvent(&event))
    {
        switch(event.type)
        {
            case SDL_QUIT:
                Exit();
                break;
            case SDL_KEYDOWN:
                OnKeyDown(event.key);
                break;
            case SDL_KEYUP:
                OnKeyUp(event.key);
                break;
            case SDL_MOUSEMOTION:
                OnMouseMotion(event.motion);
                break;
            case SDL_MOUSEBUTTONDOWN:
                OnMouseButtonDown(event.button);
                break;
            case SDL_MOUSEBUTTONUP:
                OnMouseButtonUp(event.button);
                break;
        }
    }
}

void Game::Cleanup()
{
    OnCleanup();

    SDL_GL_DeleteContext(m_glContext);
    SDL_DestroyWindow(m_window);
    SDL_Quit();
}

void Game::OnCleanup()
{
    // override
}

void Game::OnKeyDown(SDL_KeyboardEvent& event)
{
    /*
    typedef struct SDL_KeyboardEvent
    {
        Uint32 type;        // < ::SDL_KEYDOWN or ::SDL_KEYUP
        Uint32 timestamp;
        Uint32 windowID;    // < The window with keyboard focus, if any
        Uint8 state;        // < ::SDL_PRESSED or ::SDL_RELEASED
        Uint8 repeat;       // < Non-zero if this is a key repeat
        Uint8 padding2;
        Uint8 padding3;
        SDL_Keysym keysym;  // < The key that was pressed or released
    } SDL_KeyboardEvent;
    */

    // override
}

void Game::OnKeyUp(SDL_KeyboardEvent& event)
{
    /*
    typedef struct SDL_KeyboardEvent
    {
        Uint32 type;        // < ::SDL_KEYDOWN or ::SDL_KEYUP
        Uint32 timestamp;
        Uint32 windowID;    // < The window with keyboard focus, if any
        Uint8 state;        // < ::SDL_PRESSED or ::SDL_RELEASED
        Uint8 repeat;       // < Non-zero if this is a key repeat
        Uint8 padding2;
        Uint8 padding3;
        SDL_Keysym keysym;  // < The key that was pressed or released
    } SDL_KeyboardEvent;
    */

    // override
}

void Game::OnResize(uint32_t width, uint32_t height)
{
    // override
}

void Game::Exit()
{
    OnExit();

    m_state = GS_QUIT;
}

void Game::OnExit()
{
    // override
}

void Game::OnUpdate()
{
    // override
}

void Game::OnRender()
{
    // override
}

void Game::OnMouseButtonDown(SDL_MouseButtonEvent& event)
{
    /*
    typedef struct SDL_MouseButtonEvent
    {
        Uint32 type;        // < ::SDL_MOUSEBUTTONDOWN or ::SDL_MOUSEBUTTONUP
        Uint32 timestamp;
        Uint32 windowID;    // < The window with mouse focus, if any
        Uint32 which;       // < The mouse instance id, or SDL_TOUCH_MOUSEID
        Uint8 button;       // < The mouse button index
        Uint8 state;        // < ::SDL_PRESSED or ::SDL_RELEASED
        Uint8 clicks;       // < 1 for single-click, 2 for double-click, etc.
        Uint8 padding1;
        Sint32 x;           // < X coordinate, relative to window
        Sint32 y;           // < Y coordinate, relative to window
    } SDL_MouseButtonEvent;
    */

    // override
}

void Game::OnMouseButtonUp(SDL_MouseButtonEvent &event)
{
    /*
    typedef struct SDL_MouseButtonEvent
    {
        Uint32 type;        // < ::SDL_MOUSEBUTTONDOWN or ::SDL_MOUSEBUTTONUP
        Uint32 timestamp;
        Uint32 windowID;    // < The window with mouse focus, if any
        Uint32 which;       // < The mouse instance id, or SDL_TOUCH_MOUSEID
        Uint8 button;       // < The mouse button index
        Uint8 state;        // < ::SDL_PRESSED or ::SDL_RELEASED
        Uint8 clicks;       // < 1 for single-click, 2 for double-click, etc.
        Uint8 padding1;
        Sint32 x;           // < X coordinate, relative to window
        Sint32 y;           // < Y coordinate, relative to window
    } SDL_MouseButtonEvent;
    */

    // override
}

void Game::OnMouseMotion(SDL_MouseMotionEvent& event)
{
    /*
    typedef struct SDL_MouseMotionEvent
    {
        Uint32 type;
        Uint32 timestamp;
        Uint32 windowID;    // The window with mouse focus, if any
        Uint32 which;       // The mouse instance id, or SDL_TOUCH_MOUSEID
        Uint32 state;       // The current button state
        Sint32 x;           // X coordinate, relative to window
        Sint32 y;           // Y coordinate, relative to window
        Sint32 xrel;        // The relative motion in the X direction
        Sint32 yrel;        // The relative motion in the Y direction
    } SDL_MouseMotionEvent;
    */

    // override
}


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

namespace BigO.DAL.Mapper
{
    public class SubTable : System.Data.Entity.DbSet
    {
        public int Id { get; set; }
        public Nullable<int> TreeId { get; set; }
        public Nullable<int> CriteriaId { get; set; }
        public Nullable<int> DimensionId { get; set; }
        public string Code { get; set; }
        public string Info { get; set; }
        public Nullable<decimal> Weight { get; set; }
        public Nullable<decimal> Weight_Ratio { get; set; }
        public Nullable<decimal> Goal { get; set; }
        public Nullable<decimal> Achieved { get; set; }
        public Nullable<bool> IsActive { get; set; }
    }
}


text:
package net.sf.antcontrib.logic;

import net.sf.antcontrib.BuildFileTestBase;

/**
 * Since AntCallBack is basically a copy and paste of antcall, the only testing
 * done here is on the extra features provided by antcallback. It is assumed
 * that changes to antcall will be propagated to antcallback and that antcall
 * has it's own unit tests (which turns out to have been a bad assumption,
 * I can't find any unit tests for antcall).
 *
 * @author   danson
 */
public class AntCallBackTest extends BuildFileTestBase {

   /**
    * Constructor for the AntCallBackTest object
    *
    * @param name  Description of the Parameter
    */
   public AntCallBackTest( String name ) {
      super( name );
   }

   /** The JUnit setup method */
   public void setUp() {
      configureProject( "test/resources/logic/antcallbacktest.xml" );
   }

   /** A unit test for JUnit */
   public void test1() {
      expectPropertySet( "test1", "prop1", "prop1" );
   }

   /** A unit test for JUnit */
   public void test2() {
      expectPropertySet( "test2", "prop1", "prop1" );
      expectPropertySet( "test2", "prop2", "prop2" );
      expectPropertySet( "test2", "prop3", "prop3" );
   }

   /** A unit test for JUnit */
   public void test3() {
      expectPropertySet( "test3", "prop1", "prop1" );
      expectPropertySet( "test3", "prop2", "prop2" );
      expectPropertySet( "test3", "prop3", "prop3" );
   }

   /** A unit test for JUnit */
   public void test4() {
      expectPropertyUnset( "test4", "prop1" );
      expectPropertySet( "test4", "prop2", "prop2" );
      expectPropertySet( "test4", "prop3", "prop3" );
   }

   /** A unit test for JUnit */
   public void test5() {
      expectPropertySet( "test5", "prop1", "blah" );
      expectPropertySet( "test5", "prop2", "prop2" );
      expectPropertySet( "test5", "prop3", "prop3" );
   }
}


text:
(function() {
  'use strict';
  // Home View

  require('../common/core/core');
  require('../common/appMainNav/appMainNav');
  require('../common/appMainFooter/appMainFooter');
  require('./../common/globalSearchBar/globalSearchBar');

  var homePageDirective = require('./homePageDirective');
  var HomePageController = require('./HomePageController');
  var TestFactory1 = require('../appMainModule/examplePage1Module/testService1');

  module.exports = angular.module('homePageModule',
    [
      'coreModules',
      'appMainNavModule',
      'globalSearchBar',
      'appMainFooterModule'
    ])
      .directive('homePage', homePageDirective)
      .controller('HomePageController', HomePageController)
      .factory('TestFactory1', TestFactory1);

})();


text:
package com.intellij.uiDesigner.make;

import com.intellij.compiler.impl.CompilerUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.uiDesigner.FormEditingUtil;
import com.intellij.uiDesigner.GuiDesignerConfiguration;
import com.intellij.uiDesigner.GuiFormFileType;
import com.intellij.uiDesigner.UIDesignerBundle;
import com.intellij.uiDesigner.compiler.AlienFormFileException;
import com.intellij.uiDesigner.compiler.FormErrorInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.incremental.java.CopyResourcesUtil;

import java.io.DataInput;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

public final class Form2SourceCompiler implements SourceInstrumentingCompiler{

  private static VirtualFile findSourceFile(final CompileContext context, final VirtualFile formFile, final String className) {
    final Module module = context.getModuleByFile(formFile);
    if (module == null) {
      return null;
    }
    final PsiClass aClass = FormEditingUtil.findClassToBind(module, className);
    if (aClass == null) {
      return null;
    }

    final PsiFile containingFile = aClass.getContainingFile();
    if (containingFile == null){
      return null;
    }

    return containingFile.getVirtualFile();
  }

  @Override
  @NotNull
  public String getDescription() {
    return UIDesignerBundle.message("component.gui.designer.form.to.source.compiler");
  }

  @Override
  public boolean validateConfiguration(CompileScope scope) {
    return true;
  }

  @Override
  public ProcessingItem @NotNull [] getProcessingItems(final @NotNull CompileContext context) {
    final Project project = context.getProject();
    if (GuiDesignerConfiguration.getInstance(project).INSTRUMENT_CLASSES) {
      return ProcessingItem.EMPTY_ARRAY;
    }

    final ArrayList<ProcessingItem> items = new ArrayList<>();
    DumbService.getInstance(project).runReadActionInSmartMode(() -> {
      final CompileScope scope = context.getCompileScope();
      final CompileScope projectScope = context.getProjectCompileScope();

      final VirtualFile[] formFiles = projectScope.getFiles(GuiFormFileType.INSTANCE, true);
      final CompilerManager compilerManager = CompilerManager.getInstance(project);
      final BindingsCache bindingsCache = new BindingsCache(project);

      try {
        final HashMap<String, VirtualFile> class2form = new HashMap<>();

        for (final VirtualFile formFile : formFiles) {
          if (compilerManager.isExcludedFromCompilation(formFile)) {
            continue;
          }

          final String classToBind;
          try {
            classToBind = bindingsCache.getBoundClassName(formFile);
          }
          catch (AlienFormFileException e) {
            // ignore non-IDEA forms
            continue;
          }
          catch (Exception e) {
            addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.process.form.file", e)), formFile);
            continue;
          }

          if (classToBind == null) {
            continue;
          }

          final VirtualFile sourceFile = findSourceFile(context, formFile, classToBind);
          if (sourceFile == null) {
            if (scope.belongs(formFile.getUrl())) {
              addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.class.to.bind.does.not.exist", classToBind)), formFile);
            }
            continue;
          }

          final boolean inScope = scope.belongs(sourceFile.getUrl()) || scope.belongs(formFile.getUrl());

          final VirtualFile alreadyProcessedForm = class2form.get(classToBind);
          if (alreadyProcessedForm != null) {
            if (inScope) {
              addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.duplicate.bind", classToBind, alreadyProcessedForm.getPresentableUrl())), formFile);
            }
            continue;
          }
          class2form.put(classToBind, formFile);

          if (!inScope) {
            continue;
          }

          items.add(new MyInstrumentationItem(sourceFile, formFile));
        }
      }
      finally {
        bindingsCache.close();
      }
    });

    return items.toArray(ProcessingItem.EMPTY_ARRAY);
  }

  @Override
  public ProcessingItem[] process(final @NotNull CompileContext context, final ProcessingItem @NotNull [] items) {
    final ArrayList<ProcessingItem> compiledItems = new ArrayList<>();

    context.getProgressIndicator().setText(UIDesignerBundle.message("progress.compiling.ui.forms"));

    int formsProcessed = 0;

    final Project project = context.getProject();
    final FormSourceCodeGenerator generator = new FormSourceCodeGenerator(project);

    final HashSet<Module> processedModules = new HashSet<>();

    final List<File> filesToRefresh = new ArrayList<>();
    for (ProcessingItem item1 : items) {
      context.getProgressIndicator().setFraction((double)(++formsProcessed) / ((double)items.length));

      final MyInstrumentationItem item = (MyInstrumentationItem)item1;

      final VirtualFile formFile = item.getFormFile();

      if (GuiDesignerConfiguration.getInstance(project).COPY_FORMS_RUNTIME_TO_OUTPUT) {
        ApplicationManager.getApplication().runReadAction(() -> {
          final Module module = ModuleUtilCore.findModuleForFile(formFile, project);
          if (module != null && !processedModules.contains(module)) {
            processedModules.add(module);
            final String moduleOutputPath = CompilerPaths.getModuleOutputPath(module, false);
            try {
              if (moduleOutputPath != null) {
                filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(moduleOutputPath, false));
              }
              final String testsOutputPath = CompilerPaths.getModuleOutputPath(module, true);
              if (testsOutputPath != null && !testsOutputPath.equals(moduleOutputPath)) {
                filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(testsOutputPath, false));
              }
            }
            catch (IOException e) {
              addError(
                context,
                new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.copy.gui.designer.form.runtime",
                                         module.getName(), e.toString())),
                null
              );
            }
          }
        });
      }

      ApplicationManager.getApplication().invokeAndWait(() -> {
        CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
          PsiDocumentManager.getInstance(project).commitAllDocuments();
          generator.generate(formFile);
          final ArrayList<FormErrorInfo> errors = generator.getErrors();
          if (errors.size() == 0) {
            compiledItems.add(item);
          }
          else {
            for (final FormErrorInfo e : errors) {
              addError(context, e, formFile);
            }
          }
        }), "", null);
        FileDocumentManager.getInstance().saveAllDocuments();
      }, ModalityState.NON_MODAL);
    }

    CompilerUtil.refreshIOFiles(filesToRefresh);
    return compiledItems.toArray(ProcessingItem.EMPTY_ARRAY);
  }

  private static void addError(final CompileContext context, final FormErrorInfo e, final VirtualFile formFile) {
    @NlsSafe String message = e.getErrorMessage();
    if (formFile != null) {
      FormElementNavigatable navigatable = new FormElementNavigatable(context.getProject(), formFile, e.getComponentId());
      context.addMessage(CompilerMessageCategory.ERROR,
                         formFile.getPresentableUrl() + ": " + message,
                         formFile.getUrl(), -1, -1, navigatable);
    }
    else {
      context.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1);
    }
  }

  @Override
  public ValidityState createValidityState(final DataInput in) throws IOException {
    return TimestampValidityState.load(in);
  }

  private static final class MyInstrumentationItem implements ProcessingItem {
    @NotNull private final VirtualFile mySourceFile;
    private final VirtualFile myFormFile;
    private final TimestampValidityState myState;

    MyInstrumentationItem(@NotNull final VirtualFile sourceFile, final VirtualFile formFile) {
      mySourceFile = sourceFile;
      myFormFile = formFile;
      myState = new TimestampValidityState(formFile.getTimeStamp());
    }

    @Override
    @NotNull
    public VirtualFile getFile() {
      return mySourceFile;
    }

    public VirtualFile getFormFile() {
      return myFormFile;
    }

    @Override
    public ValidityState getValidityState() {
      return myState;
    }
  }

}


text:
int main()
{
  // ask for full name
  std::cout << "Enter your full name: ";
  std::string name;
  std::getline(std::cin, name);

  // ask for age
  std::cout << "Enter your age: ";
  int age;
  std::cin >> age;
  std::cin.ignore(255, '\n');

  // find out name length
  double nameLength = name.length();

  // maths
  double yearPerChar = age / nameLength;

  // print results
  std::cout << "You've lived " << yearPerChar << " years for each letter in your name.\n";

  return 0;
}


text:
package io.springlets.data.web.config;

import io.springlets.data.domain.GlobalSearch;
import io.springlets.data.web.GlobalSearchHandlerMethodArgumentResolver;
import io.springlets.data.web.datatables.DatatablesPageable;
import io.springlets.data.web.datatables.DatatablesPageableHandlerMethodArgumentResolver;
import io.springlets.data.web.datatables.DatatablesSort;
import io.springlets.data.web.datatables.DatatablesSortHandlerMethodArgumentResolver;

import org.springframework.context.annotation.Import;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation to automatically register the following beans for usage with Spring MVC:
 *
 * * {@link GlobalSearchHandlerMethodArgumentResolver}: to allow injection of
 * {@link GlobalSearch} instances into controller methods automatically created
 * from request parameters.
 * * {@link DatatablesPageableHandlerMethodArgumentResolver}: to allow
 * injection of {@link DatatablesPageable} instances into controller methods
 * automatically created from request parameters.
 * * {@link DatatablesSortHandlerMethodArgumentResolver}: to allow injection of
 * {@link DatatablesSort} instances into controller methods automatically created
 * from request parameters.
 *
 * @see SpringletsDataWebConfiguration
 * @author Cèsar Ordiñana at http://www.disid.com[DISID Corporation S.L.]
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Inherited
@Import({SpringletsDataWebConfiguration.class})
public @interface EnableSpringletsDataWebSupport {

}


text:
package ckathode.archimedes.gui;

import java.util.Locale;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;

import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;

import ckathode.archimedes.ArchimedesShipMod;
import ckathode.archimedes.blockitem.TileEntityHelm;
import ckathode.archimedes.chunk.AssembleResult;
import ckathode.archimedes.network.MsgClientHelmAction;
import ckathode.archimedes.network.MsgClientRenameShip;

public class GuiHelm extends GuiContainer
{
	public static final ResourceLocation	BACKGROUND_TEXTURE	= new ResourceLocation("archimedes", "textures/gui/shipstatus.png");

	public final TileEntityHelm				tileEntity;
	public final EntityPlayer				player;

	private GuiButton						btnRename, btnAssemble, btnUndo, btnMount;
	private GuiTextField					txtShipName;
	private boolean							busyCompiling;

	public GuiHelm(TileEntityHelm tileentity, EntityPlayer entityplayer)
	{
		super(new ContainerHelm(tileentity, entityplayer));
		tileEntity = tileentity;
		player = entityplayer;

		xSize = 256;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void initGui()
	{
		super.initGui();

		Keyboard.enableRepeatEvents(true);

		int btnx = guiLeft - 100;
		int btny = guiTop + 20;
		buttonList.clear();

		btnRename = new GuiButton(4, btnx, btny, 100, 20, StatCollector.translateToLocal("gui.shipstatus.rename"));
		buttonList.add(btnRename);

		btnAssemble = new GuiButton(1, btnx, btny += 20, 100, 20, StatCollector.translateToLocal("gui.shipstatus.compile"));
		buttonList.add(btnAssemble);

		btnUndo = new GuiButton(2, btnx, btny += 20, 100, 20, StatCollector.translateToLocal("gui.shipstatus.undo"));
		btnUndo.enabled = tileEntity.getPrevAssembleResult() != null && tileEntity.getPrevAssembleResult().getCode() != AssembleResult.RESULT_NONE;
		buttonList.add(btnUndo);

		btnMount = new GuiButton(3, btnx, btny += 20, 100, 20, StatCollector.translateToLocal("gui.shipstatus.mount"));
		btnMount.enabled = tileEntity.getAssembleResult() != null && tileEntity.getAssembleResult().getCode() == AssembleResult.RESULT_OK;
		buttonList.add(btnMount);

		txtShipName = new GuiTextField(fontRendererObj, guiLeft + 8 + xSize / 2, guiTop + 21, 120, 10);
		txtShipName.setMaxStringLength(127);
		txtShipName.setEnableBackgroundDrawing(false);
		txtShipName.setVisible(true);
		txtShipName.setCanLoseFocus(false);
		txtShipName.setTextColor(0xFFFFFF);
		txtShipName.setText(tileEntity.getShipInfo().shipName);
	}

	@Override
	public void onGuiClosed()
	{
		super.onGuiClosed();
		Keyboard.enableRepeatEvents(false);
	}

	@Override
	public void updateScreen()
	{
		super.updateScreen();
		btnUndo.enabled = tileEntity.getPrevAssembleResult() != null && tileEntity.getPrevAssembleResult().getCode() != AssembleResult.RESULT_NONE;
		btnMount.enabled = tileEntity.getAssembleResult() != null && tileEntity.getAssembleResult().getCode() == AssembleResult.RESULT_OK;

		btnRename.xPosition = btnAssemble.xPosition = btnUndo.xPosition = btnMount.xPosition = guiLeft - 100;

		int y = guiTop + 20;
		btnRename.yPosition = y;
		btnAssemble.yPosition = y += 20;
		btnUndo.yPosition = y += 20;
		btnMount.yPosition = y += 20;
	}

	@Override
	protected void drawGuiContainerForegroundLayer(int mousex, int mousey)
	{
		AssembleResult result = tileEntity.getAssembleResult();

		int color = 0x404040;
		int row = 8;
		int col0 = 8;
		int col1 = col0 + xSize / 2;

		fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.title"), col0, row, color);
		row += 5;
		fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.name"), col0, row += 10, color);

		int rcode;
		int rblocks;
		int rballoons;
		int rtes;
		float rmass;

		if (result == null)
		{
			rcode = busyCompiling ? AssembleResult.RESULT_BUSY_COMPILING : AssembleResult.RESULT_NONE;
			rblocks = rballoons = rtes = 0;
			rmass = 0f;
		} else
		{
			rcode = result.getCode();
			rblocks = result.getBlockCount();
			rballoons = result.getBalloonCount();
			rtes = result.getTileEntityCount();
			rmass = result.getMass();
			if (rcode != AssembleResult.RESULT_NONE)
			{
				busyCompiling = false;
			}
		}

		String rcodename;
		int color1;
		switch (rcode)
		{
		case AssembleResult.RESULT_NONE:
			color1 = color;
			rcodename = "gui.shipstatus.result.none";
			break;
		case AssembleResult.RESULT_OK:
			color1 = 0x40A000;
			rcodename = "gui.shipstatus.result.ok";
			break;
		case AssembleResult.RESULT_OK_WITH_WARNINGS:
			color1 = 0xFFAA00;
			rcodename = "gui.shipstatus.result.okwarn";
			break;
		case AssembleResult.RESULT_MISSING_MARKER:
			color1 = 0xB00000;
			rcodename = "gui.shipstatus.result.missingmarker";
			break;
		case AssembleResult.RESULT_BLOCK_OVERFLOW:
			color1 = 0xB00000;
			rcodename = "gui.shipstatus.result.overflow";
			break;
		case AssembleResult.RESULT_ERROR_OCCURED:
			color1 = 0xB00000;
			rcodename = "gui.shipstatus.result.error";
			break;
		case AssembleResult.RESULT_BUSY_COMPILING:
			color1 = color;
			rcodename = "gui.shipstatus.result.busy";
			break;
		case AssembleResult.RESULT_INCONSISTENT:
			color1 = 0xB00000;
			rcodename = "gui.shipstatus.result.inconsistent";
			break;
		default:
			color1 = color;
			rcodename = "gui.shipstatus.result.none";
			break;
		}

		fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.compilerresult"), col0, row += 10, color);
		fontRendererObj.drawString(StatCollector.translateToLocal(rcodename), col1, row, color1);

		float balloonratio = (float) rballoons / rblocks;
		fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.shiptype"), col0, row += 10, color);
		if (rblocks == 0)
		{
			fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.type.unknown"), col1, row, color);
		} else
		{
			fontRendererObj.drawString(StatCollector.translateToLocal(balloonratio > ArchimedesShipMod.instance.modConfig.flyBalloonRatio ? "gui.shipstatus.type.airship" : "gui.shipstatus.type.boat"), col1, row, color);
		}

		fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.count.block"), col0, row += 10, color);
		fontRendererObj.drawString(String.valueOf(rblocks), col1, row, color);

		fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.count.balloon"), col0, row += 10, color);
		fontRendererObj.drawString(String.valueOf(rballoons) + " (" + (int) (balloonratio * 100f) + "%)", col1, row, color);

		fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.count.tileentity"), col0, row += 10, color);
		fontRendererObj.drawString(String.valueOf(rtes), col1, row, color);

		fontRendererObj.drawString(StatCollector.translateToLocal("gui.shipstatus.mass"), col0, row += 10, color);
		fontRendererObj.drawString(String.format(Locale.ROOT, "%.1f %s", rmass, StatCollector.translateToLocal("gui.shipstatus.massunit")), col1, row, color);
	}

	@Override
	protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3)
	{
		GL11.glColor4f(1F, 1F, 1F, 1F);
		mc.renderEngine.bindTexture(BACKGROUND_TEXTURE);
		int x = (width - xSize) / 2;
		int y = (height - ySize) / 2;
		drawTexturedModalRect(x, y, 0, 0, xSize, ySize);

		txtShipName.drawTextBox();
	}

	@Override
	public void actionPerformed(GuiButton button)
	{
		if (button == btnRename)
		{
			if (txtShipName.isFocused())
			{
				btnRename.displayString = StatCollector.translateToLocal("gui.shipstatus.rename");
				tileEntity.getShipInfo().shipName = txtShipName.getText();
				txtShipName.setFocused(false);
				//txtShipName.setEnableBackgroundDrawing(false);

				MsgClientRenameShip msg = new MsgClientRenameShip(tileEntity, tileEntity.getShipInfo().shipName);
				ArchimedesShipMod.instance.pipeline.sendToServer(msg);
			} else
			{
				btnRename.displayString = StatCollector.translateToLocal("gui.shipstatus.done");
				txtShipName.setFocused(true);
				//txtShipName.setEnableBackgroundDrawing(true);
			}
		} else if (button == btnAssemble)
		{
			MsgClientHelmAction msg = new MsgClientHelmAction(tileEntity, 0);
			ArchimedesShipMod.instance.pipeline.sendToServer(msg);
			tileEntity.setAssembleResult(null);
			busyCompiling = true;
		} else if (button == btnUndo)
		{
			MsgClientHelmAction msg = new MsgClientHelmAction(tileEntity, 2);
			ArchimedesShipMod.instance.pipeline.sendToServer(msg);
		} else if (button == btnMount)
		{
			MsgClientHelmAction msg = new MsgClientHelmAction(tileEntity, 1);
			ArchimedesShipMod.instance.pipeline.sendToServer(msg);
		}
	}

	@Override
	protected void keyTyped(char c, int k)
	{
		if (!checkHotbarKeys(k))
		{
			if (k == Keyboard.KEY_RETURN && txtShipName.isFocused())
			{
				actionPerformed(btnRename);
			} else if (txtShipName.textboxKeyTyped(c, k))
			{} else
			{
				super.keyTyped(c, k);
			}
		}
	}
}


text:
		<title>PxContact.h File Reference</title>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<LINK HREF="NVIDIA.css" REL="stylesheet" TYPE="text/css">

				Main Page
				Class Hierarchy
				Compound List
				Compound Members

Include

Classes |
Macros

PxContact.h File Reference

#include "foundation/PxVec3.h"

This graph shows which files directly or indirectly include this file:

<map name="PxContact_8hdep" id="PxContact_8hdep">
</map>

Go to the source code of this file.

Classes

struct  	PxContactHeader

 	Base header structure for compressed contact data.  More...

struct  	PxModifyContactHeader

 	Extended header structure for modifiable contacts.  More...

struct  	PxContactPatchBase

 	Base header for a contact patch.  More...

struct  	PxContactPatch

 	Header for contact patch where all points share same material and normal.  More...

struct  	PxSimpleContact

 	Base contact point data.  More...

struct  	PxFeatureContact

 	Extended contact point data including face (feature) indices.  More...

struct  	PxModifiableContact

 	A modifiable contact point. This has additional fields per-contact to permit modification by user.  More...

struct  	PxContactStreamIterator

 	A class to iterate over a compressed contact stream. This supports read-only access to the various contact formats.  More...

Macros

#define 	PXC_CONTACT_NO_FACE_INDEX   0xffffffff

Macro Definition Documentation

          #define PXC_CONTACT_NO_FACE_INDEX   0xffffffff

Referenced by PxContactStreamIterator::getFaceIndex0(), and PxContactStreamIterator::getFaceIndex1().

Copyright © 2008-2015 NVIDIA Corporation, 2701 San Tomas Expressway, Santa Clara, CA 95050 U.S.A. All rights reserved. www.nvidia.com


text:
namespace Js
{

struct JSONObjectStack
{
    RecyclableObject* object;
    JSONObjectStack* next;

    bool Has(_In_ RecyclableObject* object)
    {
        JSONObjectStack* stack = this;
        while (stack != nullptr)
        {
            if (stack->object == object)
            {
                return true;
            }
            stack = stack->next;
        }
        return false;
    }
};

class JSONStringifier
{
private:
    // Spec defined limit on the gap length
    static const charcount_t MaxGapLength;

    struct PropertyListElement
    {
        Field(PropertyRecord const*) propertyRecord;
        Field(JavascriptString*) propertyName;

        PropertyListElement() {}
        PropertyListElement(const PropertyListElement& other)
            : propertyRecord(other.propertyRecord), propertyName(other.propertyName)
        {}
    };

    typedef SList<PropertyListElement, Recycler> PropertyList;

    ScriptContext* scriptContext;
    RecyclableObject* replacerFunction;
    PropertyList* propertyList;
    charcount_t totalStringLength;
    charcount_t indentLength;
    charcount_t gapLength;
    char16* gap;

    Var TryConvertPrimitiveObject(_In_ RecyclableObject* value);
    Var ToJSON(_In_ JavascriptString* key, _In_ RecyclableObject* valueObject);
    Var CallReplacerFunction(_In_opt_ RecyclableObject* holder, _In_ JavascriptString* key, _In_ Var value);
    _Ret_notnull_ Var ReadValue(_In_ JavascriptString* key, _In_opt_ const PropertyRecord* propertyRecord, _In_ RecyclableObject* holder);
    uint32 ReadArrayLength(_In_ RecyclableObject* value);
    JSONArray* ReadArray(_In_ RecyclableObject* arr, _In_ JSONObjectStack* objectStack);

    void ReadObjectElement(
        _In_ JavascriptString* propertyName,
        _In_opt_ PropertyRecord const* propertyRecord,
        _In_ RecyclableObject* obj,
        _In_ JSONObject* jsonObject,
        _In_ JSONObjectStack* objectStack);

    void ReadArrayElement(
        uint32 index,
        _In_ RecyclableObject* arr,
        _Out_ JSONProperty* prop,
        _In_ JSONObjectStack* objectStack);

    void CalculateStringifiedLength(uint32 propertyCount, charcount_t stepbackLength);
    void ReadProxy(_In_ JavascriptProxy* proxyObject, _In_ JSONObject* jsonObject, _In_ JSONObjectStack* stack);
    JSONObject* ReadObject(_In_ RecyclableObject* obj, _In_ JSONObjectStack* objectStack);
    void SetNullProperty(_Out_ JSONProperty* prop);
    void SetNumericProperty(double value, _In_ Var valueVar, _Out_ JSONProperty* prop);
    static charcount_t CalculateStringElementLength(_In_ JavascriptString* str);
    void ReadData(_In_ RecyclableObject* valueObj, _Out_ JSONProperty* prop);
    void ReadData(_In_ Var value, _Out_ JSONProperty* prop);
    void SetStringGap(_In_ JavascriptString* spaceString);
    void SetNumericGap(charcount_t spaceCount);
    void AddToPropertyList(_In_ Var item, _Inout_ BVSparse<Recycler>* propertyBV);
public:
    JSONStringifier(_In_ ScriptContext* scriptContext);
    void ReadSpace(_In_opt_ Var space);
    void ReadReplacer(_In_opt_ Var replacer);
    void ReadProperty(
        _In_ JavascriptString* key,
        _In_opt_ RecyclableObject* holder,
        _Out_ JSONProperty* prop,
        _In_opt_ Var value,
        _In_opt_ const PropertyRecord* propertyRecord,
        _In_ JSONObjectStack* objectStack);

    const char16* GetGap() const { return this->gap; };
    charcount_t GetGapLength() const { return this->gapLength; }
    bool HasReplacerFunction() const { return this->replacerFunction != nullptr; }

    bool HasComplexGap() const;

    static LazyJSONString* Stringify(_In_ ScriptContext* scriptContext, _In_ Var value, _In_opt_ Var replacer, _In_opt_ Var space);

}; // class JSONStringifier

} //namespace Js


text:
"use strict";

module.exports = function(sequelize, DataTypes) {
    var customerData = sequelize.define('customer_data', {
        id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
            unique: true
        },
        company_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            defaultValue: 1
        },
        group_id: {
            type: DataTypes.INTEGER(11),
            allowNull: false,
            default: 1
        },
        firstname: {
            type: DataTypes.STRING(64),
            allowNull: false,
            defaultValue: 'firstname'
        },
        lastname: {
            type: DataTypes.STRING(64),
            allowNull: false,
            defaultValue: 'lastname'
        },
        email: {
            type: DataTypes.STRING(64),
            allowNull: false,
            unique: true
        },
        address: {
            type: DataTypes.STRING(128),
            allowNull: true,
            defaultValue: 'address'
        },
        city: {
            type: DataTypes.STRING(64),
            allowNull: true,
            defaultValue: 'city'
        },
        country: {
            type: DataTypes.STRING(64),
            allowNull: true,
            defaultValue: 'country'
        },
        zip_code: {
            type: DataTypes.STRING(10),
            defaultValue: ''
        },
        telephone: {
            type: DataTypes.STRING(64),
            allowNull: true,
            defaultValue: '0'
        }
    }, {
        tableName: 'customer_data',
        associate: function(models) {
            if (models.login_data){
                customerData.hasMany(models.login_data, {foreignKey: 'customer_id'});
            }
            if (models.customer_group) {
                customerData.belongsTo(models.customer_group, {foreignKey: 'group_id'});
            }
            customerData.belongsTo(models.settings, {foreignKey: 'company_id'});
        }
    });
    return customerData;
};


text:
<?php

namespace App\Entity;

use Knp\DoctrineBehaviors\Model as ORMBehaviors;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraints as Assert;

class Page
{
    use ORMBehaviors\Translatable\Translatable;

    /** @var int */
    private $id;

    /**
     * @Assert\Valid
     */
    protected $translations;

    public static function create($title, $url, $content)
    {
        $entity = new self();
        $entity->translate('en')->setTitle($title);
        $entity->translate('en')->setUrl($url);
        $entity->translate('en')->setContent($content);

        return $entity;
    }

    public function __toString()
    {
        return $this->proxyCurrentLocaleTranslation('getTitle');
    }

    public function getId()
    {
        return $this->id;
    }

    public function __call($method, $arguments)
    {
        return PropertyAccess::createPropertyAccessor()->getValue($this->translate(), $method);
    }
}


text:
//  Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
//
//  This file is part of the VNC system.
//
//  The VNC system is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
//  USA.
//
// TightVNC distribution homepage on the Web: http://www.tightvnc.com/
//
// If the source code for the VNC system is not available from the place
// whence you received this file, check http://www.uk.research.att.com/vnc or contact
// the authors on vnc@uk.research.att.com for information on obtaining it.

/*
 * vncauth.h - describes the functions provided by the vncauth library.
 */

#define MAXPWLEN 8
#define CHALLENGESIZE 16

extern int vncEncryptPasswd(char *passwd, char *fname);
extern char *vncDecryptPasswd(char *fname);
extern void vncRandomBytes(unsigned char *bytes);
extern void vncEncryptBytes(unsigned char *bytes, const char *passwd);


text:
using NUnit.Framework;
using Umbraco.Core.Persistence.Mappers;

namespace Umbraco.Tests.Persistence.Mappers
{
    [TestFixture]
    public class PropertyGroupMapperTest : MapperTestBase
    {
        [Test]
        public void Can_Map_Id_Property()
        {
            // Act
            string column = new PropertyGroupMapper(MockSqlContext(), CreateMaps()).Map("Id");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsPropertyTypeGroup].[id]"));
        }

        [Test]
        public void Can_Map_SortOrder_Property()
        {
            // Act
            string column = new PropertyGroupMapper(MockSqlContext(), CreateMaps()).Map("SortOrder");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsPropertyTypeGroup].[sortorder]"));
        }

        [Test]
        public void Can_Map_Name_Property()
        {
            // Act
            string column = new PropertyGroupMapper(MockSqlContext(), CreateMaps()).Map("Name");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsPropertyTypeGroup].[text]"));
        }
    }
}


text:
module Azure::Peering::Mgmt::V2019_08_01_preview
  module Models
    #
    # The paginated list of peerings.
    #
    class PeeringListResult

      include MsRestAzure

      include MsRest::JSONable
      # @return [Array<Peering>] The list of peerings.
      attr_accessor :value

      # @return [String] The link to fetch the next page of peerings.
      attr_accessor :next_link

      # return [Proc] with next page method call.
      attr_accessor :next_method

      #
      # Gets the rest of the items for the request, enabling auto-pagination.
      #
      # @return [Array<Peering>] operation results.
      #
      def get_all_items
        items = @value
        page = self
        while page.next_link != nil && !page.next_link.strip.empty? do
          page = page.get_next_page
          items.concat(page.value)
        end
        items
      end

      #
      # Gets the next page of results.
      #
      # @return [PeeringListResult] with next page content.
      #
      def get_next_page
        response = @next_method.call(@next_link).value! unless @next_method.nil?
        unless response.nil?
          @next_link = response.body.next_link
          @value = response.body.value
          self
        end
      end

      #
      # Mapper for PeeringListResult class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'PeeringListResult',
          type: {
            name: 'Composite',
            class_name: 'PeeringListResult',
            model_properties: {
              value: {
                client_side_validation: true,
                required: false,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'PeeringElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'Peering'
                      }
                  }
                }
              },
              next_link: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nextLink',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="text">Tekst</string>
	<string name="enter_text_here">Vul hier uw tekst in</string>
	<string name="error_download_image_message">Er is een fout opgetreden tijdens het downloaden van de afbeelding, probeer het later opnieuw.</string>
	<string name="night_enhance_label">Nacht</string>
	<string name="revert_dialog_title">Terug naar origineel</string>
	<string name="red_eye">Roodoog</string>
	<string name="feather_error_saving_aviary_folder">Oeps, er is een fout opgetreden tijdens het opslaan van de afbeelding naar de Aviary-map. Wilt u proberen de afbeelding op te slaan naar de standaard cameramap.</string>
	<string name="feather_standalone_help_support">Help / Ondersteuning</string>
	<string name="generic_error_title">Fout</string>
	<string name="save">Klaar</string>
	<string name="feather_borders_dialog_first_time">Installeer gratis Aviary\'s pakket van mooie hoge resolutie kaders om te beginnen.</string>
	<string name="saturation">Saturatie</string>
	<string name="get_more">Krijg meer</string>
	<string name="blemish">Vlek</string>
	<string name="effects">Effecten</string>
	<string name="feather_close">Sluiten</string>
	<string name="rotate">Roteren</string>
	<string name="brightness">Helderheid</string>
	<string name="feather_standalone_large">Groot (tot 5MP)</string>
	<string name="remove">Verwijderen</string>
	<string name="adjust">Oriëntatie</string>
	<string name="revert_dialog_message">U staat op het punt om al de door u gemaakte veranderingen te verliezen. Weet u zuker dat u terug wilt gaan naar het origineel?</string>
	<string name="enhance">Verbeteren</string>
	<string name="whiten">Witter</string>
	<string name="square">Vierkant</string>
	<string name="menu_reset">Herinitialiseren</string>
	<string name="crop">Bijsnijden</string>
	<string name="feather_stickers_dialog_first_time">Installeer gratis Aviary\'s pakket van mooie hoge resolutie stickers om te beginnen.</string>
	<string name="mirror">Spiegel</string>
	<string name="feather_activity_not_found">Sorry, er bevindt zich geen toepassing op uw telefoon om deze actie mee uit te voeren. Wilt u de toepassing van de markt downloaden?</string>
	<string name="confirm">Bevestigen</string>
	<string name="yes_leave">Editor afsluiten</string>
	<string name="feather_standalone_editor">Editor</string>
	<string name="feather_view_file">Afbeelding bekijken</string>
	<string name="feather_standalone_give_five_stars">Geef ons dan alsjeblieft een 5-sterren recensie!</string>
	<string name="feather_standalone_output_image_size">Maximaal Opslag Grootte</string>
	<string name="back_enhance_label">Achtergrondverlichting</string>
	<string name="contrast">Contrast</string>
	<string name="attention">Aandacht</string>
	<string name="feather_standalone_love_aviary_question">Vind je %@ leuk?</string>
	<string name="feather_standalone_normal">Normaal (tot 3MP)</string>
	<string name="feather_delete">Verwijderen</string>
	<string name="sticker_pack_updated_1">Een stickerpakket is bijgewerkt. Klik op ok om de lijst met pakketen te herladen</string>
	<string name="sticker_pack_updated_2">Een stickerpakket is bijgewerkt. We moeten het huidige paneel herladen</string>
	<string name="sticker_pack_updated_3">Een stickerpakket is bijgewerkt. We moeten het huidige paneel herladen. Wilt u de huidige sticker toepassen?</string>
	<string name="feather_standalone_image_output_folder">Uitvoermap</string>
	<string name="filter_pack_updated">Een filterpakket is bijgewerkt. Klik op ok om de lijst met pakketen te herladen</string>
	<string name="feather_standalone_settings">Instellingen</string>
	<string name="edit_your_photo">Photo Editor</string>
	<string name="feather_standalone_general">Algemeen</string>
	<string name="feather_image_saved_in">Afbeelding opgeslagen in %1$s. Wilt u de opgeslagen afbeelding bekijken?</string>
	<string name="apply">Toepassen</string>
	<string name="auto_enhance_label">Auto</string>
	<string name="feather_error_saving_image">Oeps, er is een fout opgetreden tijdens het opslaan van de afbeelding.</string>
	<string name="infoscreen_bottom_button">Over deze editor</string>
	<string name="custom">Eigen</string>
	<string name="feather_standalone_vibration">Trilling</string>
	<string name="sharpen">Scherpte</string>
	<string name="feather_standalone_dont_ask_again">Vraag mij dit niet nogmaals</string>
	<string name="feather_crash_toast_text">Oooooeps! Ik ben gecrashd, maar er is een rapport naar mijn ontwikkelaar verstuurd om hem te helpen het probleem op te lossen.</string>
	<string name="sticker_delete_message">Weet u zeker dat u deze sticker wilt verwijderen?</string>
	<string name="tool">Gereedschap</string>
	<string name="feather_standalone_photos">Foto\'s</string>
	<string name="filter_name">Gratis</string>
	<string name="feather_tool_temperature">Warmte</string>
	<string name="feather_loading_title">Bezig met laden</string>
	<string name="tool_name">Aviary</string>
	<string name="feather_standalone_view">Zien</string>
	<string name="feather_standalone_get_this_editor">Ontwikkelaars: krijg deze editor!</string>
	<string name="menu_premium">Store</string>
	<string name="feather_standalone_image_output_folder_summary">Kies de bestemmingsmap</string>
	<string name="feather_standalone_about">Over</string>
	<string name="balance_enhance_label">Balans</string>
	<string name="border_name">Gratis</string>
	<string name="loading_image">Bezig met het laden van de afbeelding…</string>
	<string name="feather_standalone_main_button_camera">Camera</string>
	<string name="confirm_quit_message">Wacht!  U heeft uw werk niet opgeslagen.  Bent u zeker dat u deze editor wil sluiten?</string>
	<string name="stickers">Stickers</string>
	<string name="menu_cancel">Annuleren</string>
	<string name="feather_save_progress">Bezig met opslaan…</string>
	<string name="feather_standalone_you_can_change_this_property_in_settings">U kunt deze eigenschap in het instellingenpaneel wijzigen</string>
	<string name="feather_standalone_details">Details</string>
	<string name="keep_editing">Verder werken</string>
	<string name="feather_update">Bijwerken</string>
	<string name="draw">Tekening</string>
	<string name="feather_standalone_remind_me_later">Herinner me er later aan</string>
	<string name="feather_standalone_tool_order">Gereedschapsvolgorde</string>
	<string name="feather_borders">Frames</string>
	<string name="feather_standalone_main_button_gallery">Galerij</string>
	<string name="zoom_mode">Zoom-stand</string>
	<string name="feather_standalone_no_thanks">Nee, bedankt</string>
	<string name="feather_standalone_main_button_edit">Bewerk deze Foto</string>
	<string name="feather_standalone_file_saved">Bestand opgeslagen</string>
	<string name="feather_standalone_maximum">Maximaal (tot 12MP)</string>
	<string name="feather_featured">Aanbevolen</string>
	<string name="sticker_name">Demo</string>
	<string name="feather_standalone_artist">Kunstenaar</string>
	<string name="feather_standalone_edit">Bewerken</string>
	<string name="original">Origineel</string>
</resources>


text:
local _M = {}

_M.source, _M.resolution, _M.gettime = (function()
	local has_syscall, syscall = pcall(require, "syscall")
	if has_syscall and syscall.clock_gettime and syscall.c.CLOCK then
		local clock_id = syscall.c.CLOCK.REALTIME
		local function timespec_to_number(timespec)
			return tonumber(timespec.tv_sec) + tonumber(timespec.tv_nsec) * 1e-9
		end
		return "syscall.clock_gettime(CLOCK_REALTIME)",
			syscall.clock_getres and timespec_to_number(syscall.clock_getres(clock_id)) or 1e-9,
			function()
				return timespec_to_number(syscall.clock_gettime(clock_id))
			end
	end

	local has_unix, unix = pcall(require, "unix")
	-- On Apple devices lunix only uses gettimeofday()
	if has_unix and unix.clock_gettime and unix.uname and unix.uname().sysname ~= "Darwin" then
		return "unix.clock_gettime(CLOCK_REALTIME)", 1e-9, function()
			return unix.clock_gettime()
		end
	end

	if has_syscall and syscall.gettimeofday then
		local function timeval_to_number(timeval)
			return tonumber(timeval.tv_sec) + tonumber(timeval.tv_nsec) * 1e-6
		end
		return "syscall.gettimeofday()", 1e-6,
			function()
				return timeval_to_number(syscall.gettimeofday())
			end
	end

	if has_unix and unix.gettimeofday then
		return "unix.gettimeofday()", 1e-6, unix.gettimeofday
	end

	local has_socket, socket = pcall(require, "socket")
	if has_socket and socket.gettime then
		-- on windows, this uses GetSystemTimeAsFileTime, which has resolution of 1e-7
		-- on linux, this uses gettimeofday, which has resolution of 1e-6
		return "socket.gettime()", 1e-6, socket.gettime
	end

	if ngx and ngx.now then -- luacheck: ignore 113
		return "ngx.now()", 1e-3, ngx.now -- luacheck: ignore 113
	end

	return "os.time()", 1, os.time
end)()

return _M


text:
class NotificationMailer < ActionMailer::Base
  layout "notification_mailer"

  default :from => "Johnny Quids<quidlicker@example.com>"

  def welcome_email
    mail(:to => "archie@example.com", :subject => "We need dry ice")
  end

  def email_with_html_only
    mail(:to => "archie@example.com", :subject => "We need dry ice")
  end

  def welcome_html_email
    mail(:to => "archie@example.com", :subject => "We need dry ice")
  end

end


text:
$(function(){

  $.fn.hhDrop = function(options){
    var options = jQuery.extend({
        preLoadSrc:"images/loading.gif"
    }, options || {});

    var defaults = {};

    return this.each(function(){

      //榛樿
      var options = $.extend(defaults,options);
      var $this = $(this);

      var $boxSearch = $this.find('.boxSearch');
      var $lineSearchbg = $this.nextAll().find('.lineSearchbg');

      //鍑哄彂鍩庡競  鍒拌揪鍩庡競
      $boxSearch.click(function(){
        var _this = $(this);
        //鐐瑰嚮鏈韩鏄剧ず闅愯棌
        if(_this.hasClass('boxSearchHover') ){
          _this.removeClass('boxSearchHover');
          _this.children('.btn_search').removeClass('btn_search_current');
          _this.parent().find('.search_form_suggest').hide();

        }else{
          _this.addClass('boxSearchHover');
          _this.children('.btn_search').addClass('btn_search_current');
          _this.parent().find('.search_form_suggest').show();
        }

        _this.next().find('.clr_after a').click(function(){

          _this.find('span.key_word b').text($(this).text());

        });

        _this.next().find('.search_city_result a').click(function(){

          _this.find('span.key_word b').text($(this).text());

        });

        //闃绘鍐掓场
        $(document).bind('click',function(event){
          if(!$(event.target).parent().hasClass('boxSearch' )  && !$(event.target).hasClass('boxSearch') && !$(event.target).parent().parent().hasClass('boxSearch') && !$(event.target).hasClass('input_city') ){
            _this.children('.btn_search').removeClass('btn_search_current');
            _this.removeClass('boxSearchHover');
            _this.parent().find('.search_form_suggest').hide();
          }
        });

      });

  });

}

});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Fortaggle.Views.Item
{
    /// <summary>
    /// ItemStatuItemStatusDialog.xaml の相互作用ロジック
    /// </summary>
    public partial class ItemStatusDialog : UserControl
    {
        public ItemStatusDialog()
        {
            InitializeComponent();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--                                                                          -->
<!-- Copyright 2020 Mirko Raner                                               -->
<!--                                                                          -->
<!-- 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.                                           -->
<!--                                                                          -->
<project
 xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.loginject</groupId>
  <artifactId>loginject</artifactId>
  <version>1.1.0</version>
 </parent>
 <artifactId>loginject-hk2</artifactId>
 <name>loginject for HK2</name>

 <dependencies>
  <dependency>
   <groupId>org.loginject</groupId>
   <artifactId>loginject-api</artifactId>
  </dependency>
  <dependency>
   <groupId>org.glassfish.hk2</groupId>
   <artifactId>hk2</artifactId>
  </dependency>
 </dependencies>

</project>