text:
var plask = require('plask');

// Renderer sets up shaders
// retains the gl and mprogram objects
var renderer = require('./lib/renderer');

var mesh = require('./lib/mesh');
var events = require('events');
var geom = require('./lib/geom');

// A scene object needs to be created to set up EventEmitter inheritance
// The scene acts as an event emitter, the lights, cameras and meshes can trigger events
// on the scene to emit updates without direct binding.
var scene = require('./lib/scene');
var sceneGraph = new scene();
var pglUtils = require('./lib/pgl-utils');

module.exports = {
    renderer : renderer,
    mesh : mesh,
    geom : geom,
    scene : sceneGraph,
    utils : pglUtils
};


text:
function edges = computeMeshEdges(faces)
%COMPUTEMESHEDGES Computes edges array from face array
%
%   EDGES = computeMeshEdges(FACES);
%
%   Example
%   computeMeshEdges
%
%   See also
%   meshes3d
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-06-28,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

if ~iscell(faces)
    % faces is given as numeric array,
    % all faces have same number of vertices, stored in nVF variable

    % compute total number of edges
    nFaces  = size(faces, 1);
    nVF     = size(faces, 2);
    nEdges  = nFaces * nVF;

    % create all edges (with double ones)
    edges = zeros(nEdges, 2);
    for i = 1:nFaces
        f = faces(i, :);
        edges(((i-1)*nVF+1):i*nVF, :) = [f' f([2:end 1])'];
    end

else
    % faces are given as a cell array, with possibly different number of
    % vertices
    nFaces  = length(faces);

    % compute number of edges
    nEdges = 0;
    for i = nFaces
        nEdges = nEdges + length(faces{i});
    end

    % allocate memory
    edges = zeros(nEdges, 2);
    ind = 0;

    % fillup edge array
    for i = 1:nFaces
        f = faces{i};
        nVF = length(f);
        edges(ind+1:ind+nVF, :) = [f' f([2:end 1])'];
        ind = ind + nVF;
    end

end

% keep only unique edges, and return sorted result
edges = sortrows(unique(sort(edges, 2), 'rows'));

redpajama_set_name: RedPajamaGithub


text:
package com.aspose.barcode.examples.barcode_image.rendering_features;

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import com.aspose.barcode.generation.BarcodeGenerator;
//ExStart: RenderBarcodeToPrinter
public class RenderBarcodeToPrinter {
	public static void main(String[] args) {
		// Create frame instance
		Frame f = new Frame();
		// Set frame size
		f.setSize(300, 300);
		// Create and add barcode instance to frame
		f.add(new RenderBarCode());
		// Display frame
		f.setVisible(true);
	}
}

class RenderBarCode extends java.awt.Canvas {
	public void paint(Graphics g) {
		BarcodeGenerator bb = new BarcodeGenerator(com.aspose.barcode.EncodeTypes.CODE_128, "1234567");

		BufferedImage bimg = (BufferedImage) bb.generateBarCodeImage();
		int w = bimg.getWidth();
		int h = bimg.getHeight();
		int[] rgb = new int[w * h];
		bimg.getRGB(0, 0, w, h, rgb, 0, w);

		if (rgb.length > 0) {
			System.out.println("RGB OK.");
		}
		g.drawImage(bimg, 0, 0, this);
	}

	public Dimension getPreferredSize() {
		return new Dimension(300, 300);
	}
}
//ExEnd: RenderBarcodeToPrinter


text:
import incrmprod = require( './index' );

// TESTS //

// The function returns an accumulator function...
{
	incrmprod( 3 ); // $ExpectType accumulator
}

// The compiler throws an error if the function is provided an argument which is not a number...
{
	incrmprod( '5' ); // $ExpectError
	incrmprod( true ); // $ExpectError
	incrmprod( false ); // $ExpectError
	incrmprod( null ); // $ExpectError
	incrmprod( undefined ); // $ExpectError
	incrmprod( [] ); // $ExpectError
	incrmprod( {} ); // $ExpectError
	incrmprod( ( x: number ): number => x ); // $ExpectError
}

// The compiler throws an error if the function is provided an invalid number of arguments...
{
	incrmprod(); // $ExpectError
	incrmprod( 2, 3 ); // $ExpectError
}

// The function returns an accumulator function which returns an accumulated result...
{
	const acc = incrmprod( 3 );

	acc(); // $ExpectType number | null
	acc( 3.14 ); // $ExpectType number | null
}

// The compiler throws an error if the returned accumulator function is provided invalid arguments...
{
	const acc = incrmprod( 3 );

	acc( '5' ); // $ExpectError
	acc( true ); // $ExpectError
	acc( false ); // $ExpectError
	acc( null ); // $ExpectError
	acc( [] ); // $ExpectError
	acc( {} ); // $ExpectError
	acc( ( x: number ): number => x ); // $ExpectError
}


text:
from datetime import datetime

from django.forms import (
    CharField, Form, MultipleChoiceField, MultiValueField, MultiWidget,
    SelectMultiple, SplitDateTimeField, SplitDateTimeWidget, TextInput,
    ValidationError,
)
from django.test import SimpleTestCase

beatles = (('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))

class ComplexMultiWidget(MultiWidget):
    def __init__(self, attrs=None):
        widgets = (
            TextInput(),
            SelectMultiple(choices=beatles),
            SplitDateTimeWidget(),
        )
        super(ComplexMultiWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            data = value.split(',')
            return [
                data[0],
                list(data[1]),
                datetime.strptime(data[2], "%Y-%m-%d %H:%M:%S"),
            ]
        return [None, None, None]

class ComplexField(MultiValueField):
    def __init__(self, required=True, widget=None, label=None, initial=None):
        fields = (
            CharField(),
            MultipleChoiceField(choices=beatles),
            SplitDateTimeField(),
        )
        super(ComplexField, self).__init__(fields, required, widget, label, initial)

    def compress(self, data_list):
        if data_list:
            return '%s,%s,%s' % (data_list[0], ''.join(data_list[1]), data_list[2])
        return None

class ComplexFieldForm(Form):
    field1 = ComplexField(widget=ComplexMultiWidget())

class MultiValueFieldTest(SimpleTestCase):

    @classmethod
    def setUpClass(cls):
        cls.field = ComplexField(widget=ComplexMultiWidget())
        super(MultiValueFieldTest, cls).setUpClass()

    def test_clean(self):
        self.assertEqual(
            self.field.clean(['some text', ['J', 'P'], ['2007-04-25', '6:24:00']]),
            'some text,JP,2007-04-25 06:24:00',
        )

    def test_bad_choice(self):
        msg = "'Select a valid choice. X is not one of the available choices.'"
        with self.assertRaisesMessage(ValidationError, msg):
            self.field.clean(['some text', ['X'], ['2007-04-25', '6:24:00']])

    def test_no_value(self):
        """
        If insufficient data is provided, None is substituted.
        """
        msg = "'This field is required.'"
        with self.assertRaisesMessage(ValidationError, msg):
            self.field.clean(['some text', ['JP']])

    def test_has_changed_no_initial(self):
        self.assertTrue(self.field.has_changed(None, ['some text', ['J', 'P'], ['2007-04-25', '6:24:00']]))

    def test_has_changed_same(self):
        self.assertFalse(self.field.has_changed(
            'some text,JP,2007-04-25 06:24:00',
            ['some text', ['J', 'P'], ['2007-04-25', '6:24:00']],
        ))

    def test_has_changed_first_widget(self):
        """
        Test when the first widget's data has changed.
        """
        self.assertTrue(self.field.has_changed(
            'some text,JP,2007-04-25 06:24:00',
            ['other text', ['J', 'P'], ['2007-04-25', '6:24:00']],
        ))

    def test_has_changed_last_widget(self):
        """
        Test when the last widget's data has changed. This ensures that it is
        not short circuiting while testing the widgets.
        """
        self.assertTrue(self.field.has_changed(
            'some text,JP,2007-04-25 06:24:00',
            ['some text', ['J', 'P'], ['2009-04-25', '11:44:00']],
        ))

    def test_disabled_has_changed(self):
        f = MultiValueField(fields=(CharField(), CharField()), disabled=True)
        self.assertIs(f.has_changed(['x', 'x'], ['y', 'y']), False)

    def test_form_as_table(self):
        form = ComplexFieldForm()
        self.assertHTMLEqual(
            form.as_table(),
            """

Field1:
            <input type="text" name="field1_0" id="id_field1_0" required />
            <select multiple="multiple" name="field1_1" id="id_field1_1" required>
            <option value="J">John</option>
            <option value="P">Paul</option>
            <option value="G">George</option>
            <option value="R">Ringo</option>
            </select>
            <input type="text" name="field1_2_0" id="id_field1_2_0" required />
            <input type="text" name="field1_2_1" id="id_field1_2_1" required />

            """,
        )

    def test_form_as_table_data(self):
        form = ComplexFieldForm({
            'field1_0': 'some text',
            'field1_1': ['J', 'P'],
            'field1_2_0': '2007-04-25',
            'field1_2_1': '06:24:00',
        })
        self.assertHTMLEqual(
            form.as_table(),
            """

Field1:
            <input type="text" name="field1_0" value="some text" id="id_field1_0" required />
            <select multiple="multiple" name="field1_1" id="id_field1_1" required>
            <option value="J" selected>John</option>
            <option value="P" selected>Paul</option>
            <option value="G">George</option>
            <option value="R">Ringo</option>
            </select>
            <input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" required />
            <input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" required />

            """,
        )

    def test_form_cleaned_data(self):
        form = ComplexFieldForm({
            'field1_0': 'some text',
            'field1_1': ['J', 'P'],
            'field1_2_0': '2007-04-25',
            'field1_2_1': '06:24:00',
        })
        form.is_valid()
        self.assertEqual(form.cleaned_data['field1'], 'some text,JP,2007-04-25 06:24:00')


text:
<?php

namespace Plu\RerBundle\Controller;

use Plu\RerBundle\Field\EntityField;
use Plu\RerBundle\Field\IntegerField;
use Plu\RerBundle\Field\StringField;
use Plu\RerBundle\Forge\Callback\CallbackRealEntityFactory;
use Plu\RerBundle\Forge\EntityBlueprint;
use Plu\RerBundle\Forge\EntityForge;
use Plu\RerBundle\Forge\ProtoEntityFactory;
use Plu\RerBundle\Forge\RealEntityFactory;
use Plu\RerBundle\Matcher\Entity\ExactEntityMatcher;
use Plu\RerBundle\Matcher\Integer\RangeIntegerMatcher;
use Plu\RerBundle\Matcher\String\ExactStringMatcher;
use Plu\RerBundle\Repository\FileRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("/test")
 */
class TestController extends Controller
{

    /**
     * @Route("/", name="index")
     * @Template()
     */
    public function testAction()
    {
        $repo = $this->getGameRepository();

        var_dump($repo->count());

        $repo2 = $this->getPersonRepository();
        var_dump($repo2->count());

        return array('games' => $repo->searchFor($repo->getProtoEntity()));
    }

    /**
     * @Route("/filtered", name="filtered")
     * @Template()
     */
    public function filteredAction()
    {
        $repo = $this->getGameRepository();
        $repo2 = $this->getPersonRepository();

        $proto2 = $repo2->getProtoEntity();
        $matcher = new ExactStringMatcher();
        $matcher->setValue('Derp mcDerp');
        $proto2->setName($matcher);

        $proto = $repo->getProtoEntity();

        $matcher = new ExactEntityMatcher();
        $matcher->setValue($proto2);
        $proto->setOwner($matcher);

        return array('games' => $repo->searchFor($proto));
    }

    /**
     * @Route("/add", name="add")
     */
    public function addAction()
    {

        $repo = $this->getGameRepository();

        $entity = $repo->newEntity();
        $entity->setName('Lascaux');
        $entity->setMinPlayers(3);
        $entity->setMaxPlayers(5);

        $repo2 = $this->getPersonRepository();
        $proto = $repo2->getProtoEntity();
        $matcher = new ExactStringMatcher();
        $matcher->setValue('Derp mcDerp');
        $proto->setName($matcher);
        $person = $repo2->searchFor($proto)[0];

        $entity->setOwner($person);
        $repo->persist($entity);

        /*
        $repo = $this->getGameRepository();

        $entity = $repo->newEntity();
        $entity->setName('RISK');
        $entity->setMinPlayers(2);
        $entity->setMaxPlayers(6);

        $repo2 = $this->getPersonRepository();
        $person = $repo2->newEntity();
        $person->setName("Herp Derpins");
        $person->setAge(15);

        $repo2->persist($person);
        $entity->setOwner($person);
        $repo->persist($entity);
*/
        return $this->redirect($this->generateUrl('index'));
    }

    private function getGameRepository()
    {
        return new FileRepository($this->getGameBlueprint(), new EntityForge(new ProtoEntityFactory(), new CallbackRealEntityFactory()), 'wherever');
    }

    private function getGameBlueprint()
    {
        $blueprint = new EntityBlueprint();
        $blueprint->addField(new StringField('Name'));
        $blueprint->addField(new IntegerField('MinPlayers'));
        $blueprint->addField(new IntegerField('MaxPlayers'));
        $blueprint->addField(new EntityField('Owner', 'person'));
        $blueprint->setEntityName('game');
        return $blueprint;
    }

    private function getPersonRepository()
    {
        return new FileRepository($this->getPersonBlueprint(), new EntityForge(new ProtoEntityFactory(), new CallbackRealEntityFactory()), 'whatever');
    }

    private function getPersonBlueprint()
    {
        $blueprint = new EntityBlueprint();
        $blueprint->addField(new StringField('Name'));
        $blueprint->addField(new IntegerField('Age'));
        $blueprint->setEntityName('person');
        return $blueprint;
    }

}


text:
namespace Monaka {

    export interface BindKey {
        win: string;
        mac: string;
    }

    export function bindKey(win: string, mac: string): BindKey {
        return { win, mac };
    }

    export interface CommandArguments {
        text?: string;
        times?: number;
    }

    export class CutEvent extends _Event {
        constructor(public range: _Range) {
            super();
        }
    }

    export class Command {
        // isYank: boolean;

        constructor(public name: string, public bindKey: BindKey, public readOnly: boolean) { }

        public exec(editor: Editor, args?: CommandArguments) {
            return;
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) { return false; }
    }

    class SelectAll extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.selectAll();
        }
    }

    class CenterSelection extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.centerSelection();
        }
    }

    class GotoLine extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            var line = parseInt(prompt("Enter line number:"), 10);
            if (!isNaN(line)) {
                editor.gotoLine(line);
            }
        }
    }

    class Fold extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.session.toggleFold(false);
        }
    }

    class Unfold extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.session.toggleFold(true);
        }
    }

    class FoldAll extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.session.foldAll();
        }
    }

    class UnfoldAll extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.session.unfold();
        }
    }

    class FindNext extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.findNext();
        }
    }

    class FindPrevious extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.findPrevious();
        }
    }

    class Find extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            var needle = prompt("Find:", editor.getCopyText());
            editor.find(needle);
        }
    }

    class Overwrite extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.toggleOverwrite();
        }
    }

    class SelectToStart extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectFileStart();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GotoStart extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.navigateFileStart();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectUp extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectUp();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GoLineUp extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor, args: CommandArguments) {
            editor.navigateUp(args.times);
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectToEnd extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectFileEnd();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GotoEnd extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.navigateFileEnd();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectDown extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectDown();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GoLineDown extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor, args: CommandArguments) {
            editor.navigateDown(args.times);
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectWordLeft extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectWordLeft();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GotoWordLeft extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.navigateWordLeft();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectToLineStart extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectLineStart();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GotoLineStart extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.navigateLineStart();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectLeft extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectLeft();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GotoLeft extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor, args: CommandArguments) {
            editor.navigateLeft(args.times);
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectWordRight extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectWordRight();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GotoWordRight extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.navigateWordRight();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectToLineEnd extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectLineEnd();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GotoLineEnd extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.navigateLineEnd();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectRight extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectRight();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class GotoRight extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor, args: CommandArguments) {
            editor.navigateRight(args.times);
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectPageDown extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.selectPageDown();
        }
    }

    class PageDown extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.scrollPageDown();
        }
    }

    class GotoPageDown extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.gotoPageDown();
        }
    }

    class SelectPageUp extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.selectPageUp();
        }
    }

    class PageUp extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.scrollPageUp();
        }
    }

    class GotoPageUp extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.gotoPageUp();
        }
    }

    class ScrollUp extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.renderer.scrollBy(0, -2 * editor.renderer.layerConfig.lineHeight);
        }
    }

    class ScrollDown extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.renderer.scrollBy(0, 2 * editor.renderer.layerConfig.lineHeight);
        }
    }

    class SelectLineStart extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectLineStart();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectLineEnd extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.getSelection().selectLineEnd();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class ToggleRecording extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.commandManager.toggleRecording(editor);
        }
    }

    class ReplayMacro extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.commandManager.replay(editor);
        }
    }

    class JumpToMatching extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.jumpToMatching();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SelectToMatching extends Command {
        constructor(name: string, bindKey: BindKey, readOnly: boolean) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.jumpToMatching(true);
        }
    }

    class Cut extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            var range = editor.getSelectionRange();
            editor._dispatchEvent("cut", new CutEvent(range));

            if (!editor.selection.isEmpty()) {
                editor.session.remove(range);
                editor.clearSelection();
            }
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class RemoveLine extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.removeLines();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class DuplicateSelection extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.duplicateSelection();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class ToggleComment extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.toggleCommentLines();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class Replace extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            var needle = prompt("Find:", editor.getCopyText());
            if (!needle) {
                return;
            }
            var replacement = prompt("Replacement:");
            if (!replacement) {
                return;
            }
            editor.replace(replacement, { needle: needle });
        }
    }

    class ReplaceAll extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            var needle = prompt("Find:");
            if (!needle) {
                return;
            }
            var replacement = prompt("Replacement:");
            if (!replacement) {
                return;
            }
            editor.replaceAll(replacement, { needle: needle });
        }
    }

    class Undo extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.undo();
        }
    }

    class Redo extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.redo();
        }
    }

    class CopyLinesUp extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.copyLinesUp();
        }
    }

    class MoveLinesUp extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.moveLinesUp();
        }
    }

    class CopyLinesDown extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.copyLinesDown();
        }
    }

    class MoveLinesDown extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.moveLinesDown();
        }
    }

    class Del extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.remove("right");
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class Backspace extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.remove("left");
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class RemoveToLineStart extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.removeToLineStart();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class RemoveToLineEnd extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.removeToLineEnd();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class RemoveWordLeft extends Command {
        constructor(name: string, bindKey: { win: string, mac: string }, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.removeWordLeft();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class RemoveWordRight extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.removeWordRight();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class Outdent extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.blockOutdent();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class Indent extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.indent();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class InsertString extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor, str: string) {
            editor.insert(str);
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class InsertText extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor, args: CommandArguments) {
            editor.insert(lang.stringRepeat(args.text || "", args.times || 1));
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class SplitLine extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.splitLine();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class TransposeLetters extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.transposeLetters();
        }

        public multiSelectAction(editor: Editor) {
            editor.transposeSelections(1);
            return true;
        }
    }

    class ToUppercase extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.toUpperCase();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    class ToLowercase extends Command {
        constructor(name: string, bindKey: BindKey, readOnly = false) {
            super(name, bindKey, readOnly);
        }

        public exec(editor: Editor) {
            editor.toLowerCase();
        }

        public multiSelectAction(editor: Editor, args: CommandArguments) {
            editor.forEachSelection(this, args);
            return true;
        }
    }

    export var commands: Command[] = [
        new SelectAll("selectall", bindKey("Ctrl-A", "Command-A"), true),
        new CenterSelection("centerselection", bindKey(null, "Ctrl-L"), true),
        new GotoLine("gotoline", bindKey("Ctrl-L", "Command-L"), true),
        new Fold("fold", bindKey("Alt-L|Ctrl-F1", "Command-Alt-L|Command-F1"), true),
        new Unfold("unfold", bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"), true),
        new FoldAll("foldall", bindKey("Alt-0", "Command-Option-0"), true),
        new UnfoldAll("unfoldall", bindKey("Alt-Shift-0", "Command-Option-Shift-0"), true),
        new FindNext("findnext", bindKey("Ctrl-K", "Command-G"), true),
        new FindPrevious("findprevious", bindKey("Ctrl-Shift-K", "Command-Shift-G"), true),
        new Find("find", bindKey("Ctrl-F", "Command-F"), true),
        new Overwrite("overwrite", bindKey("Insert", "Insert"), true),
        new SelectToStart("selecttostart", bindKey("Ctrl-Shift-Home", "Command-Shift-Up"), true),
        new GotoStart("gotostart", bindKey("Ctrl-Home", "Command-Home|Command-Up"), true),
        new SelectUp("selectup", bindKey("Shift-Up", "Shift-Up"), true),
        new GoLineUp("golineup", bindKey("Up", "Up|Ctrl-P"), true),
        new SelectToEnd("selecttoend", bindKey("Ctrl-Shift-End", "Command-Shift-Down"), true),
        new GotoEnd("gotoend", bindKey("Ctrl-End", "Command-End|Command-Down"), true),
        new SelectDown("selectdown", bindKey("Shift-Down", "Shift-Down"), true),
        new GoLineDown("golinedown", bindKey("Down", "Down|Ctrl-N"), true),
        new SelectWordLeft("selectwordleft", bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), true),
        new GotoWordLeft("gotowordleft", bindKey("Ctrl-Left", "Option-Left"), true),
        new SelectToLineStart("selecttolinestart", bindKey("Alt-Shift-Left", "Command-Shift-Left"), true),
        new GotoLineStart("gotolinestart", bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), true),
        new SelectLeft("selectleft", bindKey("Shift-Left", "Shift-Left"), true),
        new GotoLeft("gotoleft", bindKey("Left", "Left|Ctrl-B"), true),
        new SelectWordRight("selectwordright", bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), true),
        new GotoWordRight("gotowordright", bindKey("Ctrl-Right", "Option-Right"), true),
        new SelectToLineEnd("selecttolineend", bindKey("Alt-Shift-Right", "Command-Shift-Right"), true),
        new GotoLineEnd("gotolineend", bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), true),
        new SelectRight("selectright", bindKey("Shift-Right", "Shift-Right"), true),
        new GotoRight("gotoright", bindKey("Right", "Right|Ctrl-F"), true),
        new SelectPageDown("selectpagedown", bindKey("Shift-PageDown", "Shift-PageDown"), true),
        new PageDown("pagedown", bindKey(null, "Option-PageDown"), true),
        new GotoPageDown("gotopagedown", bindKey("PageDown", "PageDown|Ctrl-V"), true),
        new SelectPageUp("selectpageup", bindKey("Shift-PageUp", "Shift-PageUp"), true),
        new PageUp("pageup", bindKey(null, "Option-PageUp"), true),
        new GotoPageUp("gotopageup", bindKey("PageUp", "PageUp"), true),
        new ScrollUp("scrollup", bindKey("Ctrl-Up", null), true),
        new ScrollDown("scrolldown", bindKey("Ctrl-Down", null), true),
        new SelectLineStart("selectlinestart", bindKey("Shift-Home", "Shift-Home"), true),
        new SelectLineEnd("selectlineend", bindKey("Shift-End", "Shift-End"), true),
        new ToggleRecording("togglerecording", bindKey("Ctrl-Alt-E", "Command-Option-E"), true),
        new ReplayMacro("replaymacro", bindKey("Ctrl-Shift-E", "Command-Shift-E"), true),
        new JumpToMatching("jumptomatching", bindKey("Ctrl-P", "Ctrl-Shift-P"), true),
        new SelectToMatching("selecttomatching", bindKey("Ctrl-Shift-P", null), true),
        // commands disabled in readOnly mode
        new Cut("cut", bindKey(null, null)),
        new RemoveLine("removeline", bindKey("Ctrl-D", "Command-D")),
        new DuplicateSelection("duplicateSelection", bindKey("Ctrl-Shift-D", "Command-Shift-D")),
        new ToggleComment("togglecomment", bindKey("Ctrl-/", "Command-/")),
        new Replace("replace", bindKey("Ctrl-R", "Command-Option-F")),
        new ReplaceAll("replaceall", bindKey("Ctrl-Shift-R", "Command-Shift-Option-F")),
        new Undo("undo", bindKey("Ctrl-Z", "Command-Z")),
        new Redo("redo", bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y")),
        new CopyLinesUp("copylinesup", bindKey("Alt-Shift-Up", "Command-Option-Up")),
        new MoveLinesUp("movelinesup", bindKey("Alt-Up", "Option-Up")),
        new CopyLinesDown("copylinesdown", bindKey("Alt-Shift-Down", "Command-Option-Down")),
        new MoveLinesDown("movelinesdown", bindKey("Alt-Down", "Option-Down")),
        new Del("del", bindKey("Delete", "Delete|Ctrl-D")),
        //new Backspace("backspace", bindKey("Command-Backspace|Option-Backspace|Shift-Backspace|Backspace", "Ctrl-Backspace|Command-Backspace|Shift-Backspace|Backspace|Ctrl-H")),
        new Backspace("backspace", bindKey("Backspace", "Backspace")),
        new RemoveToLineStart("removetolinestart", bindKey("Alt-Backspace", "Command-Backspace")),
        new RemoveToLineEnd("removetolineend", bindKey("Alt-Delete", "Ctrl-K")),
        new RemoveWordLeft("removewordleft", bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace")),
        new RemoveWordRight("removewordright", bindKey("Ctrl-Delete", "Alt-Delete")),
        new Outdent("outdent", bindKey("Shift-Tab", "Shift-Tab")),
        new Indent("indent", bindKey("Tab", "Tab")),
        new InsertString("insertstring", bindKey(null, null)),
        new InsertText("inserttext", bindKey(null, null)),
        new SplitLine("splitline", bindKey(null, "Ctrl-O")),
        new TransposeLetters("transposeletters", bindKey("Ctrl-T", "Ctrl-T")),
        new ToUppercase("touppercase", bindKey("Ctrl-U", "Ctrl-U")),
        new ToLowercase("tolowercase", bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"))
    ];
}


text:
You start tying knots on the fork. Then stick the fork into a marshmallow wall
and light a free end of a rope up. Yes, the wall slowly melts around the hot fork!

As you are about to step outside you notice an altar in the middle of the room with a chalice on it.

Do you?

[Quickly run outside and explore?](../explore-outside/explore-outside.md)

[Drink from it?](../fork-jam/choco-chalice/choco-chalice.md)

[Smash the altar](../fork-jam/altar-smash/altar-smash.md)

[Pray in the altar?](../fork-jam/altar-pray/altar-pray.md)


text:
package org.postgresql.test.jdbc2;

import org.postgresql.test.TestUtil;
import junit.framework.TestCase;
import java.sql.*;

import org.postgresql.PGNotification;

public class NotifyTest extends TestCase
{
    private Connection conn;

    public NotifyTest(String name)
    {
        super(name);
    }

    protected void setUp() throws Exception
    {
        conn = TestUtil.openDB();
    }

    protected void tearDown() throws SQLException
    {
        TestUtil.closeDB(conn);
    }

    public void testNotify() throws SQLException
    {
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("LISTEN mynotification");
        stmt.executeUpdate("NOTIFY mynotification");

        PGNotification notifications[] = ((org.postgresql.PGConnection)conn).getNotifications();
        assertNotNull(notifications);
        assertEquals(1, notifications.length);
        assertEquals("mynotification", notifications[0].getName());
        assertEquals("", notifications[0].getParameter());

        stmt.close();
    }

    public void testNotifyArgument() throws Exception
    {
        if (!TestUtil.haveMinimumServerVersion(conn, "9.0") || TestUtil.isProtocolVersion(conn, 2))
            return;

        Statement stmt = conn.createStatement();
        stmt.executeUpdate("LISTEN mynotification");
        stmt.executeUpdate("NOTIFY mynotification, 'message'");

        PGNotification notifications[] = ((org.postgresql.PGConnection)conn).getNotifications();
        assertNotNull(notifications);
        assertEquals(1, notifications.length);
        assertEquals("mynotification", notifications[0].getName());
        assertEquals("message", notifications[0].getParameter());

        stmt.close();
    }

    public void testAsyncNotify() throws Exception
    {
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("LISTEN mynotification");

        // Notify on a separate connection to get an async notify on the first.
        Connection conn2 = TestUtil.openDB();
        try {
            Statement stmt2 = conn2.createStatement();
            stmt2.executeUpdate("NOTIFY mynotification");
            stmt2.close();
        } finally {
            conn2.close();
        }

        // Wait a bit to let the notify come through..
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {}

        PGNotification notifications[] = ((org.postgresql.PGConnection)conn).getNotifications();
        assertNotNull(notifications);
        assertEquals(1, notifications.length);
        assertEquals("mynotification", notifications[0].getName());
        assertEquals("", notifications[0].getParameter());

        stmt.close();
    }
}


text:
package org.leguan.ui.controller;

import java.util.ArrayList;
import java.util.Collection;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import lombok.extern.slf4j.Slf4j;
import org.controlsfx.control.Notifications;
import org.leguan.analysis.DefaultStartContainerCreator;
import org.leguan.analysis.StartContainer;
import org.leguan.analysis.StartContainerCreator;
import org.leguan.analysis.StartItem;
import org.leguan.analysis.StartMission;
import org.leguan.analysis.StartResult;
import org.leguan.analysis.StartResultItem;
import org.leguan.analysis.StartService;
import org.leguan.config.ActionConf;
import org.leguan.config.BuildEnvConf;
import org.leguan.config.Configuration;
import org.leguan.config.ConfigurationService;
import org.leguan.config.ProjectConf;
import org.leguan.ui.UiUtils;
import org.leguan.ui.renderer.ActionListCell;
import org.leguan.ui.renderer.ActionStringConverter;
import org.leguan.ui.renderer.BuildEnvStringConverter;
import org.leguan.ui.renderer.ProjectListCell;
import org.leguan.ui.renderer.ProjectStringConverter;
import org.leguan.ui.renderer.StartItemStringConverter;

@Slf4j public class StartNewJobController extends AbstractController {

  @FXML private ComboBox<BuildEnvConf> cboBuildEnvironment;
  @FXML private ListView<StartItem> lviBranches;
  @FXML private Button btnStart;

  @FXML private ComboBox<ActionConf> cboActions;

  @FXML private ComboBox<ProjectConf> cboProjects;

  @FXML private Label lblState;

  private StartMission currentStartMission;

  private StartService startService = new StartService();

  @FXML public void initialize() {
    btnStart.setGraphic(UiUtils.createIcon("fa-play", UiUtils.ICON_SIZE_VERY_SMALL, UiUtils.ACTIONBUTTON));
    btnStart.setOnAction(action -> start());
    cboBuildEnvironment.setConverter(new BuildEnvStringConverter());
    cboActions.setCellFactory(cellfactory -> new ActionListCell());
    cboActions.setConverter(new ActionStringConverter());
    cboProjects.setCellFactory(cellfactory -> new ProjectListCell());
    cboProjects.setConverter(new ProjectStringConverter());

    BooleanBinding actionOrProjectIsNotSelected = new BooleanBinding() {
      @Override protected boolean computeValue() {
        return cboBuildEnvironment.getSelectionModel().isEmpty() || cboProjects.getSelectionModel()
            .isEmpty() || cboActions.getSelectionModel().isEmpty();
      }
    };

    cboActions.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ActionConf>() {
      @Override public void changed(ObservableValue<? extends ActionConf> observable, ActionConf oldValue,
          ActionConf newValue) {
        actionOrProjectIsNotSelected.invalidate();
      }
    });

    cboProjects.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ProjectConf>() {
      @Override public void changed(ObservableValue<? extends ProjectConf> observable, ProjectConf oldValue,
          ProjectConf newValue) {
        actionOrProjectIsNotSelected.invalidate();
        adaptBranches();
      }
    });

    btnStart.disableProperty().bind(actionOrProjectIsNotSelected);

    lviBranches.setCellFactory(CheckBoxListCell.forListView(new Callback<StartItem, ObservableValue<Boolean>>() {
      @Override public ObservableValue<Boolean> call(StartItem item) {
        BooleanProperty observable = new SimpleBooleanProperty();
        observable.set(item.isEnabled());
        observable.addListener((obs, wasSelected, isNowSelected) -> item.setEnabled(isNowSelected));
        return observable;
      }
    }, new StartItemStringConverter()));

    lblState.onMouseClickedProperty().set(new EventHandler<MouseEvent>() {
      @Override public void handle(MouseEvent event) {
        lblState.setText("");
        lblState.getStyleClass().clear();
      }
    });
  }

  private void adaptBranches() {
    Configuration configuration = new ConfigurationService().get();

    ProjectConf projectConf = cboProjects.getSelectionModel().getSelectedItem();
    ActionConf actionConf = cboActions.getSelectionModel().getSelectedItem();

    if (projectConf != null) {
      StartContainerCreator startContainerCreator = new DefaultStartContainerCreator();
      StartContainer startContainer = startContainerCreator.createStartContainer(configuration, projectConf).getStartContainer();
      startContainer.withAction(actionConf.getId());
      currentStartMission = StartMission.create().withContainer(startContainer);
      for (StartItem next : currentStartMission.getStartItems()) {
        next.setEnabled(true);
      }
      lviBranches.setItems(FXCollections.observableArrayList(currentStartMission.getStartItems()));
    }
    else
      lviBranches.setItems(FXCollections.observableArrayList());

  }

  @Override public void refreshData() {
    cboBuildEnvironment.getSelectionModel().clearSelection();
    cboActions.getSelectionModel().clearSelection();
    cboProjects.getSelectionModel().clearSelection();
    lblState.setText("");
    cboBuildEnvironment.setItems(FXCollections.observableArrayList(getConfiguration().getBuildEnvs()));
    cboActions.setItems(FXCollections.observableArrayList(getConfiguration().getActions()));
    cboProjects.setItems(FXCollections.observableArrayList(getConfiguration().getProjects()));
    lviBranches.setItems(FXCollections.observableArrayList());

    if (getConfiguration().getBuildEnvs().size() == 1)
      cboBuildEnvironment.getSelectionModel().select(getConfiguration().getBuildEnvs().get(0));

    if (getConfiguration().getProjects().size() == 1)
      cboProjects.getSelectionModel().select(getConfiguration().getProjects().get(0));

    if (getConfiguration().getActions().size() == 1)
      cboActions.getSelectionModel().select(getConfiguration().getActions().get(0));

  }

  public void start() {

    for (StartItem next : currentStartMission.getStartItems()) {
      log.info("StartItem " + next.getBranch().getTag() + "-" + next.isEnabled());

    }

    BuildEnvConf selectedBuildEnvironment = cboBuildEnvironment.getSelectionModel().getSelectedItem();

    try {
      StartResult startResult = startService.startJobs(getConfiguration(), getHistoryService(), currentStartMission, selectedBuildEnvironment);

      Collection<String> error = new ArrayList<>();
      int numberOfFailedBuilds = 0;
      for (StartResultItem nextResultItem : startResult.getStartResultItems()) {
        log.info("Result " + nextResultItem.getBranchID() + "(" + nextResultItem.getExceptions().size() + " exceptions)");
        for (Exception nextException: nextResultItem.getExceptions())
          error.add(nextException.getLocalizedMessage());

        if (!nextResultItem.getExceptions().isEmpty())
          numberOfFailedBuilds++;
      }

      if (numberOfFailedBuilds > 0)
        lblState.getStyleClass().setAll("statefailed");
      else
        lblState.getStyleClass().setAll("stateok");

      String state = "";
      if (numberOfFailedBuilds > 0) {
        state = numberOfFailedBuilds + " of " + startResult.getStartResultItems().size() + " builds failed:\n- ";
        state += String.join("\n- ", error);
      } else
        state = startResult.getStartResultItems().size() + " builds were triggered successfully";

      lblState.setText(state);
    } catch (Exception e) {
      log.error(e.getLocalizedMessage(), e);
      Notifications.create().text(e.getLocalizedMessage()).showError();

    }

  }

}


text:
amqpop
======

Tool for dispatching a child command for each message consumed from an AMQP
queue.

Benefits
--------

Designed for situations where you need to consume and act on messages from an
AMQP queue without a long running process.

Example
-------

    amqpop -h rabbit.domain.com -u user -n 2 -x logs -w 10 -- /usr/bin/ruby log_processor.rb

This command would do the following:

- Make sure only 1 instance of this amqpop command is running by using a
lock/pid file keyed based on the arguments of the command
- Connect to the AMQP server `rabbit.domain.com` as `user` with password looked
up from the auth file ~/.amqpop_auth
- Attach a unique, non durable queue to the exchange named logs
- Pass the message payload in as STDIN to `/usr/bin/ruby log_processor.rb`
- Run up to 2 parallel processes of `/usr/bin/ruby log_processor.rb`
- Once the queue has been exhausted of messages, wait for another message for 10
seconds, if one shows up inside of that time, process it immediately, and then
wait for another 10 seconds and repeat, otherwise terminate.

Usage
-----

    amqpop [options] -- <child-command>

    [options] are:
    -h <s>:  AMQP host (default: localhost)
    -u <s>:  AMQP user (default: guest)
    -p <s>:  AMQP password (default: guest)
    -n <i>:  Number of child message processing commands that can be executed in
             parallel (default: 1)
    -q <s>:  Name of the queue on the to connect to, unique if not provided
             (default: )
        -e:  Is the queue persistent (default: true)
        -a:  Does the queue remove itself
    -x <s>:  Exchange to bind the queue to. Format [name]:<routing>, example:
             logs or weather:usa.* (default: )
    -w <i>:  Amount of time in seconds to wait for more messages to show up.
             Waits forever if 0 (default: 30)

    --verbose, -v:   Verbose logging
    --version, -r:   Print version and exit
       --help, -l:   Show this message

Auth File
---------

You can put a file at ~/.amqpop_auth which is used to intelligently look up
login credentials when calling amqpop. No more sensative information in the
process list or in your history! Use one entry per line, in the format:

    host    user    pass

Example:

    192.168.1.1    consumer    1Consumer2
    192.168.1.1    other       XYother$Z
    rabbithost.domain.com    publisher_user    98pubPass234

The amount and kind of whitespace between host, user and pass don't matter, just
don't use newlines.

Note: The auth file must have world readable and writable disabled (so 660 or
600 are ok)

Tested On
---------
* OSX 10.8.2, 10.7.5
* Ruby 1.9.3-p327, 1.8.7-p358
* RabbitMQ 2.8.7
  * on Erlang R14A, Debian 6.0, kernel 2.6.32-5-686
  * on Erlang R14B04, RedHat EL5, kernel 2.6.18-238.9.1.el5xen

Acknowledgements
----------------

Thank you to William Morgan and the contributors of Trollop
(http://trollop.rubyforge.org/)


text:
<?php
/**
 * Currency rate import model (From www.webservicex.net)
 *
 * @category   Edge
 * @package    Edge_CurrencyApi
 * @author     outer/edge team <hello@outeredgeuk.com>
 */
class Edge_CurrencyApi_Model_Currency_Import_Webservicex extends Mage_Directory_Model_Currency_Import_Webservicex
{
    protected $_url = 'https://currency-api.appspot.com/api/{{CURRENCY_FROM}}/{{CURRENCY_TO}}.xml';

    protected function _convert($currencyFrom, $currencyTo, $retry=0)
    {
        $url = str_replace('{{CURRENCY_FROM}}', $currencyFrom, $this->_url);
        $url = str_replace('{{CURRENCY_TO}}', $currencyTo, $url);

        try {
            $response = $this->_httpClient
                ->setUri($url)
                ->setConfig(array('timeout' => Mage::getStoreConfig('currency/webservicex/timeout')))
                ->request('GET')
                ->getBody();

            $xml = simplexml_load_string($response, null, LIBXML_NOERROR);
            if( !$xml ) {
                $this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from %s.', $url);
                return null;
            }
            return (float) $xml->rate;
        }
        catch (Exception $e) {
            if( $retry == 0 ) {
                $this->_convert($currencyFrom, $currencyTo, 1);
            } else {
                $this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from %s.', $url);
            }
        }
    }
}


text:
'use strict';

/**@ngInject*/
function AdminController($scope) {
}

AdminController.resolve = {

};

module.exports = AdminController;


text:
package org.apache.ignite.internal.processors.query.stat;

/**
 * Any type of object statistics.
 */
public interface ObjectStatistics {
}


text:
package monix.benchmarks

import java.util.concurrent.TimeUnit

import fs2.{Stream => FS2Stream}
import monix.reactive.Observable
import org.openjdk.jmh.annotations._
import zio.stream.{Stream => ZStream}

/** To do comparative benchmarks between versions:
  *
  *     benchmarks/run-benchmark ObservableMapAccumulateBenchmark
  *
  * This will generate results in `benchmarks/results`.
  *
  * Or to run the benchmark from within SBT:
  *
  *     jmh:run -i 10 -wi 10 -f 2 -t 1 monix.benchmarks.ObservableMapAccumulateBenchmark
  *
  * Which means "10 iterations", "10 warm-up iterations", "2 forks", "1 thread".
  * Please note that benchmarks should be usually executed at least in
  * 10 iterations (as a rule of thumb), but more is better.
  */
@State(Scope.Thread)
@BenchmarkMode(Array(Mode.Throughput))
@OutputTimeUnit(TimeUnit.SECONDS)
class ObservableMapAccumulateBenchmark {
  @Param(Array("1000", "10000"))
  var n: Int = _

  @Benchmark
  def monixObservable() = {
    Observable
      .fromIterable(0 until n)
      .mapAccumulate(0) { case (acc, i) =>
        val added = acc + i
        (added, added)
      }
      .completedL
      .runSyncUnsafe()
  }

  @Benchmark
  def fs2Stream() = {
    FS2Stream
      .emits(0 until n)
      .mapAccumulate(0) { case (acc, i) =>
        val added = acc + i
        (added, added)
      }
      .compile
      .drain
  }

  @Benchmark
  def zioStream() = {
    val stream = ZStream
      .fromIterable(0 until n)
      .mapAccum(0) { case (acc, i) =>
        val added = acc + i
        (added, added)
      }
      .runDrain

    zioUntracedRuntime.unsafeRun(stream)
  }
}


text:
<?php

namespace SimpleExcel\Parser;

use SimpleExcel\Exception\SimpleExcelException;

/**
 * SimpleExcel class for parsing Microsoft Excel CSV Spreadsheet
 *
 * @author  Faisalman
 * @package SimpleExcel
 */
class CSVParser extends BaseParser implements IParser
{
    /**
    * Defines delimiter character
    *
    * @access   protected
    * @var      string
    */
    protected $delimiter;

    /**
    * Defines valid file extension
    *
    * @access   protected
    * @var      string
    */
    protected $file_extension = 'csv';

    /**
    * Load the CSV file to be parsed
    *
    * @param    string  $file_path  Path to CSV file
    */
    public function loadFile($file_path){

        if (!$this->isFileReady($file_path)) {
            return;
        }

        $this->loadString(file_get_contents($file_path));
    }

    /**
    * Load the string to be parsed
    *
    * @param    string  $str    String with CSV format
    */
    public function loadString($str){
        $this->table_arr = array();

        if(!isset($this->delimiter)){
            $numofcols = NULL;
            // assume the delimiter is semicolon
            while(($line = fgetcsv($str, 0, ';')) !== FALSE){
                if($numofcols === NULL){
                    $numofcols = count($line);
                }
                // check the number of values in each line
                if(count($line) === $numofcols){
                    array_push($this->table_arr, $line);
                } else {
                    // maybe wrong delimiter
                    // empty the array back
                    $this->table_arr = array();
                    $numofcols = NULL;
                    break;
                }
            }
            // if null, check whether values are separated by commas
            if($numofcols === NULL){
                while(($line = fgetcsv($str, 0, ',')) !== FALSE){
                    array_push($this->table_arr, $line);
                }
            }
        } else {
            while(($line = fgetcsv($str, 0, $this->delimiter)) !== FALSE){
                array_push($this->table_arr, $line);
            }
        }
    }

    /**
    * Set delimiter that should be used to parse CSV document
    *
    * @param    string  $delimiter   Delimiter character
    */
    public function setDelimiter($delimiter){
        $this->delimiter = $delimiter;
    }
}


text:
import javax.annotation.Nonnull;

class X {
    @Nonnull
    String foo() {
        return "X";
    }
}
class Y extends X{
    String foo() {
        return "Y";
    }
}
class Z extends Y {
    String foo<caret>() { // trigger quick fix for inspection here
        return "Z";
    }
}


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

Managed Object Types	Data Object Types	All Properties	All Methods

Enum -
						EventCategory

Enum Description

Enum Constants

Name	Description

error
      Returns error events.

info
      Returns informational events.

user
      Returns events pertaining to users.

warning
      Returns warning events.

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <simpleType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="EventCategory">
            <restriction base="xsd:string">
               <enumeration value="info"/>
               <enumeration value="warning"/>
               <enumeration value="error"/>
               <enumeration value="user"/>
            </restriction>
         </simpleType></textarea>

Top of page

Managed Object Types	Data Object Types	All Properties	All Methods


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

  <bean id="org.hisp.dhis.setting.SystemSettingStore" class="org.hisp.dhis.setting.hibernate.HibernateSystemSettingStore">
    <property name="clazz" value="org.hisp.dhis.setting.SystemSetting" />
    <property name="sessionFactory" ref="sessionFactory" />
    <property name="cacheable" value="true" />
  </bean>

  <bean id="org.hisp.dhis.setting.SystemSettingManager" class="org.hisp.dhis.setting.DefaultSystemSettingManager">
    <property name="systemSettingStore" ref="org.hisp.dhis.setting.SystemSettingStore" />
    <property name="flags">
      <list>
        <value>afghanistan</value>
        <value>africare</value>
        <value>akros</value>
        <value>algeria</value>
        <value>angola</value>
        <value>armenia</value>
        <value>bangladesh</value>
        <value>benin</value>
        <value>bhutan</value>
        <value>botswana</value>
        <value>burkina_faso</value>
        <value>burkina_faso_coat_of_arms</value>
        <value>burundi</value>
        <value>cambodia</value>
        <value>cameroon</value>
        <value>cape_verde</value>
        <value>chad</value>
        <value>china</value>
        <value>cidrz</value>
        <value>colombia</value>
        <value>congo_brazzaville</value>
        <value>congo_kinshasa</value>
        <value>cordaid</value>
        <value>demoland</value>
        <value>denmark</value>
        <value>ecowas</value>
        <value>ecuador</value>
        <value>east_africa_community</value>
        <value>egypt</value>
        <value>engender_health</value>
        <value>eritrea</value>
        <value>ethiopia</value>
        <value>equatorial_guinea</value>
        <value>fhi360</value>
        <value>forut</value>
        <value>gambia</value>
        <value>ghana</value>
        <value>global_fund</value>
        <value>grenada</value>
        <value>guinea</value>
        <value>guinea_bissau</value>
        <value>haiti</value>
        <value>honduras</value>
        <value>icap</value>
        <value>ippf</value>
        <value>ima</value>
        <value>india</value>
        <value>indonesia</value>
        <value>irc</value>
        <value>iran</value>
        <value>iraq</value>
        <value>ivory_coast</value>
        <value>jhpiego</value>
        <value>kenya</value>
        <value>kiribati</value>
        <value>kurdistan</value>
        <value>laos</value>
        <value>lesotho</value>
        <value>liberia</value>
        <value>malawi</value>
        <value>mauritania</value>
        <value>maldives</value>
        <value>mongolia</value>
        <value>mozambique</value>
        <value>myanmar</value>
        <value>mali</value>
        <value>mhrp</value>
        <value>msf</value>
        <value>msh</value>
        <value>msh_white</value>
        <value>msi</value>
        <value>namibia</value>
        <value>nicaragua</value>
        <value>nepal</value>
        <value>niger</value>
        <value>nigeria</value>
        <value>norway</value>
        <value>pakistan</value>
        <value>palestine</value>
        <value>palladium</value>
        <value>pepfar</value>
        <value>paraguay</value>
        <value>pathfinder</value>
        <value>philippines</value>
        <value>planned_parenthood</value>
        <value>peru</value>
        <value>psi</value>
        <value>puntland</value>
        <value>rwanda</value>
        <value>save_the_children</value>
        <value>senegal</value>
        <value>sierra_leone</value>
        <value>sierra_leone_coat_of_arms</value>
        <value>solomon_islands</value>
        <value>somalia</value>
        <value>somaliland</value>
        <value>south_africa</value>
        <value>south_africa_department_of_health</value>
        <value>south_sudan</value>
        <value>sri_lanka</value>
        <value>sudan</value>
        <value>swaziland</value>
        <value>sweden</value>
        <value>tajikistan</value>
        <value>tanzania</value>
        <value>timor_leste</value>
        <value>republic_of_trinidad_and_tobago</value>
        <value>togo</value>
        <value>tonga</value>
        <value>uganda</value>
        <value>usaid</value>
        <value>vietnam</value>
        <value>vanuatu</value>
        <value>zambia</value>
        <value>zanzibar</value>
        <value>zimbabwe</value>
        <value>who</value>
      </list>
    </property>
  </bean>

  <bean id="org.hisp.dhis.setting.TranslateSystemSettingManager" class="org.hisp.dhis.setting.DefaultTranslateSystemSettingManager">
    <property name="systemSettingManager" ref="org.hisp.dhis.setting.SystemSettingManager" />
  </bean>

</beans>


text:
package water.api;

import water.*;
import water.api.schemas3.KeyV3;
import water.api.schemas3.RemoveAllV3;
import water.util.Log;

// Best-effort cluster brain-wipe and reset.
// Useful between unrelated tests.
public class RemoveAllHandler extends Handler {
  @SuppressWarnings("unused") // called through reflection by RequestServer
  public RemoveAllV3 remove(int version, RemoveAllV3 u) {
    Futures fs = new Futures();
    // Cancel and remove leftover running jobs
    for( Job j : Job.jobs() ) { j.stop_requested(); j.remove(fs); }
    // Wipe out any and all session info
    if( RapidsHandler.SESSIONS != null ) {
      for(String k: RapidsHandler.SESSIONS.keySet() )
        (RapidsHandler.SESSIONS.get(k)).endQuietly(null);
      RapidsHandler.SESSIONS.clear();
    }
    fs.blockForPending();

    if (u.retained_keys != null && u.retained_keys.length != 0) {
      retainKeys(u.retained_keys);
    } else {
      clearAll();
    }
    Log.info("Finished removing objects");
    return u;
  }

  private void clearAll() {
    Log.info("Removing all objects");
    // Bulk brainless key removal.  Completely wipes all Keys without regard.
    new MRTask(H2O.MIN_HI_PRIORITY) {
      @Override
      public void setupLocal() {
        H2O.raw_clear();
        water.fvec.Vec.ESPC.clear();
      }
    }.doAllNodes();
    // Wipe the backing store without regard as well
    H2O.getPM().getIce().cleanUp();
    H2O.updateNotIdle();
  }

  private void retainKeys(final KeyV3[] retained_keys) {
    Log.info(String.format("Removing all objects, except for %d provided key(s)", retained_keys.length));
    final Key[] retainedKeys;
    if (retained_keys == null) {
      retainedKeys = new Key[0];
    } else {
      retainedKeys = new Key[retained_keys.length];
      for (int i = 0; i < retainedKeys.length; i++) {
        if (retained_keys[i] == null) throw new IllegalArgumentException("An attempt to retain a 'null' key detected. Cleaning operation aborted.");
        retainedKeys[i] = retained_keys[i].key();
      }
    }

    DKVManager.retain(retainedKeys);

  }
}


text:
El principal objetivo de la sesión consiste en hacer una introducción a los componentes de la interfaz de Android que nos darán soporte para poder reproducir gráficos de alto rendimiento (vídeo o gráficos 3D).

## _Surface View_

Para mostrar gráficos propios podríamos usar un componente que herede de `View`. Estos componentes funcionan bien si no necesitamos realizar repintados continuos o mostrar gráficos 3D.

Sin embargo, en el caso de tener una aplicación con una gran carga gráfica, como puede ser un videojuego, un reproductor de vídeo, o una aplicación que muestre gráficos 3D, en lugar de `View` deberemos utilizar `SurfaceView`. Esta última clase nos proporciona una superficie en la que podemos dibujar desde un hilo en segundo plano, lo cual libera al hilo principal de la aplicación de la carga gráfica.

Vamos a ver en primer lugar cómo crear subclases de `SurfaceView`, y las diferencias existentes con `View`.

Para crear una vista con `SurfaceView` tendremos que
crear una nueva subclase de dicha clase (en lugar de `View`). Pero en este caso no bastará con definir el método `onDraw`, ahora deberemos crearnos un hilo independiente y proporcionarle la superficie en la que dibujar (`SurfaceHolder`). Además, en nuestra subclase de `SurfaceView` también implementaremos la interfaz `SurfaceHolder.Callback` que nos permitirá estar al tanto de cuando la superficie se crea, cambia, o se destruye.

Cuando la superficie sea creada pondremos en marcha nuestro hilo de dibujado, y lo pararemos cuando la superficie sea destruida. A continuación mostramos un ejemplo de dicha clase:

```java
public class VistaSurface extends SurfaceView
              implements SurfaceHolder.Callback {
    HiloDibujo hilo = null;

    public VistaSurface(Context context) {
        super(context);

        SurfaceHolder holder = this.getHolder();
        holder.addCallback(this);
    }

    public void surfaceChanged(SurfaceHolder holder, int format,
                                 int width, int height) {
        // La superficie ha cambiado (formato o dimensiones)
    }

    public void surfaceCreated(SurfaceHolder holder) {
        hilo = new HiloDibujo(holder, this);
        hilo.start();
    }

    public void surfaceDestroyed(SurfaceHolder holder) {

        hilo.detener();
        try {
            hilo.join();
        } catch (InterruptedException e) { }
    }
}
```

Como vemos, la clase `SurfaceView` simplemente se
encarga de obtener la superficie y poner en marcha o parar el hilo de dibujado. En este caso la acción estará realmente en el hilo, que es donde especificaremos la forma en la que se debe dibujar
el componente. Vamos a ver a continuación cómo podríamos implementar dicho hilo:

```java
class HiloDibujo extends Thread {
    SurfaceHolder holder;
    VistaSurface vista;
    boolean continuar = true;

    public HiloDibujo(SurfaceHolder holder, VistaSurface vista) {
        this.holder = holder;
        this.vista = vista;
        continuar = true;
    }

    public void detener() {
        continuar = false;
    }

    @Override
    public void run() {
        while (continuar) {
            Canvas c = null;
            try {
                c = holder.lockCanvas(null);
                synchronized (holder) {
                    // Dibujar aqui los graficos
                    c.drawColor(Color.BLUE);
                }
            } finally {
                if (c != null) {
                    holder.unlockCanvasAndPost(c);
                }
            }
        }
    }
}
```

Podemos ver que en el bucle principal de nuestro hilo obtenermos el lienzo (`Canvas`) a partir de la superficie (`SurfaceHolder`) mediante el método `lockCanvas`. Esto deja el lienzo bloqueado para nuestro uso, por ese motivo es importante asegurarnos de que siempre se desbloquee. Para tal fin hemos puesto `unlockCanvasAndPost` dentro del bloque
`finally`. Además debemos siempre dibujar de forma sincronizada con el objeto `SurfaceHolder`, para así evitar problemas de concurrencia en el acceso a su lienzo.

Para aplicaciones como videojuegos 2D sencillos un código como el anterior puede ser suficiente (la clase `View` sería demasiado lenta para un videojuego). Sin embargo, lo realmente interesante es utilizar `SurfaceView` junto a OpenGL, para así poder mostrar gráficos 3D, o escalados, rotaciones y otras
transformaciones sobre superficies 2D de forma eficiente.

A continuación veremos un ejemplo de cómo utilizar OpenGL (concretamente OpenGL ES) vinculado a nuestra `SurfaceView`.

Realmente la implementación de nuestra clase que hereda de `SurfaceView` no cambiará, simplemente modificaremos nuestro hilo, que es quien realmente realiza el dibujado. Toda la inicialización de OpenGL deberá realizarse dentro de nuestro hilo (en el método `run`), ya que sólo se puede acceder a las operaciones
de dicha librería desde el mismo hilo en el que se inicializó. En caso de que intentásemos acceder desde otro hilo obtendríamos un error indicando que no existe ningún contexto activo de OpenGL.

En este caso nuestro hilo podría contener el siguiente código:

```java
public void run() {
    initEGL();
    initGL();

    Triangulo3D triangulo = new Triangulo3D();
    float angulo = 0.0f;

    while(continuar) {
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT |
                   GL10.GL_DEPTH_BUFFER_BIT);

        // Dibujar gráficos aquí
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
        gl.glTranslatef(0, 0, -5.0f);
        gl.glRotatef(angulo, 0, 1, 0);

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        triangulo.dibujar(gl);

        egl.eglSwapBuffers(display, surface);
        angulo += 1.0f;
    }
}
```

En primer lugar debemos inicializar la interfaz EGL, que hace de vínculo entre la plataforma nativa y la librería OpenGL:

```java
EGL10 egl;
GL10 gl;
EGLDisplay display;
EGLSurface surface;
EGLContext contexto;
EGLConfig config;

private void initEGL() {
    egl = (EGL10)EGLContext.getEGL();
    display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);

    int [] version = new int[2];
    egl.eglInitialize(display, version);

    int [] atributos = new int[] {
        EGL10.EGL_RED_SIZE, 5,
        EGL10.EGL_GREEN_SIZE, 6,
        EGL10.EGL_BLUE_SIZE, 5,
        EGL10.EGL_DEPTH_SIZE, 16,
        EGL10.EGL_NONE
    };

    EGLConfig [] configs = new EGLConfig[1];
    int [] numConfigs = new int[1];
    egl.eglChooseConfig(display, atributos, configs,
                        1, numConfigs);

    config = configs[0];
    surface = egl.eglCreateWindowSurface(display,
                        config, holder, null);
    contexto = egl.eglCreateContext(display, config,
                        EGL10.EGL_NO_CONTEXT, null);
    egl.eglMakeCurrent(display, surface, surface, contexto);

    gl = (GL10)contexto.getGL();
}
```

A continuación debemos proceder a la inicialización de la interfaz de la librería OpenGL:

```java
private void initGL() {
    int width = vista.getWidth();
    int height = vista.getHeight();
    gl.glViewport(0, 0, width, height);
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glLoadIdentity();

    float aspecto = (float)width/height;
    GLU.gluPerspective(gl, 45.0f, aspecto, 1.0f, 30.0f);
    gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
}
```

Una vez hecho esto, ya sólo nos queda ver cómo dibujar una malla 3D. Vamos a ver como ejemplo el dibujo de un triángulo:

```java
public class Triangulo3D {

    FloatBuffer buffer;

    float[] vertices = {
        -1f, -1f, 0f,
        1f, -1f, 0f,
        0f, 1f, 0f };

    public Triangulo3D() {
        ByteBuffer bufferTemporal = ByteBuffer
                   .allocateDirect(vertices.length*4);
        bufferTemporal.order(ByteOrder.nativeOrder());
        buffer = bufferTemporal.asFloatBuffer();
        buffer.put(vertices);
        buffer.position(0);
    }

    public void dibujar(GL10 gl) {
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, buffer);
        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
    }
}
```

Para finalizar, es importante que cuando la superficie se destruya se haga una limpieza de los recursos utilizados por OpenGL:

```java
private void cleanupGL() {
    egl.eglMakeCurrent(display, EGL10.EGL_NO_SURFACE,
            EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
    egl.eglDestroySurface(display, surface);
    egl.eglDestroyContext(display, contexto);
    egl.eglTerminate(display);
}
```

Podemos llamar a este método cuando el hilo se detenga (debemos asegurarnos que se haya detenido llamando a `join` previamente).

A partir de Android 1.5 se incluye la clase
`GLSurfaceView`, que ya incluye la inicialización
del contexto GL y nos evita tener que hacer esto manualmente. Esto simplificará bastante el uso de la librería. Vamos a ver a continuación un ejemplo de cómo trabajar con dicha clase.

En este caso ya no será necesario crear una subclase de  `GLSurfaceView`, ya que la inicialización y gestión del hilo de OpenGL siempre es igual. Lo único que nos interesará cambiar es lo que se muestra en la escena. Para ello deberemos crear una subclase de `GLSurfaceViewRenderer` que nos obliga a definir los siguientes métodos:

```java
public class MiRenderer implements GLSurfaceView.Renderer {

    Triangulo3D triangulo;
    float angulo;

    public MiRenderer() {
        triangulo = new Triangulo3D();
        angulo = 0;
    }

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    }

    public void onSurfaceChanged(GL10 gl, int w, int h) {
        // Al cambiar el tamaño cambia la proyección
        float aspecto = (float)w/h;
    	gl.glViewport(0, 0, w, h);

        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        GLU.gluPerspective(gl, 45.0f, aspecto, 1.0f, 30.0f);
    }

    public void onDrawFrame(GL10 gl) {
        gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT |
                   GL10.GL_DEPTH_BUFFER_BIT);

        // Dibujar gráficos aquí
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
        gl.glTranslatef(0, 0, -5.0f);
        gl.glRotatef(angulo, 0, 1, 0);

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        triangulo.dibujar(gl);

        angulo += 1.0f;
    }
}
```

Podemos observar que será el método `onDrawFrame` en el que deberemos escribir el código para mostrar los gráficos. Con hacer esto será suficiente, y no tendremos que encargarnos de crear el hilo ni de inicializar ni destruir el contexto.

Para mostrar estos gráficos en la vista deberemos proporcionar nuestro _renderer_ al objeto `GLSurfaceView`:

```java
vista = new GLSurfaceView(this);
vista.setRenderer(new MiRenderer());
setContentView(vista);
```

Por último, será importante transmitir los eventos `onPause` y `onResume` de nuestra actividad a la vista de OpenGL, para así liberar a la aplicación de la carga gráfica cuando permanezca en segundo plano. El código completo de la actividad quedaría como se
muestra a continuación:

```java
public class MiActividad extends Activity {
    GLSurfaceView vista;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vista = new GLSurfaceView(this);
        vista.setRenderer(new MiRenderer());
        setContentView(vista);
    }

    @Override
    protected void onPause() {
        super.onPause();
        vista.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        vista.onResume();
    }
}
```

## Ejercicios

Antes de empezar a crear los proyectos, debes descargarte las plantillas desde el repositorio `mastermoviles-multimedia-android` de _bitbucket_. En este repositorio se encuentran todas las plantillas que utilizaremos en los ejercicios Android de este módulo.

### Gráficos 3D

En las plantillas de la sesión tenemos una aplicación `Graficos` en la que podemos ver un ejemplo completo de cómo utilizar `SurfaceView` tanto para gráficos 2D con el `Canvas` como para gráficos 3D con OpenGL, y también de cómo utilizar `GLSurfaceView`.

* Si ejecutamos la aplicación veremos un triángulo rotando alrededor del eje Y. Observar el código fuente, y modificarlo para que el triángulo
rote alrededor del eje X, en lugar de Y.

* También podemos ver que hemos creado, además de la clase `Triangulo3D`, la clase `Cubo3D`. Modificar el código para que en lugar de mostrar el triángulo se muestre el cubo.


text:
package org.deephacks.confit.internal.mapdb;

import org.deephacks.confit.spi.Lookup;
import org.mapdb.DBMaker;
import org.mapdb.TxMaker;

import java.io.File;
import java.io.IOException;

public class MapdbUtil {
    public static File MAPDB_TEMP_FILE;
    public static MapDB mapDB;

    public static void create() {
        try {
            MAPDB_TEMP_FILE = File.createTempFile("confit.berkeley", "tmp");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        TxMaker db = DBMaker.newFileDB(MAPDB_TEMP_FILE)
                .makeTxMaker();
        Lookup.get().register(TxMaker.class, db);
        mapDB = new MapDB(db);
        mapDB.clear();
        mapDB.commit();
    }

    public static void delete() {
        mapDB.clear();
        mapDB.commit();
    }
}


text:
from liblo import *
import sys
import time
#import win32con
#from win32 import win32api
import turtle
# Global Constant(s)
UPPER_ZERO_RANGE = 8
LOWER_ZERO_RANGE = -8
MAX_DELAY_COUNT = 50
MOUSE_MOVE_INCREMENT = 3
STATES = {0: "STATIONARY",
          1: "LEFT",
          2: "RIGHT",
          3: "UP",
          4: "DOWN"}

class MuseServer(ServerThread):

    # Listen for messages on port 5001
    def __init__(self):
        ServerThread.__init__(self, 5000)
        self.x = 0
        self.y = 0           # indicates position of mouse cursor, initialized at (0, 0)
        self.delay_counter = 0          # delay counter used to eliminate false positives/negatives
        self.state = 0                  # indicates current state
        self.turtle = Cursor(self.x, self.y)
        self.move_cursor()

    # Callback method to handle accelerometer data
    @make_method('/muse/acc', 'fff')
    def acc_callback(self, path, args):
        print(100)

        if self.delay_counter == MAX_DELAY_COUNT:

            # Finite State Machine used to determine direction of movement of mouse cursor

            # STATE 0: Stationary
            # STATE 1: Move cursor left
            # STATE 2: Move cursor right
            # STATE 3: Move cursor up
            # STATE 4: Move cursor down
            print(1)
            print(STATES[self.state])

            change_in_acceleration = args[0] - self.previous_acceleration

            # If user shakes head to the left ...
            if change_in_acceleration < LOWER_ZERO_RANGE:
                if self.state == 0:
                    self.state = 1

                elif self.state == 1:
                    self.state = 4

                elif self.state == 2:
                    self.state = 0

                elif self.state == 3:
                    self.state = 0

                elif self.state == 4:
                    self.state = 0

                self.delay_counter = 0

            # If user shakes head to the right ...
            elif change_in_acceleration > UPPER_ZERO_RANGE:
                if self.state == 0:
                    self.state = 2

                elif self.state == 1:
                    self.state = 0

                elif self.state == 2:
                    self.state = 3

                elif self.state == 3:
                    self.state = 0

                elif self.state == 4:
                    self.state = 0

                self.delay_counter = 0

            # Move mouse cursor depending on which state program is in
            if self.state == 1:
                self.x -= MOUSE_MOVE_INCREMENT
            elif self.state == 2:
                self.x += MOUSE_MOVE_INCREMENT
            elif self.state == 3:
                self.y -= MOUSE_MOVE_INCREMENT
            elif self.state == 4:
                self.y += MOUSE_MOVE_INCREMENT
            print(1)
            self.move_cursor()

            self.previous_acceleration = args[0]

        else:
            # set up delay to eliminate false positives/negatives
            self.delay_counter += 1
            self.previous_acceleration = args[0]

    def move_cursor(self):
        self.turtle.move(self.x, self.y)

class Cursor(turtle.Turtle):

    def __init__(self, x, y):
        turtle.Turtle.__init__(self)
        self.penup()
        self.goto(x, y)

    def move(self,  x, y):
        self.goto(x, y)

def main():
    while True:
          try:
                    print(10)
                    server = MuseServer()
          except ServerError as e:
                    print(str(e))
                    sys.exit()

          server.start()

    while True:
        time.sleep(1)

if __name__ == "__main__":
    window = turtle.Screen()
    window.title('Title')
    main()
    window.mainloop()