text:
package org.jbromo.common.test.cdi;

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

import javax.enterprise.inject.spi.BeanManager;

import org.jbromo.common.test.common.IContainer;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

import lombok.extern.slf4j.Slf4j;

/**
 * Implements the JUnit 4 standard test case class model with Weld container.
 */
@Slf4j
public class CdiRunner extends BlockJUnit4ClassRunner {

    /**
     * Default constructor.
     * @param klass the class to test.
     * @throws InitializationError exception.
     */
    public CdiRunner(final Class<Object> klass) throws InitializationError {
        super(klass);
    }

    /**
     * Start all containers.
     */
    private void start() {
        final List<IContainer> containers = CdiContainerLoader.getInstance().getContainers();
        // Start containers.
        log.info("Start {} containers", containers.size());
        for (final IContainer container : containers) {
            container.start();
        }

        // Post-start containers.
        log.info("Post-start all containers");
        for (final IContainer container : containers) {
            container.postStart();
        }

        // Fire event for all started container.
        log.info("Fire started container event.");
        CdiContainerLoader.getInstance().getCdiContainer().select(BeanManager.class).fireEvent(new CdiStartedEvent());

    }

    /**
     * Stop all containers.
     */
    private void stop() {
        final List<IContainer> containers = CdiContainerLoader.getInstance().getContainers();
        // Fire event for all started container.
        log.info("Fire shutdown container event.");
        CdiContainerLoader.getInstance().getCdiContainer().select(BeanManager.class).fireEvent(new CdiShutdownEvent());

        // Pre-stop containers.
        log.info("Pre-stop {} containers", containers.size());
        final List<IContainer> reverse = new ArrayList<IContainer>(containers);
        Collections.reverse(reverse);
        for (final IContainer container : reverse) {
            container.preStop();
        }

        // Stop containers.
        log.info("Stop all containers");
        for (final IContainer container : reverse) {
            container.stop();
        }
    }

    @Override
    public void run(final RunNotifier arg0) {
        start();
        // Run tests.
        super.run(arg0);
        stop();

    }

    @Override
    protected Object createTest() throws Exception {
        return CdiContainerLoader.getInstance().getCdiContainer().select(getTestClass().getJavaClass());
    }

}


text:
import { createHash } from 'crypto';
import { htmlRewritingStream } from './html-rewriting-stream';

export type LoadOutputFileFunctionType = (file: string) => Promise<string>;

export type CrossOriginValue = 'none' | 'anonymous' | 'use-credentials';

export interface AugmentIndexHtmlOptions {
  /* Input contents */
  html: string;
  baseHref?: string;
  deployUrl?: string;
  sri: boolean;
  /** crossorigin attribute setting of elements that provide CORS support */
  crossOrigin?: CrossOriginValue;
  /*
   * Files emitted by the build.
   * Js files will be added without 'nomodule' nor 'module'.
   */
  files: FileInfo[];
  /** Files that should be added using 'nomodule'. */
  noModuleFiles?: FileInfo[];
  /** Files that should be added using 'module'. */
  moduleFiles?: FileInfo[];
  /*
   * Function that loads a file used.
   * This allows us to use different routines within the IndexHtmlWebpackPlugin and
   * when used without this plugin.
   */
  loadOutputFile: LoadOutputFileFunctionType;
  /** Used to sort the inseration of files in the HTML file */
  entrypoints: string[];
  /** Used to set the document default locale */
  lang?: string;
}

export interface FileInfo {
  file: string;
  name: string;
  extension: string;
}

/*
 * Helper function used by the IndexHtmlWebpackPlugin.
 * Can also be directly used by builder, e. g. in order to generate an index.html
 * after processing several configurations in order to build different sets of
 * bundles for differential serving.
 */
export async function augmentIndexHtml(params: AugmentIndexHtmlOptions): Promise<string> {
  const {
    loadOutputFile,
    files,
    noModuleFiles = [],
    moduleFiles = [],
    entrypoints,
    sri,
    deployUrl = '',
    lang,
    baseHref,
    html,
  } = params;

  let { crossOrigin = 'none' } = params;
  if (sri && crossOrigin === 'none') {
    crossOrigin = 'anonymous';
  }

  const stylesheets = new Set<string>();
  const scripts = new Set<string>();

  // Sort files in the order we want to insert them by entrypoint and dedupes duplicates
  const mergedFiles = [...moduleFiles, ...noModuleFiles, ...files];
  for (const entrypoint of entrypoints) {
    for (const { extension, file, name } of mergedFiles) {
      if (name !== entrypoint) {
        continue;
      }

      switch (extension) {
        case '.js':
          scripts.add(file);
          break;
        case '.css':
          stylesheets.add(file);
          break;
      }
    }
  }

  let scriptTags: string[] = [];
  for (const script of scripts) {
    const attrs = [`src="${deployUrl}${script}"`];

    if (crossOrigin !== 'none') {
      attrs.push(`crossorigin="${crossOrigin}"`);
    }

    // We want to include nomodule or module when a file is not common amongs all
    // such as runtime.js
    const scriptPredictor = ({ file }: FileInfo): boolean => file === script;
    if (!files.some(scriptPredictor)) {
      // in some cases for differential loading file with the same name is available in both
      // nomodule and module such as scripts.js
      // we shall not add these attributes if that's the case
      const isNoModuleType = noModuleFiles.some(scriptPredictor);
      const isModuleType = moduleFiles.some(scriptPredictor);

      if (isNoModuleType && !isModuleType) {
        attrs.push('nomodule', 'defer');
      } else if (isModuleType && !isNoModuleType) {
        attrs.push('type="module"');
      } else {
        attrs.push('defer');
      }
    } else {
      attrs.push('defer');
    }

    if (sri) {
      const content = await loadOutputFile(script);
      attrs.push(generateSriAttributes(content));
    }

    scriptTags.push(`<script ${attrs.join(' ')}></script>`);
  }

  let linkTags: string[] = [];
  for (const stylesheet of stylesheets) {
    const attrs = [`rel="stylesheet"`, `href="${deployUrl}${stylesheet}"`];

    if (crossOrigin !== 'none') {
      attrs.push(`crossorigin="${crossOrigin}"`);
    }

    if (sri) {
      const content = await loadOutputFile(stylesheet);
      attrs.push(generateSriAttributes(content));
    }

    linkTags.push(`<link ${attrs.join(' ')}>`);
  }

  const { rewriter, transformedContent } = await htmlRewritingStream(html);
  const baseTagExists = html.includes('<base');

  rewriter
    .on('startTag', (tag) => {
      switch (tag.tagName) {
        case 'html':
          // Adjust document locale if specified
          if (isString(lang)) {
            updateAttribute(tag, 'lang', lang);
          }
          break;
        case 'head':
          // Base href should be added before any link, meta tags
          if (!baseTagExists && isString(baseHref)) {
            rewriter.emitStartTag(tag);
            rewriter.emitRaw(`<base href="${baseHref}">`);

            return;
          }
          break;
        case 'base':
          // Adjust base href if specified
          if (isString(baseHref)) {
            updateAttribute(tag, 'href', baseHref);
          }
          break;
      }

      rewriter.emitStartTag(tag);
    })
    .on('endTag', (tag) => {
      switch (tag.tagName) {
        case 'head':
          for (const linkTag of linkTags) {
            rewriter.emitRaw(linkTag);
          }

          linkTags = [];
          break;
        case 'body':
          // Add script tags
          for (const scriptTag of scriptTags) {
            rewriter.emitRaw(scriptTag);
          }

          scriptTags = [];
          break;
      }

      rewriter.emitEndTag(tag);
    });

  const content = await transformedContent;

  if (linkTags.length || scriptTags.length) {
    // In case no body/head tags are not present (dotnet partial templates)
    return linkTags.join('') + scriptTags.join('') + content;
  }

  return content;
}

function generateSriAttributes(content: string): string {
  const algo = 'sha384';
  const hash = createHash(algo).update(content, 'utf8').digest('base64');

  return `integrity="${algo}-${hash}"`;
}

function updateAttribute(
  tag: { attrs: { name: string; value: string }[] },
  name: string,
  value: string,
): void {
  const index = tag.attrs.findIndex((a) => a.name === name);
  const newValue = { name, value };

  if (index === -1) {
    tag.attrs.push(newValue);
  } else {
    tag.attrs[index] = newValue;
  }
}

function isString(value: unknown): value is string {
  return typeof value === 'string';
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Neos\Flow\Aop\Advice;

/**
 * Implementation of the After Returning Advice.
 *
 */
class AfterReturningAdvice extends AbstractAdvice
{
}


text:
CREATE TABLE authors(
	author_id SERIAL PRIMARY KEY,
	parent_author_id INT,
	name VARCHAR(25) NOT NULL DEFAULT 'default_name',
	updated_at timestamp,
	created_at timestamp,
	"some_Date" date,
	some_time time,
	some_text text,
	encrypted_password varchar(50),
	"mixedCaseField" varchar(50)
);

CREATE TABLE books(
	book_id SERIAL PRIMARY KEY,
	author_id INT,
	secondary_author_id INT,
	name VARCHAR(50),
	numeric_test VARCHAR(10) DEFAULT '0',
	special NUMERIC(10,2) DEFAULT 0.0
);

CREATE TABLE venues (
	id SERIAL PRIMARY KEY,
	name varchar(50),
	city varchar(60),
	state char(2),
	address varchar(50),
	phone varchar(10) default NULL,
	UNIQUE(name,address)
);

CREATE TABLE events (
	id SERIAL PRIMARY KEY,
	venue_id int NOT NULL,
	host_id int NOT NULL,
	title varchar(60) NOT NULL,
	description varchar(10),
	type varchar(15) default NULL
);

CREATE TABLE hosts(
	id SERIAL PRIMARY KEY,
	name VARCHAR(25)
);

CREATE TABLE employees (
	id SERIAL PRIMARY KEY,
	first_name VARCHAR(255) NOT NULL,
	last_name VARCHAR(255) NOT NULL,
	nick_name VARCHAR(255) NOT NULL
);

CREATE TABLE positions (
	id SERIAL PRIMARY KEY,
	employee_id int NOT NULL,
	title VARCHAR(255) NOT NULL,
	active SMALLINT NOT NULL
);

CREATE TABLE "rm-bldg"(
    "rm-id" SERIAL PRIMARY KEY,
    "rm-name" VARCHAR(10) NOT NULL,
    "space out" VARCHAR(1) NOT NULL
);

CREATE TABLE awesome_people(
	id serial primary key,
	author_id int,
	is_awesome int default 1
);

CREATE TABLE amenities(
	amenity_id serial primary key,
	type varchar(40) NOT NULL
);

CREATE TABLE property(
	property_id serial primary key
);

CREATE TABLE property_amenities(
	id serial primary key,
	amenity_id int not null,
	property_id int not null
);

CREATE TABLE users(
	id serial primary key
);

CREATE TABLE newsletters(
	id serial primary key
);

CREATE TABLE user_newsletters(
  id serial primary key,
  user_id int not null,
  newsletter_id int not null
);

-- reproduces issue GH-96 for testing
CREATE INDEX user_newsletters_id_and_user_id_idx ON user_newsletters USING btree(id, user_id);


text:
/**
 * Criado por Fausto Junqueira em 08/01/2016.
 */

var express = require('express');
var sl = require('sugarloaf');
var app = sl(express(), __dirname + '/../config/dev/config.json');
var rotas = require('./rotas');

// Aplicar as rotas
rotas(app);

var servidor = app.sl.start(function(){
  var host = servidor.address().address;
  var port = servidor.address().port;
  console.log('[SUGARLOAG-BOILERPLATE] Aplicação ouvindo em http://%s:%s', host, port);
});


text:
require 'spec_helper'

module Codebreaker
  RSpec.describe ConsoleGame do
    subject(:console) { ConsoleGame.new }
    before { console.instance_variable_set(:@game, Game.new) }

    describe '#start' do
      before do
        allow(console).to receive(:submit)
        allow(console).to receive(:puts)
      end

      after { console.start }

      it 'assigns Game instance to @game' do
        console.start
        expect(console.instance_variable_get(:@game)).to be_instance_of(Game)
      end

      it 'explains how to use hints' do
        expect(console).to receive(:puts).with('Type \'hint\' anytime you need help')
      end

      it 'calls #submit method' do
        expect(console).to receive(:submit)
      end
    end

    describe '#submit' do
      before do
        allow(console).to receive_message_chain(:gets, :chomp)
        allow(console).to receive(:puts)
      end

      after { console.submit }

      it 'offers code-breaker to submit the guess' do
        allow(console.game).to receive(:valid_guess?)
        allow(console).to receive(:invalid_submit)
        allow(console).to receive(:puts).and_call_original
        expect(STDOUT).to receive(:puts).with('Enter your guess: ')
      end

      it 'calls #compare if the guess is valid' do
        allow(console.game).to receive(:valid_guess?).and_return(true)
        allow(console).to receive(:compare)
        expect(console).to receive(:compare)
      end

      it 'calls #invalid_submit if the guess is invalid' do
        allow(console.game).to receive(:valid_guess?).and_return(false)
        expect(console).to receive(:invalid_submit)
      end

      it 'calls #show_hint if user entered \'hint\'' do
        allow(console).to receive_message_chain(:gets, :chomp).and_return('hint')
        allow(console).to receive(:show_hint)
        expect(console).to receive(:show_hint)
      end
    end

    describe '#compare(input)' do
      before do
        allow(console.game).to receive(:compare).and_return('++++')
        allow(console).to receive(:puts)
        allow(console).to receive(:win)
        allow(console).to receive(:failed_attempt)
      end

      after { console.compare(input) }

      let(:input) { '1111' }

      it 'shows the result' do
        allow(console).to receive(:puts).and_call_original
        allow(console.game).to receive(:win?)
        expect(STDOUT).to receive(:puts).with('++++')
      end

      it 'calls #game.win?' do
        expect(console.game).to receive(:win?)
      end

      it 'calls #win if #game.win? returns true' do
        allow(console.game).to receive(:win?).and_return(true)
        expect(console).to receive(:end_game).with(:win)
      end

      it 'calls #failed_attempt if #game.win? returns false' do
        allow(console.game).to receive(:win?).and_return(false)
        expect(console).to receive(:failed_attempt)
      end
    end

    describe '#invalid_submit' do
      before { allow(console).to receive(:submit) }

      it 'warns player about invalid submit' do
        expect { console.invalid_submit }.to \
          output("A guess should have 4 numbers\n").to_stderr
      end

      it 'calls #submit method' do
        expect(console). to receive(:submit)
        console.invalid_submit
      end
    end

    describe '#end_game(decision)' do
      before do
        allow(console).to receive_message_chain(:gets, :chomp, :upcase)
        allow(console).to receive(:save)
        allow(console).to receive(:play_again)
      end

      after { console.end_game(@decision) }

      it 'shows congrats message if decision is :win' do
        @decision = :win
        allow(STDOUT).to receive(:puts).with('Do you want to save game?(Y/N)')
        expect(STDOUT).to receive(:puts).with('You won the game!')
      end

      it 'shows game over message if decision is NOT :win' do
        @decision = :game_over
        allow(STDOUT).to receive(:puts).with('Do you want to save game?(Y/N)')
        expect(STDOUT).to receive(:puts).with('Game over.')
      end

      it 'offers to save game' do
        allow(STDOUT).to \
          receive(:puts).with('Game over.')
        expect(STDOUT).to receive(:puts).with('Do you want to save game?(Y/N)')
      end

      it 'calls #save if code-breaker replies with \'Y\'' do
        allow(console).to receive(:puts)
        allow(console).to receive_message_chain(:gets, :chomp, :upcase) { 'Y' }
        expect(console).to receive(:save)
      end

      it 'doesn\'t call #save if code-breaker replies with \'N\'' do
        allow(console).to receive(:puts)
        allow(console).to receive_message_chain(:gets, :chomp, :upcase) { 'N' }
        expect(console).not_to receive(:save)
      end

      it 'calls #play_again method' do
        allow(console).to receive(:puts)
        expect(console).to receive(:play_again)
      end
    end

    describe '#failed_attempt' do
      after { console.failed_attempt }

      it 'calls #end_game with :game_over if no attempts left' do
        console.game.instance_variable_set(:@attempts, 0)
        expect(console).to receive(:end_game).with(:game_over)
      end

      it 'calls #submit if there are some attempts left' do
        console.game.instance_variable_set(:@attempts, 1)
        expect(console).to receive(:submit)
      end
    end

    describe '#show_hint' do
      after { console.show_hint }

      it 'shows hint or \'No hints left\' to the user' do
        allow(console).to receive(:submit)
        expect(console).to receive(:puts).with(Integer)
      end

      it 'calls #submit' do
        allow(console).to receive(:puts).with(Integer)
        expect(console).to receive(:submit)
      end
    end

    describe '#play_again' do
      before do
        allow(console).to receive(:start)
        allow(console).to receive_message_chain(:gets, :chomp, :upcase) { 'Y' }
      end

      after { console.play_again }

      it 'prompts the play again message' do
        expect(STDOUT).to \
          receive(:puts).with('Do you want to play again?(Y/N)')
      end

      it 'starts game if code-breaker responses with \'Y\'' do
        allow(console).to receive(:puts)
        expect(console).to receive(:start)
      end

      it 'closes game if code-breaker responses with \'N\'' do
        allow(console).to receive(:puts).with('Do you want to play again?(Y/N)')
        allow(console).to receive_message_chain(:gets, :chomp, :upcase) { 'N' }
        expect(console).to receive(:puts).with('The end.')
      end
    end

    describe '#save' do
      before do
        allow(File).to receive(:open)
        allow(console).to receive_message_chain(:gets, :chomp)
        allow(console).to receive(:play_again)
        allow(console).to receive(:puts)
      end

      after { console.save }

      it 'prompts to enter code-breakers name before saving' do
        allow(console).to receive(:puts).and_call_original
        expect(STDOUT).to receive(:puts).with('Enter your name:')
      end

      it 'it receives te name of code-breaker' do
        expect(console).to receive_message_chain(:gets, :chomp)
      end

      it 'creates #{code-breakers name}_score.txt file' do
        allow(console).to receive_message_chain(:gets, :chomp).and_return('yuriy')
        expect(File).to receive(:open).with('yuriy_score.txt', 'w')
      end

      it 'saves name, score, number of turns and hints in the .txt file' do
        allow(console).to receive_message_chain(:gets, :chomp).and_return('yuriy')
        file = double('file')
        allow(File).to receive(:open).and_yield(file)
        expect(file).to receive(:write)
          .with(/^Code-breaker: +\w+\W+Turns: \d+\W+Hints used: \d+\W+Score: +\d/m)
      end
    end
  end
end


text:
int
main ()
{
  int result = 0;

  const unsigned int N = 1000;
  const unsigned int chunk_tier = 5;
  const short use_linear_tree = 1;

  struct spamm_matrix_t *A;

  A = spamm_new(N, N, chunk_tier, use_linear_tree, row_major);

  spamm_expand(A);

  spamm_delete(&A);

  return result;
}


text:
We're trying to create a neural network that detects sentiment, and
predicts whether a Yelp review (all 5 million of them) is positive or negative.
Reviews come from words.  Maybe we can look at the set of words in a review and make a guess from that?

Well let's see.  How frequently do some words occur?  Let's grab a sample of 100k positive and
negative reviews, 200k total.

![Lots of noise](noise.png)

The chart on the left shows that most words from 200,000
reviews are indistinguishable en masse,
so that's why naive approaches may take a long time to converge.
One approach is to look at words that occur more frequently.
When we cut off words that occur less than 50 times, we get
the chart on the right. We see the beginning of a distro, but it's weak.
We have to clean up the signal for our network
using a hypothesis of what's important.

![Signal](signal.png)

So we calculate a ratio, how many words appear
in positive vs. negative reviews?  A value of 0 means
all negative reviews, 1.0 means equal distribution between
positive and negative, greater than 1.0 means more positive than
negative. Neural networks like values between -1 and 1 centered at 0.
Take the log(x)!  log(1) = 0,  log(1/x) = negative, log(n) = small.
Then lets cut out those that don't help much, the area around 0.
Voila.  A signal around 0, on the right!  Now let's train that on a simple network.

![Results](semantics.png)

The network converges in a few minutes with 94% accuracy.
The weights on the input nodes are a vector representation of
semantics, so vectors close together are similar.
Here we see words that are somewhat similar, with some noise,
as we project from a 64-dimensional space to 2 dimensions.  Neat!


text:
export default function checkAllAvailabilities (period) {
	for(let i in this.availabilities) {
		let avail = this.availabilities[i];

		if((moment(avail.startDateNy).isBetween(period.dateStart, period.dateEnd, 'minutes', '[]') ||
				moment(avail.endDateNy).isBetween(period.dateStart, period.dateEnd, 'minutes', '[]')) ||
      (moment(period.dateStart).isBetween(avail.startDateNy, avail.endDateNy, 'minutes', '[]') ||
      moment(period.dateEnd).isBetween(avail.startDateNy, avail.endDateNy, 'minutes', '[]'))) {
			return true;
		}
	}

  return false;
}


text:
typedef pcl::PointXYZRGBNormal pointType;

// This function displays the help
void
showHelp(char * program_name)
{
  std::cout << std::endl;
  std::cout << "Usage: " << program_name << " input_cloud_filename.[pcd|ply]  input2_cloud_filename.[pcd|ply]  output_cloud_filename.pcd " << std::endl;
  std::cout << "-h:  Show this help." << std::endl;
}

// This is the main function
int
main (int argc, char** argv)
{

  // Show help
  if (pcl::console::find_switch (argc, argv, "-h") || pcl::console::find_switch (argc, argv, "--help")) {
    showHelp (argv[0]);
    return 0;
  }

  // Fetch point cloud filename in arguments | Works with PCD and PLY files
  std::vector<int> filenames;
  bool file_is_pcd = false;

  filenames = pcl::console::parse_file_extension_argument (argc, argv, ".pcd");

    if (filenames.size () != 3) {
      showHelp (argv[1]);
      return -1;
    } else {
      file_is_pcd = true;
    }

  // Load file | Works with PCD and PLY filesV
  std::vector<pcl::PointCloud<pointType>::Ptr> source_clouds; // (new pcl::PointCloud<pointType> ());
  for(int i=0; i <  filenames.size() -1 ; i++){ //Last one is the output.

    pcl::PointCloud<pointType>::Ptr source_cloud  (new pcl::PointCloud<pointType> ());
    source_clouds.push_back(source_cloud);

    if (file_is_pcd) {
      if (pcl::io::loadPCDFile (argv[filenames[i]], *source_cloud) < 0)  {
        std::cout << "Error loading point cloud " << argv[filenames[i]] << std::endl << std::endl;
        return -1;
      }
    } else {
      if (pcl::io::loadPLYFile (argv[filenames[i]], *source_cloud) < 0)  {
        std::cout << "Error loading point cloud " << argv[filenames[i]] << std::endl << std::endl;
        return -1;
      }
    }

  }

  pcl::PointCloud<pointType>::Ptr result (new pcl::PointCloud<pointType> ());

  for(int i=0; i < source_clouds.size() ; i++){
    *result += *source_clouds[i];
  }

  pcl::io::savePCDFile(argv[filenames[filenames.size()-1]], *result);
  return 0;
}


text:
// Package jwt provides methods to create and check JSON Web Tokens (JWT). It only implements HMAC 256 encryption and has a very small footprint, ideal for simple usage when authorizing clients
/*

	package main

	import (
		auth "github.com/nilslice/jwt"
		"fmt"
		"net/http"
		"strings"
		"time"
	)

	func main() {
		http.HandleFunc("/auth/new", func(res http.ResponseWriter, req *http.Request) {
		claims := map[string]interface{}{"exp": time.Now().Add(time.Hour * 24).Unix()}
			token, err := auth.New(claims)
			if err != nil {
				http.Error(res, "Error", 500)
				return
			}
			res.Header().Add("Authorization", "Bearer "+token)

			res.WriteHeader(http.StatusOK)
		})

		http.HandleFunc("/auth", func(res http.ResponseWriter, req *http.Request) {
			userToken := strings.Split(req.Header.Get("Authorization"), " ")[1]

			if auth.Passes(userToken) {
				fmt.Println("ok")
			} else {
				fmt.Println("no")
			}
		})

		http.ListenAndServe(":8080", nil)
	}
*/
package jwt


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BookCollection.DAL;
using System.Collections.Generic;
using BookCollection.Logging;
using Moq;
using BookCollection.Models;
using BookCollection.DAL.SeedData;

namespace BookCollection.Tests.DAL
{
    [TestClass]
    public class BookSeederTest
    {

        Mock<ILogger> logger;
        Mock<ISeedDataProvider> dataProvider;
        Mock<IBookContext> bc;
        seedDataModel singleBook;

        [TestInitialize]
        public void Setup()
        {
            logger = new Mock<ILogger>();
            dataProvider = new Mock<ISeedDataProvider>();
            bc = new Mock<IBookContext>();
            singleBook = new seedDataModel()
            {
                Author = "Beltman, Guus",
                Title = "(50) Shades of MVC",
                AlternativeTitle = "50 tastes of MVC",
                Serie = "Great books of the world III",
                Publisher = "Atlas publishing",
                PrintedYears = "1900 2015",
                Type = "Romannetje",
                Code = "l051n",
                Subjects1 = "Lorem ipsum 1",
                Subjects2 = "Lorem ipsum 2",
                Contents = "Lodewijk XIV de zonnekoning van Frankrijk, Johanna de waanzinnige van Kastilië",
                CreateDate = ""
            };
        }

        [TestMethod]
        public void CleanUpCategoryTest()
        {
            // Arrange
            var bookInit = new BookSeeder(bc.Object, logger.Object, dataProvider.Object);

            // Act & Assert
            Assert.AreEqual("biografieën", bookInit.CleanUpCategory("biogr. studies"));

        }

        [TestMethod]
        public void SeedCategoriesTest()
        {
            // Arrange
            dataProvider.Setup(c => c.GetData()).Returns(new List<seedDataModel>() { singleBook });
            var bookInit = new BookSeeder(bc.Object, logger.Object, dataProvider.Object);

            // Act
            var list = bookInit.SeedCategories();

            // Assert
            Assert.IsTrue(list.Count == 1);
            Assert.AreEqual("Roman", list[0].Title);
        }

        [TestMethod]
        public void SeedBookTest()
        {
            // Arrange
            dataProvider.Setup(c => c.GetData()).Returns(new List<seedDataModel>() { singleBook });
            var bookInit = new BookSeeder(bc.Object, logger.Object, dataProvider.Object);

            // Act
            List<Book> list = (List<Book>)bookInit.GetBooks(
                new List<Publisher>() { new Publisher() { Name = "" } },
                new List<Author> { new Author() { Lastname = "Beltman", Firstname = "Guus" } },
                new List<Category> { new Category { Title = "Roman" } },
                new List<Subject> { new Subject { Name = "Stuff" } });

            // Assert
            Assert.IsTrue(list.Count == 1);
            Assert.AreEqual("Great books of the world", list[0].Serie);
            Assert.AreEqual("III", list[0].CodeWithinSerie);

        }
    }
}


text:
package com.adobe.internal.fxg.dom.types;

/**
 * The Font Weight enumeration.
 *
 * <pre>
 *   0 = normal
 *   1 = bold
 * </pre>
 *
 */
public enum FontWeight
{
    /**
     * The enum representing an 'normal' Font Weight.
     */
    NORMAL,

    /**
     * The enum representing an 'bold' Font Weight.
     */
    BOLD;
}


text:
package org.teamstbf.yats.model;

import java.time.LocalDate;
import java.util.Set;

import org.teamstbf.yats.commons.core.UnmodifiableObservableList;
import org.teamstbf.yats.model.item.Event;
import org.teamstbf.yats.model.item.ReadOnlyEvent;
import org.teamstbf.yats.model.item.UniqueEventList;

/**
 * The API of the Model component.
 */
public interface Model {

    /** Adds the given Event */
    void addEvent(Event event);

    /** Deletes the given Event. */
    void deleteEvent(ReadOnlyEvent target) throws UniqueEventList.EventNotFoundException;

    /**
     * Returns the filtered event list as an
     * {@code UnmodifiableObservableList<ReadOnlyEvent>}
     */
    UnmodifiableObservableList<ReadOnlyEvent> getFilteredTaskList();

    /**
     * Returns the calendar filtered event list as an
     * {@code UnmodifiableObservableList<ReadOnlyEvent>}
     */
    UnmodifiableObservableList<ReadOnlyEvent> getCalendarFilteredTaskList();

    /**
     * Returns the task filtered event list as an
     * {@code UnmodifiableObservableList<ReadOnlyEvent>}
     */
    UnmodifiableObservableList<ReadOnlyEvent> getTaskFilteredTaskList();

    /** Returns the TaskManager */
    ReadOnlyTaskManager getTaskManager();

    /**
     * Clears existing backing model and replaces with the provided new data.
     */
    void resetData(ReadOnlyTaskManager newData);

    /**
     * Updates the event located at {@code filteredEventListIndex} with
     * {@code editedEvent}.
     *
     * @throws IndexOutOfBoundsException
     *             if {@code filteredEventListIndex} < 0 or >= the size of the
     *             filtered list.
     */
    void updateEvent(int filteredEventListIndex, ReadOnlyEvent editedEvent);

    /**
     * Updates the filter of the filtered event list to filter by the given
     * keywords
     */
    void updateFilteredEventList(Set<String> keywords);

    /**
     * Updates the filter of the filtered event list to show all undone events
     */
    void updateFilteredListToShowAll();

    // @@author A0139448U

    /*
     * force saves the current state of the taskmanager for use in changing save
     * location to create a file in new location
     */
    void saveTaskManager();

    // @@author A0138952W

    /**
     * Updates the filter of the Calendar filtered event list to show specified
     * start time
     */
    void updateCalendarFilteredListToShowStartTime(LocalDate today);

    /**
     * Updates the filter of the Done task filtered event list to show done task
     */
    void updateDoneTaskList();

    /**
     * Updates the filter of the filtered event list to show specified location
     */
    void updateFilteredListToShowLocation(Set<String> keywords);

    /** Updates the filter of the filtered event list to show specified date */
    void updateFilteredListToShowEndTime(Set<String> keywords);

    /**
     * Updates the filter of the filtered event list to show specified start
     * time
     */
    void updateFilteredListToShowStartTime(Set<String> keywords);

    /**
     * Updates the filter of the filtered event list to show specified deadline
     */
    void updateFilteredListToShowDeadline(Set<String> keywords);

    /**
     * This method sorts the filtered list by deadline, and then shows it on the
     * GUI
     */
    void updateFilteredListToShowDeadline();

    /** Updates the filter of the filtered event list to show done tasks */
    void updateFilteredListToShowDone(Set<String> keywords);

    /** Updates the filter of the filtered event list to show specified tags */
    void updateFilteredListToShowTags(Set<String> keywords);

    /**
     * Updates the filter of the filtered event list to search for all tasks
     * including description with the specified keywords
     */
    void updateFilteredListToFindAll(Set<String> keywords);

    // @@author A0102778B
    /**
     * Method to get the previous state (undo command) of the task manager
     */
    void getPreviousState();

    /**
     * Method to get the next state (redo command) of the task manager
     */
    void getNextState();

    /**
     * Method to check if the undo stack is empty - nothing to undo
     */
    boolean checkEmptyUndoStack();

    /**
     * Method to check if the redo stack is empty - nothing to redo
     */
    boolean checkEmptyRedoStack();

    /**
     * Method to check if the redo stack is empty - nothing to redo
     */
    void scheduleEvent(Event event);

    /**
     * Saves an image of the previous state of the TaskManager for the undo
     * command - also clears the redo stack images because once the state is
     * mutated the previous redoes state are invalid because they are no longer
     * part of the same chain. This is an internal method used by the addEvent,
     * deteleEvent, clearEvent, editEvent methods. This method also contains a
     * check - if there are currently too many task manager states, it will
     * remove half of the earlier saved states and only keep the later half.
     */
    void saveImageOfCurrentTaskManager();

    /**
     * This method sorts the filtered list by start time, and then shows it on
     * the GUI
     */
    void updateFilteredListToShowSortedStart();

    /**
     * This method sorts the filtered list by end time, and then shows it on the
     * GUI
     */
    void updateFilteredListToShowSortedEnd();

}


text:
FROM similitude/h2-world-docker

MAINTAINER Oliver Lade <oliver@similitude.org>
# See https://groups.google.com/d/topic/h2-database/ZXOCLxNJ2kI/discussion

ENV H2_HOME /opt/h2
ENV H2_DATA /opt/h2-data
ENV H2_VERSION 1.4.182

# Install API dependencies.
RUN apt-get update && apt-get install -qq python && apt-get clean

# Add the API.
ADD /api /api


text:
<?php
namespace Payum\LaravelPackage\Model;

use Illuminate\Database\Eloquent\Model;
use Payum\Core\Model\CreditCardInterface;
use Payum\Core\Model\PaymentInterface;

class Payment extends Model implements  PaymentInterface
{
    protected $creditCard;

    /**
     * @var string
     */
    protected $table = 'payum_payments';

    /**
     * {@inheritDoc}
     */
    public function setDetails($details)
    {
        $this->setAttribute('details', json_encode($details ?: array()));
    }

    /**
     * {@inheritDoc}
     */
    public function getDetails()
    {
        return json_decode($this->getAttribute('details') ?: '{}', true);
    }

    /**
     * {@inheritDoc}
     */
    public function getNumber()
    {
        return $this->getAttribute('number');
    }

    /**
     * {@inheritDoc}
     */
    public function setNumber($number)
    {
        $this->setAttribute('number', $number);
    }

    /**
     * {@inheritDoc}
     */
    public function getDescription()
    {
        return $this->getAttribute('description');
    }

    /**
     * {@inheritDoc}
     */
    public function setDescription($description)
    {
        $this->setAttribute('description', $description);
    }

    /**
     * {@inheritDoc}
     */
    public function getClientEmail()
    {
        // TODO: Implement getClientEmail() method.
    }

    /**
     * {@inheritDoc}
     */
    public function setClientEmail($clientEmail)
    {
        $this->setAttribute('clientEmail', $clientEmail);
    }

    /**
     * {@inheritDoc}
     */
    public function getClientId()
    {
        return $this->getAttribute('clientId');
    }

    /**
     * {@inheritDoc}
     */
    public function setClientId($clientId)
    {
        $this->setAttribute('clientId', $clientId);
    }

    /**
     * {@inheritDoc}
     */
    public function getTotalAmount()
    {
        return $this->getAttribute('totalAmount');
    }

    /**
     * {@inheritDoc}
     */
    public function setTotalAmount($totalAmount)
    {
        $this->setAttribute('totalAmount', $totalAmount);
    }

    /**
     * {@inheritDoc}
     */
    public function getCurrencyCode()
    {
        return $this->getAttribute('currencyCode');
    }

    /**
     * {@inheritDoc}
     */
    public function setCurrencyCode($currencyCode)
    {
        $this->setAttribute('currencyCode', $currencyCode);
    }

    /**
     * @return mixed
     */
    public function getCreditCard()
    {
        return $this->creditCard;
    }

    /**
     * @param CreditCardInterface $creditCard
     */
    public function setCreditCard(CreditCardInterface $creditCard = null)
    {
        $this->creditCard = $creditCard;
    }
}


text:
/**********************************************************************
*
*
*
**********************************************************************/
((typeof define)[0]=='u'?function(f){module.exports=f(require)}:define)
(function(require){ var module={} // make module AMD/node compatible...
/*********************************************************************/

var base = require('./base')
var showdown = require('showdown')

//---------------------------------------------------------------------

module.markdown =
base.Filter(
	{quote: 'quote-markdown'},
	function(source){
		var converter = new showdown.Converter({
			strikethrough: true,
			tables: true,
			tasklists: true,
		})
		// XXX the problem here is that any string gets nested into a
		// 		paragraph -- this messes up partial filtering...
		return converter.makeHtml(source) })

module.quoteMarkdown =
function(source){
	// XXX
	return source }

/**********************************************************************
* vim:set ts=4 sw=4 :                               */ return module })


text:
package protobuf

import (
	"errors"

	"github.com/asdine/storm/codec/json"
	"github.com/golang/protobuf/proto"
)

const name = "protobuf"

// More details on Protocol Buffers https://github.com/golang/protobuf
var (
	Codec                       = new(protobufCodec)
	errNotProtocolBufferMessage = errors.New("value isn't a Protocol Buffers Message")
)

type protobufCodec int

// Encode value with protocol buffer.
// If type isn't a Protocol buffer Message, gob encoder will be used instead.
func (c protobufCodec) Marshal(v interface{}) ([]byte, error) {
	message, ok := v.(proto.Message)
	if !ok {
		// toBytes() may need to encode non-protobuf type, if that occurs use json
		return json.Codec.Marshal(v)
	}
	return proto.Marshal(message)
}

func (c protobufCodec) Unmarshal(b []byte, v interface{}) error {
	message, ok := v.(proto.Message)
	if !ok {
		// toBytes() may have encoded non-protobuf type, if that occurs use json
		return json.Codec.Unmarshal(b, v)
	}
	return proto.Unmarshal(b, message)
}

func (c protobufCodec) Name() string {
	return name
}


text:
package co.arcs.groove.basking.inject;

import android.app.Application;
import android.content.Context;

import java.lang.annotation.Retention;

import javax.inject.Qualifier;
import javax.inject.Singleton;

import co.arcs.groove.basking.App;
import co.arcs.groove.basking.BackgroundSyncScheduler;
import co.arcs.groove.basking.SyncManager;
import co.arcs.groove.basking.pref.AppPreferences;
import co.arcs.groove.basking.ui.SyncFragment;
import dagger.Module;
import dagger.Provides;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Module(injects = {App.class,
                   BackgroundSyncScheduler.class,
                   AppPreferences.class,
                   SyncFragment.class})
public class AppModule {

    @Qualifier
    @Retention(RUNTIME)
    public @interface ApplicationContext {
    }

    private final Application application;

    public AppModule(App application) {
        this.application = application;
    }

    @Provides
    @Singleton
    @ApplicationContext
    Context provideApplicationContext() {
        return application;
    }

    @Provides
    @Singleton
    AppPreferences provideAppPreferences() {
        return new AppPreferences(application);
    }

    @Provides
    @Singleton
    SyncManager provideSyncManager(@ApplicationContext Context context) {
        return new SyncManager(context);
    }
}


text:
package com.fincatto.documentofiscal.mdfe3.classes.consultastatusservico;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;

import com.fincatto.documentofiscal.DFAmbiente;
import com.fincatto.documentofiscal.DFBase;

/**
 * Created by Eldevan Nery Junior on 10/11/17. Pedido de Consulta do Status do Serviço MDF-e
 */
@Root(name = "consStatServMDFe")
@Namespace(reference = "http://www.portalfiscal.inf.br/mdfe")
public class MDFeConsStatServ extends DFBase {
    private static final long serialVersionUID = 7378228337172209671L;

    @Element(name = "tpAmb", required = false)
    private DFAmbiente ambiente;

    @Element(name = "xServ", required = false)
    private String servico;

    @Attribute(name = "versao", required = false)
    private String versao;

    public DFAmbiente getAmbiente() {
        return this.ambiente;
    }

    public void setAmbiente(final DFAmbiente ambiente) {
        this.ambiente = ambiente;
    }

    public String getServico() {
        return this.servico;
    }

    public void setServico(final String servico) {
        this.servico = servico;
    }

    public String getVersao() {
        return this.versao;
    }

    public void setVersao(final String versao) {
        this.versao = versao;
    }
}


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

// TESTS //

// The function returns an array of numbers..
{
	arrayShape( [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] ); // $ExpectType number[]
}

// The compiler throws an error if not provided an array-like object...
{
	arrayShape( 5 ); // $ExpectError
	arrayShape( false ); // $ExpectError
	arrayShape( true ); // $ExpectError
	arrayShape( null ); // $ExpectError
	arrayShape( undefined ); // $ExpectError
	arrayShape( {} ); // $ExpectError
}

// The compiler throws an error if the function is provided an unsupported number of arguments...
{
	arrayShape(); // $ExpectError
	arrayShape( [ 1, 2, 3 ], 3 ); // $ExpectError
}


text:
package org.elasticsearch.common.util;

import com.carrotsearch.hppc.DoubleArrayList;
import com.carrotsearch.hppc.FloatArrayList;
import com.carrotsearch.hppc.LongArrayList;
import com.carrotsearch.hppc.ObjectArrayList;
import org.apache.lucene.util.*;

import java.util.*;

/** Collections-related utility methods. */
public class CollectionUtils {
    public static void sort(LongArrayList list) {
        sort(list.buffer, list.size());
    }

    public static void sort(final long[] array, int len) {
        new IntroSorter() {

            long pivot;

            @Override
            protected void swap(int i, int j) {
                final long tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
            }

            @Override
            protected int compare(int i, int j) {
                return Long.compare(array[i], array[j]);
            }

            @Override
            protected void setPivot(int i) {
                pivot = array[i];
            }

            @Override
            protected int comparePivot(int j) {
                return Long.compare(pivot, array[j]);
            }

        }.sort(0, len);
    }

    public static void sortAndDedup(LongArrayList list) {
        list.elementsCount = sortAndDedup(list.buffer, list.elementsCount);
    }

    /** Sort and deduplicate values in-place, then return the unique element count. */
    public static int sortAndDedup(long[] array, int len) {
        if (len <= 1) {
            return len;
        }
        sort(array, len);
        int uniqueCount = 1;
        for (int i = 1; i < len; ++i) {
            if (array[i] != array[i - 1]) {
                array[uniqueCount++] = array[i];
            }
        }
        return uniqueCount;
    }

    public static void sort(FloatArrayList list) {
        sort(list.buffer, list.size());
    }

    public static void sort(final float[] array, int len) {
        new IntroSorter() {

            float pivot;

            @Override
            protected void swap(int i, int j) {
                final float tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
            }

            @Override
            protected int compare(int i, int j) {
                return Float.compare(array[i], array[j]);
            }

            @Override
            protected void setPivot(int i) {
                pivot = array[i];
            }

            @Override
            protected int comparePivot(int j) {
                return Float.compare(pivot, array[j]);
            }

        }.sort(0, len);
    }

    public static void sortAndDedup(FloatArrayList list) {
        list.elementsCount = sortAndDedup(list.buffer, list.elementsCount);
    }

    /** Sort and deduplicate values in-place, then return the unique element count. */
    public static int sortAndDedup(float[] array, int len) {
        if (len <= 1) {
            return len;
        }
        sort(array, len);
        int uniqueCount = 1;
        for (int i = 1; i < len; ++i) {
            if (Float.compare(array[i], array[i - 1]) != 0) {
                array[uniqueCount++] = array[i];
            }
        }
        return uniqueCount;
    }

    public static void sort(DoubleArrayList list) {
        sort(list.buffer, list.size());
    }

    public static void sort(final double[] array, int len) {
        new IntroSorter() {

            double pivot;

            @Override
            protected void swap(int i, int j) {
                final double tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
            }

            @Override
            protected int compare(int i, int j) {
                return Double.compare(array[i], array[j]);
            }

            @Override
            protected void setPivot(int i) {
                pivot = array[i];
            }

            @Override
            protected int comparePivot(int j) {
                return Double.compare(pivot, array[j]);
            }

        }.sort(0, len);
    }

    public static void sortAndDedup(DoubleArrayList list) {
        list.elementsCount = sortAndDedup(list.buffer, list.elementsCount);
    }

    /** Sort and deduplicate values in-place, then return the unique element count. */
    public static int sortAndDedup(double[] array, int len) {
        if (len <= 1) {
            return len;
        }
        sort(array, len);
        int uniqueCount = 1;
        for (int i = 1; i < len; ++i) {
            if (Double.compare(array[i], array[i - 1]) != 0) {
                array[uniqueCount++] = array[i];
            }
        }
        return uniqueCount;
    }

    /**
     * Checks if the given array contains any elements.
     *
     * @param array The array to check
     *
     * @return false if the array contains an element, true if not or the array is null.
     */
    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;
    }

    /**
     * Return a rotated view of the given list with the given distance.
     */
    public static <T> List<T> rotate(final List<T> list, int distance) {
        if (list.isEmpty()) {
            return list;
        }

        int d = distance % list.size();
        if (d < 0) {
            d += list.size();
        }

        if (d == 0) {
            return list;
        }

        return new RotatedList<>(list, d);
    }

    public static void sortAndDedup(final ObjectArrayList<byte[]> array) {
        int len = array.size();
        if (len > 1) {
            sort(array);
            int uniqueCount = 1;
            for (int i = 1; i < len; ++i) {
                if (!Arrays.equals(array.get(i), array.get(i - 1))) {
                    array.set(uniqueCount++, array.get(i));
                }
            }
            array.elementsCount = uniqueCount;
        }
    }

    public static void sort(final ObjectArrayList<byte[]> array) {
        new IntroSorter() {

            byte[] pivot;

            @Override
            protected void swap(int i, int j) {
                final byte[] tmp = array.get(i);
                array.set(i, array.get(j));
                array.set(j, tmp);
            }

            @Override
            protected int compare(int i, int j) {
                return compare(array.get(i), array.get(j));
            }

            @Override
            protected void setPivot(int i) {
                pivot = array.get(i);
            }

            @Override
            protected int comparePivot(int j) {
                return compare(pivot, array.get(j));
            }

            private int compare(byte[] left, byte[] right) {
                for (int i = 0, j = 0; i < left.length && j < right.length; i++, j++) {
                    int a = left[i] & 0xFF;
                    int b = right[j] & 0xFF;
                    if (a != b) {
                        return a - b;
                    }
                }
                return left.length - right.length;
            }

        }.sort(0, array.size());
    }

    public static int[] toArray(Collection<Integer> ints) {
        Objects.requireNonNull(ints);
        return ints.stream().mapToInt(s -> s).toArray();
    }

    private static class RotatedList<T> extends AbstractList<T> implements RandomAccess {

        private final List<T> in;
        private final int distance;

        public RotatedList(List<T> list, int distance) {
            if (distance < 0 || distance >= list.size()) {
                throw new IllegalArgumentException();
            }
            if (!(list instanceof RandomAccess)) {
                throw new IllegalArgumentException();
            }
            this.in = list;
            this.distance = distance;
        }

        @Override
        public T get(int index) {
            int idx = distance + index;
            if (idx < 0 || idx >= in.size()) {
                idx -= in.size();
            }
            return in.get(idx);
        }

        @Override
        public int size() {
            return in.size();
        }

    };
    public static void sort(final BytesRefArray bytes, final int[] indices) {
        sort(new BytesRefBuilder(), new BytesRefBuilder(), bytes, indices);
    }

    private static void sort(final BytesRefBuilder scratch, final BytesRefBuilder scratch1, final BytesRefArray bytes, final int[] indices) {

        final int numValues = bytes.size();
        assert indices.length >= numValues;
        if (numValues > 1) {
            new InPlaceMergeSorter() {
                final Comparator<BytesRef> comparator = BytesRef.getUTF8SortedAsUnicodeComparator();
                @Override
                protected int compare(int i, int j) {
                    return comparator.compare(bytes.get(scratch, indices[i]), bytes.get(scratch1, indices[j]));
                }

                @Override
                protected void swap(int i, int j) {
                    int value_i = indices[i];
                    indices[i] = indices[j];
                    indices[j] = value_i;
                }
            }.sort(0, numValues);
        }

    }

    public static int sortAndDedup(final BytesRefArray bytes, final int[] indices) {
        final BytesRefBuilder scratch = new BytesRefBuilder();
        final BytesRefBuilder scratch1 = new BytesRefBuilder();
        final int numValues = bytes.size();
        assert indices.length >= numValues;
        if (numValues <= 1) {
            return numValues;
        }
        sort(scratch, scratch1, bytes, indices);
        int uniqueCount = 1;
        BytesRefBuilder previous = scratch;
        BytesRefBuilder current = scratch1;
        bytes.get(previous, indices[0]);
        for (int i = 1; i < numValues; ++i) {
            bytes.get(current, indices[i]);
            if (!previous.get().equals(current.get())) {
                indices[uniqueCount++] = indices[i];
            }
            BytesRefBuilder tmp = previous;
            previous = current;
            current = tmp;
        }
        return uniqueCount;

    }

    public static <E> ArrayList<E> iterableAsArrayList(Iterable<? extends E> elements) {
        if (elements == null) {
            throw new NullPointerException("elements");
        }
        if (elements instanceof Collection) {
            return new ArrayList<>((Collection)elements);
        } else {
            ArrayList<E> list = new ArrayList<>();
            for (E element : elements) {
                list.add(element);
            }
            return list;
        }
    }

    public static <E> ArrayList<E> arrayAsArrayList(E... elements) {
        if (elements == null) {
            throw new NullPointerException("elements");
        }
        return new ArrayList<>(Arrays.asList(elements));
    }

    public static <E> ArrayList<E> asArrayList(E first, E... other) {
        if (other == null) {
            throw new NullPointerException("other");
        }
        ArrayList<E> list = new ArrayList<>(1 + other.length);
        list.add(first);
        list.addAll(Arrays.asList(other));
        return list;
    }

    public static<E> ArrayList<E> asArrayList(E first, E second, E... other) {
        if (other == null) {
            throw new NullPointerException("other");
        }
        ArrayList<E> list = new ArrayList<>(1 + 1 + other.length);
        list.add(first);
        list.add(second);
        list.addAll(Arrays.asList(other));
        return list;
    }

    public static <E> ArrayList<E> newSingletonArrayList(E element) {
        return new ArrayList<>(Collections.singletonList(element));
    }

    public static <E> LinkedList<E> newLinkedList(Iterable<E> elements) {
        if (elements == null) {
            throw new NullPointerException("elements");
        }
        LinkedList<E> linkedList = new LinkedList<>();
        for (E element : elements) {
            linkedList.add(element);
        }
        return linkedList;
    }

    public static <E> List<List<E>> eagerPartition(List<E> list, int size) {
        if (list == null) {
            throw new NullPointerException("list");
        }
        if (size <= 0) {
            throw new IllegalArgumentException("size <= 0");
        }
        List<List<E>> result = new ArrayList<>((int) Math.ceil(list.size() / size));

        List<E> accumulator = new ArrayList<>(size);
        int count = 0;
        for (E element : list) {
            if (count == size) {
                result.add(accumulator);
                accumulator = new ArrayList<>(size);
                count = 0;
            }
            accumulator.add(element);
            count++;
        }
        if (count > 0) {
            result.add(accumulator);
        }

        return result;
    }

}


text:
// **********************************************************************
//
// <copyright>
//
//  BBN Technologies
//  10 Moulton Street
//  Cambridge, MA 02138
//  (617) 873-8000
//
//  Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/layer/vpf/VPFLayer.java,v $
// $RCSfile: VPFLayer.java,v $
// $Revision: 1.21 $
// $Date: 2006/03/06 16:13:59 $
// $Author: dietrick $
//
// **********************************************************************

package com.bbn.openmap.layer.vpf;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.beancontext.BeanContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

import com.bbn.openmap.event.ProjectionListener;
import com.bbn.openmap.gui.WindowSupport;
import com.bbn.openmap.layer.OMGraphicHandlerLayer;
import com.bbn.openmap.omGraphics.DrawingAttributes;
import com.bbn.openmap.omGraphics.OMGraphic;
import com.bbn.openmap.omGraphics.OMGraphicConstants;
import com.bbn.openmap.omGraphics.OMGraphicList;
import com.bbn.openmap.proj.GeoProj;
import com.bbn.openmap.proj.Projection;
import com.bbn.openmap.proj.coords.LatLonPoint;
import com.bbn.openmap.util.PaletteHelper;
import com.bbn.openmap.util.PropUtils;

/**
 * Implement an OpenMap Layer for display of NIMA data sources in the VPF
 * (Mil-Std 2407) format.
 *

 * The properties needed to configure this layer to display VPF data include
 * some "magic" strings specific to the VPF database you are trying to display.
 * {@link com.bbn.openmap.layer.vpf.DescribeDB DescribeDB}is a utility to help
 * you figure out what those strings are.
 *
 *

 *
 *
 *
 *     #-----------------------------
 *     # Properties for a VMAP political layer
 *     #-----------------------------
 *     # Mandatory properties
 *     # Mandatory for all layers
 *     vmapPol.class= com.bbn.openmap.layer.vpf.VPFLayer
 *     vmapPol.prettyName= Political Boundaries from VMAP
 *     # Mandatory - choose .vpfPath or .libraryBean
 *     # .vpfPath specifies a ';' separated list of paths to data, each of these
 *     #directories should have a "lat" or "lat." file in them.
 *     vmapPol.vpfPath= e:/VMAPLV0
 *     # .libraryBean specifies a separate object in the properties file that
 *     # locates vpf data.  You should use this option if you have multiple VPF
 *     # layers displaying the same VPF database.  (For example, you have 3 VMAP
 *     # layers, displaying coastlines, railroads and rivers.  Each layer would
 *     # then specify the same libraryBean name.  This reduces the memory
 *     # consumption of the VPF layers.)
 *     # See {@link com.bbn.openmap.layer.vpf.LibraryBean LibraryBean javadoc} for properties info. (Example below)
 *     vmapPol.libraryBean= VMAPdata
 *     VMAPData.class=com.bbn.openmap.layer.vpf.LibraryBean
 *     VMAPData.vpfPath=e:/VMAPLV0
 *     # Don't forget to add VMAPData to the openmap.components property list, too.
 *     #
 *     #Optional (default is true) changes how features are located.  Should
 *     #use this option for multiple coverage types, or when null pointer errors
 *     #are encountered.
 *     vmapPol.searchByFeature=true
 *
 *     #Limit which VPF library is used (optional).  If not specified,
 *     #all available libraries will be checked and used.
 *     vmapPol.libraryName=noamer
 *     #
 *     # Choose either .defaultLayer or .coverageType
 *     #
 *     # .defaultLayer results in the layer looking up the remainder of the
 *     # properties in the defaultVPFLayers.properties files.
 *     vmapPol.defaultLayer= vmapPolitical
 *     #
 *     # .coverageType continues in this property file - chose the VMAP bnd
 *     # (Boundary) coverage
 *     vmapPol.coverageType= bnd
 *     # Select if we want edges (polylines), areas (filled polygons) or text
 *     # This is a space-separated list of "edge" "area" "text" "epoint" and "cpoint"
 *     vmapPol.featureTypes= edge area
 *     #For DCW, the remaining 3 properties are ignored
 *     #Select the text featureclasses we'd like to display.  Since we didn't
 *     #select text above, this is ignored
 *     vmapPol.text=
 *     #Select the edge featureclasses we'd like to display. In this case,
 *     #draw political boundaries and coastline, but skip anything else.
 *     vmapPol.edge=polbndl coastl
 *     #Select the area featureclasses we'd like to display. In this case,
 *     #draw politcal areas, but skip anything else.
 *     vmapPol.area=polbnda
 *     #Selectable drawing attributes - for default values, they don't need to
 *     #be included.  A hex ARGB color looks like FF000000 for black.
 *     vmapPol.lineColor=hex ARGB color value - Black is default.
 *     vmapPol.fillColor=hex ARGB color value - Clear is default.
 *     vmapPol.lineWidth=float value, 1f is the default, 10f is the max.
 *
 *     # The column name in the feature table that should be displayed.  The easiest
 *     # way to find out what these columns should be for an application is to run the
 *     # application with the other properties set for the layer, and then bring up
 *     # the layer's palette.  When the feature is selected, there are additional
 *     # controls that let you display the coverage column names and display type,
 *     # and the coverage column names in the popup are the ones that can be used
 *     # in the properties (the column names are in parenthesis).  NOTE:   The features
 *     # have to be added to the map and visible (proper scale setting < 30,000,000)
 *     # in order for the palette controls to be visible.
 *     vmapPol.attribute=na2
 *     # How the attributes should be displayed, either 'label', 'tooltip', or 'information line'
 *     vmapPol.attributeDisplay=label
 *
 *     #------------------------------------
 *     # End of properties for a VMAP political layer
 *     #------------------------------------
 *
 *     ### Now a VMAP Coastline layer
 *     vmapCoast.class=com.bbn.openmap.layer.vpf.VPFLayer
 *     vmapCoast.prettyName=VMAP Coastline Layer
 *     vmapCoast.vpfPath=/u5/vmap/vmaplv0
 *     ## a predefined layer from the VPF predefined layer set found in
 *     ## com/bbn/openmap/layer/vpf/defaultVPFLayers.properties
 *     vmapCoast.defaultLayer=vmapCoastline
 *
 *     ### Now a DCW Political layer
 *     # Basic political boundaries with DCW
 *     dcwPolitical.class=com.bbn.openmap.layer.vpf.VPFLayer
 *     dcwPolitical.prettyName=DCW Political Boundaries
 *     dcwPolitical.vpfPath=path to data
 *     dcwPolitical.coverageType=po
 *     dcwPolitical.featureTypes=edge area
 *
 *
 *
 *

 */

public class VPFLayer
      extends OMGraphicHandlerLayer
      implements ProjectionListener, ActionListener, Serializable {

   private static final long serialVersionUID = 1L;

   public static Logger logger = Logger.getLogger("com.bbn.openmap.layer.vpf.VPFLayer");

   /** property extension used to set the VPF root directory */
   public static final String pathProperty = "vpfPath";
   /**
    * property extension used to set the desired coverage type. Examples of
    * coverage types include "po" for DCW and "hyd" for VMAP Level 0.
    */
   public static final String coverageTypeProperty = "coverageType";
   /**
    * Property extension used to set the desired feature types. e.g. line area
    * text
    */
   public static final String featureTypesProperty = "featureTypes";
   /** property extension used to specify a default property set */
   public static final String defaultLayerProperty = "defaultLayer";
   /**
    * Property that lets you search for graphics via feature type. Dangerously
    * slow for features that have many graphics spread out over several tiles.
    * Set to true to search by feature, false (default) to get the tiles first,
    * and then look for graphics.
    */
   public static final String searchByFeatureProperty = "searchByFeature";
   /** Property method for setting VPF data path */
   public static final String libraryProperty = "libraryBean";
   /** Property for setting VPF cutoff scale */
   public static final String cutoffScaleProperty = "cutoffScale";
   /** Property for setting VPF library name to use */
   public static final String LibraryNameProperty = "libraryName";
   /** the object that knows all the nitty-gritty vpf stuff */
   protected transient LibrarySelectionTable lst;
   /** our own little graphics factory */
   protected transient LayerGraphicWarehouseSupport warehouse;
   /** are we searching by feature table (true) or tile (false) */
   protected boolean searchByFeatures = false;
   /** the name of the data bean to look for in beancontext */
   protected String libraryBeanName = null;

   /**
    * hang onto prefix used to initialize warehouse in setProperties()
    */
   protected String prefix;
   /** hang onto properties file used to initialize warehouse */
   protected Properties props;

   /** the path to the root VPF directory */
   protected String[] dataPaths = null;
   /** the coverage type that we display */
   protected String coverageType = "po";

   protected int cutoffScale = LibrarySelectionTable.DEFAULT_BROWSE_CUTOFF;
   /** the library name to focus on */
   protected String libraryName = null;

   /**
    * Construct a VPF layer.
    */
   public VPFLayer() {
      setProjectionChangePolicy(new com.bbn.openmap.layer.policy.ListResetPCPolicy(this));
      setRenderPolicy(new com.bbn.openmap.layer.policy.BufferedImageRenderPolicy(this));
      setMouseModeIDsForEvents(new String[] {
         "Gestures"
      });
   }

   /**
    * Construct a VPFLayer, and sets its name.
    *
    * @param name the name of the layer.
    */
   public VPFLayer(String name) {
      this();
      setName(name);
   }

   /**
    * Sets the features (lines, areas, text, points) that get displayed.
    *
    * @param features a whitespace-separated list of features to display.
    */
   public void setFeatures(String features) {
      warehouse.setFeatures(features);
   }

   /**
    * Another way to set the parameters of the DcwLayer.
    *
    * @see #pathProperty
    * @see #coverageTypeProperty
    * @see #featureTypesProperty
    */
   public void setProperties(String prefix, Properties props) {
      super.setProperties(prefix, props);
      setAddToBeanContext(true);

      String realPrefix = PropUtils.getScopedPropertyPrefix(prefix);

      cutoffScale = PropUtils.intFromProperties(props, realPrefix + cutoffScaleProperty, cutoffScale);

      libraryBeanName = props.getProperty(realPrefix + libraryProperty, libraryBeanName);

      libraryName = props.getProperty(realPrefix + LibraryNameProperty, libraryName);

      String path[] = PropUtils.initPathsFromProperties(props, realPrefix + pathProperty);

      if (path != null && path.length != 0) {
         setPath(path);
      }
      String defaultProperty = props.getProperty(realPrefix + defaultLayerProperty);

      if (defaultProperty != null) {
         prefix = defaultProperty;
         props = VPFUtil.getDefaultProperties();
      }

      // need to save these so we can call setProperties on the
      // warehouse,
      // which we probably can't construct yet
      this.prefix = prefix;
      this.props = props;

      String coverage = props.getProperty(realPrefix + coverageTypeProperty);
      if (coverage != null) {
         setDataTypes(coverage);
      }

      searchByFeatures = PropUtils.booleanFromProperties(props, realPrefix + searchByFeatureProperty, searchByFeatures);

      checkWarehouse(searchByFeatures);
      if (warehouse != null) {
         warehouse.setProperties(prefix, props);
         warehouse.setUseLibraries(PropUtils.parseSpacedMarkers(libraryName));

         box = null;
         resetPalette();
      }

      try {
         // force lst and warehosue to re-init with current
         // properties

         // LST now set when paths are set.
      } catch (IllegalArgumentException iae) {
         logger.warning("Illegal Argument Exception.\n\nPerhaps a file not found.  Check to make sure that the paths to the VPF data directories are the parents of \"lat\" or \"lat.\" files. \n\n"
               + iae);
      }
   }

   public Properties getProperties(Properties props) {
      props = super.getProperties(props);

      String realPrefix = PropUtils.getScopedPropertyPrefix(this);

      props.put(realPrefix + cutoffScaleProperty, Integer.toString(cutoffScale));

      if (libraryBeanName != null) {
         props.put(realPrefix + libraryProperty, libraryBeanName);
      } else {
         StringBuffer paths = new StringBuffer();
         String[] ps = getPath();

         for (int i = 0; ps != null && i < ps.length; i++) {
            paths.append(ps[i]);
            if (i < ps.length - 1)
               paths.append(";");
         }

         props.put(realPrefix + pathProperty, paths.toString());
      }

      // For the library in a vpf package
      props.put(realPrefix + LibraryNameProperty, PropUtils.unnull(libraryName));

      props.put(realPrefix + coverageTypeProperty, getDataTypes());
      props.put(realPrefix + searchByFeatureProperty, Boolean.toString(searchByFeatures));

      if (warehouse != null) {
         warehouse.getProperties(props);
      }

      return props;
   }

   /** Where we store our default properties once we've loaded them. */
   private Properties defaultProps;

   /**
    * Set the data path to a single place.
    */
   public void setPath(String newPath) {
      logger.fine("setting paths to " + newPath);
      setPath(new String[] {
         newPath
      });
   }

   /**
    * Set the data path to multiple places.
    */
   public void setPath(String[] newPaths) {
      dataPaths = newPaths;

      lst = null;
      initLST();
   }

   /**
    * Returns the list of paths we use to look for data.
    *
    * @return the list of paths. Don't modify the array!
    */
   public String[] getPath() {
      return dataPaths;
   }

   /**
    * Set the coveragetype of the layer.
    *
    * @param dataTypes the coveragetype to display.
    */
   public void setDataTypes(String dataTypes) {
      coverageType = dataTypes;
   }

   /**
    * Get the current coverage type.
    *
    * @return the current coverage type.
    */
   public String getDataTypes() {
      return coverageType;
   }

   /**
    * Enable/Disable the display of areas.
    */
   public void setAreasEnabled(boolean value) {
      warehouse.setAreaFeatures(value);
   }

   /**
    * Find out if areas are enabled.
    */
   public boolean getAreasEnabled() {
      return warehouse.drawAreaFeatures();
   }

   /**
    * Enable/Disable the display of edges.
    */
   public void setEdgesEnabled(boolean value) {
      warehouse.setEdgeFeatures(value);
   }

   /**
    * Find out if edges are enabled.
    */
   public boolean getEdgesEnabled() {
      return warehouse.drawEdgeFeatures();
   }

   /**
    * Enable/Disable the display of entity points.
    */
   public void setEPointsEnabled(boolean value) {
      warehouse.setEPointFeatures(value);
   }

   /**
    * Find out if entity points are enabled.
    */
   public boolean getEPointsEnabled() {
      return warehouse.drawEPointFeatures();
   }

   /**
    * Enable/Disable the display of connected points.
    */
   public void setCPointsEnabled(boolean value) {
      warehouse.setCPointFeatures(value);
   }

   /**
    * Find out if connected points are enabled.
    */
   public boolean getCPointsEnabled() {
      return warehouse.drawCPointFeatures();
   }

   /**
    * Enable/Disable the display of text.
    */
   public void setTextEnabled(boolean value) {
      warehouse.setTextFeatures(value);
   }

   /**
    * Find out if text is enabled.
    */
   public boolean getTextEnabled() {
      return warehouse.drawTextFeatures();
   }

   /**
    * Get the DrawingAttributes used for the coverage type.
    */
   public DrawingAttributes getDrawingAttributes() {
      return warehouse.getDrawingAttributes();
   }

   /**
    * Set the drawing attributes for the coverage type.
    */
   public void setDrawingAttributes(DrawingAttributes da) {
      warehouse.setDrawingAttributes(da);
   }

   /**
    * initialize the library selection table.
    */
   protected void initLST() {
      logger.fine("initializing Library Selection Table (LST)");

      try {
         if (lst == null) {
            if (libraryBeanName != null) {
               LibraryBean libraryBean = null;
               BeanContext beanContext = getBeanContext();
               if (beanContext == null) {
                  // no bean context yet
                  return;
               }
               for (Object obj : beanContext) {
                  if (obj instanceof LibraryBean) {
                     LibraryBean lb = (LibraryBean) obj;
                     if (libraryBeanName.equals(lb.getName())) {
                        if (logger.isLoggable(Level.FINE)) {
                           logger.fine(getName() + ": setting library bean to " + lb.getName());
                        }
                        libraryBean = lb;
                        break;
                     }
                  }
               }
               if (libraryBean != null) {
                  lst = libraryBean.getLibrarySelectionTable();
                  warehouse = libraryBean.getWarehouse();
                  // Set the warehouse with the properties
                  // received when the layer was created.
                  warehouse.setProperties(getPropertyPrefix(), props);
                  searchByFeatures = true; // because it is.
                  box = null;// force GUI to rebuild

                  logger.fine("VPFLayer.initLST(libraryBean)");
               } else {
                  if (logger.isLoggable(Level.FINE)) {
                     // Encasing it in a debug statement,
                     // because we could get here by adding the
                     // LayerHandler to the MapHandler before
                     // the LibraryBean.
                     logger.fine("Couldn't find libraryBean " + libraryBeanName + " to read VPF data");
                  }
               }
            } else {
               if (dataPaths == null) {
                  logger.info("VPFLayer|" + getName() + ": path not set");
               } else {
                  logger.fine("VPFLayer.initLST(dataPaths)");
                  lst = new LibrarySelectionTable(dataPaths);
                  lst.setCutoffScale(cutoffScale);
               }
            }
         }
      } catch (com.bbn.openmap.io.FormatException f) {
         throw new java.lang.IllegalArgumentException(f.getMessage());
         // } catch (NullPointerException npe) {
         // throw new
         // java.lang.IllegalArgumentException("VPFLayer|" +
         // getName() +
         // ": path name not valid");
      }
   }

   public void setWarehouse(LayerGraphicWarehouseSupport wh) {
      warehouse = wh;
   }

   public LayerGraphicWarehouseSupport getWarehouse() {
      return warehouse;
   }

   /**
    * If the warehouse gets set as a result of this method being called, the
    * properties will beed to be reset on it.
    *
    * @param sbf Search by features.
    */
   public void checkWarehouse(boolean sbf) {
      if (warehouse == null) {
         logger.fine("need to create warehouse");
         if (lst != null && lst.getDatabaseName() != null && lst.getDatabaseName().equals("DCW")) {
            warehouse = new VPFLayerDCWWarehouse();
         } else if (sbf) {
            warehouse = new VPFFeatureGraphicWarehouse();
         } else {
            warehouse = new VPFLayerGraphicWarehouse();
         }
      } else if ((sbf && !(warehouse instanceof VPFFeatureGraphicWarehouse))
            || (!sbf && warehouse instanceof VPFFeatureGraphicWarehouse)) {
         warehouse = null;
         checkWarehouse(sbf);
      }
   }

   /**
    * Use doPrepare() method instead. This was the old method call to do the
    * same thing doPrepare is now doing, from the OMGraphicHandler superclass.
    * doPrepare() launches a thread to do the work.
    *
    * @deprecated use doPrepare() instead of computeLayer();
    */
   public void computeLayer() {
      doPrepare();
   }

   /**
    * Use prepare instead. This was the old method call to do the same thing
    * prepare() is now doing.
    *
    * @deprecated use prepare() instead of getRectangle();
    */
   public OMGraphicList getRectangle() {
      return prepare();
   }

   /**
    * Create the OMGraphicList to use on the map. OMGraphicHandler methods call
    * this.
    */
   public synchronized OMGraphicList prepare() {
      if (lst == null) {
         try {
            initLST();
         } catch (IllegalArgumentException iae) {
            logger.warning("VPFLayer.prepare: Illegal Argument Exception.\n\nPerhaps a file not found.  Check to make sure that the paths to the VPF data directories are the parents of \"lat\" or \"lat.\" files. \n\n"
                  + iae);
            return null;
         }

         if (lst == null) {
            if (logger.isLoggable(Level.FINE)) {
               logger.fine("VPFLayer| " + getName() + " prepare(), Library Selection Table not set.");
            }

            return null;
         }
      }

      if (warehouse == null) {
         StringBuffer dpb = new StringBuffer();
         if (dataPaths != null) {
            for (int num = 0; num < dataPaths.length; num++) {
               if (num > 0) {
                  dpb.append(":");
               }
               dpb.append(dataPaths[num]);
            }
         }

         logger.warning("VPFLayer.getRectangle:  Data path probably wasn't set correctly (" + dpb.toString()
               + ").  The warehouse not initialized.");
         return null;
      }

      Projection p = getProjection();

      if (p == null || !(p instanceof GeoProj)) {
         if (logger.isLoggable(Level.FINE)) {
            logger.fine("VPFLayer.getRectangle() called with a projection (" + p + ") set in the layer, which isn't being handled.");
         }
         return new OMGraphicList();
      }

      LatLonPoint upperleft = (LatLonPoint) p.getUpperLeft();
      LatLonPoint lowerright = (LatLonPoint) p.getLowerRight();
      if (logger.isLoggable(Level.FINER)) {
         logger.finer("VPFLayer.getRectangle: " + coverageType /*
                                                                * + " " +
                                                                * dynamicArgs
                                                                */);
      }

      warehouse.clear();

      // int edgecount[] = new int[] { 0 , 0 };
      // int textcount[] = new int[] { 0 , 0 };
      // int areacount[] = new int[] { 0 , 0 };

      // Check both dynamic args and palette values when
      // deciding what to draw.
      if (logger.isLoggable(Level.FINE)) {
         logger.fine("calling draw with boundaries: " + upperleft + " " + lowerright);
      }
      long start = System.currentTimeMillis();

      StringTokenizer t = new StringTokenizer(coverageType);
      while (t.hasMoreTokens()) {
         String currentCoverage = t.nextToken();
         if (searchByFeatures) {
            lst.drawFeatures((int) p.getScale(), p.getWidth(), p.getHeight(), currentCoverage, (VPFFeatureWarehouse) warehouse,
                             upperleft, lowerright);
         } else {
            lst.drawTile((int) p.getScale(), p.getWidth(), p.getHeight(), currentCoverage, warehouse, upperleft, lowerright);
         }
      }
      long stop = System.currentTimeMillis();

      // if (Debug.debugging("vpfdetail")) {
      // Debug.output("Returned " + edgecount[0] +
      // " polys with " + edgecount[1] + " points\n" +
      // "Returned " + textcount[0] +
      // " texts with " + textcount[1] + " points\n" +
      // "Returned " + areacount[0] +
      // " areas with " + areacount[1] + " points");
      // }

      if (logger.isLoggable(Level.FINE)) {
         logger.fine("read time: " + ((stop - start) / 1000d) + " seconds");
      }

      OMGraphicList omglist = warehouse.getGraphics();

      // Don't forget to project.
      start = System.currentTimeMillis();
      omglist.project(p);
      stop = System.currentTimeMillis();

      if (logger.isLoggable(Level.FINE)) {
         logger.fine("proj time: " + ((stop - start) / 1000d) + " seconds");
      }
      return omglist;
   }

   private transient JPanel box;

   /**
    * Gets the palette associated with the layer.
    *
    * @return Component or null
    */
   public Component getGUI() {

      if (lst == null) {
         try {
            initLST();
         } catch (IllegalArgumentException iie) {
            logger.warning(iie.getMessage());
         }
      }

      if (warehouse == null) {
         return (new javax.swing.JLabel("VPF Layer data not loaded properly."));
      }

      if (box == null) {

         box = new JPanel();
         box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
         box.setAlignmentX(Component.LEFT_ALIGNMENT);

         JPanel stuff = new JPanel();

         JPanel pal = null;
         ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               int index = Integer.parseInt(e.getActionCommand(), 10);
               switch (index) {
                  case 0:
                     warehouse.setEdgeFeatures(!warehouse.drawEdgeFeatures());
                     break;
                  case 1:
                     warehouse.setTextFeatures(!warehouse.drawTextFeatures());
                     break;
                  case 2:
                     warehouse.setAreaFeatures(!warehouse.drawAreaFeatures());
                     break;
                  case 3:
                     warehouse.setEPointFeatures(!warehouse.drawEPointFeatures());
                     break;
                  case 4:
                     warehouse.setCPointFeatures(!warehouse.drawCPointFeatures());
                     break;
                  default:
                     throw new RuntimeException("argh!");
               }
            }
         };

         pal = PaletteHelper.createCheckbox("Show:", new String[] {
            VPFUtil.Edges,
            VPFUtil.Text,
            VPFUtil.Area,
            VPFUtil.EPoint,
            VPFUtil.CPoint
         }, new boolean[] {
            warehouse.drawEdgeFeatures(),
            warehouse.drawTextFeatures(),
            warehouse.drawAreaFeatures(),
            warehouse.drawEPointFeatures(),
            warehouse.drawCPointFeatures()
         }, al);

         stuff.add(pal);

         if (lst != null) {
            Component warehouseGUI = warehouse.getGUI(lst);
            if (warehouseGUI != null) {
               stuff.add(warehouseGUI);
            }
         }
         box.add(stuff);

         JPanel pal2 = new JPanel();
         JButton config = new JButton("Configure Layer");
         config.setActionCommand(ConfigCmd);
         config.addActionListener(this);
         pal2.add(config);

         JButton redraw = new JButton("Redraw Layer");
         redraw.setActionCommand(RedrawCmd);
         redraw.addActionListener(this);
         pal2.add(redraw);
         box.add(pal2);
      }
      return box;
   }

   public final static String ConfigCmd = "CONFIGURE";
   protected WindowSupport configWindowSupport = null;

   public void actionPerformed(ActionEvent e) {
      String cmd = e.getActionCommand();
      if (cmd == RedrawCmd) {
         setList(null);
         if (isVisible()) {
            doPrepare();
         }
      } else if (cmd == ConfigCmd) {
         if (configWindowSupport == null) {
            configWindowSupport = new WindowSupport(new VPFConfig(this), "Configure " + getName() + " Features");
         } else {
            configWindowSupport.setTitle(getName());
         }
         configWindowSupport.displayInWindow();
      } else {
         super.actionPerformed(e);
      }
   }

   protected void setConfigSettings(String prefix, Properties props) {
      lst = null;
      setProperties(prefix, props);
      if (isVisible()) {
         doPrepare();
      }

      if (configWindowSupport != null) {
         configWindowSupport.setTitle(getName());
         configWindowSupport.killWindow();
      }
   }

   public String getToolTipTextFor(OMGraphic omg) {
      return (String) omg.getAttribute(OMGraphicConstants.TOOLTIP);
   }

   public String getInfoText(OMGraphic omg) {
      return (String) omg.getAttribute(OMGraphicConstants.INFOLINE);
   }
}


text:
package viewmodels

import (
	"github.com/peterhoward42/frost/server/urls"
)

// The TopLevelViewModel is the model for the top level application view (in the MVC sense).
// It is recommended that instances are created using the constructor functions.
type TopLevelViewModel struct {
	// One of these pointers being set to non-null signifies the viewing mode required as
	// well as addressing the sub model for that mode.
	QuickStart *QuickStartViewModel
	Playground *PlaygroundViewModel
	ComingSoon *ComingSoonViewModel // not really a model, but keeps things symmetrical

	QuickStartURL string
	PlaygroundURL string
}

func NewTopLevelViewModel() *TopLevelViewModel {
	return &TopLevelViewModel{
		QuickStartURL: urls.URLQuickstart,
		PlaygroundURL: urls.URLPlaygroundExampleSpaceDelim,
		ComingSoon: nil,
	}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

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

exports.default = {
  authenticityToken: function authenticityToken() {
    var token = document.querySelector('meta[name="csrf-token"]');
    if (token && token instanceof window.HTMLMetaElement) {
      return token.content;
    }
    return null;
  },
  authenticityHeaders: function authenticityHeaders() {
    var otherHeaders = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    return (0, _assign2.default)(otherHeaders, {
      'X-CSRF-Token': this.authenticityToken(),
      'X-Requested-With': 'XMLHttpRequest'
    });
  }
};