text:
package com.github.cameltooling.idea.completion;

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

import com.github.cameltooling.idea.CamelLightCodeInsightFixtureTestCaseIT;
import com.github.cameltooling.idea.service.CamelPreferenceService;
import com.intellij.codeInsight.lookup.LookupElement;
import org.hamcrest.Matchers;

import static org.junit.Assert.assertThat;

/**
 * Testing smart completion with Camel Java DSL
 */
public class JavaEndpointSmartCompletionTestIT extends CamelLightCodeInsightFixtureTestCaseIT {

    protected void tearDown() throws Exception {
        try {
            CamelPreferenceService.getService().setOnlyShowKameletOptions(true);
        } finally {
            super.tearDown();
        }
    }

    public void testConsumerCompletion() {
        myFixture.configureByFiles("CompleteJavaEndpointConsumerTestData.java");
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertThat(strings, Matchers.not(Matchers.contains("file:inbox?fileExist", "file:inbox?forceWrites")));
        assertThat(strings, Matchers.hasItems("file:inbox?autoCreate", "file:inbox?include", "file:inbox?delay", "file:inbox?delete"));
        assertTrue("There are many options", strings.size() > 60);
    }

    public void testProducerCompletion() {
        myFixture.configureByFiles("CompleteJavaEndpointProducerTestData.java");
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertThat(strings, Matchers.not(Matchers.contains("file:outbox?autoCreate", "file:outbox?include", "file:outbox?delay", "file:outbox?delete")));
        assertThat(strings, Matchers.hasItems("file:outbox?fileExist", "file:outbox?forceWrites"));
        assertTrue("There is less options", strings.size() < 30);
    }

    private String getJavaInTheMiddleUnresolvedOptionsTestData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10&ex<caret>\")\n"
            + "                .to(\"file:outbox?delete=true&fileExist=Append\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaInTheMiddleUnresolvedOptionsCompletion() {
        myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", getJavaInTheMiddleUnresolvedOptionsTestData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertThat(strings, Matchers.not(Matchers.contains("timer:trigger?repeatCount=10")));
        assertThat(strings, Matchers.contains("timer:trigger?repeatCount=10&exceptionHandler",
            "timer:trigger?repeatCount=10&exchangePattern"));
        assertEquals("There is less options", 2, strings.size());
    }

    private String getJavaInTheMiddleOfResolvedOptionsData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10&fixed<caret>Rate=false\")\n"
            + "                .to(\"file:outbox?delete=true&fileExist=Append\");\n"
            + "        }\n"
            + "    }";
    }

    public void testJavaInTheMiddleOfResolvedOptionsCompletion() {
        myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", getJavaInTheMiddleOfResolvedOptionsData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertEquals("Expect 0 options", 0, strings.size());
    }

    private String getJavaAfterAmpOptionsTestData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10&<caret>\")\n"
            + "                .to(\"file:outbox?delete=true&fileExist=Append\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaAfterAmpOptionsCompletion() {
        myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", getJavaAfterAmpOptionsTestData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertDoesntContain(strings, "timer:trigger?repeatCount=10");
        assertContainsElements(strings, "timer:trigger?repeatCount=10&bridgeErrorHandler",
            "timer:trigger?repeatCount=10&daemon",
            "timer:trigger?repeatCount=10&delay",
            "timer:trigger?repeatCount=10&exceptionHandler",
            "timer:trigger?repeatCount=10&exchangePattern",
            "timer:trigger?repeatCount=10&fixedRate",
            "timer:trigger?repeatCount=10&pattern",
            "timer:trigger?repeatCount=10&period",
            "timer:trigger?repeatCount=10&synchronous",
            "timer:trigger?repeatCount=10&time",
            "timer:trigger?repeatCount=10&timer");
        assertTrue("There is less options", strings.size() < 13);
    }

    private String getJavaCaretAfterQuestionMarkWithPreDataOptionsTestData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?re<caret>\")\n"
            + "                .to(\"file:outbox?delete=true&fileExist=Append\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaAfterQuestionMarkWithPreDataOptionsCompletion() {
        myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", getJavaCaretAfterQuestionMarkWithPreDataOptionsTestData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNull("Don't except any elements, because it the 're' is unique and return the repeatCount", strings);
    }

    private String getJavaEndOfLineTestData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=0&exchangePattern=RobustInOnly&<caret>\")\n"
            + "                .to(\"file:outbox?delete=true&fileExist=Append\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaEndOfLineOptionsCompletion() {
        myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", getJavaEndOfLineTestData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertTrue("There are many options", strings.size() > 9);
    }

    private String getJavaInsertAfterQuestionMarkTestData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?per<caret>repeatCount=0&exchangePattern=RobustInOnly\")\n"
            + "                .to(\"file:outbox?delete=true&fileExist=Append\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaInsertAfterQuestionMarkTestData() {
        String javaInsertAfterQuestionMarkTestData = getJavaInsertAfterQuestionMarkTestData();
        myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", javaInsertAfterQuestionMarkTestData);
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertEquals("There are many options", 1, strings.size());
        assertThat(strings, Matchers.contains("timer:trigger?period"));
        myFixture.type('\n');
        javaInsertAfterQuestionMarkTestData = javaInsertAfterQuestionMarkTestData.replace("<caret>", "iod=");
        myFixture.checkResult(javaInsertAfterQuestionMarkTestData);
    }

    private String getJavaMultilineTestData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10&\" +\n"
            + "                \"fixedRate=false\"+ \n"
            + "                \"&daemon=false\" + \n"
            + "                \"&period=10<caret>\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaMultilineTestData() {
        myFixture.configureByText("CamelRoute.java", getJavaMultilineTestData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertTrue("There are many options", strings.size() > 1);
        assertThat(strings, Matchers.not(Matchers.containsInAnyOrder(
            "timer:trigger?repeatCount=10&",
            "&fixedRate=false",
            "&daemon=false",
            "&period=10")));
        myFixture.type('\n');
        String javaInsertAfterQuestionMarkTestData = getJavaMultilineTestData().replace("<caret>", "&bridgeErrorHandler=");
        myFixture.checkResult(javaInsertAfterQuestionMarkTestData);
    }

    private String getJavaMultilineTest2Data() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10\"\n"
            + "                + \"&fixedRate=false<caret>\"\n"
            + "                + \"&daemon=false\" \n"
            + "                + \"&period=10\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaMultilineTest2Data() {
        myFixture.configureByText("CamelRoute.java", getJavaMultilineTest2Data());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertTrue("There are many options", strings.size() > 1);
        assertThat(strings, Matchers.not(Matchers.containsInAnyOrder(
            "timer:trigger?repeatCount=10",
            "&fixedRate=false",
            "&daemon=false",
            "&period=10")));
        myFixture.type('\n');
        String javaInsertAfterQuestionMarkTestData = getJavaMultilineTest2Data().replace("<caret>", "&bridgeErrorHandler=");
        myFixture.checkResult(javaInsertAfterQuestionMarkTestData);
    }

    private String getJavaMultilineTest3Data() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10\"+\n"
            + "                 \"&fixedRate=false\"+\n"
            + "                 \"&daemon=false\" \n"
            + "                + \"&period=10&<caret>\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaMultilineTest3Data() {
        myFixture.configureByText("CamelRoute.java", getJavaMultilineTest3Data());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertTrue("There are many options", strings.size() > 1);
        assertThat(strings, Matchers.not(Matchers.containsInAnyOrder(
            "timer:trigger?repeatCount=10",
            "&fixedRate=false",
            "&daemon=false",
            "&period=10")));
        myFixture.type('\n');
        String javaInsertAfterQuestionMarkTestData = getJavaMultilineTest3Data().replace("<caret>", "bridgeErrorHandler=");
        myFixture.checkResult(javaInsertAfterQuestionMarkTestData);
    }

    private String getJavaMultilineInFixSearchData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10\"+\n"
            + "                 \"&ex<caret>fixedRate=false\"+\n"
            + "                 \"&daemon=false\" \n"
            + "                + \"&period=10\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaMultilineInFixSearchData() {
        myFixture.configureByText("CamelRoute.java", getJavaMultilineInFixSearchData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertTrue("There are many options", strings.size() > 1);
        assertThat(strings, Matchers.containsInAnyOrder("&exceptionHandler", "&exchangePattern"));
        assertThat(strings, Matchers.not(Matchers.containsInAnyOrder(
            "timer:trigger?repeatCount=10",
            "&fixedRate=false",
            "&daemon=false",
            "&period=10")));
        myFixture.type('\n');
        String javaInsertAfterQuestionMarkTestData = getJavaMultilineInFixSearchData().replace("<caret>", "ceptionHandler=");
        myFixture.checkResult(javaInsertAfterQuestionMarkTestData);
    }

    private String getJavaMultilineTest4SearchData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"timer:trigger?repeatCount=10\"+\n"
            + "                 \"&fixedRate=false\"+\n"
            + "                 \"&daemon=false&\" \n"
            + "                + \"period=10<caret>\");\n"
            + "        }\n"
            + "    }";
    }
    public void testJavaMultilineTest4Data() {
        myFixture.configureByText("CamelRoute.java", getJavaMultilineTest4SearchData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertTrue("There are many options", strings.size() > 1);
        assertThat(strings, Matchers.not(Matchers.containsInAnyOrder(
            "timer:trigger?repeatCount=10",
            "fixedRate=false",
            "daemon=false",
            "period=10")));
        myFixture.type('\n');
        String javaMarkTestData = getJavaMultilineTest4SearchData().replace("<caret>", "&bridgeErrorHandler=");
        myFixture.checkResult(javaMarkTestData);
    }

    static String getJavaSourceKameletSuggestionsData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"kamelet:<caret>\");\n"
            + "        }\n"
            + "    }";
    }

    /**
     * Ensure that the name of the available source Kamelets can be suggested
     */
    public void testJavaSourceKameletSuggestions() {
        myFixture.configureByText("CamelRoute.java", getJavaSourceKameletSuggestionsData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertDoesntContain(strings, "kamelet:avro-deserialize-action", "kamelet:aws-sqs-sink");
        assertContainsElements(strings, "kamelet:aws-s3-source", "kamelet:ftp-source", "kamelet:webhook-source");
        myFixture.type("ft\n");
        String javaMarkTestData = getJavaSourceKameletSuggestionsData().replace("<caret>", "ftp-source");
        myFixture.checkResult(javaMarkTestData);
    }

    private String getJavaNonSourceKameletSuggestionsData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"stream:in\")"
            + "                .to(\"kamelet:<caret>\");\n"
            + "        }\n"
            + "    }";
    }

    /**
     * Ensure that the name of the available non source Kamelets can be suggested
     */
    public void testJavaNonSourceKameletSuggestions() {
        myFixture.configureByText("CamelRoute.java", getJavaNonSourceKameletSuggestionsData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertDoesntContain(strings, "kamelet:aws-s3-source", "kamelet:ftp-source", "kamelet:webhook-source");
        assertContainsElements(strings, "kamelet:avro-deserialize-action", "kamelet:aws-sqs-sink");
        myFixture.type("avro-d\n");
        String javaMarkTestData = getJavaNonSourceKameletSuggestionsData().replace("<caret>", "avro-deserialize-action");
        myFixture.checkResult(javaMarkTestData);
    }

    /**
     * Ensures that suggestions are only instances of {@link OptionSuggestion} when name of Kamelets are proposed.
     */
    public void testJavaKameletSuggestionsInstancesOfOptionSuggestion() {
        myFixture.configureByText("CamelRoute.java", getJavaSourceKameletSuggestionsData());
        myFixture.completeBasic();
        LookupElement[] suggestions = myFixture.getLookupElements();
        assertNotNull(suggestions);
        assertTrue(
            "Only instances of OptionSuggestion are expected",
            Arrays.stream(suggestions)
                .map(LookupElement::getObject)
                .anyMatch(o -> o instanceof OptionSuggestion)
        );
    }

    private String getJavaKameletOptionSuggestionsData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"kamelet:ftp-source?<caret>\");\n"
            + "        }\n"
            + "    }";
    }

    /**
     * Ensure that the configuration option of a given Kamelet can be suggested with other options.
     */
    public void testJavaKameletOptionSuggestions() {
        CamelPreferenceService.getService().setOnlyShowKameletOptions(false);
        myFixture.configureByText("CamelRoute.java", getJavaKameletOptionSuggestionsData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertContainsElements(strings, "kamelet:ftp-source?connectionHost", "kamelet:ftp-source?connectionPort", "kamelet:ftp-source?bridgeErrorHandler");
        myFixture.type("user\n");
        String javaMarkTestData = getJavaKameletOptionSuggestionsData().replace("<caret>", "username=");
        myFixture.checkResult(javaMarkTestData);
    }

    /**
     * Ensure that the configuration option of a given Kamelet can be suggested without other options.
     */
    public void testJavaKameletOptionAloneSuggestions() {
        CamelPreferenceService.getService().setOnlyShowKameletOptions(true);
        myFixture.configureByText("CamelRoute.java", getJavaKameletOptionSuggestionsData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertDoesntContain(strings, "kamelet:ftp-source?bridgeErrorHandler");
        assertContainsElements(strings, "kamelet:ftp-source?connectionHost", "kamelet:ftp-source?connectionPort");
        myFixture.type("connectionH\n");
        String javaMarkTestData = getJavaKameletOptionSuggestionsData().replace("<caret>", "connectionHost=");
        myFixture.checkResult(javaMarkTestData);
    }

    /**
     * Ensures that suggestions are only instances of {@link OptionSuggestion} when configuration options of a given
     * Kamelet are proposed.
     */
    public void testJavaKameletOptionSuggestionsInstancesOfOptionSuggestion() {
        myFixture.configureByText("CamelRoute.java", getJavaKameletOptionSuggestionsData());
        myFixture.completeBasic();
        LookupElement[] suggestions = myFixture.getLookupElements();
        assertNotNull(suggestions);
        assertTrue(
            "Only instances of OptionSuggestion are expected",
            Arrays.stream(suggestions)
                .map(LookupElement::getObject)
                .anyMatch(o -> o instanceof OptionSuggestion)
        );
    }

    private String getJavaKameletOptionValueSuggestionsData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"kamelet:ftp-source?passiveMode=<caret>\");\n"
            + "        }\n"
            + "    }";
    }

    /**
     * Ensure that the values of a configuration option of a given Kamelet can be suggested
     */
    public void testJavaKameletOptionValueSuggestions() {
        myFixture.configureByText("CamelRoute.java", getJavaKameletOptionValueSuggestionsData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        assertContainsElements(strings, "kamelet:ftp-source?passiveMode=true", "kamelet:ftp-source?passiveMode=false");
        myFixture.type('\n');
        String javaMarkTestData = getJavaKameletOptionValueSuggestionsData().replace("<caret>", "false");
        myFixture.checkResult(javaMarkTestData);
    }

    /**
     * Ensures that suggestions are only instances of {@link OptionSuggestion} when the values of a configuration option
     * of a given Kamelet are proposed.
     */
    public void testJavaKameletOptionValueSuggestionsInstancesOfOptionSuggestion() {
        myFixture.configureByText("CamelRoute.java", getJavaKameletOptionValueSuggestionsData());
        myFixture.completeBasic();
        LookupElement[] suggestions = myFixture.getLookupElements();
        assertNotNull(suggestions);
        assertTrue(
            "Only instances of OptionSuggestion are expected",
            Arrays.stream(suggestions)
                .map(LookupElement::getObject)
                .anyMatch(o -> o instanceof OptionSuggestion)
        );
    }

    private String getJavaKameletOptionFilteredSuggestionsData() {
        return "import org.apache.camel.builder.RouteBuilder;\n"
            + "public class MyRouteBuilder extends RouteBuilder {\n"
            + "        public void configure() throws Exception {\n"
            + "            from(\"kamelet:ftp-source?passiveMode=true&bridgeErrorHandler=true&<caret>\");\n"
            + "        }\n"
            + "    }";
    }

    /**
     * Ensure that configuration options of a given Kamelet can be filtered
     */
    public void testJavaKameletOptionFilteredSuggestions() {
        myFixture.configureByText("CamelRoute.java", getJavaKameletOptionFilteredSuggestionsData());
        myFixture.completeBasic();
        List<String> strings = myFixture.getLookupElementStrings();
        assertNotNull(strings);
        String prefix = "kamelet:ftp-source?passiveMode=true&bridgeErrorHandler=true&";
        assertDoesntContain(strings, prefix + "passiveMode", prefix + "bridgeErrorHandler");
        assertContainsElements(strings, prefix + "connectionHost", prefix + "connectionPort");
        myFixture.type("user\n");
        String javaMarkTestData = getJavaKameletOptionFilteredSuggestionsData().replace("<caret>", "username=");
        myFixture.checkResult(javaMarkTestData);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.8.0/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="./assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="./assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="./assets/TweenJS_16x16.png">

	<title>TweenJS v0.5.0 API Documentation : </title>

            API Documentation for: 0.5.0

APIs

Classes

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

CSSPlugin

Ease

Event

EventDispatcher

MotionGuidePlugin

SamplePlugin

Timeline

Tween

TweenJS

CreateJS

TweenJS

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

                        <meta HTTP-EQUIV="REFRESH" content="0; url=./modules/TweenJS.html">

redpajama_set_name: RedPajamaGithub


text:
kShotgunCost = 25
kShotgunDropCost = 25
kShotgunTechResearchTime = 60


text:
package org.apache.cassandra.cli;

import java.util.List;

/**
 * @author Pavel A. Yaskevich
 */
public class CliUserHelp
{
    public String banner;

    public String help;

    public List<CliCommandHelp> commands;
}


text:
//
// Code modified from: http://jsfiddle.net/AceJJ/2755/
//
var fireworks = false

var SCREEN_WIDTH = window.innerWidth,
    SCREEN_HEIGHT = window.innerHeight,
    mousePos = {
        x: 400,
        y: 300
    },

    // create canvas
    canvas = document.createElement('canvas'),
    context = canvas.getContext('2d'),
    particles = [],
    rockets = [],
    MAX_PARTICLES = 400,
    colorCode = 0;

// init
var runLoop0
var runLoop1
var runLoop2
function FIREWORKS() {
    if (fireworks){ return }
    fireworks = true
    document.body.appendChild(canvas);
    canvas.width = SCREEN_WIDTH;
    canvas.height = SCREEN_HEIGHT;
    runLoop0 = setInterval(() => launchFrom(SCREEN_WIDTH*.2), 400);
    runLoop1 = setInterval(() => launchFrom(SCREEN_WIDTH*.8), 400);
    runLoop2 = setInterval(loop, 1000 / 50);
}

function quite(){
    clearInterval(runLoop0)
    clearInterval(runLoop1)
    setTimeout(function (){
        fireworks = false
        clearInterval(runLoop2)
        document.body.removeChild(canvas);
    }, 10000)
}

function launch() {
    launchFrom(mousePos.x);
}

function launchFrom(x) {
    if (rockets.length < 10) {
        var rocket = new Rocket(x);
        rocket.explosionColor = Math.floor(Math.random() * 360 / 10) * 10;
        rocket.vel.y = Math.random() * -3 - 4;
        rocket.vel.x = Math.random() * 6 - 3;
        rocket.size = 8;
        rocket.shrink = 0.999;
        rocket.gravity = 0.01;
        rockets.push(rocket);
    }
}

var savedState
function loop() {
    // update screen size
    if (SCREEN_WIDTH != window.innerWidth) {
        canvas.width = SCREEN_WIDTH = window.innerWidth;
    }
    if (SCREEN_HEIGHT != window.innerHeight) {
        canvas.height = SCREEN_HEIGHT = window.innerHeight;
    }

		savedState = context.getImageData(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
		context.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)

    for (y = 0; y < SCREEN_HEIGHT; y++) {
			for (x = 0; x < SCREEN_WIDTH; x++) {
				savedState.data[4*(x+y*SCREEN_WIDTH)+3] = savedState.data[4*(x+y*SCREEN_WIDTH)+3] > .3 ? savedState.data[4*(x+y*SCREEN_WIDTH)+3]*.95 : 0
			}
		}

    // Clear canvas.
		context.putImageData(savedState, 0, 0)
    var existingRockets = [];

    for (var i = 0; i < rockets.length; i++) {
        // update and render
        rockets[i].update();
        rockets[i].render(context);

        // calculate distance with Pythagoras
        var distance = Math.sqrt(Math.pow(mousePos.x - rockets[i].pos.x, 2) + Math.pow(mousePos.y - rockets[i].pos.y, 2));

        // random chance of 1% if rockets is above the middle
        var randomChance = rockets[i].pos.y < (SCREEN_HEIGHT * 2 / 3) ? (Math.random() * 100 <= 1) : false;

/* Explosion rules
             - 80% of screen
            - going down
            - close to the mouse
            - 1% chance of random explosion
        */
        if (rockets[i].pos.y < SCREEN_HEIGHT / 5 || rockets[i].vel.y >= 0 || distance < 50 || randomChance) {
            rockets[i].explode();
        } else {
            existingRockets.push(rockets[i]);
        }
    }

    rockets = existingRockets;

    var existingParticles = [];

    for (var i = 0; i < particles.length; i++) {
        particles[i].update();

        // render and save particles that can be rendered
        if (particles[i].exists()) {
            particles[i].render(context);
            existingParticles.push(particles[i]);
        }
    }

    // update array with existing particles - old particles should be garbage collected
    particles = existingParticles;

    while (particles.length > MAX_PARTICLES) {
        particles.shift();
    }
}

function Particle(pos) {
    this.pos = {
        x: pos ? pos.x : 0,
        y: pos ? pos.y : 0
    };
    this.vel = {
        x: 0,
        y: 0
    };
    this.shrink = .97;
    this.size = 2;

    this.resistance = 1;
    this.gravity = 0;

    this.flick = false;

    this.alpha = 1;
    this.fade = 0;
    this.color = 0;
}

Particle.prototype.update = function() {
    // apply resistance
    this.vel.x *= this.resistance;
    this.vel.y *= this.resistance;

    // gravity down
    this.vel.y += this.gravity;

    // update position based on speed
    this.pos.x += this.vel.x;
    this.pos.y += this.vel.y;

    // shrink
    this.size *= this.shrink;

    // fade out
    this.alpha -= this.fade;
};

Particle.prototype.render = function(c) {
    if (!this.exists()) {
        return;
    }

    c.save();

    c.globalCompositeOperation = 'lighter';

    var x = this.pos.x,
        y = this.pos.y,
        r = this.size / 2;

    var gradient = c.createRadialGradient(x, y, 0.1, x, y, r);
    gradient.addColorStop(0.1, "rgba(255,255,255," + this.alpha + ")");
    gradient.addColorStop(0.8, "hsla(" + this.color + ", 100%, 50%, " + this.alpha + ")");
    gradient.addColorStop(1, "hsla(" + this.color + ", 100%, 50%, 0.1)");

    c.fillStyle = gradient;

    c.beginPath();
    c.arc(this.pos.x, this.pos.y, this.flick ? Math.random() * this.size : this.size, 0, Math.PI * 2, true);
    c.closePath();
    c.fill();

    c.restore();
};

Particle.prototype.exists = function() {
    return this.alpha >= 0.1 && this.size >= 1;
};

function Rocket(x) {
    Particle.apply(this, [{
        x: x,
        y: SCREEN_HEIGHT}]);

    this.explosionColor = 0;
}

Rocket.prototype = new Particle();
Rocket.prototype.constructor = Rocket;

Rocket.prototype.explode = function() {
    var f = document.getElementById('fireworks')
    var f1 = document.getElementById('fireworks1')
    var f2 = document.getElementById('fireworks2')
    var f3 = document.getElementById('fireworks3')
    var f4 = document.getElementById('fireworks4')

    if (!f.currentTime || f.ended){ f.play() }
    else if (!f1.currentTime || f1.ended){ f1.play() }
    else if (!f2.currentTime || f2.ended){ f2.play() }
    else if (!f3.currentTime || f3.ended){ f3.play() }
    else if (!f4.currentTime || f4.ended){ f4.play() }

    var count = Math.random() * 10 + 80;

    for (var i = 0; i < count; i++) {
        var particle = new Particle(this.pos);
        var angle = Math.random() * Math.PI * 2;

        // emulate 3D effect by using cosine and put more particles in the middle
        var speed = Math.cos(Math.random() * Math.PI / 2) * 15;

        particle.vel.x = Math.cos(angle) * speed;
        particle.vel.y = Math.sin(angle) * speed;

        particle.size = 10;

        particle.gravity = 0.2;
        particle.resistance = 0.92;
        particle.shrink = Math.random() * 0.05 + 0.93;

        particle.flick = true;
        particle.color = this.explosionColor;

        particles.push(particle);
    }
};

Rocket.prototype.render = function(c) {
    if (!this.exists()) {
        return;
    }

    c.save();

    c.globalCompositeOperation = 'lighter';

    var x = this.pos.x,
        y = this.pos.y,
        r = this.size / 2;

    var gradient = c.createRadialGradient(x, y, 0.1, x, y, r);
    gradient.addColorStop(0.1, "rgba(255, 255, 255 ," + this.alpha + ")");
    gradient.addColorStop(1, "rgba(0, 0, 0, " + 0 + ")");

    c.fillStyle = gradient;

    c.beginPath();
    c.arc(this.pos.x, this.pos.y, this.flick ? Math.random() * this.size / 2 + this.size / 2 : this.size, 0, Math.PI * 2, true);
    c.closePath();
    c.fill();

    c.restore();
};


text:
define(function () {
  'use strict';
  return function() {
    console.debug('Development mode, no templates to inject.');
  };
});


text:
/*
This file contains main function for Shared Assembly.
*/

////////////////////////////////////////////////////////////////////////////////

#if defined(GKC_OS_WINDOWS)
	#include "Windows/sa_main.cpp"
#elif defined(GKC_OS_LINUX)
	#include "Linux/sa_main.cpp"
#else
	#error Error OS type!
#endif

//others
#include "_sys_base.cpp"

////////////////////////////////////////////////////////////////////////////////


text:
$(function() {
  var PromoSlider = new MasterSlider();
  PromoSlider.setup('masterslider-promo' , {
	  width: 1400,    // PromoSlider standard width
	  height: 580,   // PromoSlider standard height
	  space: 1,
	  speed: 70,
	  layout: 'fullwidth',
	  loop: true,
	  preload: 0,
	  autoplay: true,
  });
  // adds Arrows navigation control to the PromoSlider.
  PromoSlider.control('arrows');
  PromoSlider.control('lightbox');
  PromoSlider.control('thumblist' , {autohide:false ,dir:'h',align:'bottom', width:200, height:120, margin:0, space:0 , hideUnder:500});
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/toast_layout"
     android:orientation="horizontal"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:padding="10dp"
     android:paddingLeft="10dp"
     android:paddingRight="10dp"
     android:layout_marginLeft="10dp"
     android:layout_marginRight="10dp">

     <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#DAAA"
        android:paddingTop="5dp"
        android:paddingBottom="5dp">

            <ImageView
                android:id="@+id/toastImage"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:src="@drawable/ic_pb"
                android:padding="10dp"
                />

            <TextView
                 android:id="@+id/toastText"
                 android:layout_width="wrap_content"
                 android:layout_height="fill_parent"
                 android:textSize="10pt"
                 android:textStyle="bold"
                 android:textColor="#000"
                 android:layout_gravity="center_vertical"
                 android:gravity="center"
                 android:layout_marginRight="10dp"
                 />

    </LinearLayout>

</LinearLayout>


text:
require_relative 'base'

DB.create_table?(:comments) do
  primary_key :id
  foreign_key :author_id, :authors, index: true, on_delete: :cascade
  foreign_key :post_slug, :posts, type: String, index: true, on_delete: :cascade, on_update: :cascade
  String :body, text: true, null: false
  Float :created_at
  Float :updated_at
end

class Comment < Sequel::Model
  plugin :auto_validations, not_null: :presence
  plugin :timestamps

  set_allowed_columns :body

  many_to_one :author
  many_to_one :post

  def validate
    super
    validates_not_null [:author, :post]
  end
end

class CommentSerializer < BaseSerializer
  attribute :body

  has_one :author
  has_one :post
end

CommentController = proc do
  helpers do
    def find(id)
      Comment.with_pk(id.to_i)
    end

    def role
      Array(super).tap do |a|
        a << :owner if resource&.author == current_user
      end
    end
  end

  show do
    next resource, include: 'author'
  end

  create(roles: :logged_in) do |attr|
    comment = Comment.new(attr)
    comment.save(validate: false)
    next_pk comment
  end

  update(roles: %i[owner superuser]) do |attr|
    resource.set(attr)
    resource.save_changes(validate: false)
  end

  destroy(roles: %i[owner superuser]) do
    resource.destroy
  end

  has_one :post do
    pluck do
      resource.post
    end

    graft(roles: :superuser, sideload_on: :create) do |rio|
      resource.post = Post.with_pk!(rio[:id].to_i)
      resource.save_changes(validate: !sideloaded?)
    end
  end

  has_one :author do
    pluck do
      resource.author
    end

    graft(roles: :superuser, sideload_on: :create) do |rio|
      halt 403, 'You may only assign yourself as comment author!' \
        unless role?(:superuser) || rio[:id].to_i == current_user.id

      resource.author = Author.with_pk!(rio[:id].to_i)
      resource.save_changes(validate: !sideloaded?)
    end
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../">
  <title data-ice="title">lib/Generic/MethodsProxy.js | DEEP Core Library API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home
  Identifier
  Source

  Repository

    <input class="search-input">

AWS
CRegion

CService

AWS/IAM
CAction

CCollection

CExtractable

CFactory

CPolicy

CResource

CStatement

AWS/IAM/Exception
CInvalidArnException

AWS/Lambda
CContext

CErrorResponse

CRequest

CResolver

CResponse

CRuntime

AWS/Lambda/Exception
CContextAlreadySentException

CInvalidCognitoIdentityException

CMissingRuntimeContextException

CMissingUserContextException

Exception
CDatabaseOperationException

CException

CInvalidArgumentException

CMethodsNotImplementedException

Generic
CMethodsProxy

CObjectStorage

CObjectVector

CUniversalRequire

HTTP
CHelper

OOP
CInterface

Runtime
CSandbox

lib/Generic/MethodsProxy.js

/**
 * Created by AlexanderC on 11/10/15.
 */

'use strict';

export class MethodsProxy {
  /**
   * @param {Object} target
   */
  constructor(target) {
    this._target = target;
    this._decorator = null;
  }

  /**
   * @returns {Object}
   */
  get target() {
    return this._target;
  }

  /**
   * @param {Function} decorator
   * @returns {MethodsProxy}
   */
  decorate(decorator) {
    this._decorator = decorator;

    return this;
  }

  /**
   * @param {Object} handler
   * @param {String|String[]} explMethods
   * @returns {Object}
   */
  proxyOverride(handler, ...explMethods) {
    let methods = Object.keys(handler).concat(explMethods);

    for (let i in methods) {
      if (!methods.hasOwnProperty(i)) {
        continue;
      }

      let prop = methods[i];

      if (!handler.hasOwnProperty(prop) &&
        explMethods.indexOf(prop) === -1) {
        continue;
      }

      if (typeof handler[prop] === 'function') {
        Object.defineProperty(
          this._target,
          prop,
          {
            value: (...args) => {
              return (typeof this._decorator === 'function') ?
                this._decorator(handler, prop, ...args) :
                handler[prop](...args);
            },
          }
        );
      }
    }

    return this._target;
  }

  /**
   * @param {Object} handler
   * @param {String|String[]} explMethods
   * @returns {Object}
   *
   * @todo Replace typeof hook with hasOwnProperty() when get rid of babel
   */
  proxy(handler, ...explMethods) {
    return this.proxyOverride(
      handler,
      ...(explMethods.filter((prop) => typeof this._target[prop] === 'undefined'))
    );
  }
}

  Generated by ESDoc(0.3.1)


text:
package com.sun.xml.internal.txw2;

import java.util.AbstractList;
import java.util.Collections;
import java.util.List;
import javax.xml.namespace.QName;

/**
 * Pluggable datatype writer.
 *
 * @author Kohsuke Kawaguchi
 */
public interface DatatypeWriter<DT> {

    /**
     * Gets the Java class that this writer can write.
     *
     * @return
     *      must not be null. Must be the same value always.
     */
    Class<DT> getType();

    /**
     * Prints the given datatype object and appends that result
     * into the given buffer.
     *
     * @param dt
     *      the datatype object to be printed.
     * @param resolver
     *      allows the converter to declare additional namespace prefixes.
     */
    void print(DT dt, NamespaceResolver resolver, StringBuilder buf);

    static final List<DatatypeWriter<?>> BUILTIN = Collections.unmodifiableList(new AbstractList() {

        private DatatypeWriter<?>[] BUILTIN_ARRAY = new DatatypeWriter<?>[] {
            new DatatypeWriter<String>() {
                public Class<String> getType() {
                    return String.class;
                }
                public void print(String s, NamespaceResolver resolver, StringBuilder buf) {
                    buf.append(s);
                }
            },
            new DatatypeWriter<Integer>() {
                public Class<Integer> getType() {
                    return Integer.class;
                }
                public void print(Integer i, NamespaceResolver resolver, StringBuilder buf) {
                    buf.append(i);
                }
            },
            new DatatypeWriter<Float>() {
                public Class<Float> getType() {
                    return Float.class;
                }
                public void print(Float f, NamespaceResolver resolver, StringBuilder buf) {
                    buf.append(f);
                }
            },
            new DatatypeWriter<Double>() {
                public Class<Double> getType() {
                    return Double.class;
                }
                public void print(Double d, NamespaceResolver resolver, StringBuilder buf) {
                    buf.append(d);
                }
            },
            new DatatypeWriter<QName>() {
                public Class<QName> getType() {
                    return QName.class;
                }
                public void print(QName qn, NamespaceResolver resolver, StringBuilder buf) {
                    String p = resolver.getPrefix(qn.getNamespaceURI());
                    if(p.length()!=0)
                        buf.append(p).append(':');
                    buf.append(qn.getLocalPart());
                }
            }
        };

        public DatatypeWriter<?> get(int n) {
          return BUILTIN_ARRAY[n];
        }

        public int size() {
          return BUILTIN_ARRAY.length;
        }
      });
}


text:
package realmrelay.packets.client;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import realmrelay.packets.Packet;

public class PongPacket extends Packet {

	public int serial;
	public int time;

	@Override
	public void parseFromInput(DataInput in) throws IOException {
		this.serial = in.readInt();
		this.time = in.readInt();
	}

	@Override
	public void writeToOutput(DataOutput out) throws IOException {
		out.writeInt(this.serial);
		out.writeInt(this.time);
	}

}


text:
#!/usr/bin/env node

function getTime(minutes) {
    var baseTime = new Date();
    baseTime.setHours('00');
    baseTime.setMinutes('00');
    baseTime.setSeconds('00');

    return baseTime.getTime() + minutes * 60 * 1000;

}

/* Return basal rate(U / hr) at the provided timeOfDay */

function basalLookup() {
    var now = new Date();
    basalRate = Math.round(basalprofile_data[basalprofile_data.length-1].rate*100)/100

    for (var i = 0; i < basalprofile_data.length - 1; i++) {
        if ((now >= getTime(basalprofile_data[i].minutes)) && (now < getTime(basalprofile_data[i + 1].minutes))) {
            basalRate = basalprofile_data[i].rate.toFixed(2);
            break;
        }
    }
}

function fileHM(file) {
    var filedate = new Date(fs.statSync(file).mtime);
    var HMS = filedate.toLocaleTimeString().split(":")
    return HMS[0].concat(":", HMS[1]);
}

if (!module.parent) {
    var argv = require('yargs')
        .usage('$0 <glucose.json> <iob.json> <current_basal_profile.json> <currenttemp.json> <requestedtemp.json> <enactedtemp.json> [meal.json]')
        .demand(6)
        .strict(true)
        .help('help');

    var fs = require('fs');

    var params = argv.argv;
    var inputs = params._;

    var glucose_input = inputs[0];
    var iob_input = inputs[1];
    var basalprofile_input = inputs[2];
    var currenttemp_input = inputs[3];
    var requestedtemp_input = inputs[4];
    var enactedtemp_input = inputs[5];
    var meal_input = inputs[6];

    if (inputs.length > 7) {
        argv.showHelp();
        console.error('Too many arguments');
        process.exit(1);
    }

    var cwd = process.cwd()
    var file = cwd + '/' + glucose_input;
    var glucose_data = require(file);
    var bgTime = fileHM(file);
    if (glucose_data[0].dateString) {
        var bgDate = new Date(glucose_data[0].dateString);
        var HMS = bgDate.toLocaleTimeString().split(":")
        bgTime = HMS[0].concat(":", HMS[1]);
    }

    var bgnow = glucose_data[0].glucose;
    var delta = glucose_data[0].glucose - glucose_data[1].glucose;
    var tick = delta;
    if (delta >= 0) { tick = "+" + delta; }
    var iob_data = require(cwd + '/' + iob_input);
    iob = iob_data[0].iob.toFixed(1);
    var basalprofile_data = require(cwd + '/' + basalprofile_input);
    var basalRate;
    basalLookup();
    file = cwd + '/' + currenttemp_input;
    var temp = require(file);
    var temp_time = fileHM(file);
    var tempstring;
    if (temp.duration < 1) {
        tempstring = "No temp basal";
    } else {
        tempstring = "Tmp: " + temp.duration + "m @ " + temp.rate.toFixed(1);
    }
    try {
        var requestedtemp = require(cwd + '/' + requestedtemp_input);
    } catch (e) {
        return console.error("Could not parse requestedtemp: ", e);
    }
    var reqtempstring;
    if (typeof requestedtemp.duration === 'undefined') {
        reqtempstring = "None";
    }
    else if (requestedtemp.duration < 1) {
        reqtempstring = "Cancel";
    } else {
        reqtempstring = requestedtemp.duration + "m@" + requestedtemp.rate.toFixed(1) + "U";
    }
    //var enactedtemp = require(cwd + '/' + enactedtemp_input);
    //if (enactedtemp.duration < 1) {
        //enactedstring = "Cancel";
    //} else {
        //enactedstring = enactedtemp.duration + "m@" + enactedtemp.rate.toFixed(1) + "U";
    //}
    tz = new Date().toString().match(/([-+][0-9]+)\s/)[1]
    //enactedDate = new Date(enactedtemp.timestamp.concat(tz));
    //enactedHMS = enactedDate.toLocaleTimeString().split(":")
    //enactedat = enactedHMS[0].concat(":", enactedHMS[1]);

    var mealCOB = "???";
    if (typeof meal_input !== 'undefined') {
        try {
            meal_data = JSON.parse(fs.readFileSync(meal_input, 'utf8'));
            //console.error(JSON.stringify(meal_data));
            if (typeof meal_data.mealCOB !== 'undefined') {
                mealCOB = meal_data.mealCOB;
            }
        } catch (e) {
            //console.error("Optional feature Meal Assist not configured.");
        }
    }

//console.log("");

console.log("");
    console.log("<title>");
        console.log( bgnow + " " + tick + " at " + bgTime );
    console.log("</title>");
    console.log('<meta http-equiv="refresh" content="60">');
    console.log('<meta name="viewport" content="width=500">');
console.log("");

console.log("");

        console.log("
");
        console.log( bgnow + " " + tick + " at " + bgTime );
        console.log("
");
        console.log( "IOB: " + iob + "U, eventually " + requestedtemp.eventualBG + " mg/dL" );
        console.log("
");
        //+ "Act: " + enactedstring
        //+ " at " + enactedat + "\n"
        console.log( tempstring );
        console.log( "U/hr at " + temp_time );
        console.log("
");
        console.log("
");
        console.log( "Req: " + reqtempstring );
        console.log("
");
        console.log( requestedtemp.reason );
        console.log("
");
        console.log( "Sched: " + basalRate + "U/hr" );
        console.log("
");
        console.log( "mealCOB: " + mealCOB + "g" );

console.log("");

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<title>Pluggin jRating : Ajax rating system with jQuery</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" href="jquery/jRating.jquery.css" type="text/css" />

Full documentation on MyjQueryPlugins.com/jRating

Live demonstration on jRating demonstration page

jRating plugin

	Exemple 1 (Basic exemple without options) :

<?php
echo htmlentities('

');
?>

	Exemple 2 (type : small - average 10 - id 2 - 40 stars) :

<?php
echo htmlentities('

');
?>

	Exemple 3 (step : true - average 18 - id 3 - 15 stars) :

<?php
echo htmlentities('

');
?>

	Exemple 4 (Rate is disabled) :

<?php
echo htmlentities('

');
?>

	Exemple 5 (With onSuccess & onError methods) :

<?php
echo htmlentities('

');
?>

	Exemple 6 (Disabled rate info) :

<?php
echo htmlentities('

');
?>

	Datas sent to the server :

	Server response :


text:
#import "ReunionMapHomeViewController.h"
#import "MapKit+KGOAdditions.h"
#import "MapModule.h"
#import <QuartzCore/QuartzCore.h>
#import "UIKit+KGOAdditions.h"
#import "KGOSidebarFrameViewController.h"
#import "KGOAppDelegate+ModuleAdditions.h"

@implementation ReunionMapHomeViewController

@synthesize startFrame, startRegion;

- (void)viewDidLoad {
    [super viewDidLoad];

    // region and annotations may be set before _mapView was set up
    if (self.annotations.count) {
        [_mapView addAnnotations:self.annotations];
        if (!_didSetRegion) {
            MKCoordinateRegion region = [MapHomeViewController regionForAnnotations:self.annotations restrictedToClass:NULL];
            if (region.center.latitude && region.center.longitude) {
                _mapView.region = region;
            }
        }
    } else {
        [_mapView centerAndZoomToDefaultRegion];
    }

    // set up search bar
    if ([KGO_SHARED_APP_DELEGATE() navigationStyle] == KGONavigationStyleTabletSidebar) {
        _searchController.showsSearchOverlay = NO;
    }

    if (_didSetRegion) {
        _didSetRegion = NO;

        _mapBorder.clipsToBounds = YES;
        _mapBorder.autoresizesSubviews = NO;

        CGRect mapEndFrame = _mapView.frame;

        // fake up our own autoresizing here
        KGOSidebarFrameViewController *homescreen = (KGOSidebarFrameViewController *)[KGO_SHARED_APP_DELEGATE() homescreen];
        CGFloat hScaling = homescreen.container.bounds.size.width / self.view.bounds.size.width;
        CGFloat vScaling = homescreen.container.bounds.size.height / self.view.bounds.size.height;

        CGPoint mapLowerRight = CGPointMake(round(hScaling * mapEndFrame.size.width),
                                            round(vScaling * mapEndFrame.size.height));

        mapEndFrame.size = CGSizeMake(mapLowerRight.x - mapEndFrame.origin.x, mapLowerRight.y - mapEndFrame.origin.y);

        CGRect mapStartFrame = [_mapView convertRect:mapEndFrame toView:self.view];
        CGRect borderEndFrame = _mapBorder.frame;
        CGRect borderStartFrame = self.startFrame;
        _mapBorder.frame = borderStartFrame;

        _mapView.region = self.endRegion;

        mapStartFrame = [self.view convertRect:mapStartFrame toView:_mapBorder];
        _mapView.frame = mapStartFrame;

        CGRect frame = mapStartFrame;
        frame.origin.x -= 4; // cheat to make alignment look better

        MKCoordinateRegion region = [_mapView convertRect:frame toRegionFromView:_mapBorder];
        _mapView.region = region;

        [UIView animateWithDuration:1
                              delay:0
                            options:0
                         animations:^(void) {

            _mapView.frame = mapEndFrame;
            _mapBorder.frame = borderEndFrame;

        } completion:^(BOOL finished) {
            _mapBorder.autoresizesSubviews = YES;

        }];
    }
}

- (void)setEndRegion:(MKCoordinateRegion)endRegion
{
    _endRegion = endRegion;
    _didSetRegion = YES;
}

- (MKCoordinateRegion)endRegion
{
    return _endRegion;
}

@end


text:
package gov.hhs.fha.nhinc.admindistribution.nhin.proxy;

import oasis.names.tc.emergency.edxl.de._1.EDXLDistribution;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author dunnek
 */
public class NhinAdminDistributionProxyNoOpImpl implements NhinAdminDistributionProxy {
    private Log log = null;

    public NhinAdminDistributionProxyNoOpImpl() {
        log = createLogger();
    }

    protected Log createLogger() {
        return LogFactory.getLog(getClass());
    }

    public void sendAlertMessage(EDXLDistribution body, AssertionType assertion, NhinTargetSystemType target,
            NhincConstants.GATEWAY_API_LEVEL apiLevel) {
        log.info("begin send alert");
    }
}


text:
<?php

require_once dirname(dirname(dirname(__FILE__))) . '/vendor/lusitanian/oauth/src/OAuth/bootstrap.php';

class Controller_Login extends Controller_Account
{

    protected function _preDispatch()
    {
        parent::_preDispatch();
    }

    public function get()
    {
        $this->_preDispatch();

        $this->_redirect($_SERVER['HTTP_REFERER']);
    }
}


text:
require 'rest-client'
require 'pathname'
require 'find'
require 'digest/md5'
require 'json'

module CloudDrive

  class Node

    def initialize(account)
      @account = account
    end

    def build_node_path(node)
      path = []
      loop do
        path.push node["name"]

        break if node.has_key?('isRoot') && node['isRoot'] == true

        results = find_by_id(node["parents"][0])
        if results[:success] == false
          raise "No parent node found with ID #{node["parents"][0]}"
        end

        node = results[:data]

        break if node.has_key?('isRoot') && node['isRoot'] === true
      end

      path = path.reverse
      path.join('/')
    end

    def create_new_folder(name, parent_id = nil)
      if parent_id == nil
        parent_id = get_root['id']
      end

      body = {
          :name => name,
          :parents => [
              parent_id
          ],
          :kind => "FOLDER"
      }

      retval = {
          :success => false,
          :data => []
      }

      RestClient.post(
          "#{@account.metadata_url}nodes",
          body.to_json,
          :Authorization => "Bearer #{@account.access_token}"
      ) do |response, request, result|
        data = JSON.parse(response.body)
        retval[:data] = data
        if response.code === 201
          retval[:success] = true
          @account.save_node(data)
        end
      end

      retval
    end

    def create_directory_path(path)
      retval = {
        :success => true,
        :data => {}
      }

      path = get_path_array(path)
      previous_node = get_root

      match = nil
      path.each_with_index do |folder, index|
        xary = path.slice(0, index + 1)
        if (match = find_by_path(xary.join('/'))) === nil
          result = create_new_folder(folder, previous_node["id"])
          if result[:success] === false
            return result
          end

          match = result[:data]
        end

        previous_node = match
      end

      if match == nil
        retval[:data] = previous_node
      else
        retval[:data] = match
      end

      retval
    end

    # If given a local file, the MD5 will be compared as well
    def exists?(remote_file, local_file = nil)
      if (file = find_by_path(remote_file)) == nil
        if local_file != nil
          if (file = find_by_md5(Digest::MD5.file(local_file).to_s)) != nil
            path = build_node_path(file)
            return {
                :success => true,
                :data => {
                    "message" => "File with same MD5 exists at #{path}: #{file.to_json}",
                    "path_match" => false,
                    "md5_match" => true
                }
            }
          end
        end
        return {
            :success => false,
            :data => {
                "message" => "File #{remote_file} does not exist"
            }
        }
      end

      retval = {
          :success => true,
          :data => {
              "message" => "File #{remote_file} exists",
              "path_match" => true,
              "md5_match" => false,
              "node" => file
          }
      }

      if local_file != nil
        if file["contentProperties"] != nil && file["contentProperties"]["md5"] != nil
          if Digest::MD5.file(local_file).to_s != file["contentProperties"]["md5"]
            retval[:data]["message"] = "File #{remote_file} exists but checksum doesn't match"
          else
            retval[:data]["message"] = "File #{remote_file} exists and is identical"
            retval[:data]["md5_match"] = true
          end
        else
          retval[:data]["message"] = "File #{remote_file} exists, but no checksum is available"
        end
      end

      retval
    end

    def find_by_id(id)
      retval = {
          :success => false,
          :data => {}
      }

      results = @account.db.execute("SELECT raw_data FROM nodes WHERE id = ?;", id)
      if results.empty?
        return retval
      end

      if results.count > 1
        raise "Multiple nodes with same ID found: #{results[:data].to_json}"
      end

      {
          :success => true,
          :data => JSON.parse(results[0][0])
      }
    end

    def find_by_md5(hash)
      results = @account.db.execute("SELECT raw_data FROM nodes WHERE md5 = ?;", hash)
      if results.empty?
        return nil
      end

      if results.count > 1
        raise "Multiple nodes with same MD5: #{results.to_json}"
      end

      JSON.parse(results[0][0])
    end

    def find_by_name(name)
      retval = []
      results = @account.db.execute("SELECT raw_data FROM nodes WHERE name = ?;", name)
      if results.empty?
        return retval
      end

      results.each do |result|
          retval.push(JSON.parse(result[0]))
      end

      retval
    end

    def find_by_path(path)
      path = path.gsub(/\A\//, '')
      path = path.gsub(/\/$/, '')

      if path == ''
        return get_root
      end

      path_info = Pathname.new(path)

      found_nodes = find_by_name(path_info.basename.to_s)
      if found_nodes.empty?
        return nil
      end

      match = nil
      found_nodes.each do |node|
        if build_node_path(node) == path
          match = node
        end
      end

      match
    end

    # @TODO: there's probably a better way to do this locally than check the last
    # `id` in the `parent` string is the parent...
    def get_children(id)
      retval = {
        :success => true,
        :data => []
      }

      nodes = @account.db.execute("SELECT raw_data FROM nodes WHERE parents LIKE '%#{id}';")
      if nodes.kind_of?(Array)
        nodes.each do |node|
          retval[:data].push(JSON.parse(node[0]))
        end
      else
        retval[:data] = JSON.parse(nodes)
      end

      retval
    end

    def get_path_array(path)
      return path if path.kind_of?(Array)

      path = path.split('/')
      path.reject! do |value|
        value.empty?
      end

      path
    end

    def get_path_string(path)
      path = path.join '/' if path.kind_of?(Array)

      path.chomp
    end

    def get_root
      results = find_by_name('root')
      if results.empty?
        raise "No node by the name of 'root' found in database"
      end

      results.each do |node|
        if node.has_key?('isRoot') && node['isRoot'] === true
          return node
        end
      end

      nil
    end

    def upload_dir(src_path, dest_root, overwrite = false, show_progress = false)
      src_path = File.expand_path(src_path)

      dest_root = get_path_array(dest_root)
      dest_root.push(get_path_array(src_path).last)
      dest_root = get_path_string(dest_root)

      retval = []
      Find.find(src_path) do |file|
        # Skip root directory, no need to make it
        next if file == src_path || File.directory?(file)

        path_info = Pathname.new(file)
        remote_dest = path_info.dirname.sub(src_path, dest_root).to_s

        result = upload_file(file, remote_dest, overwrite)
        if show_progress == true
          if result[:success] == true
            puts "Successfully uploaded file #{file}: #{result[:data].to_json}"
          else
            puts "Failed to uploaded file #{file}: #{result[:data].to_json}"
          end
        end

        retval.push(result)

        # Since uploading a directory can take a while (depending on number/size of files)
        # we will check if we need to renew our authorization after each file upload to
        # make sure our authentication doesn't expire.
        if (Time.new.to_i - @account.token_store["last_authorized"]) > 60
          result = @account.renew_authorization
          if result[:success] === false
            raise "Failed to renew authorization: #{result[:data].to_json}"
          end
        end
      end

      retval
    end

    def upload_file(src_path, dest_path, overwrite = false)
      retval = {
          :success => false,
          :data => {}
      }

      path_info = Pathname.new(src_path)
      dest_path = get_path_string(get_path_array(dest_path))

      result = create_directory_path(dest_path)
      return result if result[:success] == false

      dest_folder = result[:data]

      result = exists?("#{dest_path}/#{path_info.basename}", src_path)
      if result[:success] == true
        if overwrite == false
          retval[:data] = result[:data]

          return retval
        end

        if result[:data]["md5_match"]
          retval[:data]["message"] = "Identical file already exists at #{dest_path}."

          return retval
        end

        return overwrite_file(src_path, result[:data]["node"])
      end

      body = {
          :metadata => {
              :kind => 'FILE',
              :name => path_info.basename,
              :parents => [
                  dest_folder["id"]
              ]
          }.to_json,
          :content => File.new(File.expand_path(src_path), 'rb')
      }

      RestClient.post("#{@account.content_url}nodes", body, :Authorization => "Bearer #{@account.access_token}") do |response, request, result|
        retval[:data] = JSON.parse(response.body)
        if response.code === 201
          retval[:success] = true
          @account.save_node(retval[:data])
        end
      end

      retval
    end

    def overwrite_file(src_path, node)
      retval = {
        :success => false,
        :data => {}
      }

      body = {
          :content => File.new(File.expand_path(src_path), 'rb')
      }

      RestClient.put("#{@account.content_url}nodes/#{node["id"]}/content", body, :Authorization => "Bearer #{@account.access_token}") do |response, request, result|
        retval[:data] = JSON.parse(response.body)
        if response.code === 200
          retval[:success] = true
          @account.save_node(retval[:data])
        end
      end

      retval
    end

  end

end


text:
package fi.imberg.juhani.ernu.parser.parsers;

import fi.imberg.juhani.ernu.interpreter.interfaces.Node;
import fi.imberg.juhani.ernu.interpreter.nodes.ImportNode;
import fi.imberg.juhani.ernu.parser.Parser;
import fi.imberg.juhani.ernu.parser.Token;
import fi.imberg.juhani.ernu.parser.TokenType;
import fi.imberg.juhani.ernu.parser.exceptions.LangException;

import java.util.ArrayList;
import java.util.List;

/**
 * Parses an expression for an import statement. For example from math import sqrt
 */
public class ImportParser implements PrefixParser {
    @Override
    public Node parse(Parser parser, Token token) throws LangException {
        String what = "";
        String as = "";
        List<String> subs = new ArrayList<>();
        while (!(parser.isNext(TokenType.EOL) || parser.isNext(TokenType.AS) || parser.isNext(TokenType.IMPORT))) {
            what += parser.consume().getContent();
        }
        if (parser.match(TokenType.AS)) {
            as = parser.consume().getContent();
        } else if (parser.match(TokenType.IMPORT)) {
            do {
                subs.add(parser.consume(TokenType.IDENTIFIER).getContent());
            } while (parser.match(TokenType.COMMA));
        }
        return new ImportNode(what, as, subs);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Polyschistes mairei Werner

### Remarks
null


text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.enterprise.gsafeed.groups;

import javax.xml.bind.annotation.XmlRegistry;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the com.google.enterprise.gsafeed.generated.groups package.
 * <p>An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

  /**
   * Create a new ObjectFactory that can be used to create new
   * instances of schema derived classes for package:
   * com.google.enterprise.gsafeed.generated.groups
   */
  public ObjectFactory() {
  }

  /**
   * Create an instance of {@link Principal}
   */
  public Principal createPrincipal() {
    return new Principal();
  }

  /**
   * Create an instance of {@link Members}
   */
  public Members createMembers() {
    return new Members();
  }

  /**
   * Create an instance of {@link Xmlgroups}
   */
  public Xmlgroups createXmlgroups() {
    return new Xmlgroups();
  }

  /**
   * Create an instance of {@link Membership}
   */
  public Membership createMembership() {
    return new Membership();
  }
}


text:
<?php
namespace Riskio\EventScheduler\TemporalExpression;

use DateTimeInterface;
use Riskio\EventScheduler\ValueObject\Semester as SemesterValueObject;

class Semester implements TemporalExpressionInterface
{
    /**
     * @var SemesterValueObject
     */
    protected $semester;

    public function __construct(int $semester)
    {
        $this->semester = new SemesterValueObject($semester);
    }

    public function includes(DateTimeInterface $date) : bool
    {
        $semester = SemesterValueObject::fromNativeDateTime($date);

        return $this->semester->sameValueAs($semester);
    }
}


text:
using System;
using System.Collections.Generic;

namespace EnterSentials.Framework
{
    public interface IContextProvidingEvent : IEvent
    {
        IEnumerable<Tuple<Type, object>> GetContext();
    }
}


text:
namespace Daishi.SQLBuilder.UnitTests {
    internal class DummyPOCOWithIntId {
        public int Id { get; set; }
    }
}


text:
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

# 1.1.0 (2020-01-09)

### Features

* **env:** init env package


text:
desc "roff FILE [TO]", "Simulate the operation of ROFF"
option 'asis',    :aliases=>'-a', :type=>'boolean', :desc=>"Do not attempt to decode file first"
option "debug",   :aliases=>'-D', :type=>'boolean', :desc=>"Produce debugging output"
option "dir",     :aliases=>'-d', :type=>'string',  :desc=>"Set working directory"
option "expand",  :aliases=>'-e', :type=>'boolean', :desc=>"Expand freezer archives into multiple files"
option "shard",   :aliases=>'-S', :type=>'string',  :desc=>"Select shards with this pattern (only with frozen files)"
option "summary", :aliases=>'-s', :type=>'boolean', :desc=>"Print a processing summary at the end"
def roff(from, to='-')
  check_for_unknown_options(from, to)
  shard = options[:shard]
  from, shard_2 = Bun::File.get_shard(from)
  shard = shard_2 || shard
  File::Baked.roff(from, to, options.merge(shard: shard, promote: !options[:asis]))
end


text:
package com.intellij.editor;

import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.testFramework.EditorTestUtil;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import org.jetbrains.annotations.NotNull;

import java.io.File;

/**
 * @author Rustam Vishnyakov
 */
public class XmlEditorTest extends LightCodeInsightTestCase {
  private String getTestFilePath(boolean isOriginal) {
    return "/xml/tests/testData/editor/" + getTestName(true) + (isOriginal ? ".xml" : "_after.xml") ;
  }

  public void testEnterPerformance() throws Exception {
    configureByFile(getTestFilePath(true));
    EditorTestUtil.performTypingAction(myEditor, '\n');
    PlatformTestUtil.assertTiming("PHP editor performance", 7500, 1, new Runnable() {
      public void run() {
        for (int i = 0; i < 3; i ++) {
          EditorTestUtil.performTypingAction(myEditor, '\n');
        }
      }
    });
    checkResultByFile(getTestFilePath(false));
  }

  public void testHardWrap() throws Exception {
    configureFromFileText("a.xml",
                          "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n" +
                          "<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\">\n" +
                          "<g>\n" +
                          "        <path clip-path=\"url(#SVGID_2_)\" fill=\"#ffffff\" stroke=\"<selection>#000000</selection>\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-miterlimit=\"10\" d=\"M19.333,8.333V12c0,1.519-7.333,4-7.333,4s-7.333-2.481-7.333-4V8.333\"/>\n" +
                          "</g>\n" +
                          "</svg>");

    CodeStyleSettings clone = CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings().clone();
    clone.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN = true;
    try {
      CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(clone);
      EditorTestUtil.performTypingAction(getEditor(), 'x');
    }
    finally {
      CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings();
    }
    checkResultByText("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n" +
                      "<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\">\n" +
                      "<g>\n" +
                      "        <path clip-path=\"url(#SVGID_2_)\" fill=\"#ffffff\" stroke=\"x\" stroke-width=\"2\" stroke-linecap=\"round\" \n" +
                      "              stroke-linejoin=\"round\" stroke-miterlimit=\"10\" d=\"M19.333,8.333V12c0,1.519-7.333,4-7.333,4s-7.333-2.481-7.333-4V8.333\"/>\n" +
                      "</g>\n" +
                      "</svg>");
  }

  @NotNull
  @Override
  protected String getTestDataPath() {
    return PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/');
  }

}


text:
package org.drools.camel.component;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.naming.Context;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.dataformat.JaxbDataFormat;
import org.apache.camel.util.jndi.JndiContext;
import org.drools.camel.testdomain.Person;
import org.drools.grid.GridNode;
import org.drools.grid.impl.GridImpl;
import org.junit.Before;
import org.junit.Test;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.api.command.BatchExecutionCommand;
import org.kie.api.command.Command;
import org.kie.internal.command.CommandFactory;
import org.kie.api.runtime.ExecutionResults;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.kie.api.runtime.rule.FactHandle;

/**
 * Camel - JAXB reproducer test
 * https://bugzilla.redhat.com/show_bug.cgi?id=771203
 * https://bugzilla.redhat.com/show_bug.cgi?id=771209
 */
public class JaxbInsertTest {

    private StatefulKnowledgeSession ksession;
    private ProducerTemplate template;

    @Before
    public void setUp() throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        ksession = kbuilder.newKnowledgeBase().newStatefulKnowledgeSession();
        initializeTemplate(ksession);
    }

    /**
     * camel context startup and template creation
     */
    private void initializeTemplate(StatefulKnowledgeSession session) throws Exception {
        CamelContext context = configure(session);
        this.template = context.createProducerTemplate();
        context.start();
    }

    /**
     * configures camel-drools integration and defines 3 routes:
     * 1) testing route (connection to drools with JAXB command format)
     * 2) unmarshalling route (for unmarshalling command results)
     * 3) marshalling route (enables creating commands through API and converting to XML)
     */
    private CamelContext configure(StatefulKnowledgeSession session) throws Exception {
        GridImpl grid = new GridImpl(new HashMap<String, Object>());
        GridNode node = grid.createGridNode("testnode");

        Context context = new JndiContext();
        context.bind("testnode", node);
        node.set("ksession", session);

        CamelContext camelContext = new DefaultCamelContext(context);
        camelContext.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                JaxbDataFormat jdf = new JaxbDataFormat();
                jdf.setContextPath("org.drools.camel.testdomain");
                jdf.setPrettyPrint(true);

                from("direct:test-session").policy(new DroolsPolicy())
                        .unmarshal(jdf)
                        .to("drools://testnode/ksession")
                        .marshal(jdf);
                from("direct:unmarshall").policy(new DroolsPolicy())
                        .unmarshal(jdf);
                from("direct:marshall").policy(new DroolsPolicy())
                        .marshal(jdf);
            }
        });

        return camelContext;
    }

    /**
     * bz771203
     * creates batch-execution command with insert. Marshalls it to XML
     * and send to drools
     */
    @Test
    public void testInsert() throws Exception {
        Person p = new Person("Alice", "spicy meals", 30);
        List<Command> commands = new ArrayList<Command>();
        commands.add(CommandFactory.newInsert(p, "tempPerson"));
        BatchExecutionCommand command = CommandFactory.newBatchExecution(commands);
        String xmlCommand = template.requestBody("direct:marshall", command, String.class);

        String xml = template.requestBody("direct:test-session", xmlCommand, String.class);
        ExecutionResults res = (ExecutionResults) template.requestBody("direct:unmarshall", xml);

        Object o = res.getFactHandle("tempPerson");
        assertTrue("returned String instead of FactHandle instance", o instanceof FactHandle);
    }

    @Test
    public void testInsertElements() {
        List<Person> persons = new ArrayList<Person>();
        persons.add(new Person("John", "nobody", 50));
        persons.add(new Person("Peter", "himself", 24));

        insertElements(persons);
        assertEquals(2, ksession.getFactCount());
    }

    private void insertElements(List<Person> objects) {
        String insertElements =
            "<batch-execution>\n"
            + "  <insert-elements return-objects=\"true\">\n"
            + "    <list>\n";
        for(Person p : objects) {
            insertElements += "      <element xsi:type=\"person\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
                + "        <age>" + p.getAge() + "</age>\n"
                + "        <likes>" + p.getLikes() + "</likes>\n"
                + "        <name>" + p.getName() + "</name>\n"
                + "      </element>\n";
        }
        insertElements +=
            "    </list>\n"
            + "  </insert-elements>\n"
            + "</batch-execution>";
        template.requestBody("direct:test-session", insertElements, String.class);
    }

}