text:
package org.apache.zeppelin.rest;

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

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.scheduler.Job.Status;
import org.apache.zeppelin.server.ZeppelinServer;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.gson.Gson;

/**
 * Test against spark cluster.
 * Spark cluster is started by CI server using testing/startSparkCluster.sh
 */
public class ZeppelinSparkClusterTest extends AbstractTestRestApi {
    Gson gson = new Gson();
    AuthenticationInfo anonymous;

    @BeforeClass
    public static void init() throws Exception {
        AbstractTestRestApi.startUp();
    }

    @AfterClass
    public static void destroy() throws Exception {
        AbstractTestRestApi.shutDown();
    }

    @Before
    public void setUp() {
        anonymous = new AuthenticationInfo("anonymous");
    }

    private void waitForFinish(Paragraph p) {
        while (p.getStatus() != Status.FINISHED
                && p.getStatus() != Status.ERROR
                && p.getStatus() != Status.ABORT) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                LOG.error("Exception in WebDriverManager while getWebDriver ", e);
            }
        }
    }

    @Test
    public void basicRDDTransformationAndActionTest() throws IOException {
        // create new note
        Note note = ZeppelinServer.notebook.createNote(anonymous);

        // run markdown paragraph, again
        Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
        Map config = p.getConfig();
        config.put("enabled", true);
        p.setConfig(config);
        p.setText("%spark print(sc.parallelize(1 to 10).reduce(_ + _))");
        p.setAuthenticationInfo(anonymous);
        note.run(p.getId());
        waitForFinish(p);
        assertEquals(Status.FINISHED, p.getStatus());
        assertEquals("55", p.getResult().message().get(0).getData());
        ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
    }

    @Test
    public void sparkSQLTest() throws IOException {
        // create new note
        Note note = ZeppelinServer.notebook.createNote(anonymous);
        int sparkVersion = getSparkVersionNumber(note);
        // DataFrame API is available from spark 1.3
        if (sparkVersion >= 13) {
            // test basic dataframe api
            Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
            Map config = p.getConfig();
            config.put("enabled", true);
            p.setConfig(config);
            p.setText("%spark val df=sqlContext.createDataFrame(Seq((\"hello\",20)))\n" +
                    "df.collect()");
            p.setAuthenticationInfo(anonymous);
            note.run(p.getId());
            waitForFinish(p);
            assertEquals(Status.FINISHED, p.getStatus());
            assertTrue(p.getResult().message().get(0).getData().contains(
                    "Array[org.apache.spark.sql.Row] = Array([hello,20])"));

            // test display DataFrame
            p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
            config = p.getConfig();
            config.put("enabled", true);
            p.setConfig(config);
            p.setText("%spark val df=sqlContext.createDataFrame(Seq((\"hello\",20)))\n" +
                    "z.show(df)");
            p.setAuthenticationInfo(anonymous);
            note.run(p.getId());
            waitForFinish(p);
            assertEquals(Status.FINISHED, p.getStatus());
            assertEquals(InterpreterResult.Type.TABLE, p.getResult().message().get(1).getType());
            assertEquals("_1\t_2\nhello\t20\n", p.getResult().message().get(1).getData());

            // test display DataSet
            if (sparkVersion >= 20) {
                p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
                config = p.getConfig();
                config.put("enabled", true);
                p.setConfig(config);
                p.setText("%spark val ds=spark.createDataset(Seq((\"hello\",20)))\n" +
                        "z.show(ds)");
                p.setAuthenticationInfo(anonymous);
                note.run(p.getId());
                waitForFinish(p);
                assertEquals(Status.FINISHED, p.getStatus());
                assertEquals(InterpreterResult.Type.TABLE, p.getResult().message().get(1).getType());
                assertEquals("_1\t_2\nhello\t20\n", p.getResult().message().get(1).getData());
            }
            ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
        }
    }

    @Test
    public void sparkRTest() throws IOException {
      // create new note
      Note note = ZeppelinServer.notebook.createNote(anonymous);
      int sparkVersion = getSparkVersionNumber(note);

      if (isSparkR() && sparkVersion >= 14) {   // sparkr supported from 1.4.0
        // restart spark interpreter
        List<InterpreterSetting> settings =
          ZeppelinServer.notebook.getBindedInterpreterSettings(note.getId());

        for (InterpreterSetting setting : settings) {
          if (setting.getName().equals("spark")) {
            ZeppelinServer.notebook.getInterpreterSettingManager().restart(setting.getId());
            break;
          }
        }

        String sqlContextName = "sqlContext";
        if (sparkVersion >= 20) {
          sqlContextName = "spark";
        }
        Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
        Map config = p.getConfig();
        config.put("enabled", true);
        p.setConfig(config);
        p.setText("%r localDF <- data.frame(name=c(\"a\", \"b\", \"c\"), age=c(19, 23, 18))\n" +
            "df <- createDataFrame(" + sqlContextName + ", localDF)\n" +
            "count(df)"
        );
        p.setAuthenticationInfo(anonymous);
        note.run(p.getId());
        waitForFinish(p);
        System.err.println("sparkRTest=" + p.getResult().message().get(0).getData());
        assertEquals(Status.FINISHED, p.getStatus());
        assertEquals("[1] 3", p.getResult().message().get(0).getData().trim());
      }
      ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
    }

    @Test
    public void pySparkTest() throws IOException {
        // create new note
        Note note = ZeppelinServer.notebook.createNote(anonymous);
        note.setName("note");
        int sparkVersion = getSparkVersionNumber(note);

        if (isPyspark() && sparkVersion >= 12) {   // pyspark supported from 1.2.1
            // run markdown paragraph, again
            Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
            Map config = p.getConfig();
            config.put("enabled", true);
            p.setConfig(config);
            p.setText("%pyspark print(sc.parallelize(range(1, 11)).reduce(lambda a, b: a + b))");
            p.setAuthenticationInfo(anonymous);
            note.run(p.getId());
            waitForFinish(p);
            assertEquals(Status.FINISHED, p.getStatus());
            assertEquals("55\n", p.getResult().message().get(0).getData());
            if (sparkVersion >= 13) {
                // run sqlContext test
                p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
                config = p.getConfig();
                config.put("enabled", true);
                p.setConfig(config);
                p.setText("%pyspark from pyspark.sql import Row\n" +
                        "df=sqlContext.createDataFrame([Row(id=1, age=20)])\n" +
                        "df.collect()");
                p.setAuthenticationInfo(anonymous);
                note.run(p.getId());
                waitForFinish(p);
                assertEquals(Status.FINISHED, p.getStatus());
                assertEquals("[Row(age=20, id=1)]\n", p.getResult().message().get(0).getData());

                // test display Dataframe
                p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
                config = p.getConfig();
                config.put("enabled", true);
                p.setConfig(config);
                p.setText("%pyspark from pyspark.sql import Row\n" +
                        "df=sqlContext.createDataFrame([Row(id=1, age=20)])\n" +
                        "z.show(df)");
                p.setAuthenticationInfo(anonymous);
                note.run(p.getId());
                waitForFinish(p);
                assertEquals(Status.FINISHED, p.getStatus());
                assertEquals(InterpreterResult.Type.TABLE, p.getResult().message().get(0).getType());
                // TODO (zjffdu), one more \n is appended, need to investigate why.
                assertEquals("age\tid\n20\t1\n", p.getResult().message().get(0).getData());

                // test udf
                p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
                config = p.getConfig();
                config.put("enabled", true);
                p.setConfig(config);
                p.setText("%pyspark sqlContext.udf.register(\"f1\", lambda x: len(x))\n" +
                       "sqlContext.sql(\"select f1(\\\"abc\\\") as len\").collect()");
                p.setAuthenticationInfo(anonymous);
                note.run(p.getId());
                waitForFinish(p);
                assertEquals(Status.FINISHED, p.getStatus());
                assertEquals("[Row(len=u'3')]\n", p.getResult().message().get(0).getData());
            }
            if (sparkVersion >= 20) {
                // run SparkSession test
                p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
                config = p.getConfig();
                config.put("enabled", true);
                p.setConfig(config);
                p.setText("%pyspark from pyspark.sql import Row\n" +
                        "df=sqlContext.createDataFrame([Row(id=1, age=20)])\n" +
                        "df.collect()");
                p.setAuthenticationInfo(anonymous);
                note.run(p.getId());
                waitForFinish(p);
                assertEquals(Status.FINISHED, p.getStatus());
                assertEquals("[Row(age=20, id=1)]\n", p.getResult().message().get(0).getData());

                // test udf
                p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
                config = p.getConfig();
                config.put("enabled", true);
                p.setConfig(config);
                // use SQLContext to register UDF but use this UDF through SparkSession
                p.setText("%pyspark sqlContext.udf.register(\"f1\", lambda x: len(x))\n" +
                        "spark.sql(\"select f1(\\\"abc\\\") as len\").collect()");
                p.setAuthenticationInfo(anonymous);
                note.run(p.getId());
                waitForFinish(p);
                assertEquals(Status.FINISHED, p.getStatus());
                assertEquals("[Row(len=u'3')]\n", p.getResult().message().get(0).getData());
            }
        }
        ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
    }

    @Test
    public void pySparkAutoConvertOptionTest() throws IOException {
        // create new note
        Note note = ZeppelinServer.notebook.createNote(anonymous);
        note.setName("note");

        int sparkVersionNumber = getSparkVersionNumber(note);

        if (isPyspark() && sparkVersionNumber >= 14) {   // auto_convert enabled from spark 1.4
            // run markdown paragraph, again
            Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
            Map config = p.getConfig();
            config.put("enabled", true);
            p.setConfig(config);

            String sqlContextName = "sqlContext";
            if (sparkVersionNumber >= 20) {
                sqlContextName = "spark";
            }

            p.setText("%pyspark\nfrom pyspark.sql.functions import *\n"
                    + "print(" + sqlContextName + ".range(0, 10).withColumn('uniform', rand(seed=10) * 3.14).count())");
            p.setAuthenticationInfo(anonymous);
            note.run(p.getId());
            waitForFinish(p);
            assertEquals(Status.FINISHED, p.getStatus());
            assertEquals("10\n", p.getResult().message().get(0).getData());
        }
        ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
    }

    @Test
    public void zRunTest() throws IOException {
        // create new note
        Note note = ZeppelinServer.notebook.createNote(anonymous);
        Paragraph p0 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
        Map config0 = p0.getConfig();
        config0.put("enabled", true);
        p0.setConfig(config0);
        p0.setText("%spark z.run(1)");
        p0.setAuthenticationInfo(anonymous);
        Paragraph p1 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
        Map config1 = p1.getConfig();
        config1.put("enabled", true);
        p1.setConfig(config1);
        p1.setText("%spark val a=10");
        p1.setAuthenticationInfo(anonymous);
        Paragraph p2 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
        Map config2 = p2.getConfig();
        config2.put("enabled", true);
        p2.setConfig(config2);
        p2.setText("%spark print(a)");
        p2.setAuthenticationInfo(anonymous);

        note.run(p0.getId());
        waitForFinish(p0);
        assertEquals(Status.FINISHED, p0.getStatus());

        // z.run is not blocking call. So p1 may not be finished when p0 is done.
        waitForFinish(p1);
        note.run(p2.getId());
        waitForFinish(p2);
        assertEquals(Status.FINISHED, p2.getStatus());
        assertEquals("10", p2.getResult().message().get(0).getData());

        Paragraph p3 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
        Map config3 = p3.getConfig();
        config3.put("enabled", true);
        p3.setConfig(config3);
        p3.setText("%spark println(new java.util.Date())");
        p3.setAuthenticationInfo(anonymous);

        p0.setText(String.format("%%spark z.runNote(\"%s\")", note.getId()));
        note.run(p0.getId());
        waitForFinish(p0);
        waitForFinish(p1);
        waitForFinish(p2);
        waitForFinish(p3);

        assertEquals(Status.FINISHED, p3.getStatus());
        String p3result = p3.getResult().message().get(0).getData();
        assertNotEquals(null, p3result);
        assertNotEquals("", p3result);

        p0.setText(String.format("%%spark z.run(\"%s\", \"%s\")", note.getId(), p3.getId()));
        p3.setText("%%spark println(\"END\")");

        note.run(p0.getId());
        waitForFinish(p0);
        waitForFinish(p3);

        assertNotEquals(p3result, p3.getResult().message());

        ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
    }

    @Test
    public void pySparkDepLoaderTest() throws IOException {
        // create new note
        Note note = ZeppelinServer.notebook.createNote(anonymous);
        int sparkVersionNumber = getSparkVersionNumber(note);

        if (isPyspark() && sparkVersionNumber >= 14) {
            // restart spark interpreter
            List<InterpreterSetting> settings =
                    ZeppelinServer.notebook.getBindedInterpreterSettings(note.getId());

            for (InterpreterSetting setting : settings) {
                if (setting.getName().equals("spark")) {
                    ZeppelinServer.notebook.getInterpreterSettingManager().restart(setting.getId());
                    break;
                }
            }

            // load dep
            Paragraph p0 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
            Map config = p0.getConfig();
            config.put("enabled", true);
            p0.setConfig(config);
            p0.setText("%dep z.load(\"com.databricks:spark-csv_2.11:1.2.0\")");
            p0.setAuthenticationInfo(anonymous);
            note.run(p0.getId());
            waitForFinish(p0);
            assertEquals(Status.FINISHED, p0.getStatus());

            // write test csv file
            File tmpFile = File.createTempFile("test", "csv");
            FileUtils.write(tmpFile, "a,b\n1,2");

            // load data using libraries from dep loader
            Paragraph p1 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
            p1.setConfig(config);

            String sqlContextName = "sqlContext";
            if (sparkVersionNumber >= 20) {
                sqlContextName = "spark";
            }
            p1.setText("%pyspark\n" +
                    "from pyspark.sql import SQLContext\n" +
                    "print(" + sqlContextName + ".read.format('com.databricks.spark.csv')" +
                    ".load('"+ tmpFile.getAbsolutePath() +"').count())");
            p1.setAuthenticationInfo(anonymous);
            note.run(p1.getId());

            waitForFinish(p1);
            assertEquals(Status.FINISHED, p1.getStatus());
            assertEquals("2\n", p1.getResult().message().get(0).getData());
        }
        ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
    }

    /**
     * Get spark version number as a numerical value.
     * eg. 1.1.x => 11, 1.2.x => 12, 1.3.x => 13 ...
     */
    private int getSparkVersionNumber(Note note) {
        Paragraph p = note.addParagraph(AuthenticationInfo.ANONYMOUS);
        note.setName("note");
        Map config = p.getConfig();
        config.put("enabled", true);
        p.setConfig(config);
        p.setText("%spark print(sc.version)");
        p.setAuthenticationInfo(anonymous);
        note.run(p.getId());
        waitForFinish(p);
        assertEquals(Status.FINISHED, p.getStatus());
        String sparkVersion = p.getResult().message().get(0).getData();
        System.out.println("Spark version detected " + sparkVersion);
        String[] split = sparkVersion.split("\\.");
        int version = Integer.parseInt(split[0]) * 10 + Integer.parseInt(split[1]);
        return version;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fungal Diversity 29: 65 (2007)

#### Original name
Lactarius strigosipes Montoya & Band.-Muñoz

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<!--
 Networking section
-->

<!--
Case 1 Static network with IPV4
-->
<% if (@obj.is_static?) && ((@obj.type & PackerFiles::Network::IPV4) > 0) -%>

<networking>
   <ipv6 config:type="boolean">false</ipv6>
   <keep_install_network config:type="boolean">true</keep_install_network>
   <dns>
      <dhcp_hostname config:type="boolean">true</dhcp_hostname>
      <dhcp_resolv config:type="boolean">true</dhcp_resolv>
      <domain>local</domain>
      <hostname>linux</hostname>
   </dns>
   <interfaces config:type="list">
      <interface>
         <bootproto>static</bootproto>
         <device><%= @obj.interface -%></device>
         <startmode>onboot</startmode>
         <ipaddr><%= @obj.ip -%></ipaddr>
        <netmask><%= @obj.mask -%></netmask>
        <nameservers config:type="list">
	   <% @obj.dns.each do |dns| -%>
             <nameserver><%= dns -%></nameserver>
	   <% end -%>
          </nameservers>
      </interface>
   </interfaces>
   <routing>
        <ip_forward config:type="boolean">false</ip_forward>
        <routes config:type="list">
          <route>
            <destination>default</destination>
            <device>-</device>
            <gateway><%= @obj.gateway -%></gateway>
            <netmask>-</netmask>
          </route>
        </routes>
   </routing>
</networking>

<!--
Case 2 Static network with IPV6
-->
<% elsif (@obj.is_static?) && ((@obj.type & PackerFiles::Network::IPV6) > 0) -%>

<networking>
   <ipv6 config:type="boolean">true</ipv6>
   <keep_install_network config:type="boolean">true</keep_install_network>
   <dns>
      <dhcp_hostname config:type="boolean">true</dhcp_hostname>
      <dhcp_resolv config:type="boolean">true</dhcp_resolv>
      <domain>local</domain>
      <hostname>linux</hostname>
   </dns>
   <interfaces config:type="list">
      <interface>
         <bootproto>static</bootproto>
         <device><%= @obj.interface -%></device>
         <startmode>onboot</startmode>
         <ipaddr><%= @obj.ip -%></ipaddr>
        <netmask><%= @obj.mask -%></netmask>
        <nameservers config:type="list">
	   <% @obj.dns.each do |dns| -%>
             <nameserver><%= dns -%></nameserver>
	   <% end -%>
          </nameservers>
      </interface>
   </interfaces>
   <routing>
        <ip_forward config:type="boolean">false</ip_forward>
        <routes config:type="list">
          <route>
            <destination>default</destination>
            <device>-</device>
            <gateway><%= @obj.gateway -%></gateway>
            <netmask>-</netmask>
          </route>
        </routes>
   </routing>
</networking>

<!--
Case 3 DHCP network with IPV6
-->
<% elsif (!@obj.is_static?) && ((@obj.type & PackerFiles::Network::IPV6) > 0) -%>

<networking>
   <ipv6 config:type="boolean">true</ipv6>
   <keep_install_network config:type="boolean">true</keep_install_network>
   <dns>
      <dhcp_hostname config:type="boolean">true</dhcp_hostname>
      <dhcp_resolv config:type="boolean">true</dhcp_resolv>
      <domain>local</domain>
      <hostname>linux</hostname>
   </dns>
   <interfaces config:type="list">
      <interface>
         <bootproto>dhcp6</bootproto>
         <device><%= @obj.interface -%></device>
         <startmode>onboot</startmode>
      </interface>
   </interfaces>
</networking>

<!--
Case 4 DHCP network with IPV4
-->
<% elsif (!@obj.is_static?) && ((@obj.type & PackerFiles::Network::IPV4) > 0) -%>

<networking>
   <ipv6 config:type="boolean">false</ipv6>
   <keep_install_network config:type="boolean">true</keep_install_network>
   <dns>
      <dhcp_hostname config:type="boolean">true</dhcp_hostname>
      <dhcp_resolv config:type="boolean">true</dhcp_resolv>
      <domain>local</domain>
      <hostname>linux</hostname>
   </dns>
   <interfaces config:type="list">
      <interface>
         <bootproto>dhcp</bootproto>
         <device><%= @obj.interface -%></device>
         <startmode>onboot</startmode>
      </interface>
   </interfaces>
</networking>

<% end -%>

<!--
Firewall section
-->
<firewall>
<enable_firewall config:type="boolean">false</enable_firewall>
<start_firewall config:type="boolean">false</start_firewall>
</firewall>


text:
Title: Testing
Date: 3000-07-09
Slug: plugin-test

Testeando un poco la cosa

[Normal boring link](http://www.example.com). But this is a [cool link](this>) that links to this site.

Search in [Wikipedia](wikipedia_en>python), ([here](wikipedia_es>python) in spanish). Also can [search](ddg>python) it.


text:
import getpass

# step 1: get a word from first user
#(we're using getpass sothe word doesn't appear)
word = getpass.getpass("user 1, enter a word")

# if wrong guesses reaches six, we end the game
wrong_guesses = 0

# list of correct guesses from the second user
right_guesses = []

# this makes the indented code below repeat forever
while True:
    # tells user two to guess a letter
    letter = input ("User 2, guess a letter:")

    #checking if user two's letter is in the word
    if letter in word:
        print ("correct!")
        # adding the correct guess to the list
        right_guesses.append(letter)
        print(right_guesses)
    # but, if the letter is NOT in the word:
    else:
        print ("wrong!")
        # increases wrong guesses by one
        wrong_guesses = wrong_guesses + 1
    if wrong_guesses == 6:
        print ("you lose!")
        break
    # for each letter in the word
    for letter in word:
        # if the letter in the word was guessed correctly:
        if letter in right_guesses:
            print (letter, end="")
        # if the letter was NOT guessed yet:
        else:
            print (" _ ", end="")
    print()

    if wrong_guesses > 0:
        print ("0")
    if wrong_guesses > 1:
        print ("/",end="")
    if wrong_guesses > 2:
        print ("\\")
    if wrong_guesses > 3:
        print (" | ")
    if wrong_guesses > 4:
        print ("/",end="")
    if wrong_guesses > 5:
        print ("\\")
        print ("you lose!")
        break


text:
require 'active_admin'
require 'rails4_test/engine'

module Rails4Test
end


text:
package gov.nih.nci.cacis.mirth;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.commons.io.FileUtils;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;

/**
 * Test class for the XSLForMirthFormatter
 *
 * @author vinodh.rc@semanticbits.com
 *
 */
public class XSLForMirthFormatterTest {

    /**
     * Tests the xsl formatter
     * @throws IOException io error thrown, if any
     * @throws URISyntaxException error thrown, if any
     */
    @Test
    public void checkFormatter() throws IOException, URISyntaxException {
        final String origXslFile = getClass().getClassLoader().getResource("sample.xsl").getFile();
        final File xslFile = new File(origXslFile);
        final String xslFileNm = xslFile.getName();
        final String outputDir = xslFile.getParent() + "/formatted/";
        final String[] args = { outputDir, origXslFile };
        XSLForMirthFormatter.main(args);

        final File actualFrmtdXsl = new File(outputDir + xslFileNm);
        assertTrue(actualFrmtdXsl.exists());

        final String actualFrmtdXslContent = FileUtils.readFileToString(actualFrmtdXsl);
        assertNotNull(actualFrmtdXslContent);

        final String expectedFrmtdXsl = getClass().getClassLoader().getResource("sample.formatted").getFile();
        final String expectedFrmtdXslContent = FileUtils.readFileToString(new File(expectedFrmtdXsl));
        assertNotNull(expectedFrmtdXslContent);

        assertEquals(expectedFrmtdXslContent, actualFrmtdXslContent);

    }
}


text:
{% extends 'forms/captcha.html' %}
{% block instructions %}

Ci siamo quasi

Per favore, ci aiuti a combattere lo spam seguendo le indicazioni riportate qui sotto

{% endblock %}


text:
#include "config.h"
#include "WKFrame.h"

#include "WKAPICast.h"
#include "WebFrameProxy.h"

#ifdef __BLOCKS__
#include <Block.h>
#endif

using namespace WebKit;

WKTypeID WKFrameGetTypeID()
{
    return toAPI(WebFrameProxy::APIType);
}

bool WKFrameIsMainFrame(WKFrameRef frameRef)
{
    return toImpl(frameRef)->isMainFrame();
}

WKFrameLoadState WKFrameGetFrameLoadState(WKFrameRef frameRef)
{
    WebFrameProxy* frame = toImpl(frameRef);
    switch (frame->loadState()) {
        case WebFrameProxy::LoadStateProvisional:
            return kWKFrameLoadStateProvisional;
        case WebFrameProxy::LoadStateCommitted:
            return kWKFrameLoadStateCommitted;
        case WebFrameProxy::LoadStateFinished:
            return kWKFrameLoadStateFinished;
    }

    ASSERT_NOT_REACHED();
    return kWKFrameLoadStateFinished;
}

WKURLRef WKFrameCopyProvisionalURL(WKFrameRef frameRef)
{
    return toCopiedURLAPI(toImpl(frameRef)->provisionalURL());
}

WKURLRef WKFrameCopyURL(WKFrameRef frameRef)
{
    return toCopiedURLAPI(toImpl(frameRef)->url());
}

WKURLRef WKFrameCopyUnreachableURL(WKFrameRef frameRef)
{
    return toCopiedURLAPI(toImpl(frameRef)->unreachableURL());
}

void WKFrameStopLoading(WKFrameRef frameRef)
{
    toImpl(frameRef)->stopLoading();
}

WKStringRef WKFrameCopyMIMEType(WKFrameRef frameRef)
{
    return toCopiedAPI(toImpl(frameRef)->mimeType());
}

WKStringRef WKFrameCopyTitle(WKFrameRef frameRef)
{
    return toCopiedAPI(toImpl(frameRef)->title());
}

WKPageRef WKFrameGetPage(WKFrameRef frameRef)
{
    return toAPI(toImpl(frameRef)->page());
}

WKArrayRef WKFrameCopyChildFrames(WKFrameRef frameRef)
{
    return toAPI(toImpl(frameRef)->childFrames().leakRef());
}

WKFrameRef WKFrameGetParentFrame(WKFrameRef frameRef)
{
    return toAPI(toImpl(frameRef)->parentFrame());
}

WKCertificateInfoRef WKFrameGetCertificateInfo(WKFrameRef frameRef)
{
    return toAPI(toImpl(frameRef)->certificateInfo());
}

bool WKFrameCanProvideSource(WKFrameRef frameRef)
{
    return toImpl(frameRef)->canProvideSource();
}

bool WKFrameCanShowMIMEType(WKFrameRef frameRef, WKStringRef mimeTypeRef)
{
    return toImpl(frameRef)->canShowMIMEType(toWTFString(mimeTypeRef));
}

bool WKFrameIsDisplayingStandaloneImageDocument(WKFrameRef frameRef)
{
    return toImpl(frameRef)->isDisplayingStandaloneImageDocument();
}

bool WKFrameIsDisplayingMarkupDocument(WKFrameRef frameRef)
{
    return toImpl(frameRef)->isDisplayingMarkupDocument();
}

bool WKFrameIsFrameSet(WKFrameRef frameRef)
{
    return toImpl(frameRef)->isFrameSet();
}

void WKFrameGetMainResourceData(WKFrameRef frameRef, WKFrameGetResourceDataFunction callback, void* context)
{
    toImpl(frameRef)->getMainResourceData(DataCallback::create(context, callback));
}

void WKFrameGetResourceData(WKFrameRef frameRef, WKURLRef resourceURL, WKFrameGetResourceDataFunction callback, void* context)
{
    toImpl(frameRef)->getResourceData(toImpl(resourceURL), DataCallback::create(context, callback));
}

#ifdef __BLOCKS__
static void callGetResourceDataBlockAndDispose(WKDataRef data, WKErrorRef error, void* context)
{
    WKFrameGetResourceDataBlock block = (WKFrameGetResourceDataBlock)context;
    block(data, error);
    Block_release(block);
}

void WKFrameGetMainResourceData_b(WKFrameRef frameRef, WKFrameGetResourceDataBlock block)
{
    WKFrameGetMainResourceData(frameRef, callGetResourceDataBlockAndDispose, Block_copy(block));
}

void WKFrameGetResourceData_b(WKFrameRef frameRef, WKURLRef resourceURL, WKFrameGetResourceDataBlock block)
{
    WKFrameGetResourceData(frameRef, resourceURL, callGetResourceDataBlockAndDispose, Block_copy(block));
}
#endif

void WKFrameGetWebArchive(WKFrameRef frameRef, WKFrameGetWebArchiveFunction callback, void* context)
{
    toImpl(frameRef)->getWebArchive(DataCallback::create(context, callback));
}

#ifdef __BLOCKS__
static void callGetWebArchiveBlockAndDispose(WKDataRef archiveData, WKErrorRef error, void* context)
{
    WKFrameGetWebArchiveBlock block = (WKFrameGetWebArchiveBlock)context;
    block(archiveData, error);
    Block_release(block);
}

void WKFrameGetWebArchive_b(WKFrameRef frameRef, WKFrameGetWebArchiveBlock block)
{
    WKFrameGetWebArchive(frameRef, callGetWebArchiveBlockAndDispose, Block_copy(block));
}
#endif


text:
'use strict';

var util = require('util');
var vows = require('vows');
var assert = require('assert');

var net = require('net');
var bramqp = require('../lib/bramqp');

var puts = require('vows').console.puts({
	stream : process.stdout
});

var connectAMQP = function () {
	var self = this;
	var socket = net.connect({host: 'localhost', port: 5672});

	bramqp.initialize(socket, 'rabbitmq/full/amqp0-9-1.stripped.extended', function(error, handle){
		handle.openAMQPCommunication('guest', 'guest', true, function() {
			self.callback(null, handle);
		});
	});
};

var connectVerify = function(handle) {
	handle.closeAMQPCommunication(function() {
		handle.socket.end();
	});
};

vows.describe('concurrent connections').addBatch({
	'concurrent connection 1' : {
		topic : connectAMQP,
		'should be connected' : connectVerify,
	},
	'concurrent connection 2' : {
		topic : connectAMQP,
		'should be connected' : connectVerify,
	},
	'concurrent connection 3' : {
		topic : connectAMQP,
		'should be connected' : connectVerify,
	},
	'concurrent connection 4' : {
		topic : connectAMQP,
		'should be connected' : connectVerify,
	},
	'concurrent connection 5' : {
		topic : connectAMQP,
		'should be connected' : connectVerify,
	}
}).export(module);


text:
package com.android.server.power;

/**
 * Low-level suspend blocker mechanism equivalent to holding a partial wake lock.
 *
 * This interface is used internally to avoid introducing internal dependencies
 * on the high-level wake lock mechanism.
 */
interface SuspendBlocker {
    /**
     * Acquires the suspend blocker.
     * Prevents the CPU from going to sleep.
     *
     * Calls to acquire() nest and must be matched by the same number
     * of calls to release().
     */
    void acquire();

    /**
     * Releases the suspend blocker.
     * Allows the CPU to go to sleep if no other suspend blockers are held.
     *
     * It is an error to call release() if the suspend blocker has not been acquired.
     * The system may crash.
     */
    void release();

	void bootFastSleepRelease();

	void bootFastWakeAcquire();
}


text:
import Sequelize, { Op } from 'sequelize';
import config from '../config';

const sequelize = new Sequelize(config.databaseUrl, {
  operatorsAliases: Op,
  define: {
    freezeTableName: true,
  },
});

export default sequelize;


text:
package javasmmr.zoowsome.services.factories;

import javasmmr.zoowsome.models.animals.Animal;
import javasmmr.zoowsome.models.animals.Dolphin;
import javasmmr.zoowsome.models.animals.Piranha;
import javasmmr.zoowsome.models.animals.Sardine;
import javasmmr.zoowsome.models.animals.WaterType;
import javasmmr.zoowsome.services.factories.RandomAnimalPropGen;

public class AquaticFactory extends SpeciesFactory{
	@Override
	public Animal getAnimal(String type) throws Exception {

		RandomAnimalPropGen rpg = new RandomAnimalPropGen();
		String name = rpg.getRandomName();
		int nrOfLegs = rpg.getRandomNrOfLegs(1, 10);
		int avgSwimDepth = rpg.getRandomAvgSwimDepth(1, 100);
		WaterType waterType = rpg.getRandomWaterType();
		double maintenanceCost = rpg.getRandomMaintenanceCost();

		if (Constants.Animals.Aquatics.Dolphin.equals(type)) {
			return new Dolphin(name, nrOfLegs, avgSwimDepth, waterType, maintenanceCost, 0.1);
		} else if (Constants.Animals.Aquatics.Sardine.equals(type)) {
			return new Sardine(name, nrOfLegs, avgSwimDepth, waterType, maintenanceCost, 0.001);
		} else if (Constants.Animals.Aquatics.Piranha.equals(type)) {
			return new Piranha(name, nrOfLegs, avgSwimDepth, waterType, maintenanceCost, 0.95);
		} else {
			throw new Exception("Invalid animal exception!");
		}
	}
}


text:
'use strict';

var encode = require('./encode');
var d = require('./decode');

exports.encode = encode;
exports.decode = d.decode;
exports.decodeFromReader = d.decodeFromReader;


text:
/* global expect */

"use strict";

describe("Datepicker directive", function () {
    var date, elm, scope;

    beforeEach(module("app.directives.datepicker"));

    it('should put the date in the model', function () {
        return inject(function ($compile, $rootScope) {
            scope = $rootScope.$new();
            date = new Date('2016-05-23T00:00:00.000Z');
            elm = angular.element('<input data-ng-date-picker=\'\' data-ng-model=\'x\'></input>');
            $compile(elm)(scope);
            elm.datepicker('setDate', date);
            $.datepicker._selectDate(elm);
            expect(scope.x).toEqual('23/05/2016');
        });
    });
});


text:
import {Config, CONFIG_CONST} from "../../config/Config";
import {InvestInfo} from "../../models/db/InvestInfo";
import {InvestBase} from "./InvestBase";
import {NumberService} from "../numbers/NumberService";
import {ErrorService} from "../ErrorService";
import {TimeServiceV2} from "../time/TimeServiceV2";
import {InvestTotalInfo} from "../../models/db/InvestTotalInfo";
import {ExtraInvestService} from "./ExtraInvestService";
import {PlatformService} from "../platform/PlatformService";
import {AppSettings} from "../../config/AppSettings";
import {SettingService} from "../settings/SettingService";
import {EnumDbTableName} from "../../models/EnumModel";
import {NotificationService} from "../notification/NotificationService";
import {DoubleInvestService} from "./DoubleInvestService";
import {AwardService} from "../award/AwardService";
import {ConstVars} from "../../global/ConstVars";
import {InvestTableService} from "../dbservices/services/InvestTableService";
import moment  = require('moment');
import BlueBirdPromise = require('bluebird');

let log4js = require('log4js'),
    log = log4js.getLogger('InvestService'),
    numberService = new NumberService(),
    extraInvestService = new ExtraInvestService(),
    notificationService = new NotificationService(),
    doubleInvestService = new DoubleInvestService();

export class InvestService extends InvestBase {

    /**
     * 入口方法
     * @param request request对象实例
     */
    async executeAutoInvest(request: any): BlueBirdPromise<any> {
        //本期执行投注时,发现上期仍然没有开奖,则改用其他开奖源更新开奖数据
        return InvestTableService.getInvestInfoHistoryByTableName(EnumDbTableName.INVEST_TOTAL, CONFIG_CONST.currentSelectedInvestPlanType, 1)
            .then((historyData: Array<InvestInfo>) => {
                if (historyData.length > 0 && historyData[0].status === 0) {//上期未开奖 则从其他开奖源更新上期奖号
                    return AwardService.saveOrUpdateHistoryAwardByDate(moment().format(ConstVars.momentDateFormatter))
                        .then(() => {
                            return this.calculateWinMoney();
                        });
                } else {
                    return this.calculateWinMoney();
                }
            })
            .then(() => {
                log.info('正在产生投注号码...');
                //产生当期的投注号码
                return numberService.generateInvestNumber();
            })
            .then(() => {
                log.info('正在保存表%s 投注记录...', EnumDbTableName.INVEST_TOTAL);
                return this.initAllPlanInvestInfo(EnumDbTableName.INVEST_TOTAL)
                    .then((allInvestTotalInfo: Array<InvestTotalInfo>) => {
                        log.info('%s表记录已保存数据%s条', EnumDbTableName.INVEST_TOTAL, allInvestTotalInfo.length);
                        return InvestTableService.saveOrUpdateInvestInfoListByTableName(EnumDbTableName.INVEST_TOTAL, allInvestTotalInfo);
                    })
                    .then(() => {
                        //表invest_total第一次初始化完毕 重置标识
                        if (Config.isInvestTotalTableInitCompleted) Config.isInvestTotalTableInitCompleted = false;

                        //发送invest_total表 投注提醒通知
                        if (AppSettings.totalTableBuyNotification) return notificationService.sendBuyNumberNotification();
                    });
            })
            .then(() => {
                if (AppSettings.runtime_IsInDoubleInvestMode) {//倍投模式
                    log.info("检查已启用倍投模式,倍投模式执行中...");
                    return doubleInvestService.executeDoubleInvestService(request);
                }
            })
            .then(() => {
                //投注前保存 投注号码
                log.info('当前选择的方案%s 是否可真实投注..条件检查结果如下:', CONFIG_CONST.currentSelectedInvestPlanType);
                //检查是否满足投注条件
                return this.doCheck();
            })
            .then(() => {
                let messageType = CONFIG_CONST.isRealInvest ? "真实投注" : "模拟投注";
                log.info('正在保存表%s %s记录...', EnumDbTableName.INVEST, messageType);
                //真实后模拟投注后 更新各个方案的账户余额
                return this.initAllPlanInvestInfo(EnumDbTableName.INVEST)
                    .then((allPlanInvestInfo: Array<InvestInfo>) => {
                        log.info('%s表 %s记录已保存', EnumDbTableName.INVEST, messageType);
                        //保存投注记录
                        return InvestTableService.saveOrUpdateInvestInfoListByTableName(EnumDbTableName.INVEST, allPlanInvestInfo);
                    })
                    .then(() => {
                        //表invest第一次初始化完毕 重置标识
                        if (Config.isInvestTableInitCompleted) Config.isInvestTableInitCompleted = false;

                        //发送invest表 投注提醒通知
                        if (AppSettings.investTableBuyNotification) return notificationService.sendBuyNumberNotification();
                    });
            })
            .then(() => {
                //当前期号
                let currentPeriod = TimeServiceV2.getCurrentPeriodNumber(new Date());
                return InvestTableService.getInvestInfoByTableName(EnumDbTableName.INVEST, currentPeriod, CONFIG_CONST.currentSelectedInvestPlanType);
            })
            .then((investInfo: InvestInfo) => {
                if (!investInfo) return BlueBirdPromise.resolve();

                //doCheck全部验证通过 则表明可投注,不管是模拟投注还是真实投注,当前的真实投注值都应该增加,此值可用于判断已经投注的次数,模拟或者真实
                Config.currentInvestTotalCount++;
                //真实投注执行登录操作 确保买号后的金额仍然大于最小利润 这里用买号以后的账号余额和最小盈利比较目的,因为买号后当前账号余额可能为负值,说明余额不足了,所以没必要再执行真实投注了,即使开奖以后金额又够投注了,也算今天输了
                if (investInfo.currentAccountBalance > CONFIG_CONST.minAccountBalance) {
                    if (CONFIG_CONST.isRealInvest) {
                        return PlatformService.loginAndInvest(request, investInfo);
                    } else if (!CONFIG_CONST.isRealInvest && !AppSettings.isUseReverseInvestNumbers && AppSettings.isEnableInvestInMock) {
                        //在当前账号余额充足的情况下 当前是模拟投注并且是非取反投注时 才进行此操作 达到投注条件 是否可以不考虑设置中真实投注选项,自行投注
                        return extraInvestService.executeExtraInvest(request, investInfo);//该方法内部会根据条件 自动切换到真实投注
                    }

                } else {//投注后 如果买号以后的金额已经为负值了,说明从这期开始账号余额就不足了,所以直接切换到模拟投注
                    log.info("方案【%s】 买号后账户余额为: %s,小于最小值:%s,已无法进行真实购买!自动进入模拟投注模式!", CONFIG_CONST.currentSelectedInvestPlanType, investInfo.currentAccountBalance, CONFIG_CONST.minAccountBalance);
                    return SettingService.switchToMockInvest();
                }
            })
            .catch((e) => {
                ErrorService.appInvestErrorHandler(log, e);
            });
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;

namespace Azure.Search.Documents.Models
{
    /// <summary>
    /// A single bucket of a range facet query result that reports the number
    /// of documents with a field value falling within a particular range.
    /// </summary>
    /// <typeparam name="T">
    /// A type that matches the type of the field to which the facet was
    /// applied. Valid types include <see cref="DateTimeOffset"/>,
    /// <see cref="Double"/>, and <see cref="Int64"/>.
    /// </typeparam>
    public class RangeFacetResult<T> where T : struct
    {
        /// <summary>
        /// Gets the approximate count of documents falling within the bucket
        /// described by this facet.
        /// </summary>
        public long Count { get; }

        /// <summary>
        /// Gets a value indicating the inclusive lower bound of the facet's
        /// range, or <c>null</c> to indicate that there is no lower bound
        /// (for the first bucket).
        /// </summary>
        public T? From { get; }

        /// <summary>
        /// Gets a value indicating the exclusive upper bound of the facet's
        /// range, or <c>null</c> to indicate that there is no upper bound
        /// (for the last bucket).
        /// </summary>
        public T? To { get; }

        /// <summary>
        /// Creates a new instance of the RangeFacetResult class.
        /// </summary>
        /// <param name="count">
        /// The approximate count of documents falling within the bucket
        /// described by this facet.
        /// </param>
        /// <param name="from">
        /// A value indicating the inclusive lower bound of the facet's range,
        /// or <c>null</c> to indicate that there is no lower bound (for the
        /// first bucket).
        /// </param>
        /// <param name="to">
        /// A value indicating the exclusive upper bound of the facet's range,
        /// or <c>null</c> to indicate that there is no upper bound (for the
        /// last bucket).
        /// </param>
        public RangeFacetResult(long count, T? from, T? to)
        {
            From = from;
            To = to;
            Count = count;
        }
    }
}


text:
You are given a number N, you need to print the number of positions where digits exactly divides N.

###Input format

The first line contains T (number of test cases) followed by T lines (each containing N).

###Constraints
	1 <=T <= 15
	0 < N < 1010

###Output Format
For each test case print the number of positions in N where digits in that number exactly divides the number N in separate line.

*Note*

Same digits repeated twice, should be counted twice.

###Input

	1
	12
###Output

	2
###Explanation

* 2 digits in the number 12 divide the number exactly.
* Digits at ten's place, 1, divides 12 exactly in 12 parts, and
* digit at one's place, 2 divides 12 equally in 6 parts.

###Credits
Problem from [Hackerrank](https://www.hackerrank.com/challenges/find-digits).
This challenge was a part of [Pragyan 12](http://en.wikipedia.org/wiki/Pragyan).


text:
try:
    from .pyolite import Pyolite
except ImportError as exp:
    # need this in order to make versioneer work
    pass


text:
package com.google.errorprone.refaster.testdata.template;

import com.google.common.truth.IterableSubject;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import java.util.Collection;

/**
 * Tests for {@code UFreeIdent} accepting two references to the same wildcard.
 *
 * @author Kurt Alfred Kluever
 */
public class WildcardUnificationTemplate {
  @BeforeTemplate
  static void containsAllOf(IterableSubject subject, Collection<?> expected) {
    subject.hasSize(expected.size());
    subject.containsAtLeastElementsIn(expected);
  }

  @AfterTemplate
  static void containsExactly(IterableSubject subject, Collection<?> expected) {
    subject.containsExactlyElementsIn(expected);
  }
}


text:
package org.apache.sling.distribution.transport.impl;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.InputStream;
import java.net.URI;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.distribution.DistributionRequest;
import org.apache.sling.distribution.common.DistributionException;
import org.apache.sling.distribution.common.RecoverableDistributionException;
import org.apache.sling.distribution.log.impl.DefaultDistributionLog;
import org.apache.sling.distribution.packaging.DistributionPackage;
import org.apache.sling.distribution.packaging.DistributionPackageBuilder;
import org.apache.sling.distribution.packaging.DistributionPackageInfo;
import org.apache.sling.distribution.packaging.impl.AbstractDistributionPackage;
import org.apache.sling.distribution.packaging.impl.DistributionPackageUtils;
import org.apache.sling.distribution.transport.DistributionTransportSecret;
import org.apache.sling.distribution.transport.DistributionTransportSecretProvider;
import org.apache.sling.distribution.util.RequestUtils;

/**
 * default HTTP implementation of {@link DistributionTransport}
 */
public class SimpleHttpDistributionTransport implements DistributionTransport {

    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String EXECUTOR_CONTEXT_KEY_PREFIX = "ExecutorContextKey";

    /**
     * The Digest header, see section-4.3.2
     * of Instance Digests in HTTP (RFC3230)
     */
    private static final String DIGEST_HEADER = "Digest";

    /**
     * distribution package origin uri
     */
    private static final String PACKAGE_INFO_PROPERTY_ORIGIN_URI = "internal.origin.uri";

    private final DefaultDistributionLog log;
    private final DistributionEndpoint distributionEndpoint;
    private final DistributionPackageBuilder packageBuilder;
    private final DistributionTransportSecretProvider secretProvider;
    private final String contextKeyExecutor;

    public SimpleHttpDistributionTransport(DefaultDistributionLog log, DistributionEndpoint distributionEndpoint,
                                           DistributionPackageBuilder packageBuilder,
                                           DistributionTransportSecretProvider secretProvider) {
        this.log = log;

        this.distributionEndpoint = distributionEndpoint;
        this.packageBuilder = packageBuilder;
        this.secretProvider = secretProvider;
        this.contextKeyExecutor = EXECUTOR_CONTEXT_KEY_PREFIX + "_" + getHostAndPort(distributionEndpoint.getUri()) + "_" + UUID.randomUUID();
    }

    public void deliverPackage(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionPackage distributionPackage,
                               @Nonnull DistributionTransportContext distributionContext) throws DistributionException {
        String hostAndPort = getHostAndPort(distributionEndpoint.getUri());

        DistributionPackageInfo info = distributionPackage.getInfo();
        URI packageOrigin = info.get(PACKAGE_INFO_PROPERTY_ORIGIN_URI, URI.class);

        if (packageOrigin != null && hostAndPort.equals(getHostAndPort(packageOrigin))) {
            log.debug("skipping distribution of package {} to same origin {}", distributionPackage.getId(), hostAndPort);
        } else {

            try {
                Executor executor = getExecutor(distributionContext);

                Request req = Request.Post(distributionEndpoint.getUri()).useExpectContinue();

                // add the message body digest, see https://tools.ietf.org/html/rfc3230#section-4.3.2
                if (distributionPackage instanceof AbstractDistributionPackage) {
                    AbstractDistributionPackage adb = (AbstractDistributionPackage) distributionPackage;
                    if (adb.getDigestAlgorithm() != null && adb.getDigestMessage() != null) {
                        req.addHeader(DIGEST_HEADER, String.format("%s=%s", adb.getDigestAlgorithm(), adb.getDigestMessage()));
                    }
                }

                InputStream inputStream = null;
                try {
                    inputStream = DistributionPackageUtils.createStreamWithHeader(distributionPackage);

                    req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM);

                    Response response = executor.execute(req);
                    response.returnContent(); // throws an error if HTTP status is >= 300

                } finally {
                    IOUtils.closeQuietly(inputStream);
                }

                log.debug("delivered packageId={}, endpoint={}", distributionPackage.getId(), distributionEndpoint.getUri());
            } catch (HttpHostConnectException e) {
                throw new RecoverableDistributionException("endpoint not available " + distributionEndpoint.getUri(), e);
            } catch (HttpResponseException e) {
                int statusCode = e.getStatusCode();
                if (statusCode == 404 || statusCode == 401) {
                    throw new RecoverableDistributionException("not enough rights for " + distributionEndpoint.getUri(), e);
                }
                throw new DistributionException(e);
            } catch (Exception e) {
                throw new DistributionException(e);

            }
        }
    }

    @Nullable
    public RemoteDistributionPackage retrievePackage(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionRequest distributionRequest, @Nonnull DistributionTransportContext distributionContext) throws DistributionException {
        log.debug("pulling from {}", distributionEndpoint.getUri());

        try {
            URI distributionURI = RequestUtils.appendDistributionRequest(distributionEndpoint.getUri(), distributionRequest);

            Executor executor = getExecutor(distributionContext);

            // TODO : add queue parameter
            InputStream inputStream = HttpTransportUtils.fetchNextPackage(executor, distributionURI);

            if (inputStream == null) {
                return null;
            }

            final DistributionPackage responsePackage = packageBuilder.readPackage(resourceResolver, inputStream);
            responsePackage.getInfo().put(PACKAGE_INFO_PROPERTY_ORIGIN_URI, distributionURI);
            log.debug("pulled package with info {}", responsePackage.getInfo());

            return new DefaultRemoteDistributionPackage(responsePackage, executor, distributionURI);
        } catch (HttpHostConnectException e) {
            log.debug("could not connect to {} - skipping", distributionEndpoint.getUri());
        } catch (Exception ex) {
            log.error("cannot retrieve packages", ex);
        }

        return null;
    }

    private Executor authenticate(DistributionTransportSecret secret, Executor executor) {
        Map<String, String> credentialsMap = secret.asCredentialsMap();
        if (credentialsMap != null) {
            URI uri = distributionEndpoint.getUri();
            executor = executor.auth(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()),
                    credentialsMap.get(USERNAME), credentialsMap.get(PASSWORD)).authPreemptive(
                    new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()));
            log.debug("authenticate user={}, endpoint={}", secret.asCredentialsMap().get(USERNAME), distributionEndpoint.getUri());
        }
        return executor;
    }

    private String getHostAndPort(URI uri) {
        return uri.getHost() + ":" + uri.getPort();
    }

    private Executor getExecutor(DistributionTransportContext distributionContext) {
        if (distributionContext.containsKey(contextKeyExecutor)) {
            return distributionContext.get(contextKeyExecutor, Executor.class);
        }

        Executor executor = Executor.newInstance();

        DistributionTransportSecret secret = secretProvider.getSecret(distributionEndpoint.getUri());
        executor = authenticate(secret, executor);

        distributionContext.put(contextKeyExecutor, executor);

        return executor;
    }

}


text:
<!DOCTYPE html>

        <meta charset=utf-8 />
        <title>Cross-browser event delegation with vanilla JS</title>

Click any Element

            <form id="form" data-input="the form">

                    Name: <input type="text" id="name" data-input="the name field" tabindex="2">

                    Email: <input type="email" id="email" data-input="the email field" tabindex="3">

                    Question: <textarea id="question" rows="10" data-input="the question field" tabindex="4"></textarea>

                    <input type="submit" id="btn" data-input="the button" tabindex="5">

            </form>

Click event was triggered by: <output data-input="this output field" id="op">[none]</output>


text:
from . rotation import rotate_and_flip
from . matrix import make_matrix_coord_map

def make_cube_coord_map(dx, dy, dz, xy_serpentine=True, offset=0,
                        xy_rotation=0, z_rotation=0,
                        y_flip=False, z_flip=False):
    result = []
    plane_offset = offset
    for z in range(dz):
        plane = make_matrix_coord_map(dx, dy, serpentine=xy_serpentine,
                                      offset=plane_offset, rotation=xy_rotation,
                                      y_flip=y_flip)
        plane_offset += (dx * dy)
        result.append(plane)

    result = rotate_and_flip(result, z_rotation, z_flip)

    return result

def make_cube_coord_map_positions(coord_map):
    num = 0
    dx, dy, dz = (0, 0, len(coord_map))

    for xy in coord_map:
        if len(xy) > dx:
            dy = len(xy)
        for x in xy:
            if len(x) > dx:
                dx = len(x)
            num += len(x)

    result = [None] * num
    for z in range(dz):
        for y in range(dy):
            for x in range(dx):
                result[coord_map[z][y][x]] = [x, y, z]
    return result


text:
int main(int argc, char **argv)
{
    using namespace warpcoil;
    std::vector<char> file;
    auto file_writer = Si::make_container_sink(file);
    cpp::shared_code_generator<decltype(file_writer)> shared(file_writer, indentation_level());
    Si::append(file_writer, cpp::headers);
    std::vector<char> interfaces;
    auto interfaces_writer = Si::make_container_sink(interfaces);
    {
        indentation_level const top_level;
        cpp::generate_serializable_interface(interfaces_writer, shared, top_level,
                                             Si::make_c_str_range("benchmark_service_a"),
                                             warpcoil::create_benchmark_interface_a());
        cpp::generate_serializable_interface(interfaces_writer, shared, top_level,
                                             Si::make_c_str_range("benchmark_service_b"),
                                             warpcoil::create_benchmark_interface_b());
    }
    file.insert(file.end(), interfaces.begin(), interfaces.end());
    return run_code_generator_command_line_tool(Si::make_iterator_range(argv, argv + argc),
                                                std::cerr, Si::make_contiguous_range(file));
}


text:
package it.cloud.flexiant;

import java.util.Map;

import it.cloud.utils.CloudException;

public class VirtualMachine extends it.cloud.VirtualMachine {

	public VirtualMachine(String name, String ami, int instances, String size, int diskSize, double maxPrice, String os,
			String keyName, String sshUser, String sshPassword, Map<String, String> otherParams) throws CloudException {
		super(name, ami, instances, size, diskSize, maxPrice, os, keyName, sshUser, sshPassword, otherParams);
	}

	@Override
	public void addRunningInstance(String id, String contractId) {
		throw new RuntimeException("Method not implemented.");
	}

	@Override
	public String getIp(String id) {
		throw new RuntimeException("Method not implemented.");
	}

	@Override
	public void terminate(String id) {
		throw new RuntimeException("Method not implemented.");
	}

}


text:
package cucumber.eclipse.editor.editors;

import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
import org.eclipse.jface.text.reconciler.MonoReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.editors.text.TextSourceViewerConfiguration;

public class GherkinConfiguration extends TextSourceViewerConfiguration {

	private GherkinKeywordScanner keywordScanner;
	private ColorManager colorManager;
	private Editor editor;

	public GherkinConfiguration(Editor editor, ColorManager colorManager) {
		this.editor = editor;
		this.colorManager = colorManager;
	}
	public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
		return new String[] { IDocument.DEFAULT_CONTENT_TYPE};
	}

	protected GherkinKeywordScanner getGherkinKeywordScanner() {
		if (keywordScanner == null) {
			keywordScanner = new GherkinKeywordScanner(colorManager);
			keywordScanner.setDefaultReturnToken(
				new Token(
					new TextAttribute(
						colorManager.getColor(GherkinColors.DEFAULT))));
		}
		return keywordScanner;
	}

	public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
		PresentationReconciler reconciler = new PresentationReconciler();

		DefaultDamagerRepairer dr = new GherkinDamagerRepairer(getGherkinKeywordScanner());
		reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
		reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);

		return reconciler;
	}

	@Override
	public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
        ContentAssistant ca = new ContentAssistant();
        IContentAssistProcessor cap = new GherkinKeywordsAssistProcessor();
        ca.setContentAssistProcessor(cap, IDocument.DEFAULT_CONTENT_TYPE);
        ca.setInformationControlCreator(getInformationControlCreator(sourceViewer));
        return ca;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.editors.text.TextSourceViewerConfiguration#getReconciler
	 * (org.eclipse.jface.text.source.ISourceViewer)
	 */
	@Override
	public IReconciler getReconciler(ISourceViewer sourceViewer) {

		IReconcilingStrategy strategy = new GherkinReconcilingStrategy(editor);

		MonoReconciler reconciler = new MonoReconciler(strategy, false);
		return reconciler;
	}

	@Override
	public int getTabWidth(ISourceViewer sourceViewer) {
		return 2;
	}
}


text:
package br.ufrn.imd.netfrix.model;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.StringProperty;

public class Series {
	private IntegerProperty id;
	private StringProperty 	name;

	public Series() {}

	public Series(int id, String name) {
		this.id.set(id);
		this.name.set(name);
	}

	public int getId() {
		return id.get();
	}

	public IntegerProperty getIdProperty() {
		return id;
	}

	public void setId(int id) {
		this.id.set(id);
	}

	public String getName() {
		return name.get();
	}

	public StringProperty getNameProperty() {
		return name;
	}

	public void setName(String name) {
		this.name.set(name);
	}
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTipoComprobantesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tipo_comprobantes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('descripcion');
            $table->boolean('estado');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tipo_comprobantes');
    }
}


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Reapop</title>
  </head>
  <body>
    <div id="root"/>
    <script src="static/demo.js"></script>
  </body>
</html>


text:
#include "sequence_partitioner.h"

#include "partition_command.h"

#include <core/structures/vector_iterator.h>

#include <engine/thorium/modules/message_helper.h>

#include <core/system/memory.h>
#include <core/system/memory_pool.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <inttypes.h>

/*
#define BIOSAL_SEQUENCE_PARTITIONER_DEBUG
*/

void biosal_sequence_partitioner_init(struct thorium_actor *actor);
void biosal_sequence_partitioner_destroy(struct thorium_actor *actor);
void biosal_sequence_partitioner_receive(struct thorium_actor *actor, struct thorium_message *message);

void biosal_sequence_partitioner_verify(struct thorium_actor *actor);

int biosal_sequence_partitioner_get_store(uint64_t index, int block_size, int store_count);
uint64_t biosal_sequence_partitioner_get_index_in_store(uint64_t index, int block_size, int store_count);
void biosal_sequence_partitioner_generate_command(struct thorium_actor *actor, int stream_index);

struct thorium_script biosal_sequence_partitioner_script = {
    .identifier = SCRIPT_SEQUENCE_PARTITIONER,
    .init = biosal_sequence_partitioner_init,
    .destroy = biosal_sequence_partitioner_destroy,
    .receive = biosal_sequence_partitioner_receive,
    .size = sizeof(struct biosal_sequence_partitioner),
    .name = "biosal_sequence_partitioner"
};

void biosal_sequence_partitioner_init(struct thorium_actor *actor)
{
    struct biosal_sequence_partitioner *concrete_actor;

    concrete_actor = (struct biosal_sequence_partitioner *)thorium_actor_concrete_actor(actor);

    core_vector_init(&concrete_actor->stream_entries, sizeof(uint64_t));
    core_vector_init(&concrete_actor->stream_positions, sizeof(uint64_t));
    core_vector_init(&concrete_actor->stream_global_positions, sizeof(uint64_t));
    core_vector_init(&concrete_actor->store_entries, sizeof(uint64_t));

    core_queue_init(&concrete_actor->available_commands, sizeof(struct biosal_partition_command));
    core_map_init(&concrete_actor->active_commands, sizeof(int),
                    sizeof(struct biosal_partition_command));

    concrete_actor->store_count = -1;
    concrete_actor->block_size = -1;

    concrete_actor->command_number = 0;

    concrete_actor->last_progress = -1;
}

void biosal_sequence_partitioner_destroy(struct thorium_actor *actor)
{
    struct biosal_sequence_partitioner *concrete_actor;

    concrete_actor = (struct biosal_sequence_partitioner *)thorium_actor_concrete_actor(actor);

    core_vector_destroy(&concrete_actor->stream_entries);
    core_vector_destroy(&concrete_actor->stream_positions);
    core_vector_destroy(&concrete_actor->stream_global_positions);
    core_vector_destroy(&concrete_actor->store_entries);

    core_queue_destroy(&concrete_actor->available_commands);
    core_map_destroy(&concrete_actor->active_commands);
}

void biosal_sequence_partitioner_receive(struct thorium_actor *actor, struct thorium_message *message)
{
    int tag;
    int source;
    int count;
    void *buffer;
    int bytes;
    struct biosal_sequence_partitioner *concrete_actor;
    struct biosal_partition_command command;
    struct thorium_message response;
    int command_number;
    struct biosal_partition_command *active_command;
    int stream_index;
    struct biosal_partition_command *command_bucket;
    int i;

    thorium_message_get_all(message, &tag, &count, &buffer, &source);

    concrete_actor = (struct biosal_sequence_partitioner *)thorium_actor_concrete_actor(actor);

    if (tag == ACTION_SEQUENCE_PARTITIONER_SET_BLOCK_SIZE) {
        thorium_message_unpack_int(message, 0, &concrete_actor->block_size);
        thorium_actor_send_reply_empty(actor, ACTION_SEQUENCE_PARTITIONER_SET_BLOCK_SIZE_REPLY);

        biosal_sequence_partitioner_verify(actor);
/*
        thorium_actor_log(self, "DEBUG biosal_sequence_partitioner_receive received block size\n");
        */
    } else if (tag == ACTION_SEQUENCE_PARTITIONER_SET_ENTRY_VECTOR) {

            /*
        thorium_actor_log(self, "DEBUG biosal_sequence_partitioner_receive unpacking vector, %d bytes\n",
                        count);
                        */

        core_vector_init(&concrete_actor->stream_entries, 0);
        core_vector_unpack(&concrete_actor->stream_entries, buffer);

        /*
        thorium_actor_log(self, "DEBUG after unpack\n");
        */

        thorium_actor_send_reply_empty(actor, ACTION_SEQUENCE_PARTITIONER_SET_ENTRY_VECTOR_REPLY);

        /*
        thorium_actor_log(self, "DEBUG biosal_sequence_partitioner_receive received received entry vector\n");
        */
        biosal_sequence_partitioner_verify(actor);

    } else if (tag == ACTION_SEQUENCE_PARTITIONER_SET_ACTOR_COUNT) {

        thorium_message_unpack_int(message, 0, &concrete_actor->store_count);
        thorium_actor_send_reply_empty(actor, ACTION_SEQUENCE_PARTITIONER_SET_ACTOR_COUNT_REPLY);

        biosal_sequence_partitioner_verify(actor);
        /*
        thorium_actor_log(self, "DEBUG biosal_sequence_partitioner_receive received received store count\n");
        */

    } else if (tag == ACTION_SEQUENCE_PARTITIONER_GET_COMMAND) {

        if (core_queue_dequeue(&concrete_actor->available_commands, &command)) {

            bytes = biosal_partition_command_pack_size(&command);

            /*
            thorium_actor_log(self, "DEBUG partitioner has command, packing %d bytes!\n", bytes);
            */

            buffer = thorium_actor_allocate(actor, bytes);
            biosal_partition_command_pack(&command, buffer);

            thorium_message_init(&response, ACTION_SEQUENCE_PARTITIONER_GET_COMMAND_REPLY,
                            bytes, buffer);
            thorium_actor_send_reply(actor, &response);

            /* store the active command
             */
            command_number = biosal_partition_command_name(&command);
            command_bucket = (struct biosal_partition_command *)core_map_add(&concrete_actor->active_commands,
                            &command_number);
            *command_bucket = command;

            /* there may be other command available too !
             */
        }

    } else if (tag == ACTION_SEQUENCE_PARTITIONER_GET_COMMAND_REPLY_REPLY) {
        /*
         * take the name of the command, find it in the active
         * command, generate a new command, and send ACTION_SEQUENCE_PARTITIONER_COMMAND_IS_READY
         * as a reply
         */

        thorium_message_unpack_int(message, 0, &command_number);

        active_command = core_map_get(&concrete_actor->active_commands,
                        &command_number);

        if (active_command == NULL) {
            return;
        }

        stream_index = biosal_partition_command_stream_index(active_command);
        active_command = NULL;
        core_map_delete(&concrete_actor->active_commands,
                        &command_number);

        biosal_sequence_partitioner_generate_command(actor, stream_index);

        if (core_map_size(&concrete_actor->active_commands) == 0
                        && core_queue_size(&concrete_actor->available_commands) == 0) {

            thorium_actor_send_reply_empty(actor, ACTION_SEQUENCE_PARTITIONER_FINISHED);
        }

    } else if (tag == ACTION_ASK_TO_STOP
                    && source == thorium_actor_supervisor(actor)) {

#ifdef BIOSAL_SEQUENCE_PARTITIONER_DEBUG
        thorium_actor_log(self, "DEBUG biosal_sequence_partitioner_receive ACTION_ASK_TO_STOP\n");
#endif

        thorium_actor_send_to_self_empty(actor,
                        ACTION_STOP);

    } else if (tag == ACTION_SEQUENCE_PARTITIONER_PROVIDE_STORE_ENTRY_COUNTS_REPLY) {
        /* generate commands
         */
        for (i = 0; i < core_vector_size(&concrete_actor->stream_entries); i++) {

            biosal_sequence_partitioner_generate_command(actor, i);
        }
    }
}

void biosal_sequence_partitioner_verify(struct thorium_actor *actor)
{
    struct biosal_sequence_partitioner *concrete_actor;
    int i;
    int64_t entries;
    uint64_t position;
    uint64_t stream_entries;
    int bytes;
    void *buffer;
    struct thorium_message message;
    int64_t remaining;
    int remainder;
    uint64_t *bucket_for_store_count;
    struct core_vector_iterator iterator;

    concrete_actor = (struct biosal_sequence_partitioner *)thorium_actor_concrete_actor(actor);

    /*
     * check if parameters are
     * initialized
     */
    if (concrete_actor->block_size == -1) {
        return;
    }

    if (concrete_actor->store_count == -1) {
        return;
    }

    if (core_vector_size(&concrete_actor->stream_entries) == 0) {
        return;
    }

    /* at this point, all parameters are ready.
     * prepare <stream_entries.size> commands
     */

    position = 0;

    entries = 0;

    /*
    thorium_actor_log(self, "DEBUG generating initial positions\n");
    */
    /* generate stream positions, stream global positions, and total
     */
    for (i = 0; i < core_vector_size(&concrete_actor->stream_entries); i++) {

        core_vector_push_back(&concrete_actor->stream_positions, &position);

        core_vector_push_back(&concrete_actor->stream_global_positions, &entries);

        stream_entries = *(uint64_t *)core_vector_at(&concrete_actor->stream_entries, i);

#ifdef BIOSAL_SEQUENCE_PARTITIONER_DEBUG
        thorium_actor_log(self, "DEBUG stream_entries %i %" PRIu64 "\n",
                        i, stream_entries);
#endif

        entries += stream_entries;
    }

    concrete_actor->total = entries;

    /* compute the number of entries for each store
     */

    entries = concrete_actor->total / concrete_actor->store_count;

    /* make sure that this is a multiple of block size
     * examples:
     * total= 20000
     * store_count= 2
     * block_size= 8192
     * 20000 / 2 = 10000
     * 10000 % 8192 = 1808
     * difference = 8192 - 1808 = 6384
     * 10000 + 6384 = 16384
     */

    if (entries % concrete_actor->block_size != 0) {
        remainder = entries % concrete_actor->block_size;
        entries -= remainder;
    }

    /* make sure that at most one store has less
     * than block size
     */
    if (entries < concrete_actor->block_size) {
        entries = concrete_actor->block_size;
    }

#ifdef BIOSAL_SEQUENCE_PARTITIONER_DEBUG
    thorium_actor_log(self, "DEBUG93 entries for stores %d\n", (int)entries);
#endif

    remaining = concrete_actor->total;

    if (remaining <= entries) {
        entries = remaining;
    }

    /* example: 10000, block_size 4096,  3 stores
     *
     * total entries remaining
     * 10000 4096    5904
     * 10000 4096    1808
     * 10000 1808    0
     */
    for (i = 0; i < concrete_actor->store_count; i++) {
        core_vector_push_back(&concrete_actor->store_entries, &entries);

        remaining -= entries;

        if (remaining < entries) {
            entries = remaining;
        }

    }

    core_vector_iterator_init(&iterator, &concrete_actor->store_entries);

    while (core_vector_iterator_has_next(&iterator)) {
        core_vector_iterator_next(&iterator, (void **)&bucket_for_store_count);

        if (remaining >= concrete_actor->block_size) {
            *bucket_for_store_count += concrete_actor->block_size;
            remaining -= concrete_actor->block_size;
        } else if (remaining == 0) {
            break;
        } else {
            /* between 1 and block_size - 1 inclusively
             */
            *bucket_for_store_count += remaining;
            remaining = 0;
        }
    }

    core_vector_iterator_destroy(&iterator);

#ifdef BIOSAL_SEQUENCE_PARTITIONER_DEBUG
    thorium_actor_log(self, "DEBUG biosal_sequence_partitioner_verify sending store counts\n");
#endif

    bytes = core_vector_pack_size(&concrete_actor->store_entries);
    buffer = thorium_actor_allocate(actor, bytes);
    core_vector_pack(&concrete_actor->store_entries, buffer);

    thorium_message_init(&message, ACTION_SEQUENCE_PARTITIONER_PROVIDE_STORE_ENTRY_COUNTS,
                    bytes, buffer);
    thorium_actor_send_reply(actor, &message);
}

uint64_t biosal_sequence_partitioner_get_index_in_store(uint64_t index, int block_size, int store_count)
{
    /*
       irb(main):014:0> (1000000 / 8192) / 72 * 81 = 8192
     */

    return ( ( index / ((uint64_t)block_size) ) / (uint64_t)store_count ) * (uint64_t)block_size +
            index % block_size;
}

int biosal_sequence_partitioner_get_store(uint64_t index, int block_size, int store_count)
{
    /*
     * idea:
     *
     * first          ... last                 ........ store
     *
     * 0 * block_size ... 1 * block_size - 1   ........ store 0
     * 1 * block_size ... 2 * block_size - 1   ........ store 1
     * 2 * block_size ... 3 * block_size - 1   ........ store 2
     * 3 * block_size ... 3 * block_size - 1   ........ store 3
     * ...
     *
     * pattern:
     *
     * x * block_size ... (x + 1) * block_size - 1   ........ store (x % store_count)
     *
     *
     * Given an index i and block_size b, we have:
     *
     * (x * b) <= i <= ( (x + 1) * b - 1 )
     *
     * (x * b) <= i
     * x <= i / b (Equation 1.)
     *
     * i <= ( (x + 1) * b - 1 )
     * i <= (x + 1) * b - 1
     * i + 1 <= (x + 1) * b
     * ( i + 1 ) / b <= (x + 1)
     * ( i + 1 ) / b <= x + 1
     * ( i + 1 ) / b - 1 <= x (Equation 2.)
     *
     * So, dividing index by block_size gives x.
     */

    /* do the calculation in 64 bits to be sure.
     */

    if (store_count == 0) {
        return 0;
    }

    return ( index / (uint64_t) block_size) % ( (uint64_t) store_count);
}

void biosal_sequence_partitioner_generate_command(struct thorium_actor *actor, int stream_index)
{
    uint64_t *bucket_for_stream_position;
    uint64_t *bucket_for_global_position;
    struct biosal_partition_command command;

    int store_index;
    uint64_t stream_entries;
    uint64_t stream_first;
    uint64_t stream_last;
    int64_t available_in_stream;

    uint64_t store_first;
    uint64_t store_last;

    struct biosal_sequence_partitioner *concrete_actor;
    int64_t actual_block_size;
    int distance;

    uint64_t global_first;
    uint64_t global_last;
    uint64_t next_block_first;

    int command_name;

    int blocks;
    float progress;
    struct thorium_actor *self = actor;

    concrete_actor = (struct biosal_sequence_partitioner *)thorium_actor_concrete_actor(actor);

    /*
    thorium_actor_log(self, "DEBUG biosal_sequence_partitioner_generate_command %d\n",
                    stream_index);
*/

    bucket_for_stream_position = (uint64_t *)core_vector_at(&concrete_actor->stream_positions, stream_index);
    bucket_for_global_position = (uint64_t *)core_vector_at(&concrete_actor->stream_global_positions,
                    stream_index);

    /*
    thorium_actor_log(self, "DEBUG got buckets.\n");
*/

    /* compute feasible block size given the stream and the store.
     */
    global_first = *bucket_for_global_position;

    actual_block_size = concrete_actor->block_size;

    next_block_first = global_first +
            (concrete_actor->block_size - global_first % concrete_actor->block_size);

    distance = next_block_first - global_first;

    if (distance < actual_block_size) {
        actual_block_size = distance;
    }

    store_index = biosal_sequence_partitioner_get_store(global_first, concrete_actor->block_size,
                    concrete_actor->store_count);

    stream_entries = *(uint64_t *)core_vector_at(&concrete_actor->stream_entries, stream_index);

    stream_first = *bucket_for_stream_position;

    /* check out what is left in the stream
     */
    available_in_stream = stream_entries - *bucket_for_stream_position;

#ifdef BIOSAL_SEQUENCE_PARTITIONER_DEBUG
    thorium_actor_log(self, "DEBUG stream_entries %" PRIu64 " !\n", stream_entries);
    thorium_actor_log(self, "DEBUG bucket_for_stream_position %" PRIu64 " !\n", *bucket_for_stream_position);
    thorium_actor_log(self, "DEBUG available_in_stream %" PRIu64 " !\n", available_in_stream);
#endif

    if (available_in_stream < actual_block_size) {
#ifdef BIOSAL_SEQUENCE_PARTITIONER_DEBUG
#endif
        actual_block_size = available_in_stream;
    }

    /* can't do that
     */
    if (actual_block_size == 0) {
#ifdef BIOSAL_SEQUENCE_PARTITIONER_DEBUG
        thorium_actor_log(self, "DEBUG stream %d actual_block_size %d\n",
                        stream_index, actual_block_size);
#endif
        return;
    }

    stream_first = *bucket_for_stream_position;
    stream_last = stream_first + actual_block_size - 1;

    store_first = biosal_sequence_partitioner_get_index_in_store(global_first,
                    concrete_actor->block_size, concrete_actor->store_count);

    store_last = store_first + actual_block_size - 1;

    global_last = global_first + actual_block_size - 1;

    /*
    thorium_actor_log(self, "DEBUG %" PRIu64 " goes in store %d\n",
                    global_first, store_index);
*/
    biosal_partition_command_init(&command, concrete_actor->command_number,
                    stream_index, stream_first, stream_last,
                    store_index, store_first, store_last,
                    global_first, global_last);

    concrete_actor->command_number++;

    core_queue_enqueue(&concrete_actor->available_commands,
                    &command);

#ifdef BIOSAL_SEQUENCE_PARTITIONER_DEBUG
    thorium_actor_log(self, "DEBUG906 in partitioner:\n");
    biosal_partition_command_print(&command);
#endif

    /* update positions
     */

    *bucket_for_stream_position = stream_last + 1;
    *bucket_for_global_position = global_last + 1;

    /*
    thorium_actor_log(self, "DEBUG command is ready\n");
    */

    /* emit a signal
     */
    thorium_actor_send_reply_empty(actor, ACTION_SEQUENCE_PARTITIONER_COMMAND_IS_READY);

    command_name = biosal_partition_command_name(&command);

    blocks = (int)(concrete_actor->total / concrete_actor->block_size);

    if (concrete_actor->total % concrete_actor->block_size != 0) {
        blocks++;
    }

    progress = (0.0 + command_name) / blocks;

    if (concrete_actor->last_progress < 0
                    || progress >= concrete_actor->last_progress + 0.04
                    || command_name == blocks - 1) {

        thorium_actor_log(self, "partitioner/%d generated partition command # %d (total %" PRIu64 ", block_size %d, blocks %d, progress %.2f)\n",
                    thorium_actor_name(actor),
                    command_name,
                    concrete_actor->total, concrete_actor->block_size,
                    blocks, progress);

        concrete_actor->last_progress = progress;
    }

    biosal_partition_command_destroy(&command);

}


text:
import os
import re
import logging

__version__ = '1.4.49'

class NullHandler(logging.Handler):
    def emit(self, record):
        pass

# Configure default logger to do nothing
log = logging.getLogger('botocore')
log.addHandler(NullHandler())

_first_cap_regex = re.compile('(.)([A-Z][a-z]+)')
_number_cap_regex = re.compile('([a-z])([0-9]+)')
_end_cap_regex = re.compile('([a-z0-9])([A-Z])')
# The regex below handles the special case where some acryonym
# name is pluralized, e.g GatewayARNs, ListWebACLs, SomeCNAMEs.
_special_case_transform = re.compile('[A-Z]{3,}s$')
# Prepopulate the cache with special cases that don't match
# our regular transformation.
_xform_cache = {
    ('CreateCachediSCSIVolume', '_'): 'create_cached_iscsi_volume',
    ('CreateCachediSCSIVolume', '-'): 'create-cached-iscsi-volume',
    ('DescribeCachediSCSIVolumes', '_'): 'describe_cached_iscsi_volumes',
    ('DescribeCachediSCSIVolumes', '-'): 'describe-cached-iscsi-volumes',
    ('DescribeStorediSCSIVolumes', '_'): 'describe_stored_iscsi_volumes',
    ('DescribeStorediSCSIVolumes', '-'): 'describe-stored-iscsi-volumes',
    ('CreateStorediSCSIVolume', '_'): 'create_stored_iscsi_volume',
    ('CreateStorediSCSIVolume', '-'): 'create-stored-iscsi-volume',
}
ScalarTypes = ('string', 'integer', 'boolean', 'timestamp', 'float', 'double')

BOTOCORE_ROOT = os.path.dirname(os.path.abspath(__file__))

# Used to specify anonymous (unsigned) request signature
UNSIGNED = object()

def xform_name(name, sep='_', _xform_cache=_xform_cache):
    """Convert camel case to a "pythonic" name.

    If the name contains the ``sep`` character, then it is
    returned unchanged.

    """
    if sep in name:
        # If the sep is in the name, assume that it's already
        # transformed and return the string unchanged.
        return name
    key = (name, sep)
    if key not in _xform_cache:
        if _special_case_transform.search(name) is not None:
            is_special = _special_case_transform.search(name)
            matched = is_special.group()
            # Replace something like ARNs, ACLs with _arns, _acls.
            name = name[:-len(matched)] + sep + matched.lower()
        s1 = _first_cap_regex.sub(r'\1' + sep + r'\2', name)
        s2 = _number_cap_regex.sub(r'\1' + sep + r'\2', s1)
        transformed = _end_cap_regex.sub(r'\1' + sep + r'\2', s2).lower()
        _xform_cache[key] = transformed
    return _xform_cache[key]


text:
/*
    -- clMAGMA (version 1.3.0) --
       Univ. of Tennessee, Knoxville
       Univ. of California, Berkeley
       Univ. of Colorado, Denver
       @date November 2014

       @precisions normal z -> s d c

       @author Ichitaro Yamazaki
       @author Stan Tomov
*/
#include "clmagma_runtime.h"
#include "common_magma.h"
#include "magmablas.h"

#define NB 64

/**
    Purpose
    -------
    ZLASCL2 scales the M by N complex matrix A by the real diagonal matrix dD.
    TYPE specifies that A may be full, upper triangular, lower triangular.

    Arguments
    ---------
    \param[in]
    type    magma_type_t
            TYPE indices the storage type of the input matrix A.
            = MagmaFull:   full matrix.
            = MagmaLower:  lower triangular matrix.
            = MagmaUpper:  upper triangular matrix.
            Other formats that LAPACK supports, MAGMA does not currently support.

    \param[in]
    m       INTEGER
            The number of rows of the matrix A.  M >= 0.

    \param[in]
    n       INTEGER
            The number of columns of the matrix A.  N >= 0.

    \param[in]
    dD      DOUBLE PRECISION vector, dimension (M)
            The diagonal matrix containing the scalar factors. Stored as a vector.

    \param[in,out]
    dA      COMPLEX*16 array, dimension (LDDA,N)
            The matrix to be scaled by dD.  See TYPE for the
            storage type.

    \param[in]
    ldda    INTEGER
            The leading dimension of the array A.  LDDA >= max(1,M).

    \param[out]
    info    INTEGER
      -     = 0:  successful exit
      -     < 0:  if INFO = -i, the i-th argument had an illegal value.

    @ingroup magma_zaux2
    ********************************************************************/
extern "C" void
magmablas_zlascl_2x2(
    magma_type_t type, magma_int_t m,
    const magmaDoubleComplex_ptr dW, size_t dW_offset, magma_int_t lddw,
    magmaDoubleComplex_ptr dA, size_t dA_offset, magma_int_t ldda,
    magma_int_t *info, magma_queue_t queue )
{
    *info = 0;
    if ( type != MagmaLower && type != MagmaUpper )
        *info = -1;
    else if ( m < 0 )
        *info = -2;
    else if ( ldda < max(1,m) )
        *info = -4;

    if (*info != 0) {
        magma_xerbla( __func__, -(*info) );
        return;  //info;
    }

    size_t  LocalWorkSize[1] = { NB };
    size_t GlobalWorkSize[1] = { ((m + NB - 1)/NB)*NB };

    cl_int ciErrNum;
    cl_kernel ckKernel = NULL;

    if (type == MagmaLower) {
      ckKernel = g_runtime.get_kernel( "zlascl_2x2_lower_kernel" );
    }
    else {
      ckKernel = g_runtime.get_kernel( "zlascl_2x2_upper_kernel" );
    }

    if(!ckKernel){
      printf ("Error: cannot locate kernel in line %d, file %s\n", __LINE__, __FILE__);
      return;
    }

    int offset_A = (int)dW_offset;
    int offset_B = (int)dA_offset;
    int nn = 0;
    ciErrNum  = clSetKernelArg( ckKernel, nn++, sizeof(cl_int), (void*)&m        );
    ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(cl_mem), (void*)&dW       );
    ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(cl_int), (void*)&offset_A );
    ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(cl_int), (void*)&lddw     );
    ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(cl_mem), (void*)&dA       );
    ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(cl_int), (void*)&offset_B );
    ciErrNum |= clSetKernelArg( ckKernel, nn++, sizeof(cl_int), (void*)&ldda     );
    if (ciErrNum != CL_SUCCESS){
      printf("Error: clSetKernelArg at %d in file %s, %s\n", __LINE__, __FILE__,
             magma_strerror(ciErrNum));
      return;
    }

    // launch kernel
    ciErrNum = clEnqueueNDRangeKernel(
                  queue, ckKernel, 1, NULL, GlobalWorkSize, LocalWorkSize, 0, NULL, NULL);
    if (ciErrNum != CL_SUCCESS)
    {
        printf("Error: clEnqueueNDRangeKernel at %d in file %s \"%s\"\n",
               __LINE__, __FILE__, magma_strerror(ciErrNum));
        return;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.funtime</groupId>
    <artifactId>parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <maven.deploy.skip>true</maven.deploy.skip>
    </properties>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/release</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <dependencyManagement>
        <dependencies>

            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.3.1.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-parent</artifactId>
                <version>1.0.2.RELEASE</version>
                <!--<version>Angel.SR4</version>-->
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>


text:
package cn.byhieg.threadtutorial.char05.one2more;

import cn.byhieg.threadtutorial.char05.one2one.list.*;

/**
 * Created by byhieg on 17/2/1.
 * Mail to byhieg@gmail.com
 */
public class Producer implements Runnable{

    private MyQueue queue;

    public Producer(MyQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        for (;;) {
            queue.push(System.currentTimeMillis());
        }
    }
}


text:
require 'formula'

class Ioping < Formula
  homepage 'http://code.google.com/p/ioping/'
  url 'https://ioping.googlecode.com/files/ioping-0.8.tar.gz'
  sha1 '7d4fe1414cdd5887c332426a8844e17eca5e5646'

  head 'http://ioping.googlecode.com/svn/trunk/'

  def install
    system "make"
    system "make", "install", "PREFIX=#{prefix}"
  end

  test do
    system "#{bin}/ioping", "-v"
  end
end


text:
import {closestByTag} from '../../../src/dom';
import {isExperimentOn} from '../../../src/experiments';
import {user} from '../../../src/log';
import {viewerFor} from '../../../src/viewer';
import {urls} from '../../../src/config';

/**
 * Sets up a special document wide listener that relays requests
 * from ad iframes to the viewer to perform A2A navigations.
 * Requests are denied if the requests come from iframes that
 * do not currently have focus.
 * @param {!Window} win
 */
export function setupA2AListener(win) {
  if (win.a2alistener) {
    return;
  }
  win.a2alistener = true;
  if (!isExperimentOn(win, 'alp')) {
    return;
  }
  win.addEventListener('message', handleMessageEvent.bind(null, win));
}

/**
 * Handles a potential a2a message.
 * @param {!Window} win
 * @param {!Event} event
 * @visibleForTesting
 */
export function handleMessageEvent(win, event) {
  const data = event.data;
  // Only handle messages starting with the magic string.
  if (typeof data != 'string' || data.indexOf('a2a;') != 0) {
    return;
  }
  const origin = event.origin;
  const nav = JSON.parse(data.substr(/* 'a2a;'.length */ 4));
  const source = event.source;
  const activeElement = win.document.activeElement;
  // Check that the active element is an iframe.
  user().assert(activeElement.tagName == 'IFRAME',
      'A2A request with invalid active element %s %s %s',
      activeElement, nav.url, origin);
  let found = false;
  let sourceParent = source;
  const activeWindow = activeElement.contentWindow;
  while (sourceParent != win.top) {
    if (sourceParent == activeWindow) {
      found = true;
      break;
    }
    sourceParent = sourceParent.parent;
  }
  // Check that the active iframe contains the iframe that sent us
  // the message.
  user().assert(found,
      'A2A request from invalid source win %s %s', nav.url, origin);
  // Check that the iframe is contained in an ad.
  user().assert(closestByTag(activeElement, 'amp-ad'),
      'A2A request from non-ad frame %s %s', nav.url, origin);
  // We only allow AMP shaped URLs.
  user().assert(nav.url.indexOf(urls.cdn) == 0,
      'Invalid ad A2A URL %s %s', nav.url, origin);
  viewerFor(win).navigateTo(nav.url, 'ad-' + origin);
}


text:
namespace {

int ATTRIBUTE_NOINLINE Factorial(uint32_t n) {
  return (n == 1) ? 1 : n * Factorial(n - 1);
}

double CalculatePi(int depth) {
  double pi = 0.0;
  for (int i = 0; i < depth; ++i) {
    double numerator = static_cast<double>(((i % 2) * 2) - 1);
    double denominator = static_cast<double>((2 * i) - 1);
    pi += numerator / denominator;
  }
  return (pi - 1.0) * 4;
}

std::set<int> ConstructRandomSet(int size) {
  std::set<int> s;
  for (int i = 0; i < size; ++i)
    s.insert(i);
  return s;
}

pthread_mutex_t test_vector_mu;
std::vector<int>* test_vector = nullptr;

}  // end namespace

#ifdef DEBUG
static void BM_Factorial(benchmark::State& state) {
  int fac_42 = 0;
  while (state.KeepRunning())
    fac_42 = Factorial(8);
  // Prevent compiler optimizations
  CHECK(fac_42 != std::numeric_limits<int>::max());
}
BENCHMARK(BM_Factorial);
#endif

static void BM_CalculatePiRange(benchmark::State& state) {
  double pi = 0.0;
  while (state.KeepRunning())
    pi = CalculatePi(state.range_x());
  std::stringstream ss;
  ss << pi;
  state.SetLabel(ss.str());
}
BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024);

static void BM_CalculatePi(benchmark::State& state) {
  static const int depth = 1024;
  double pi ATTRIBUTE_UNUSED = 0.0;
  while (state.KeepRunning()) {
    pi = CalculatePi(depth);
  }
}
BENCHMARK(BM_CalculatePi)->Threads(8);
BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32);
BENCHMARK(BM_CalculatePi)->ThreadPerCpu();

static void BM_SetInsert(benchmark::State& state) {
  while (state.KeepRunning()) {
    state.PauseTiming();
    std::set<int> data = ConstructRandomSet(state.range_x());
    state.ResumeTiming();
    for (int j = 0; j < state.range_y(); ++j)
      data.insert(rand());
  }
  state.SetItemsProcessed(state.iterations() * state.range_y());
  state.SetBytesProcessed(state.iterations() * state.range_y() * sizeof(int));
}
BENCHMARK(BM_SetInsert)->RangePair(1<<10,8<<10, 1,10);

template<typename Q>
static void BM_Sequential(benchmark::State& state) {
  Q q;
  typename Q::value_type v;
  while (state.KeepRunning())
    for (int i = state.range_x(); --i; )
      q.push_back(v);
  const int64_t items_processed =
      static_cast<int64_t>(state.iterations()) * state.range_x();
  state.SetItemsProcessed(items_processed);
  state.SetBytesProcessed(items_processed * sizeof(v));
}
BENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>)->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10);

static void BM_StringCompare(benchmark::State& state) {
  std::string s1(state.range_x(), '-');
  std::string s2(state.range_x(), '-');
  int r = 0;
  while (state.KeepRunning())
    r |= s1.compare(s2);
  // Prevent compiler optimizations
  CHECK(r != std::numeric_limits<int>::max());
}
BENCHMARK(BM_StringCompare)->Range(1, 1<<20);

static void BM_SetupTeardown(benchmark::State& state) {
  if (state.thread_index == 0) {
    pthread_mutex_init(&test_vector_mu, nullptr);
    // No need to lock test_vector_mu here as this is running single-threaded.
    test_vector = new std::vector<int>();
  }
  int i = 0;
  while (state.KeepRunning()) {
    pthread_mutex_lock(&test_vector_mu);
    if (i%2 == 0)
      test_vector->push_back(i);
    else
      test_vector->pop_back();
    pthread_mutex_unlock(&test_vector_mu);
    ++i;
  }
  if (state.thread_index == 0) {
    delete test_vector;
    pthread_mutex_destroy(&test_vector_mu);
  }
}
BENCHMARK(BM_SetupTeardown)->ThreadPerCpu();

static void BM_LongTest(benchmark::State& state) {
  double tracker = 0.0;
  while (state.KeepRunning())
    for (int i = 0; i < state.range_x(); ++i)
      tracker += i;
  CHECK(tracker != 0.0);
}
BENCHMARK(BM_LongTest)->Range(1<<16,1<<28);

int main(int argc, const char* argv[]) {
  benchmark::Initialize(&argc, argv);

  CHECK(Factorial(8) == 40320);
  CHECK(CalculatePi(1) == 0.0);

  benchmark::RunSpecifiedBenchmarks();
}


text:
#ifndef VTKMITKEVENTPROVIDER_H_HEADER_INCLUDED_C1C53723
#define VTKMITKEVENTPROVIDER_H_HEADER_INCLUDED_C1C53723

#include "mitkRenderWindow.h"
#include <MitkCoreExports.h>

#include "vtkInteractorObserver.h"

namespace mitk
{
  /**
  * \brief Integrates into the VTK event mechanism to generate MITK specific events.
  * This class is NON-QT dependent pandon to the current MITK event handling code in QmitkRenderWindow.
  * \ingroup Renderer
  */
  class MITKCORE_EXPORT vtkEventProvider : public vtkInteractorObserver
  {
  public:
    static vtkEventProvider *New();
    vtkTypeMacro(vtkEventProvider, vtkInteractorObserver);

    // Satisfy the superclass API. Enable/disable listening for events.
    virtual void SetEnabled(int) override;
    virtual void SetInteractor(vtkRenderWindowInteractor *iren) override;

    // Interface to MITK
    virtual void SetMitkRenderWindow(mitk::RenderWindow *renWin);
    mitk::RenderWindow *GetRenderWindow();

  protected:
    vtkEventProvider();
    ~vtkEventProvider();

    // methods for processing events - callback for the observer/command pattern of vtkCommand
    static void ProcessEvents(vtkObject *object, unsigned long event, void *clientdata, void *calldata);

    mitk::RenderWindow *m_RenderWindow;

    // adds the MITK interaction event types to the VTK observer/command pattern
    void AddInteractionEvent(unsigned long ievent);
    // removes the MITK interaction event types
    void RemoveInteractionEvent(unsigned long ievent);
    typedef std::vector<unsigned long> InteractionEventsVectorType;
    InteractionEventsVectorType m_InteractionEventsVector;

  private:
    vtkEventProvider(const vtkEventProvider &); // Not implemented.
    void operator=(const vtkEventProvider &);   // Not implemented.
  };
}
#endif /* VTKMITKEVENTPROVIDER_H_HEADER_INCLUDED_C1C53723 */