text:
<?php
/**
 * User: Javier Bravo
 * Date: 10/05/15
 */

namespace Simpleue\Unitary\Worker;

use Simpleue\Mocks\QueueWorkerSpy;
use Simpleue\Mocks\QueueSpy;
use Simpleue\Mocks\JobSpy;
use Simpleue\Mocks\LoggerSpy;

class QueueWorkerTest extends \PHPUnit_Framework_TestCase {

    private $queueWorkerSpy;
    private $sourceQueueMock;
    private $jobHandlerMock;

    protected function setUp() {
        date_default_timezone_set('Europe/London');

        $this->sourceQueueMock = new QueueSpy();
        $this->jobHandlerMock = new JobSpy();
        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock);
    }

    public function testRunMaxIterations() {
        $this->queueWorkerSpy->setMaxIterations(3);
        $this->queueWorkerSpy->start();
        $this->assertEquals(3, $this->queueWorkerSpy->getIterations());

        $this->queueWorkerSpy->setMaxIterations(10);
        $this->queueWorkerSpy->start();
        $this->assertEquals(10, $this->queueWorkerSpy->getIterations());
    }

    public function testRunManageSuccessfulJob() {
        $this->queueWorkerSpy->setMaxIterations(10);
        $this->queueWorkerSpy->start();
        $this->assertEquals(10, $this->sourceQueueMock->getNextCounter, 'Get Next counter');
        $this->assertEquals(10, $this->sourceQueueMock->successfulCounter, 'Successful counter');
        $this->assertEquals(0, $this->sourceQueueMock->failedCounter, 'Failed counter');
        $this->assertEquals(0, $this->sourceQueueMock->errorCounter, 'Error counter');
        $this->assertEquals(0, $this->sourceQueueMock->nothingToDoCounter, 'Nothing to do counter');
        $this->assertEquals(0, $this->sourceQueueMock->stoppedCounter, 'Stop inst. management counter');
        $this->assertEquals(30, $this->sourceQueueMock->getMessageBodyCounter, 'Message body counter');
    }

    public function testStopInstruction() {
        $this->sourceQueueMock = $this->getMock('Simpleue\Mocks\QueueSpy', array('getNext'));
        $this->sourceQueueMock->expects($this->at(0))->method('getNext')->willReturn(1);
        $this->sourceQueueMock->expects($this->at(1))->method('getNext')->willReturn(1);
        $this->sourceQueueMock->expects($this->at(2))->method('getNext')->willReturn('STOP');

        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock);
        $this->queueWorkerSpy->setMaxIterations(10);
        $this->queueWorkerSpy->start();
        $this->assertEquals(3, $this->queueWorkerSpy->getIterations());
        $this->assertEquals(2, $this->sourceQueueMock->successfulCounter, 'Successful counter');
        $this->assertEquals(0, $this->sourceQueueMock->failedCounter, 'Failed counter');
        $this->assertEquals(0, $this->sourceQueueMock->errorCounter, 'Error counter');
        $this->assertEquals(0, $this->sourceQueueMock->nothingToDoCounter, 'Nothing to do counter');
        $this->assertEquals(1, $this->sourceQueueMock->stoppedCounter, 'Stop inst. management counter');
        $this->assertEquals(8, $this->sourceQueueMock->getMessageBodyCounter, 'Message body counter');
    }

    public function testNothingToDo() {
        $this->sourceQueueMock = $this->getMock('Simpleue\Mocks\QueueSpy', array('getNext'));
        $this->sourceQueueMock->expects($this->at(0))->method('getNext')->willReturn(false);
        $this->sourceQueueMock->expects($this->at(1))->method('getNext')->willReturn(1);
        $this->sourceQueueMock->expects($this->at(2))->method('getNext')->willReturn(false);
        $this->sourceQueueMock->expects($this->at(3))->method('getNext')->willReturn(0);
        $this->sourceQueueMock->expects($this->at(4))->method('getNext')->willReturn('');

        $this->jobHandlerMock = $this->getMock('Simpleue\Mocks\JobSpy', array('isMyJob'));
        $this->jobHandlerMock->expects($this->at(0))->method('isMyJob')->willReturn(true);
        $this->jobHandlerMock->expects($this->at(1))->method('isMyJob')->willReturn(false);
        $this->jobHandlerMock->expects($this->at(2))->method('isMyJob')->willReturn(true);

        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock);
        $this->queueWorkerSpy->setMaxIterations(5);
        $this->queueWorkerSpy->start();
        $this->assertEquals(5, $this->queueWorkerSpy->getIterations());
        $this->assertEquals(2, $this->sourceQueueMock->successfulCounter, 'Successful counter');
        $this->assertEquals(0, $this->sourceQueueMock->failedCounter, 'Failed counter');
        $this->assertEquals(0, $this->sourceQueueMock->errorCounter, 'Error counter');
        $this->assertEquals(3, $this->sourceQueueMock->nothingToDoCounter, 'Nothing to do counter');
        $this->assertEquals(0, $this->sourceQueueMock->stoppedCounter, 'Stop inst. management counter');
        $this->assertEquals(7, $this->sourceQueueMock->getMessageBodyCounter, 'Message body counter');
    }

    public function testRunManagedFailedJobs() {
        $this->jobHandlerMock = $this->getMock('Simpleue\Mocks\JobSpy', array('manage'));
        $this->jobHandlerMock->expects($this->at(0))->method('manage')->willReturn(true);
        $this->jobHandlerMock->expects($this->at(1))->method('manage')->willReturn(false);
        $this->jobHandlerMock->expects($this->at(2))->method('manage')->willReturn(true);
        $this->jobHandlerMock->expects($this->at(3))->method('manage')->willReturn(true);
        $this->jobHandlerMock->expects($this->at(4))->method('manage')->willReturn(false);

        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock);
        $this->queueWorkerSpy->setMaxIterations(5);
        $this->queueWorkerSpy->start();
        $this->assertEquals(5, $this->queueWorkerSpy->getIterations());
        $this->assertEquals(3, $this->sourceQueueMock->successfulCounter, 'Successful counter');
        $this->assertEquals(2, $this->sourceQueueMock->failedCounter, 'Failed counter');
        $this->assertEquals(0, $this->sourceQueueMock->errorCounter, 'Error counter');
        $this->assertEquals(0, $this->sourceQueueMock->nothingToDoCounter, 'Nothing to do counter');
        $this->assertEquals(0, $this->sourceQueueMock->stoppedCounter, 'Stop inst. management counter');
        $this->assertEquals(15, $this->sourceQueueMock->getMessageBodyCounter, 'Message body counter');
    }

    public function testHandlerManageExceptions() {
        $this->jobHandlerMock = $this->getMock('Simpleue\Mocks\JobSpy', array('manage'));
        $this->jobHandlerMock->expects($this->at(0))->method('manage')->willReturn(true);
        $this->jobHandlerMock->expects($this->at(1))->method('manage')->willThrowException(new \Exception('Testing exceptions'));
        $this->jobHandlerMock->expects($this->at(2))->method('manage')->willReturn(false);
        $this->jobHandlerMock->expects($this->at(3))->method('manage')->willThrowException(new \Exception('Testing exceptions'));

        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock);
        $this->queueWorkerSpy->setMaxIterations(4);
        $this->queueWorkerSpy->start();
        $this->assertEquals(4, $this->queueWorkerSpy->getIterations());
        $this->assertEquals(1, $this->sourceQueueMock->successfulCounter, 'Successful counter');
        $this->assertEquals(1, $this->sourceQueueMock->failedCounter, 'Failed counter');
        $this->assertEquals(2, $this->sourceQueueMock->errorCounter, 'Error counter');
        $this->assertEquals(0, $this->sourceQueueMock->nothingToDoCounter, 'Nothing to do counter');
        $this->assertEquals(0, $this->sourceQueueMock->stoppedCounter, 'Stop inst. management counter');
        $this->assertEquals(12, $this->sourceQueueMock->getMessageBodyCounter, 'Message body counter');
    }

    public function testSourceQueueGetNextExceptions() {
        $this->sourceQueueMock = $this->getMock('Simpleue\Mocks\QueueSpy', array('getNext'));
        $this->sourceQueueMock->expects($this->at(0))->method('getNext')->willThrowException(new \Exception('Testing exceptions'));
        $this->sourceQueueMock->expects($this->at(1))->method('getNext')->willReturn(1);
        $this->sourceQueueMock->expects($this->at(2))->method('getNext')->willThrowException(new \Exception('Testing exceptions'));

        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock);
        $this->queueWorkerSpy->setMaxIterations(3);
        $this->queueWorkerSpy->start();
        $this->assertEquals(3, $this->queueWorkerSpy->getIterations());
        $this->assertEquals(1, $this->sourceQueueMock->successfulCounter, 'Successful counter');
        $this->assertEquals(0, $this->sourceQueueMock->failedCounter, 'Failed counter');
        $this->assertEquals(0, $this->sourceQueueMock->nothingToDoCounter, 'Nothing to do counter');
        $this->assertEquals(0, $this->sourceQueueMock->stoppedCounter, 'Stop inst. management');
        $this->assertEquals(3, $this->sourceQueueMock->getMessageBodyCounter, 'Message body counter');
    }

    public function testSourceQueueSuccessfulAndFailedExceptions() {
        $this->jobHandlerMock = $this->getMock('Simpleue\Mocks\JobSpy', array('manage'));
        $this->sourceQueueMock = $this->getMock('Simpleue\Mocks\QueueSpy', array('successful', 'failed'));
        $this->jobHandlerMock->expects($this->at(0))->method('manage')->willReturn(true);
        $this->sourceQueueMock->expects($this->at(0))->method('successful')->willThrowException(new \Exception('Testing exceptions'));
        $this->jobHandlerMock->expects($this->at(1))->method('manage')->willReturn(true);
        $this->sourceQueueMock->expects($this->at(1))->method('successful')->willReturn(1);
        $this->jobHandlerMock->expects($this->at(2))->method('manage')->willReturn(false);
        $this->sourceQueueMock->expects($this->at(2))->method('failed')->willThrowException(new \Exception('Testing exceptions'));
        $this->jobHandlerMock->expects($this->at(3))->method('manage')->willReturn(false);
        $this->sourceQueueMock->expects($this->at(3))->method('failed')->willReturn(1);

        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock);
        $this->queueWorkerSpy->setMaxIterations(4);
        $this->queueWorkerSpy->start();
        $this->assertEquals(4, $this->queueWorkerSpy->getIterations());
        $this->assertEquals(2, $this->sourceQueueMock->errorCounter, 'Error counter');
        $this->assertEquals(0, $this->sourceQueueMock->nothingToDoCounter, 'Nothing to do counter');
        $this->assertEquals(0, $this->sourceQueueMock->stoppedCounter, 'Stop inst. management counter');
        $this->assertEquals(12, $this->sourceQueueMock->getMessageBodyCounter, 'Message body counter');
    }

    public function testWorkerExitsGracefullyOnSigINT() {
        if (!function_exists('pcntl_signal')) {
            $this->markTestSkipped('Enable pcntl_* extension to run this test');
        }

        if (defined('HHVM_VERSION')) {
            $this->markTestSkipped('The Graceful Exit feature does not work for HHVM');
        }

        $this->jobHandlerMock->setQuitCount(3);
        $this->jobHandlerMock->setSignalToTest(SIGINT);
        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock, 10, true);
        $this->queueWorkerSpy->start();
        $this->assertEquals(3, $this->queueWorkerSpy->getIterations());
        $this->assertEquals(3, $this->jobHandlerMock->getmanageCounter());
    }

    public function testWorkerExitsGracefullyOnSigTERM() {
        if (!function_exists('pcntl_signal')) {
            $this->markTestSkipped('Enable pcntl_* extension to run this test');
        }

        if (defined('HHVM_VERSION')) {
            $this->markTestSkipped('The Graceful Exit feature does not work for HHVM');
        }

        $this->jobHandlerMock->setQuitCount(8);
        $this->jobHandlerMock->setSignalToTest(SIGTERM);
        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock, 10, true);
        $this->queueWorkerSpy->start();
        $this->assertEquals(8, $this->queueWorkerSpy->getIterations());
        $this->assertEquals(8, $this->jobHandlerMock->getmanageCounter());
    }

    public function testLoggerDebug() {
        $loggerSpy = new LoggerSpy();
        $this->queueWorkerSpy->setMaxIterations(1);
        $this->queueWorkerSpy->setLogger($loggerSpy);
        $this->queueWorkerSpy->start();
        $this->assertEquals(3, count($loggerSpy->debugMessages));

        $loggerSpy = new LoggerSpy();
        $this->queueWorkerSpy->setMaxIterations(3);
        $this->queueWorkerSpy->setLogger($loggerSpy);
        $this->queueWorkerSpy->start();
        $this->assertEquals(5, count($loggerSpy->debugMessages));
    }

    public function testLoggerError() {
        $loggerSpy = new LoggerSpy();
        $this->jobHandlerMock = $this->getMock('Simpleue\Mocks\JobSpy', array('manage'));
        $this->jobHandlerMock->expects($this->at(0))->method('manage')->willReturn(true);
        $this->jobHandlerMock->expects($this->at(1))->method('manage')->willThrowException(new \Exception('Testing exceptions'));
        $this->jobHandlerMock->expects($this->at(2))->method('manage')->willReturn(false);
        $this->jobHandlerMock->expects($this->at(3))->method('manage')->willThrowException(new \Exception('Testing exceptions'));

        $this->queueWorkerSpy = new QueueWorkerSpy($this->sourceQueueMock, $this->jobHandlerMock);
        $this->queueWorkerSpy->setMaxIterations(4);
        $this->queueWorkerSpy->setLogger($loggerSpy);
        $this->queueWorkerSpy->start();
        $this->assertEquals(2, count($loggerSpy->errorMessages));
    }
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
	<title>Comics News</title>

	<link href="css/materialize.min.css" type="text/css" rel="stylesheet" media="screen,projection"/>
	<link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

Comics News

Início

Cadastrar

Início

Cadastrar

			menu

							{{noticia.data}}
 publicado por {{noticia.autor}}

						{{noticia.titulo}}

{{noticia.resumo}}

Comics News

As notícias e novidades de seus filmes favoritos aparecem aqui primeiro.

				autoria Jerry Martins

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <integer name="feed_columns">3</integer>
</resources>


text:
package it.geosolutions.jaiext.scale;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.awt.*;
import java.awt.image.ComponentSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.renderable.ParameterBlock;
import java.io.IOException;

import javax.media.jai.BorderExtender;
import javax.media.jai.ImageLayout;
import javax.media.jai.Interpolation;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.ROI;
import javax.media.jai.ROIShape;
import javax.media.jai.RenderedOp;
import javax.media.jai.TiledImage;

import it.geosolutions.jaiext.range.NoDataContainer;
import it.geosolutions.jaiext.range.Range;
import it.geosolutions.jaiext.range.RangeFactory;
import it.geosolutions.jaiext.testclasses.TestBase;
import it.geosolutions.rendered.viewer.RenderedImageBrowser;

/**
 * This test-class is an extension of the TestBase class inside the jt-utilities project. By calling the testGlobal() method with the selected
 * parameters is possible to create an image with the selected preferences and then process it with the preferred interpolation type. Inside the
 * testGlobal() method are tested images with all the possible data type by calling the testImage() method. This method is used for creating an image
 * with the user-defined parameters(data type, ROI, No Data Range) and then scaling it with the supplied interpolation type. If the user wants to see
 * a scaled image with the selected type of test, must set JAI.Ext.Interactive parameter to true, JAI.Ext.TestSelector from 0 to 5 and
 * JAI.Ext.InverseScale to 0 or 1 (Magnification/reduction) to the Console. The methods testImageAffine() testGlobalAffine() are not supported, they
 * are defined in the jt-affine project.
 */
public class TestScale extends TestBase {

    protected void testGlobal(boolean useROIAccessor, boolean isBinary, boolean bicubic2Disabled,
            boolean noDataRangeUsed, boolean roiPresent,
            it.geosolutions.jaiext.testclasses.TestBase.InterpolationType interpType,
            it.geosolutions.jaiext.testclasses.TestBase.TestSelection testSelect,
            ScaleType scaleValue) {

        // ImageTest
        // starting dataType
        int dataType = DataBuffer.TYPE_BYTE;
        testImage(dataType, useROIAccessor, isBinary, bicubic2Disabled,
                noDataRangeUsed, roiPresent, interpType, testSelect, scaleValue);

        dataType = DataBuffer.TYPE_USHORT;
        testImage(dataType, useROIAccessor, isBinary, bicubic2Disabled,
                noDataRangeUsed, roiPresent, interpType, testSelect, scaleValue);

        dataType = DataBuffer.TYPE_INT;
        testImage(dataType, useROIAccessor, isBinary, bicubic2Disabled,
                noDataRangeUsed, roiPresent, interpType, testSelect, scaleValue);

        if (!isBinary) {
            dataType = DataBuffer.TYPE_SHORT;
            testImage(dataType, useROIAccessor, isBinary, bicubic2Disabled,
                    noDataRangeUsed, roiPresent, interpType, testSelect, scaleValue);

            dataType = DataBuffer.TYPE_FLOAT;
            testImage(dataType, useROIAccessor, isBinary, bicubic2Disabled,
                    noDataRangeUsed, roiPresent, interpType, testSelect, scaleValue);

            dataType = DataBuffer.TYPE_DOUBLE;
            testImage(dataType, useROIAccessor, isBinary, bicubic2Disabled,
                    noDataRangeUsed, roiPresent, interpType, testSelect, scaleValue);
        }

    }

    protected <T extends Number & Comparable<? super T>> void testImage(int dataType,
            boolean useROIAccessor, boolean isBinary, boolean bicubic2Disabled,
            boolean noDataRangeUsed, boolean roiPresent, InterpolationType interpType,
            TestSelection testSelect, ScaleType scaleValue) {

        Number noDataValue = getNoDataValueFor(dataType);

        testImage(dataType, useROIAccessor, isBinary, noDataRangeUsed, roiPresent, interpType,
                testSelect,
                scaleValue, noDataValue);

    }

    protected void testImage(int dataType, boolean useROIAccessor, boolean isBinary,
            boolean noDataRangeUsed, boolean roiPresent, InterpolationType interpType,
            TestSelection testSelect, ScaleType scaleValue, Number noDataValue) {
        RenderedImage sourceImage = createTestImage(dataType, DEFAULT_WIDTH, DEFAULT_HEIGHT, noDataValue,
                isBinary);

        testImage(dataType, noDataValue, useROIAccessor, isBinary, noDataRangeUsed, roiPresent,
                interpType,
                testSelect, scaleValue, sourceImage);
    }

    protected Number getNoDataValueFor(int dataType) {
        Number noDataValue;
        switch(dataType){
            case DataBuffer.TYPE_BYTE:
                noDataValue = (byte) 100;
                break;
            case DataBuffer.TYPE_USHORT:
                noDataValue = (short) (Short.MAX_VALUE - 1);
                break;
            case DataBuffer.TYPE_SHORT:
                noDataValue = (short) (-255);
                break;
            case DataBuffer.TYPE_INT:
                noDataValue = Integer.MAX_VALUE - 1;
                break;
            case DataBuffer.TYPE_FLOAT:
                noDataValue = -15.2f;
                break;
            case DataBuffer.TYPE_DOUBLE:
                noDataValue = Double.NEGATIVE_INFINITY;
                break;
            default:
                throw new IllegalArgumentException("Wrong data type " + dataType);

        }
        return noDataValue;
    }

    protected  void testImage(int dataType, Number noDataValue,
            boolean useROIAccessor, boolean isBinary, boolean noDataRangeUsed, boolean roiPresent,
            InterpolationType interpType, TestSelection testSelect,
            ScaleType scaleValue, RenderedImage sourceImage) {
        RenderedImage destinationIMG = testAndReturnImage(dataType, noDataValue, useROIAccessor,
                isBinary, noDataRangeUsed, roiPresent,
                interpType, testSelect, scaleValue, sourceImage);

        //Final Image disposal
        if(destinationIMG instanceof RenderedOp){
            ((RenderedOp)destinationIMG).dispose();
        }
    }

    protected RenderedImage testAndReturnImage(int dataType, Number noDataValue,
            boolean useROIAccessor, boolean isBinary, boolean noDataRangeUsed, boolean roiPresent,
            InterpolationType interpType, TestSelection testSelect,
            ScaleType scaleValue, RenderedImage sourceImage) {
        if (scaleValue == ScaleType.REDUCTION) {
            scaleX = 0.5f;
            scaleY = 0.5f;
        } else {
            scaleX = 1.5f;
            scaleY = 1.5f;
        }

        // No Data Range
        if (isBinary) {
            // destination no data Value
            destinationNoData = 0;
        } else {
            // destination no data Value
            destinationNoData = 255;
        }
        Range noDataRange = null;
        if (noDataRangeUsed && !isBinary) {
            switch(dataType){
            case DataBuffer.TYPE_BYTE:
                noDataRange = RangeFactory.create(noDataValue.byteValue(), true, noDataValue.byteValue(), true);
                break;
            case DataBuffer.TYPE_USHORT:
                noDataRange = RangeFactory.create(noDataValue.shortValue(), true, noDataValue.shortValue(), true);
                break;
            case DataBuffer.TYPE_SHORT:
                noDataRange = RangeFactory.create(noDataValue.shortValue(), true, noDataValue.shortValue(), true);
                break;
            case DataBuffer.TYPE_INT:
                noDataRange = RangeFactory.create(noDataValue.intValue(), true, noDataValue.intValue(), true);
                break;
            case DataBuffer.TYPE_FLOAT:
                noDataRange = RangeFactory.create(noDataValue.floatValue(), true, noDataValue.floatValue(), true,true);
                break;
            case DataBuffer.TYPE_DOUBLE:
                noDataRange = RangeFactory.create(noDataValue.doubleValue(), true, noDataValue.doubleValue(), true,true);
                break;
                default:
                    throw new IllegalArgumentException("Wrong data type");

            }
        }

        // ROI
        ROIShape roi = null;

        if (roiPresent) {
            roi = roiCreation();
        }

        // Hints are used only with roiAccessor
        RenderingHints hints = null;

        if (useROIAccessor) {
            hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                    BorderExtender.createInstance(BorderExtender.BORDER_ZERO));
        }

        // Interpolator initialization
        Interpolation interp = null;

        // Interpolators
        switch (interpType) {
        case NEAREST_INTERP:
            // Nearest-Neighbor
            interp = new javax.media.jai.InterpolationNearest();
            break;
        case BILINEAR_INTERP:
            // Bilinear
            interp = new javax.media.jai.InterpolationBilinear(DEFAULT_SUBSAMPLE_BITS);

            if (hints != null) {
                hints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, BorderExtender
                        .createInstance(BorderExtender.BORDER_COPY)));
            } else {
                hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                        BorderExtender.createInstance(BorderExtender.BORDER_COPY));
            }

            break;
        case BICUBIC_INTERP:
            // Bicubic
            interp = new javax.media.jai.InterpolationBicubic(DEFAULT_SUBSAMPLE_BITS);

            if (hints != null) {
                hints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, BorderExtender
                        .createInstance(BorderExtender.BORDER_COPY)));
            } else {
                hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                        BorderExtender.createInstance(BorderExtender.BORDER_COPY));
            }

            break;
        default:
            break;
        }

        // Background
        double[] bkg = new double[]{destinationNoData};

        // Scale operation
        RenderedImage destinationIMG = ScaleDescriptor.create(sourceImage, scaleX, scaleY,
                transX, transY, interp, roi, useROIAccessor, noDataRange, bkg, hints);

        if (INTERACTIVE && dataType == DataBuffer.TYPE_BYTE
                && TEST_SELECTOR == testSelect.getType() && INVERSE_SCALE == scaleValue.getType()) {
            RenderedImageBrowser.showChain(destinationIMG, false, roiPresent);
            try {
                System.in.read();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            // image tile calculation for searching possible errors
            ((PlanarImage) destinationIMG).getTiles();
        }

        // Check minimum and maximum value for a tile
        Raster simpleTile = destinationIMG.getTile(destinationIMG.getMinTileX(),
                destinationIMG.getMinTileY());

        int tileWidth = simpleTile.getWidth();
        int tileHeight = simpleTile.getHeight();

        switch (dataType) {
        case DataBuffer.TYPE_BYTE:
        case DataBuffer.TYPE_USHORT:
        case DataBuffer.TYPE_SHORT:
        case DataBuffer.TYPE_INT:
            if (!isBinary) {
                int minValue = Integer.MAX_VALUE;
                int maxValue = Integer.MIN_VALUE;

                for (int i = 0; i < tileHeight; i++) {
                    for (int j = 0; j < tileWidth; j++) {
                        int value = simpleTile.getSample(j, i, 0);
                        if (value > maxValue) {
                            maxValue = value;
                        }

                        if (value < minValue) {
                            minValue = value;
                        }
                    }
                }
                // Check if the values are not max and minimum value
                assertNotEquals(minValue, maxValue);
                assertNotEquals(minValue, Integer.MAX_VALUE);
                assertNotEquals(maxValue, Integer.MIN_VALUE);
            }
            break;
        case DataBuffer.TYPE_FLOAT:
            float minValuef = Float.MAX_VALUE;
            float maxValuef = -Float.MAX_VALUE;

            for (int i = 0; i < tileHeight; i++) {
                for (int j = 0; j < tileWidth; j++) {
                    float valuef = simpleTile.getSample(j, i, 0);

                    if(Float.isNaN(valuef)||valuef==Float.POSITIVE_INFINITY||valuef==Float.POSITIVE_INFINITY){
                        valuef=255;
                    }

                    if (valuef > maxValuef) {
                        maxValuef = valuef;
                    }

                    if (valuef < minValuef) {
                        minValuef = valuef;
                    }
                }
            }
            // Check if the values are not max and minimum value
            assertFalse((int) minValuef == (int) maxValuef);
            assertFalse(minValuef == Float.MAX_VALUE);
            assertFalse(maxValuef == -Float.MAX_VALUE);
            break;
        case DataBuffer.TYPE_DOUBLE:
            double minValued = Double.MAX_VALUE;
            double maxValued = -Double.MAX_VALUE;

            for (int i = 0; i < tileHeight; i++) {
                for (int j = 0; j < tileWidth; j++) {
                    double valued = simpleTile.getSampleDouble(j, i, 0);

                    if(Double.isNaN(valued)||valued==Double.POSITIVE_INFINITY||valued==Double.POSITIVE_INFINITY){
                        valued=255;
                    }

                    if (valued > maxValued) {
                        maxValued = valued;
                    }

                    if (valued < minValued) {
                        minValued = valued;
                    }
                }
            }
            // Check if the values are not max and minimum value
            assertFalse((int) minValued == (int) maxValued);
            assertFalse(minValued == Double.MAX_VALUE);
            assertFalse(maxValued == -Double.MAX_VALUE);
            break;
        default:
            throw new IllegalArgumentException("Wrong data type");
        }

        // Control if the ROI has been expanded
        PlanarImage planarIMG = (PlanarImage) destinationIMG;
        int imgWidthROI = destinationIMG.getWidth() * 3 / 4 - 1;
        int imgHeightROI = destinationIMG.getHeight() * 3 / 4 - 1;

        int tileInROIx = planarIMG.XToTileX(imgWidthROI);
        int tileInROIy = planarIMG.YToTileY(imgHeightROI);

        Raster testTile = destinationIMG.getTile(tileInROIx, tileInROIy);

        switch (dataType) {
        case DataBuffer.TYPE_BYTE:
        case DataBuffer.TYPE_USHORT:
        case DataBuffer.TYPE_SHORT:
        case DataBuffer.TYPE_INT:
            if (!isBinary) {
                int value = testTile.getSample(testTile.getMinX() + 2, testTile.getMinY() + 1, 0);
                assertFalse(value == (int) destinationNoData);
            }
            break;
        case DataBuffer.TYPE_FLOAT:
            float valuef = testTile.getSampleFloat(testTile.getMinX() + 2, testTile.getMinY() + 1,
                    0);
            assertFalse((int) valuef == (int) destinationNoData);
            break;
        case DataBuffer.TYPE_DOUBLE:
            double valued = testTile.getSampleDouble(testTile.getMinX() + 2,
                    testTile.getMinY() + 1, 0);

            assertFalse(valued == destinationNoData);
            break;
        default:
            throw new IllegalArgumentException("Wrong data type");
        }

        // Forcing to retrieve an array of all the image tiles
        // Control if the scale operation has been correctly performed
        // width
        assertEquals((int) (DEFAULT_WIDTH * scaleX), destinationIMG.getWidth());
        // height
        assertEquals((int) (DEFAULT_HEIGHT * scaleY), destinationIMG.getHeight());
        return destinationIMG;
    }

    public void assertNoDataBleedByte(Interpolation interpolation) {
        final byte constant = (byte) (0xff & 255);
        RenderedImage source = getConstantImage(10, 10, new Byte[] {constant});
        assertNoDataBleed(interpolation, source, 255);
    }

    public void assertNoDataBleedShort(Interpolation interpolation) {
        final short constant = (short) (0xffff & 65535);
        RenderedImage source = getConstantImage(10, 10, new Short[] {constant});
        assertNoDataBleed(interpolation, source, constant);
    }

    public void assertNoDataBleedFloat(Interpolation interpolation) {
        final float constant = 65535;
        RenderedImage source = getConstantImage(10, 10, new Float[] {constant});
        assertNoDataBleed(interpolation, source, (int) constant);
    }

    public void assertNoDataBleedDouble(Interpolation interpolation) {
        final double constant = 65535;
        RenderedImage source = getConstantImage(10, 10, new Double[] {constant});
        assertNoDataBleed(interpolation, source, (int) constant);
    }

    private void assertNoDataBleed(Interpolation interpolation, RenderedImage source, int expectedValue) {
        RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,BorderExtender.createInstance(BorderExtender.BORDER_COPY));
        RenderedImage scaled= ScaleDescriptor.create(source, 2f, 2f,
                0f, 0f, interpolation, null, null, RangeFactory.create(0, 0), null, hints);
        // make sure all pixels are solid like the input ones
        Raster raster = scaled.getData();
        for (int i = raster.getMinY(); i < raster.getMinY() + raster.getHeight(); i++) {
            for (int j = raster.getMinX(); j < raster.getMinX() + raster.getWidth(); j++) {
                int value = raster.getSample(j, i, 0);
                assertEquals("Unexpected value at " + i + ", " + j + ": " + value, expectedValue, value);
            }
        }
    }

    protected RenderedImage getConstantImage(float width, float height, Number[] values) {
        ParameterBlock pb = new ParameterBlock();
        pb.add(width);
        pb.add(height);
        pb.add(values);
        return JAI.create("constant", pb);
    }

    protected void assertInterpolateInHole(Interpolation interpolation) {
        assertInterpolateInHole(DataBuffer.TYPE_BYTE, interpolation);
        assertInterpolateInHole(DataBuffer.TYPE_USHORT, interpolation);
    }

    protected void assertInterpolateInHole(int dataType, Interpolation interpolation) {
        // build image with high ring at borders and almost nodata in the middle
        SampleModel sm = new ComponentSampleModel(dataType, 10, 10, 1, 10, new int[] {0});
        int width = 10;
        int height = 10;
        TiledImage source = new TiledImage(0, 0, 10, 10, 0, 0, sm, PlanarImage.createColorModel(sm));
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if(x == 0 || x == (width - 1) || y == 0 || y == (height - 1)) {
                    source.setSample(x, y, 0, 255);
                } else {
                    source.setSample(x, y, 0, 1);
                }

            }
        }
        RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,BorderExtender.createInstance(BorderExtender.BORDER_COPY));
        RenderedImage scaled= ScaleDescriptor.create(source, 2f, 2f,
                0f, 0f, interpolation, null, null, RangeFactory.create(0, 0), null, hints);
        // make sure none of the pixels became 0
        Raster raster = scaled.getData();
        for (int i = raster.getMinY(); i < raster.getMinY() + raster.getHeight(); i++) {
            for (int j = raster.getMinX(); j < raster.getMinX() + raster.getWidth(); j++) {
                int value = raster.getSample(j, i, 0);
                assertTrue("Expected valid value but found nodata", value > 0);
            }
        }
    }

    /**
     * Build a 4x4 image with pixels having value as the sum of their coordinates, attaches
     * a ROI covering the 4 central pixels, and scales up by a factor of 2 with the given interpolation
     * @param dataType
     * @return
     */
    protected RenderedImage buildImageWithROI(int dataType, Interpolation interpolation, boolean useROIAccessor, Range noData) {

        int width = 4;
        int height = 4;
        SampleModel sm = new ComponentSampleModel(dataType, width, height, 1, width, new int[] {0});
        TiledImage source =
                new TiledImage(0, 0, width, height, 0, 0, sm, PlanarImage.createColorModel(sm));
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                source.setSample(x, y, 0, x + y);
            }
        }

        // build a ROI covering the center of the image and associate
        ROI roi = new ROIShape(new Rectangle(1, 1, 2, 2));
        RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,BorderExtender.createInstance(BorderExtender.BORDER_COPY));
        hints.put(JAI.KEY_IMAGE_LAYOUT, new ImageLayout(0, 0, width * 2, height * 2, 0, 0, width * 2, height * 2, null, null));
        return ScaleDescriptor.create(source, 2f, 2f, 0f, 0f, interpolation, roi, useROIAccessor, noData, new double[] {0}, hints);
    }

    protected void testPackedImage(InterpolationType interpolation) {
        boolean roiPresent = true;
        boolean noDataRangeUsed = true;
        boolean useROIAccessor = true;
        Number noData = 3;
        Number validData = 1;

        int[] dataTypes =
                new int[] {DataBuffer.TYPE_BYTE, DataBuffer.TYPE_USHORT, DataBuffer.TYPE_INT};

        for (ScaleType scaleType : ScaleType.values()) {
            for (int dataType : dataTypes) {
                MultiPixelPackedSampleModel sm =
                        new MultiPixelPackedSampleModel(dataType, DEFAULT_WIDTH, DEFAULT_HEIGHT, 2);
                RenderedImage image =
                        createTestImage(DEFAULT_WIDTH, DEFAULT_HEIGHT, 0, 1, validData, sm);
                testImage(
                        image.getSampleModel().getDataType(),
                        noData,
                        useROIAccessor,
                        false,
                        noDataRangeUsed,
                        roiPresent,
                        interpolation,
                        TestSelection.ROI_ACCESSOR_NO_DATA,
                        scaleType,
                        image);
            }
        }
    }

    protected void testNoDataOutput(InterpolationType interpolation) {
        boolean roiPresent = true;
        boolean useROIAccessor = true;
        Number noData = 3;

        int[] dataTypes =
                new int[] {DataBuffer.TYPE_BYTE, DataBuffer.TYPE_USHORT, DataBuffer.TYPE_INT};
        for (ScaleType scaleType : ScaleType.values()) {
            for (int dataType : dataTypes) {
                Number[] noDataValues = new Number[] {null, getNoDataValueFor(dataType)};
                for (Number noDataValue : noDataValues) {

                    RenderedImage source = createTestImage(dataType, DEFAULT_WIDTH, DEFAULT_HEIGHT, noDataValue, false);
                    RenderedImage result = testAndReturnImage(
                            dataType,
                            noData,
                            useROIAccessor,
                            false,
                            noDataValue != null,
                            roiPresent,
                            interpolation,
                            TestSelection.ROI_ACCESSOR_NO_DATA,
                            scaleType,
                            source);

                    // right now it's using the background data as destination nodata... believe
                    // this is wrong, but won't get down this alley for now as it would require
                    // reviewing and changing many jai-ext operations
                    checkNoData(result, noDataValue == null ? null: 255);

                    ((RenderedOp) result).dispose();
                }

            }
        }
    }

    private void checkNoData(RenderedImage result, Number noDataValue) {
        Object property = result.getProperty(NoDataContainer.GC_NODATA);
        if (noDataValue != null) {
            assertThat(property, instanceOf(NoDataContainer.class));
            NoDataContainer container = (NoDataContainer) property;
            assertEquals(noDataValue.doubleValue(), container.getAsSingleValue(), 0d);
        } else {
            assertEquals(property, Image.UndefinedProperty);
        }
    }

    protected void testROILayout(int interpolation) {
        testROILayout(DataBuffer.TYPE_BYTE, interpolation);
        testROILayout(DataBuffer.TYPE_USHORT, interpolation);
        testROILayout(DataBuffer.TYPE_SHORT, interpolation);
        testROILayout(DataBuffer.TYPE_INT, interpolation);
        testROILayout(DataBuffer.TYPE_FLOAT, interpolation);
        testROILayout(DataBuffer.TYPE_DOUBLE, interpolation);
    }

    protected void testROILayout(int dataType, int interpolationType) {
        RenderedImage testIMG = createTestImage(dataType, 1, 1, null,
                false);
        PlanarImage testImgWithROI = PlanarImage.wrapRenderedImage(testIMG);
        ROIShape roi = new ROIShape(new Rectangle(0, 0, 1, 1));
        testImgWithROI.setProperty("roi", roi);

        ImageLayout targetLayout = new ImageLayout();
        targetLayout.setTileWidth(512);
        targetLayout.setTileHeight(512);
        RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, targetLayout);
        RenderedOp scaled = ScaleDescriptor.create(testIMG, 1000f, 1000f, 0f, 0f,
                Interpolation.getInstance(interpolationType), roi, false, null, null,
                hints);
        ROI scaledRoi = (ROI) scaled.getProperty("roi");

        // ROI is aligned withe the image and has the expected tile size
        assertEquals(scaled.getBounds(), scaledRoi.getBounds());
        PlanarImage scaleRoiImage = scaledRoi.getAsImage();
        assertEquals(scaled.getTileHeight(), scaleRoiImage.getTileHeight());
        assertEquals(scaled.getTileWidth(), scaleRoiImage.getTileWidth());
        assertEquals(512, scaleRoiImage.getTileWidth());
        assertEquals(512, scaleRoiImage.getTileHeight());
    }
}


text:
IKinectEngagementManager.KinectManualEngagedHands Property
==========================================================

Gets the list of the body/hand pairs that have been manually set as engaged.

Syntax
======

<colgroup>
<col width="100%" />
</colgroup>

C++

public:
property IVectorView<BodyHandPair>^ KinectManualEngagedHands {
         IVectorView<BodyHandPair>^ get ();
}

<colgroup>
<col width="100%" />
</colgroup>

C#

public IReadOnlyList<BodyHandPair>KinectManualEngagedHands { get; }

#### Property value

[C++]
 [C\#]

Type: [IVectorView](http://msdn.microsoft.com/en-us/library/br226058.aspx)\<[BodyHandPair](../../../Kinect.Input/BodyHandPair_Class.md)\>
Type: [IReadOnlyList](http://msdn.microsoft.com/en-us/library/hh192385.aspx)\<[BodyHandPair](../../../Kinect.Input/BodyHandPair_Class.md)\>

The list of the body/hand pairs that have been manually set as engaged.

Remarks
=======

Requirements
============

**Namespace:**Microsoft.Kinect.Toolkit.Input
**Assembly:** (in )

See also
========

#### Reference

[IKinectEngagementManager Interface](../../IKinectEngagementManager.md)
 [Microsoft.Kinect.Toolkit.Input Namespace](../../../Kinect.Toolkit.Input.md)


text:
namespace ChordsKaraoke.Editor.ViewModels.Commands
{
    public class SaveTimelineAsCommand : ViewModelCommand<TimelineViewModel>
    {
        public SaveTimelineAsCommand(TimelineViewModel model)
            : base(model)
        {
        }

        public override void Execute(object parameter)
        {
            ViewModel.SaveFile(null);
        }
    }
}


text:
This will give you the basic overview of writing base level functions. You can also use higher level
abstractions that make it easier such as [lambda](lambda/README.md).

Also, for complete examples in various languages, see the [examples directory](/examples).
We have language libraries for [Go](https://github.com/iron-io/functions_go), [Javascript](https://github.com/iron-io/functions_js) and
[Ruby](https://github.com/iron-io/functions_ruby).

## Code

The most basic code layout in any language is as follows, this is pseudo code and is not meant to run.

```ruby
# Read and parse from STDIN
body = JSON.parse(STDIN)

# Do something
return_struct = doSomething(body)

# Respond if sync:
STDOUT.write(JSON.generate(return_struct))
# or update something if async
db.update(return_struct)
```

## Inputs

Inputs are provided through standard input and environment variables. We'll just talk about the default input format here, but you can find others [here](function-format.md).
To read in the function body, just read from STDIN.

You will also have access to a set of environment variables.

* REQUEST_URL - the full URL for the request
* ROUTE - the matched route
* METHOD - the HTTP method for the request
* HEADER_X - the HTTP headers that were set for this request. Replace X with the upper cased name of the header and replace dashes in the header with underscores.
* X - any configuration values you've set for the Application or the Route. Replace X with the upper cased name of the config variable you set. Ex: `minio_secret=secret` will be exposed via MINIO_SECRET env var

Warning: these may change before release.

## Logging

Standard out is where you should write response data for synchronous functions. Standard error
is where you should write for logging, as [it was intended](http://www.jstorimer.com/blogs/workingwithcode/7766119-when-to-use-stderr-instead-of-stdout).

So to write output to logs, simply log to STDERR. Here are some examples in a few languages.

In Go, simply use the [log](https://golang.org/pkg/log/) package, it writes to STDERR by default.

```go
log.Println("hi")
```

In Node.js:

```node
console.error("hi");
```

[More details for Node.js here](http://stackoverflow.com/a/27576486/105562).

In Ruby:

```ruby
STDERR.puts("hi")
```

## Next Steps

* [Packaging your function](packaging.md)


text:
require_relative '../../model/message'
require_relative 'service_renderer_helper'
require 'htmlentities'

class GitlabRenderer

  attr_accessor :verbose

  def initialize(verbose)
    @verbose = verbose
  end

  include ServiceRendererHelper

  def process_event(event)
    d = event.data

    ret = Message.new
    ret.header = HTMLEntities.new.decode d.title.gsub(/<\/?[^>]*>/, "").strip.gsub(/\n/, " ").gsub(/  /, " ")
    if d.summary.nil?
      ret.content = ""
    else
      ret.content = HTMLEntities.new.decode d.summary.gsub(/<\/?[^>]*>/, "").strip.gsub(/\n/, "").gsub(/  /, " ")
    end

    ret
  end

end


text:
class Hypergraph;
class SentenceMetadata;

// Workflow: for each sentence to be translated
//   1) call ProcessMarkupHints(markup)
//   2) call Translate(...)
//   3) call SentenceComplete()
class Translator {
 public:
  Translator() : state_(kUninitialized) {}
  virtual ~Translator();
  // returns true if goal reached, false otherwise
  // minus_lm_forest will contain the unpruned forest. the
  // feature values from the phrase table / grammar / etc
  // should be in the forest already - the "late" features
  // should not just copy values that are available without
  // any context or computation.
  // SentenceMetadata contains information about the sentence,
  // but it is an input/output parameter since the Translator
  // is also responsible for setting the value of src_len.
  bool Translate(const std::string& src,
                 SentenceMetadata* smeta,
                 const std::vector<double>& weights,
                 Hypergraph* minus_lm_forest);

  // This is called before Translate(...) with the sentence-
  // level markup passed in. This can be used to set sentence-
  // specific behavior of the translator.
  void ProcessMarkupHints(const std::map<std::string, std::string>& kv);

  // Free any sentence-specific resources
  void SentenceComplete();
 protected:
  virtual bool TranslateImpl(const std::string& src,
                             SentenceMetadata* smeta,
                             const std::vector<double>& weights,
                             Hypergraph* minus_lm_forest) = 0;
  virtual void ProcessMarkupHintsImpl(const std::map<std::string, std::string>& kv);
  virtual void SentenceCompleteImpl();
 private:
  enum State { kUninitialized, kReadyToTranslate, kTranslated };
  State state_;
};

class SCFGTranslatorImpl;
class SCFGTranslator : public Translator {
 public:
  SCFGTranslator(const boost::program_options::variables_map& conf);
 protected:
  bool TranslateImpl(const std::string& src,
                 SentenceMetadata* smeta,
                 const std::vector<double>& weights,
                 Hypergraph* minus_lm_forest);
  void ProcessMarkupHintsImpl(const std::map<std::string, std::string>& kv);
  void SentenceCompleteImpl();
 private:
  boost::shared_ptr<SCFGTranslatorImpl> pimpl_;
};

class FSTTranslatorImpl;
class FSTTranslator : public Translator {
 public:
  FSTTranslator(const boost::program_options::variables_map& conf);
 private:
  bool TranslateImpl(const std::string& src,
                 SentenceMetadata* smeta,
                 const std::vector<double>& weights,
                 Hypergraph* minus_lm_forest);
 private:
  boost::shared_ptr<FSTTranslatorImpl> pimpl_;
};

#endif


text:
package com.gynt.mex;

public class Main {

	public static void main(String[] args) {
		System.out.println(1 << 7);
		System.out.println((short) (0xF << 12));
		System.out.println(Integer.toBinaryString((short) (0x0F << 12)));
		System.out.println(Integer.toBinaryString(750));
	}

}


text:
<!DOCTYPE html>

    <title>Hunter and Thief</title>
    <link rel="stylesheet" type="text/css" href="ht.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet">
    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="navbar.css" rel="stylesheet" type="text/css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
   <link href='http://fonts.googleapis.com/css?family=Economica' rel='stylesheet' type='text/css'>

Hunters and Thieves

About

Code

Tutorial

Login Name:

	        <form id="dif" class = "dif" action = "" onsubmit="return setNickname()">
        	<input class = "input" id = "nickNames" placeholder = "Enter Nickname.."/>

	        </form>

Currently Logged in as:

Lobby Room

Users Online

                <form name="chatsubmit"  onsubmit="return inputMessage()">
                <input id="chatinput" name="chatinput" placeholder="Insert Message here"/>
                </form>


text:
from __future__ import absolute_import, unicode_literals
from gaebusiness.business import CommandExecutionException
from tekton.gae.middleware.json_middleware import JsonResponse
from litestrangeira_app import facade

def index():
    cmd = facade.list_litestrangeiras_cmd()
    litestrangeira_list = cmd()
    short_form=facade.litestrangeira_short_form()
    litestrangeira_short = [short_form.fill_with_model(m) for m in litestrangeira_list]
    return JsonResponse(litestrangeira_short)

def save(**litestrangeira_properties):
    cmd = facade.save_litestrangeira_cmd(**litestrangeira_properties)
    return _save_or_update_json_response(cmd)

def update(litestrangeira_id, **litestrangeira_properties):
    cmd = facade.update_litestrangeira_cmd(litestrangeira_id, **litestrangeira_properties)
    return _save_or_update_json_response(cmd)

def delete(litestrangeira_id):
    facade.delete_litestrangeira_cmd(litestrangeira_id)()

def _save_or_update_json_response(cmd):
    try:
        litestrangeira = cmd()
    except CommandExecutionException:
        return JsonResponse({'errors': cmd.errors})
    short_form=facade.litestrangeira_short_form()
    return JsonResponse(short_form.fill_with_model(litestrangeira))


text:
import _ from 'lodash';
import bcrypt from 'bcrypt';
import { HTTPError } from 'netiam-errors';
import moment from 'moment';
import {
  OAUTH_INVALID_CREDENTIALS,
  OAUTH_INVALID_PASSWORD,
  OAUTH_PASSWORD_MISSING,
  OAUTH_USERNAME_MISSING
} from '../errors';

const TOKEN_TYPE_ACCESS = 'access_token';
const TOKEN_TYPE_REFRESH = 'refresh_token';

const ACCESS_TOKEN_TYPE_BEARER = 'bearer';

export default function({
  req,
  res,
  userModel,
  tokenModel,
  usernameField,
  passwordField,
  tokenField,
  accessTokenTTL,
  refreshTokenTTL
}) {
  const { username, password, scope, state } = req.body;

  if (!_.isString(username) || username.length === 0) {
    return Promise.reject(new HTTPError(OAUTH_USERNAME_MISSING));
  }

  if (!_.isString(password) || password.length === 0) {
    return Promise.reject(new HTTPError(OAUTH_PASSWORD_MISSING));
  }

  return userModel.findOne({ where: { [usernameField]: username } }).then(async (user) => {
    if (!user) return Promise.reject(new HTTPError(OAUTH_INVALID_CREDENTIALS));

    const match = await bcrypt.compare(password, user[passwordField]);
    if (!match) return Promise.reject(new HTTPError(OAUTH_INVALID_PASSWORD));

    const accessToken = tokenModel.create({
      type: TOKEN_TYPE_ACCESS,
      expires_at: moment()
        .add(accessTokenTTL, 'hours')
        .format(),
      ownerId: user.id
    });
    const refreshToken = tokenModel.create({
      type: TOKEN_TYPE_REFRESH,
      expires_at: moment()
        .add(refreshTokenTTL, 'days')
        .format(),
      ownerId: user.id
    });

    return Promise.all([accessToken, refreshToken]).then((tokens) => {
      const [accessToken, refreshToken] = tokens;
      res.body = {
        access_token: accessToken[tokenField],
        refresh_token: refreshToken[tokenField],
        token_type: ACCESS_TOKEN_TYPE_BEARER,
        expires_in: moment(accessToken.expires_at).diff(moment(), 'seconds'),
        user_id: user.id
      };
    });
  });
}


text:
'use strict';

var _datahub = require('./datahub');

var _datahub2 = _interopRequireDefault(_datahub);

var _hubWatcher = require('./hub-watcher');

var _hubWatcher2 = _interopRequireDefault(_hubWatcher);

var _hubForwarder = require('./hub-forwarder');

var _hubForwarder2 = _interopRequireDefault(_hubForwarder);

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

module.exports = _datahub2.default;
module.exports.HubWatcher = _hubWatcher2.default;
module.exports.HubForwarder = _hubForwarder2.default;


text:
layout: base
title:  'Statistics of root in UD_Nayini-AHA'
udver: '2'
---

## Treebank Statistics: UD_Nayini-AHA: Relations: `root`

This relation is universal.

10 nodes (13%) are attached to their parents as `root`.

10 instances of `root` (100%) are left-to-right (parent precedes child).
Average distance between parent and child is 5.1.

The following 1 pairs of parts of speech are connected with `root`: -<tt>VERB</tt> (10; 100% instances).

~~~ conllu
# visual-style 4	bgColor:blue
# visual-style 4	fgColor:white
# visual-style 0	bgColor:blue
# visual-style 0	fgColor:white
# visual-style 0 4 root	color:blue
1	عبدولو	عبدولو	NOUN	N_SING	Number=Sing	4	nsubj	_	_
2	فردا	فردا	ADV	ADV	_	4	advmod	_	_
3	صحبی	صحب	NOUN	N_SING	Number=Sing	2	nmod	_	_
4	شو	ش	VERB	V_PRS	Number=Sing|Person=3|Tense=Pres	0	root	_	SpaceAfter=No
5	.	.	PUNCT	DELM	_	4	punct	_	_

~~~


text:
package org.bitcoins.core.util

import org.bitcoins.core.crypto.ECPrivateKeyUtil
import org.bitcoins.core.protocol.blockchain._
import org.bitcoins.crypto.CryptoUtil
import scodec.bits.ByteVector

import scala.annotation.tailrec
import scala.util.{Failure, Success, Try}

/** Created by chris on 5/16/16.
  * source of values: [[https://en.bitcoin.it/wiki/Base58Check_encoding]]
  */
sealed abstract class Base58 {
  import Base58Type._

  val base58Characters =
    "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
  val base58Pairs: Map[Char, Int] = base58Characters.zipWithIndex.toMap

  /** Verifies a given [[org.bitcoins.core.protocol.blockchain.Base58Type Base58Type]]
    * string against its checksum (last 4 decoded bytes).
    */
  def decodeCheck(input: String): Try[ByteVector] = {
    val decodedTry: Try[ByteVector] = Try(decode(input))
    decodedTry.flatMap { decoded =>
      if (decoded.length < 4)
        Failure(new IllegalArgumentException("Invalid input"))
      else {
        val splitSeqs = decoded.splitAt(decoded.length - 4)
        val data: ByteVector = splitSeqs._1
        val checksum: ByteVector = splitSeqs._2
        val actualChecksum: ByteVector =
          CryptoUtil.doubleSHA256(data).bytes.take(4)
        if (checksum == actualChecksum) Success(data)
        else Failure(new IllegalArgumentException("checksums don't validate"))
      }
    }
  }

  /** Encodes a sequence of bytes to a [[org.bitcoins.core.protocol.blockchain.Base58Type Base58Type]] string. */
  def encode(bytes: ByteVector): String = {
    val ones: String = bytes.toSeq.takeWhile(_ == 0).map(_ => '1').mkString
    @tailrec
    def loop(current: BigInt, str: String): String =
      current match {
        case _ if current == BigInt(0) =>
          ones + str.reverse
        case _: BigInt =>
          val quotient: BigInt = current / BigInt(58L)
          val remainder: BigInt = current.mod(58L)
          val char = base58Characters.charAt(remainder.toInt).toString
          val accum = str + char
          loop(quotient, accum)
      }
    if (bytes.isEmpty) ""
    else {
      val big: BigInt = BigInt(1, bytes.toArray)
      loop(big, "")
    }
  }

  /** Encodes a hex string to its [[org.bitcoins.core.protocol.blockchain.Base58Type Base58Type]] representation. */
  def encode(hex: String): String = {
    val bytes = BytesUtil.decodeHex(hex)
    encode(bytes)
  }

  /** Encodes a [[scala.Byte Byte]] to its
    * [[org.bitcoins.core.protocol.blockchain.Base58Type Base58Type]] representation.
    */
  def encode(byte: Byte): String = encode(ByteVector.fromByte(byte))

  /** Takes in [[org.bitcoins.core.protocol.blockchain.Base58Type Base58Type]]
    * string and returns sequence of [[scala.Byte Byte]]s.
    * [[https://github.com/ACINQ/bitcoin-lib/blob/master/src/main/scala/fr/acinq/bitcoin/Base58.scala]]
    */
  def decode(input: String): ByteVector = {
    val zeroes = ByteVector(input.takeWhile(_ == '1').map(_ => 0: Byte))
    val trim = input.dropWhile(_ == '1').toList
    val decoded = trim.foldLeft(BigInt(0))((a, b) =>
      a.*(BigInt(58L)).+(BigInt(base58Pairs(b))))
    if (trim.isEmpty) zeroes
    else zeroes ++ ByteVector(decoded.toByteArray.dropWhile(_ == 0))
  }

  /** Determines if a string is a valid [[org.bitcoins.core.protocol.blockchain.Base58Type Base58Type]] string. */
  def isValid(base58: String): Boolean =
    validityChecks(base58) match {
      case Success(bool) => bool
      case Failure(_)    => false
    }

  /** Checks a private key that begins with a symbol corresponding that private key to a compressed public key ('K', 'L', 'c').
    * In a Base58-encoded private key corresponding to a compressed public key, the 5th-to-last byte should be 0x01.
    */
  private def checkCompressedPubKeyValidity(base58: String): Boolean = {
    val decoded = Base58.decode(base58)
    val compressedByte = decoded(decoded.length - 5)
    compressedByte == 0x01.toByte
  }

  /** Checks if the string begins with an Address prefix byte/character.
    * ('1', '3', 'm', 'n', '2')
    */
  private def isValidAddressPreFixByte(byte: Byte): Boolean = {
    val validAddressPreFixBytes: ByteVector =
      MainNetChainParams.base58Prefixes(PubKeyAddress) ++ MainNetChainParams
        .base58Prefixes(ScriptAddress) ++
        TestNetChainParams.base58Prefixes(PubKeyAddress) ++ TestNetChainParams
          .base58Prefixes(ScriptAddress)
    validAddressPreFixBytes.toSeq.contains(byte)
  }

  /** Checks if the string begins with a private key prefix byte/character.
    * ('5', '9', 'c')
    */
  private def isValidSecretKeyPreFixByte(byte: Byte): Boolean = {
    val validSecretKeyPreFixBytes: ByteVector =
      MainNetChainParams.base58Prefixes(SecretKey) ++ TestNetChainParams
        .base58Prefixes(SecretKey)
    validSecretKeyPreFixBytes.toSeq.contains(byte)
  }

  /** Checks the validity of a [[org.bitcoins.core.protocol.blockchain.Base58Type Base58Type]] string.
    * A [[org.bitcoins.core.protocol.blockchain.Base58Type Base58Type]] string must not contain ('0', 'O', 'l', 'I').
    * If the string is an address: it must have a valid address prefix byte and  must be between 26-35 characters in length.
    * If the string is a private key: it must have a valid private key prefix byte and must have a byte size of 32.
    * If the string is a private key corresponding to a compressed public key, the 5th-to-last byte must be 0x01.
    */
  private def validityChecks(base58: String): Try[Boolean] =
    Try {
      val decoded = decode(base58)
      val firstByte = decoded.head
      val compressedPubKey = List('K', 'L', 'c').contains(base58.head)
      val hasInvalidChar: Boolean = {
        Vector('0', 'O', 'l', 'I').exists(c => base58.contains(c))
      }
      if (hasInvalidChar) false
      else if (compressedPubKey) checkCompressedPubKeyValidity(base58)
      else if (isValidAddressPreFixByte(firstByte))
        base58.length >= 26 && base58.length <= 35
      else if (isValidSecretKeyPreFixByte(firstByte)) {
        val byteSize = ECPrivateKeyUtil.fromWIFToPrivateKey(base58).bytes.size
        byteSize == 32
      } else false
    }
}

object Base58 extends Base58


text:
#include "symbol_lookup.hpp"

#include "declaration.hpp"
#include "qual_type.hpp"
#include "type_base.hpp"
#include "package.hpp"

/* Notes on namespace / lookup semantics:

Private virtual can be truly virtual.
Public virtual is virtual, but referencing them without a base expression is non-polymorphic.

## Type resolution is virtual and non-polymorphic
Type . Type
SFIELD . Type  => decltype(SFIELD).TYPE
field . Type   => decltype(field).TYPE
ref . Type     => decltype(ref).TYPE

## The types of all the following are determined statically:
Type . SFIELD  ## of course non-polymorphic
Type . field   ## invalid; produces field's declared type

SFIELD . SFIELD  ## "polymorphic" (but statically known)
SFIELD . field   ## non-polymorphic

field . SFIELD  ## "polymorphic" (but statically known)
field . field   ## non-polymorphic

ref . SFIELD  ## polymorphic     (determined by the actual object type)
ref . field   ## non-polymorphic (determined by the declared type of ref)

*/

static const TxEntityDeclaration* get_symbols_declaration( TxEntitySymbol* entitySymbol ) {
    const TxEntityDeclaration* decl = entitySymbol->get_type_decl();
    if ( !decl ) {
        if ( !entitySymbol->is_overloaded() )
            decl = entitySymbol->get_first_field_decl();
        else
            // overloaded field, can't match
            return nullptr;
    }
    return decl;
}

static TxScopeSymbol* inner_search_symbol( TxScopeSymbol* vantageScope, const TxIdentifier& ident );

static TxScopeSymbol* get_explicit_outer( TxScopeSymbol* scope ) {
//    std::cout << "From '" << scope->get_full_name() << "': get_explicit_outer()" << std::endl;
    for ( auto outer = scope->get_outer(); outer; outer = outer->get_outer() ) {
//        std::cout << "     '" << scope->get_full_name() << "': get_explicit_outer()" << std::endl;
        // Note that we skip all code scopes (statement blocks) and only access type and module namespaces.
        if ( typeid( *outer ) != typeid( TxScopeSymbol ) ) {
            //LOG_INFO( scope->LOGGER(), "Substituting '#' with '" << outer << "'" );
            return outer;
        }
    }
    THROW_LOGIC( "Missing explicit outer scope" );
}

static TxScopeSymbol* special_lookup( TxScopeSymbol* scope, const std::string& name) {
    if ( name == "#" )
        return get_explicit_outer( scope );
    else if ( auto entScope = dynamic_cast<TxEntitySymbol*>( scope ) ) {
        if ( name.find( '#' ) != std::string::npos ) {
            // sought name is a hashified, fully qualified name (e.g. my#SType#E)
            auto fullName = dehashify( name );
            if ( auto hashedSym = inner_search_symbol( scope, TxIdentifier( fullName ) ) ) {
                if ( auto hashedEntSym = dynamic_cast<TxEntitySymbol*>( hashedSym ) ) {
                    if ( auto hashedDecl = get_symbols_declaration( hashedEntSym ) ) {
                        if ( hashedDecl->get_decl_flags() & TXD_GENPARAM ) {
                            // symbol distinctly (non-overloaded) refers to a GENPARAM
                            // Resolves e.g:  my#SType#E = my.SType.E  to binding  -P---- ---B--  my.$SType<tx#~Float,tx#~Double>.E
                            if ( auto thisDecl = get_symbols_declaration( entScope ) ) {
                                if ( auto thisType = thisDecl->get_definer()->qtype() ) {
                                    if ( auto bindingDecl = thisType->lookup_param_binding( hashedDecl ) ) {
                                        //scope->LOGGER()->debug( "Resolved %-16s = %-16s to binding\t%s", name.c_str(),
                                        //                         hashedSym->get_full_name().str().c_str(), bindingDecl->str().c_str() );
                                        return bindingDecl->get_symbol();
                                    }
                                }
                            }
                        }
                    }
                }
                return hashedSym;
            }
        }
    }
    return nullptr;
}

static inline TxScopeSymbol* inner_lookup_member( TxScopeSymbol* scope, const std::string& name ) {
    //std::cout << "From '" << scope->get_full_name() << "': inner_lookup_member(" << name << ")" << std::endl;
    return scope->get_member_symbol( name );
}

static TxScopeSymbol* inner_lookup_inherited_member( const TxActualType* type, const std::string& name ) {
    ASSERT( name != CONSTR_IDENT, "Can't look up constructors as *inherited* members; in: " << type );
    //std::cerr << "lookup_inherited_member(" << name << ")" << std::endl;
    for ( ; type; type = type->get_base_type() ) {
        if ( auto member = inner_lookup_member( type->get_declaration()->get_symbol(), name ) )
            return member;
        ASSERT( type->is_integrated(), "In inherited member lookup for '" << name << "' - type not integrated: " << type );
        for ( auto interf : type->get_interfaces() ) {
            if ( auto memberEnt = inner_lookup_inherited_member( interf, name ) )
                return memberEnt;
        }
    }
    return nullptr;
}

static TxScopeSymbol* inner_lookup_inherited_member( TxScopeSymbol* scope, const std::string& name )  {
    if ( auto symbol = inner_lookup_member( scope, name ) )
        return symbol;

    if ( auto entSym = dynamic_cast<TxEntitySymbol*>( scope ) ) {
        if ( const TxEntityDeclaration* entDecl = get_symbols_declaration( entSym ) ) {
            // Note: The starting scope might not be resolved at this point and we don't (and shouldn't need to) force-resolve it here.
            //       (since when e.g. resolving base types recursion error would occur)
            if ( auto qtype = entDecl->get_definer()->attempt_qtype() ) {
                if ( qtype->is_integrated() ) {
                    return inner_lookup_inherited_member( qtype.type(), name );
                }
                else {
                    //std::cerr << "In search for '" << name << "' - scope's type not integrated: " << qtype << std::endl;
                    return inner_lookup_member( qtype->get_declaration()->get_symbol(), name );
                }
            }
            //else
            //    std::cerr << "In search for '" << name << "' - scope's type not resolved: " << entDecl << std::endl;
        }
    }
    return nullptr;
}

static TxScopeSymbol* inner_search_name( TxScopeSymbol* vantageScope, const std::string& name ) {
    // Inherited symbols take precedence over symbols in outer namespaces.
    // As we search the lexical namespaces from inner-most and outwards, if the namespace is a type then look for inherited symbols.

    if ( auto sym = special_lookup( vantageScope, name ) )
        return sym;
    for ( auto scope = vantageScope; scope; scope = scope->get_outer() ) {
        if ( auto member = inner_lookup_inherited_member( scope, name ) ) {
            return member;
        }
        else if ( dynamic_cast<TxModule*>( scope ) ) {
            // member lookup within a module failed - skip parent modules and do global lookup via root namespace (package)
            return inner_lookup_member( scope->get_root_scope(), name );
        }
    }
    return nullptr;
}

/** (capable of searching for compound identifiers) */
static TxScopeSymbol* inner_search_symbol( TxScopeSymbol* vantageScope, const TxIdentifier& ident ) {
    auto member = inner_search_name( vantageScope, ident.segment( 0 ) );
    if ( member && !ident.is_plain() ) {
        TxIdentifier rest( ident, 1 );
        for ( auto it = rest.segments_cbegin(); it != rest.segments_cend(); ++it ) {
            member = inner_lookup_member( member, *it );
            if ( !member )
                break;
        }
        //return inner_lookup_member( member, TxIdentifier( ident, 1 ) );
    }
    return member;
}

TxScopeSymbol* lookup_member( TxScopeSymbol* vantageScope, TxScopeSymbol* scope, const std::string& name ) {
    auto symbol = special_lookup( scope, name );
    if ( !symbol )
        symbol = inner_lookup_member( scope, name );
    // FUTURE: implement visibility check
    return symbol;
}

TxScopeSymbol* lookup_inherited_member( TxScopeSymbol* vantageScope, TxScopeSymbol* scope, const std::string& name )  {
    auto symbol = special_lookup( scope, name );
    if ( !symbol )
        symbol = inner_lookup_inherited_member( scope, name );
    // FUTURE: implement visibility check
    return symbol;
}

TxScopeSymbol* lookup_inherited_member( TxScopeSymbol* vantageScope, const TxActualType* type, const std::string& name )  {
    auto symbol = special_lookup( type->get_declaration()->get_symbol(), name );
    if ( !symbol )
        symbol = inner_lookup_inherited_member( type, name );
    // FUTURE: implement visibility check
    return symbol;
}

TxScopeSymbol* search_name( TxScopeSymbol* vantageScope, const std::string& name ) {
    auto symbol = inner_search_name( vantageScope, name );
    // FUTURE: implement visibility check
    return symbol;
}

/** (capable of searching for compound identifiers) */
TxScopeSymbol* search_symbol( TxScopeSymbol* vantageScope, const std::string& identifier ) {
    auto symbol = inner_search_symbol( vantageScope, identifier );
    // FUTURE: implement visibility check
    return symbol;
}


text:
    <% if (tickets.length>0) { %>

            Requested tickets

            Section
            Category
            Quantity
            Price

        <% _.each(tickets, function (ticketRequest, index, tickets) { %>

            <%= ticketRequest.ticketPrice.section.name %>
            <%= ticketRequest.ticketPrice.ticketCategory.description %>
            <%= ticketRequest.quantity %>
            $<%=ticketRequest.ticketPrice.price%>
            <span class="glyphicon glyphicon-trash" data-index='<%= index %>'/>

        <% }); %>

Total ticket count: <%= totals.tickets %>

Total price: $<%=totals.price%>

    <% } else { %>
    No tickets requested.
    <% } %>