text:
<?php

namespace Hypertd\AddressbookBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Hypertd\AddressbookBundle\Entity\Contact;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class ContactController extends Controller
{
	/**
     * @Route("/addressbook/contact")
     */
    public function indexAction()
    {
    	$repository = $this->getDoctrine()
		->getRepository('HypertdAddressbookBundle:Contact');

		$contacts = $repository->findAll();

        $response = new Response();
		$response->headers->set('Content-Type', 'xml');
		return $this->render('HypertdAddressbookBundle:Addressbook:contact.xml.php', array("contacts" => $contacts), $response);
    }

	/**
     * @Route("/addressbook/contact/create")
     */
    public function createAction(Request $request)
    {
    	$firstname = $request->request->get('firstname'); // get a $_POST parameter
    	$lastname = $request->request->get('lastname'); // get a $_POST parameter
    	$city = $request->request->get('city'); // get a $_POST parameter
    	$address1 = $request->request->get('address_1'); // get a $_POST parameter
    	$address2 = $request->request->get('address_2'); // get a $_POST parameter
    	$postal = $request->request->get('postal'); // get a $_POST parameter
    	$tel = $request->request->get('tel_home'); // get a $_POST parameter
    	$tel2 = $request->request->get('tel_mobile'); // get a $_POST parameter

        $contact = new Contact();

		//set firstname
		if(isset($firstname) && !empty($firstname)){
			$contact->setFirstname($firstname);
		}
		else{
			$contact->setFirstname("");
		}

		//set lastname
		if(isset($lastname) && !empty($lastname)){
			$contact->setLastname($lastname);
		}
		else{
			$contact->setLastname("");
		}

		//set city
		if(isset($city) && !empty($city)){
			$contact->setCity($city);
		}
		else{
			$contact->setCity("");
		}

		if(isset($address1) && !empty($address1)){
			$contact->setAddress1($address1);
		}
		else{
			$contact->setAddress1("");
		}

		if(isset($address2) && !empty($address2)){
			$contact->setAddress2($address2);
		}
		else{
			$contact->setAddress2("");
		}

		if(isset($postal) && !empty($postal)){
			$contact->setPostal($postal);
		}
		else{
			$contact->setPostal("");
		}

		if(isset($tel) && !empty($tel)){
			$contact->setTel($tel);
		}
		else{
			$contact->setTel("");
		}

		if(isset($tel2) && !empty($tel2)){
			$contact->setTel2($tel2);
		}
		else{
			$contact->setTel2("");
		}

		$em = $this->getDoctrine()->getManager();
		$em->persist($contact);
		$em->flush();

		return new Response();
    }

	/**
     * @Route("/addressbook/contact/update")
     */
    public function editAction(Request $request)
    {
    	$firstname = $request->request->get('firstname'); // get a $_POST parameter
    	$lastname = $request->request->get('lastname'); // get a $_POST parameter
    	$city = $request->request->get('city'); // get a $_POST parameter
    	$address1 = $request->request->get('address_1'); // get a $_POST parameter
    	$address2 = $request->request->get('address_2'); // get a $_POST parameter
    	$postal = $request->request->get('postal'); // get a $_POST parameter
    	$tel = $request->request->get('tel_home'); // get a $_POST parameter
    	$tel2 = $request->request->get('tel_mobile'); // get a $_POST parameter

        $em = $this->getDoctrine()->getManager();
		$contact = $em->getRepository('HypertdAddressbookBundle:Contact')->find($request->request->get('id'));

		if ($contact) {
			if(isset($firstname) && !empty($firstname)){
				$contact->setFirstname($firstname);
			}

			if(isset($lastname) && !empty($lastname)){
				$contact->setLastname($lastname);
			}
			//set city
			if(isset($city) && !empty($city)){
				$contact->setCity($city);
			}

			if(isset($address1) && !empty($address1)){
				$contact->setAddress1($address1);
			}

			if(isset($address2) && !empty($address2)){
				$contact->setAddress2($address2);
			}

			if(isset($postal) && !empty($postal)){
				$contact->setPostal($postal);
			}

			if(isset($tel) && !empty($tel)){
				$contact->setTel($tel);
			}

			if(isset($tel2) && !empty($tel2)){
				$contact->setTel2($tel2);
			}

			$em->flush();
		}

		return new Response();
    }

	/**
     * @Route("/addressbook/contact/delete")
     */
    public function deleteAction(Request $request)
    {
    	$em = $this->getDoctrine()->getManager();
    	$contact = $em->getRepository('HypertdAddressbookBundle:Contact')->find($request->request->get('id'));
		$em->remove($contact);
		$em->flush();

		return new Response();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
-->
<document>
  <properties>
    <title>Commons SCXML JS Change Log</title>
  </properties>
  <body>

    <release version="1.0" date="in SVN">
      <action dev="jbeard" type="add">
        [21-05-2010] Initial commit.
      </action>
      <action dev="rahul" type="add">
        [26-06-2010] Added Maven 2 build for site generation.
      </action>
    </release>

  </body>
</document>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Unicity\Spring\Object\Factory {

	use \Unicity\Common;
	use \Unicity\Spring;
	use \Unicity\Throwable;

	class ListElement extends Spring\Object\Factory {

		/**
		 * This method returns an object matching the description specified by the element.
		 *
		 * @access public
		 * @param Spring\Object\Parser $parser                      a reference to the parser
		 * @param \SimpleXMLElement $element                        the element to be parsed
		 * @return mixed                                            an object matching the description
		 *                                                          specified by the element
		 * @throws Throwable\Parse\Exception                        indicates that a problem occurred
		 *                                                          when parsing
		 */
		public function getObject(Spring\Object\Parser $parser, \SimpleXMLElement $element) {
			$object = new Common\Mutable\ArrayList();

			$children = $parser->getElementChildren($element, null);
			foreach ($children as $child) {
				$object->addValue($parser->getObjectFromElement($child));
			}

			return $object;
		}

	}

}


text:
<resources>
    <string name="app_name">Visualize</string>

    <!-- COMPLETED (4) Add string for Settings -->
    <string name="action_settings">Settings</string>

    <!-- - - - - - - - - - - - - - - -
          - Used by Preferences  -
          - - - - - - - - - - - - - - - -->

    <!-- Value in SharedPreferences for red color option -->
    <string name="pref_color_red_value" translatable="false">red</string>

    <!-- Value in SharedPreferences for blue color option -->
    <string name="pref_color_blue_value" translatable="false">blue</string>

    <!-- Value in SharedPreferences for green color option -->
    <string name="pref_color_green_value" translatable="false">green</string>
</resources>


text:
package ro.cs.products.util;

/**
 * Return codes.
 *
 * @author Cosmin Cara
 */
public class ReturnCode {
    public static final int OK = 0;
    public static final int EMPTY_PRODUCT = -1;
    public static final int DOWNLOAD_ERROR = -2;
    public static final int CONNECTION_ERROR = -3;
    public static final int ERROR = -4;
}


text:
require_dependency "tent/application_controller"

module Tent
  class Admin::PagesController < ApplicationController

    def index
      site_name = params[:site_name]
    end

    def edit
      raise 'tent::pages#edit'
    end
  end
end


text:
from ast import literal_eval
from collections import defaultdict
from datetime import timedelta
from logging import getLogger

from .decorators import periodic, setup_coro

from helper_bot.settings import Dungeon, Url, BotConfig

logger = getLogger(__name__)

# @setup_coro
# @periodic(30)
# async def update_sales(bot, redis):
#     async with bot.session.get(Url.SHOPS) as s:
#         sales = await s.json()
#     for item in sales['res']:
#         key = f"sale:{item.get('item_id')}:{item.get('code')}"
#         value = f"{item.get('price')},{item.get('quantity')}"
#         await redis.setex(key, 15*60, value)

# @setup_coro
# @periodic(15)
# async def send_alert(redis):
#     async for _ in redis.iscan(match='sale:*'):
#         pass

@setup_coro
@periodic(3600)
async def update_group_members(bot, redis):
    for group in BotConfig.ALLOWED_GROUPS:
        async with bot.session.get(Url.GROUP + group) as s:
            group_members = await s.json()
        try:
            members = group_members['res']
            await redis.delete(group)
            for member in members:
                await redis.sadd(group, member['nickname'])
        except KeyError:
            logger.warning('update members fallito')

@setup_coro
@periodic(30)
async def build_maps(bot, redis):
    async for key in redis.iscan(match='dungeon:*'):
        dungeon_name = key.split(':')[1]
        map_key = f'map:{dungeon_name}'
        try:
            dungeon_map = literal_eval(await redis.get(map_key))
        except ValueError:
            await redis.delete(key)
            logger.warning(f'mappa non trovata di {map_key}')
            continue
        dungeon_string = await redis.get(key)
        dungeon = []
        try:
            for line in dungeon_string.split(':')[:-1]:
                line = line.split(',')
                if line not in dungeon:
                    dungeon.append(line)
        except AttributeError:
            continue
        ordered_dungeon = defaultdict(list)
        for entry in sorted(dungeon, key=lambda x: x[1]):
            ordered_dungeon[entry[0]].append(entry[1:])
        for user, entries in ordered_dungeon.items():
            processed = []
            reply = ''
            for i, entry in enumerate(entries):
                event = entry[1]
                if event in Dungeon.ROOMS or 'mostro' in event:
                    if i >= 2 and entries[i - 1][1] in Dungeon.DIRECTIONS:
                        try:
                            number = int(entries[i - 2][1])
                            direction_emoji = entries[i - 1][1]
                            direction = Dungeon.DIRECTIONS[direction_emoji]
                            dungeon_map[number - 1][direction] = event
                            processed += [i, i-2, i-1]
                            reply += f'Hai aggiunto *{event}* alla stanza numero {number} direzione {direction_emoji}\n'
                        except ValueError:
                            continue
            if reply:
                id_ = await redis.hget(user, 'user_id')
                private_chat = bot.private(id_)
                await private_chat.send_text(reply, parse_mode='Markdown')
                new_position = number + 1
                if number < len(dungeon_map):
                    next_room = dungeon_map[number]
                    await redis.hset(user, 'position', new_position)
                    if any(next_room):
                        await private_chat.send_text(
                            Dungeon.stringify_room(new_position, *next_room, await redis.hgetall(f"custom_emojis:{user}") or Dungeon.EMOJIS),
                            parse_mode='Markdown')
            not_processed = [','.join([user] + entry) for i, entry in enumerate(entries) if i not in processed]
            dungeon_ttl = await redis.ttl(key)
            remaining = ':'.join(not_processed)
            await redis.setex(
                key,
                dungeon_ttl if dungeon_ttl > 1 else int(timedelta(days=2, hours=7).total_seconds()),
                remaining + ':' if remaining else '')
        map_ttl = await redis.ttl(map_key)
        await redis.setex(map_key, map_ttl if map_ttl > 1 else int(timedelta(days=7).total_seconds()), str(dungeon_map))


text:
package io.apiman.cli.managerapi.command.gateway;

import io.apiman.cli.command.gateway.model.Gateway;
import io.apiman.cli.command.gateway.model.GatewayTestResponse;
import retrofit.client.Response;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;

import java.util.List;

/**
 * @author Pete Cornish {@literal <outofcoffee@gmail.com>}
 */
public interface GatewayApi {
    @POST("/gateways")
    Response create(@Body Gateway gateway);

    @GET("/gateways")
    List<Gateway> list();

    @GET("/gateways/{gatewayId}")
    Gateway fetch(@Path("gatewayId") String gatewayId);

    @PUT("/gateways")
    GatewayTestResponse test(@Body Gateway gateway);
}


text:
package org.cagrid.gaards.websso.test.system.steps;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import gov.nih.nci.cagrid.testing.system.haste.Step;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.gaards.websso.test.system.WebSSOSystemTest;
import org.springframework.core.io.ClassPathResource;
import org.xml.sax.SAXException;
import sun.net.www.protocol.https.HttpsURLConnectionImpl;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpNotFoundException;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;
import com.meterware.httpunit.controls.SelectionFormControl;

public class AssertWebSSOApplicationStep extends Step {

	private String webssoClient1URL = null;
	private String webssoClient2URL = null;
	private int webssoHttpsPort;
	private int jasigHttpsPort;
	private int acegiHttpsPort;

	private final Log log = LogFactory.getLog(getClass());

	public AssertWebSSOApplicationStep(String webssoClient1URL,
			String webssoClient2URL,int webssoHttpsPort,int jasigHttpsPort,int acegiHttpsPort) {
		this.webssoClient1URL = webssoClient1URL;
		this.webssoClient2URL = webssoClient2URL;
		this.jasigHttpsPort=jasigHttpsPort;
		this.acegiHttpsPort=acegiHttpsPort;
		this.webssoHttpsPort=webssoHttpsPort;

		log.info("WebSSOClient1URL  " + webssoClient1URL + "WebSSOClient2URL  "
				+ webssoClient2URL);
		HostnameVerifier hostnameVerifier = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		HttpsURLConnectionImpl.setDefaultHostnameVerifier(hostnameVerifier);
	}

	@Override
	public void runStep() throws Throwable {
		String passPhrase="changeit";
		ClassPathResource resource=new ClassPathResource("cacerts.cert");

		File certsFile=createCertsFile(resource,passPhrase);
		InstallCertStep jasigCertStep=new InstallCertStep(certsFile,"localhost",jasigHttpsPort,2);
		jasigCertStep.runStep();
		InstallCertStep acegiCertStep=new InstallCertStep(certsFile,"localhost",acegiHttpsPort,3);
		acegiCertStep.runStep();
		InstallCertStep webssoCertStep=new InstallCertStep(certsFile,"localhost",webssoHttpsPort,4);
		webssoCertStep.runStep();
		log.info("OutputCerts file "+certsFile.getAbsolutePath());
		System.setProperty("javax.net.ssl.trustStore", certsFile.getAbsolutePath());
		System.setProperty("javax.net.ssl.trustStorePassword", passPhrase);
		multipleApplicationsLoginAndLogout();
	}

	private File createCertsFile(ClassPathResource resource,String passPhrase) throws Exception{
		String certsFile = "cacerts-httpunit.cert";
		InputStream in = new FileInputStream(resource.getFile());
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		ks.load(in, passPhrase.toCharArray());
		in.close();

		File outputFile = new File("resources",certsFile);
		OutputStream out = new FileOutputStream(outputFile);
		ks.store(out, passPhrase.toCharArray());
		out.close();
		return outputFile;
	}

	private void multipleApplicationsLoginAndLogout() throws Exception {
		// login 1
		WebConversation conversation = new WebConversation();
		WebRequest request = new GetMethodWebRequest(webssoClient2URL);
		WebResponse response = tryGetResponse(conversation, request);
		request = applicationLogin(conversation, response);
		response = tryGetResponse(conversation, request);
		assertUserInformation(response);

		// login 2
		WebRequest request2 = new GetMethodWebRequest(webssoClient2URL);// login into application2
		WebResponse response2 = tryGetResponse(conversation, request2);
		assertUserInformation(response2);

		// logout
		WebLink link = response.getLinkWith("logout");
		link.click(); // logout of the application
		WebRequest newRequest = new GetMethodWebRequest(webssoClient1URL);
		WebResponse outputResponse = tryGetResponse(conversation, newRequest);
		WebTable usersData = outputResponse
				.getTableStartingWith("Single Sign On User Data");

		assertNull("users data must be null ", usersData); // return null for user data (ie) logged out of second application
	}

	private WebRequest applicationLogin(WebConversation conversation,
			WebResponse response) throws SAXException, Exception {
		WebRequest request;
		WebForm loginForm = response.getForms()[0];
		request = loginForm.getRequest();

		SelectionFormControl asDorianOptions = (SelectionFormControl) response
				.getElementWithID("dorianName");
		request
				.setParameter("dorianName",asDorianOptions.getOptionValues()[1]);

		response = tryGetResponse(conversation, request);
		loginForm = response.getForms()[0];
		request = loginForm.getRequest();

		SelectionFormControl asUrlOptions = (SelectionFormControl) response
				.getElementWithID("authenticationServiceURL");
		String[] urls = asUrlOptions.getOptionValues();
		request.setParameter("authenticationServiceURL", urls[1]);

		response = tryGetResponse(conversation, request);
		loginForm = response.getForms()[0];
		request = loginForm.getRequest();

		request.setParameter("username", "jdoe2");
		request.setParameter("password", "K00lM0N$$2");
		return request;
	}

	private void assertUserInformation(WebResponse response)
			throws SAXException {
		WebTable usersData = response
				.getTableStartingWith("Single Sign On User Data");
		String[][] tableRows = usersData.asText();
		String userGridInformation = tableRows[1][0];

		assertTrue(userGridInformation
				.contains("/C=US/O=abc/OU=xyz/OU=caGrid/OU=Dorian/CN=jdoe2"));
		assertTrue(userGridInformation.contains("John2"));
		assertTrue(userGridInformation.contains("Doe2"));
		assertTrue(userGridInformation
				.contains("/wsrf/services/cagrid/DelegatedCredential"));
		assertTrue(userGridInformation.contains("jdoe2@cagrid.org"));
	}

	/**
	 * try getting a response for the given Conversation and Request
	 */
	public WebResponse tryGetResponse(WebConversation conversation,
			WebRequest request) throws Exception {
		WebResponse response = null;
		try {
			response = conversation.getResponse(request);
		} catch (HttpNotFoundException nfe) {
			log.error("The URL '" + request.getURL()+ "' is not active any more");
			throw nfe;
		} catch (Exception e) {
			log.error(e);
			throw e;
		}
		return response;
	}

	public static void main(String[] args) throws Throwable{
		String jasigURL="http://localhost:44546/webssoclientjasigexample-"+WebSSOSystemTest.getProjectVersion()+"/protected";
		String acegiURL="http://localhost:44842/webssoclientacegiexample-"+WebSSOSystemTest.getProjectVersion()+"/protected";
		AssertWebSSOApplicationStep applicationStep=new AssertWebSSOApplicationStep(jasigURL,acegiURL,18443,28443,38443);
		applicationStep.runStep();
	}
}


text:
package DBIx::Class::Storage::DBI::Firebird;

use strict;
use warnings;

# Because DBD::Firebird is more or less a copy of
# DBD::Interbase, inherit all the workarounds contained
# in ::Storage::DBI::InterBase as opposed to inheriting
# directly from ::Storage::DBI::Firebird::Common
use base qw/DBIx::Class::Storage::DBI::InterBase/;
use mro 'c3';

1;

=head1 NAME

DBIx::Class::Storage::DBI::Firebird - Driver for the Firebird RDBMS via
L<DBD::Firebird>

=head1 DESCRIPTION

This is an empty subclass of L<DBIx::Class::Storage::DBI::InterBase> for use
with L<DBD::Firebird>, see that driver for details.

=head1 FURTHER QUESTIONS?

Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.

=head1 COPYRIGHT AND LICENSE

This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
redistribute it and/or modify it under the same terms as the
L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.


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

namespace Smartsheet.Api.Models
{
    /// <summary>
    /// Represents the BulkItemRowResult object. </summary>
    /// <seealso href="http://smartsheet-platform.github.io/api-docs/?shell#partial-success">Partial Success</seealso>
    public class BulkItemRowResult : BulkItemResult<Row>
    {
    }
}


text:
package org.optaplanner.examples.coachshuttlegathering.persistence;

import java.io.File;
import java.util.Collection;

import org.junit.runners.Parameterized;
import org.optaplanner.examples.common.persistence.SolutionDao;
import org.optaplanner.examples.common.persistence.SolutionDaoTest;

public class CoachShuttleGatheringDaoTest extends SolutionDaoTest {

    @Override
    protected SolutionDao createSolutionDao() {
        return new CoachShuttleGatheringDao();
    }

    @Parameterized.Parameters(name = "{index}: {0}")
    public static Collection<Object[]> getSolutionFilesAsParameters() {
        return getSolutionFilesAsParameters(new CoachShuttleGatheringDao());
    }

    public CoachShuttleGatheringDaoTest(File solutionFile) {
        super(solutionFile);
    }

}


text:
package gov.nasa.worldwind.data;

import gov.nasa.worldwind.*;
import gov.nasa.worldwind.avlist.*;
import gov.nasa.worldwind.cache.*;
import gov.nasa.worldwind.exception.WWRuntimeException;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.util.*;
import org.w3c.dom.Document;

import java.io.File;
import java.lang.Thread;

/**
 * @author dcollins
 * @version $Id: TiledRasterProducer.java 1171 2013-02-11 21:45:02Z dcollins $
 */
public abstract class TiledRasterProducer extends AbstractDataStoreProducer
{
    private static final long DEFAULT_TILED_RASTER_PRODUCER_CACHE_SIZE = 300000000L; // ~300 megabytes
    private static final int DEFAULT_TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD = 3000; // 3000 pixels
    private static final int DEFAULT_WRITE_THREAD_POOL_SIZE = 2;
    private static final int DEFAULT_TILE_WIDTH_AND_HEIGHT = 512;
    private static final int DEFAULT_SINGLE_LEVEL_TILE_WIDTH_AND_HEIGHT = 512;
    private static final double DEFAULT_LEVEL_ZERO_TILE_DELTA = 36d;

    // List of source data rasters.
    private java.util.List<DataRaster> dataRasterList = new java.util.ArrayList<DataRaster>();
    // Data raster caching.
    private MemoryCache rasterCache;
    // Concurrent processing helper objects.
    private final java.util.concurrent.ExecutorService tileWriteService;
    private final java.util.concurrent.Semaphore tileWriteSemaphore;
    private final Object fileLock = new Object();
    // Progress counters.
    private int tile;
    private int tileCount;

    private DataRasterReaderFactory readerFactory;

    public TiledRasterProducer(MemoryCache cache, int writeThreadPoolSize)
    {
        if (cache == null)
        {
            String message = Logging.getMessage("nullValue.CacheIsNull");
            Logging.logger().severe(message);
            throw new IllegalArgumentException(message);
        }
        if (writeThreadPoolSize < 1)
        {
            String message = Logging.getMessage("generic.ArgumentOutOfRange", "writeThreadPoolSize < 1");
            Logging.logger().severe(message);
            throw new IllegalArgumentException(message);
        }

        this.rasterCache = cache;
        this.tileWriteService = this.createDefaultTileWriteService(writeThreadPoolSize);
        this.tileWriteSemaphore = new java.util.concurrent.Semaphore(writeThreadPoolSize, true);

        try
        {
            readerFactory = (DataRasterReaderFactory) WorldWind.createConfigurationComponent(
                AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME);
        }
        catch (Exception e)
        {
            readerFactory = new BasicDataRasterReaderFactory();
        }
    }

    public TiledRasterProducer()
    {
        this(createDefaultCache(), DEFAULT_WRITE_THREAD_POOL_SIZE);
    }

    public Iterable<DataRaster> getDataRasters()
    {
        return this.dataRasterList;
    }

    protected DataRasterReaderFactory getReaderFactory()
    {
        return this.readerFactory;
    }

    // TODO: this describes the file types the producer will read. Make that more clear in the method name.

    public String getDataSourceDescription()
    {
        DataRasterReader[] readers = this.getDataRasterReaders();
        if (readers == null || readers.length < 1)
            return "";

        // Collect all the unique format suffixes available in all readers. If a reader does not publish any
        // format suffixes, then collect it's description.
        java.util.Set<String> suffixSet = new java.util.TreeSet<String>();
        java.util.Set<String> descriptionSet = new java.util.TreeSet<String>();
        for (DataRasterReader reader : readers)
        {
            String description = reader.getDescription();
            String[] names = reader.getSuffixes();

            if (names != null && names.length > 0)
                suffixSet.addAll(java.util.Arrays.asList(names));
            else
                descriptionSet.add(description);
        }

        // Create a string representation of the format suffixes (or description if no suffixes are available) for
        // all readers.
        StringBuilder sb = new StringBuilder();
        for (String suffix : suffixSet)
        {
            if (sb.length() > 0)
                sb.append(", ");
            sb.append("*.").append(suffix);
        }
        for (String description : descriptionSet)
        {
            if (sb.length() > 0)
                sb.append(", ");
            sb.append(description);
        }
        return sb.toString();
    }

    public void removeProductionState()
    {
        java.io.File installLocation = this.installLocationFor(this.getStoreParameters());

        if (installLocation == null || !installLocation.exists())
        {
            String message = Logging.getMessage("TiledRasterProducer.NoInstallLocation",
                this.getStoreParameters().getValue(AVKey.DATASET_NAME));
            Logging.logger().warning(message);
            return;
        }

        try
        {
            WWIO.deleteDirectory(installLocation);
        }
        catch (Exception e)
        {
            String message = Logging.getMessage("TiledRasterProducer.ExceptionRemovingProductionState",
                this.getStoreParameters().getValue(AVKey.DATASET_NAME));
            Logging.logger().log(java.util.logging.Level.SEVERE, message, e);
        }
    }

    protected abstract DataRaster createDataRaster(int width, int height, Sector sector, AVList params);

    protected abstract DataRasterReader[] getDataRasterReaders();

    protected abstract DataRasterWriter[] getDataRasterWriters();

    protected MemoryCache getCache()
    {
        return this.rasterCache;
    }

    protected java.util.concurrent.ExecutorService getTileWriteService()
    {
        return this.tileWriteService;
    }

    protected java.util.concurrent.Semaphore getTileWriteSemaphore()
    {
        return this.tileWriteSemaphore;
    }

    protected void doStartProduction(AVList parameters) throws Exception
    {
        // Copy production parameters to prevent changes to caller's reference.
        this.productionParams = parameters.copy();
        this.initProductionParameters(this.productionParams);

        // Assemble the source data rasters.
        this.assembleDataRasters();

        // Initialize the level set parameters, and create the level set.
        this.initLevelSetParameters(this.productionParams);
        LevelSet levelSet = new LevelSet(this.productionParams);
        // Install the each tiles of the LevelSet.
        this.installLevelSet(levelSet, this.productionParams);

        // Wait for concurrent tasks to complete.
        this.waitForInstallTileTasks();

        // Clear the raster cache.
        this.getCache().clear();

        // Install the data descriptor for this tiled raster set.
        this.installConfigFile(this.productionParams);
    }

    protected String validateProductionParameters(AVList parameters)
    {
        StringBuilder sb = new StringBuilder();

        Object o = parameters.getValue(AVKey.FILE_STORE_LOCATION);
        if (o == null || !(o instanceof String) || ((String) o).length() < 1)
            sb.append((sb.length() > 0 ? ", " : "")).append(Logging.getMessage("term.fileStoreLocation"));

        o = parameters.getValue(AVKey.DATA_CACHE_NAME);
        if (o == null || !(o instanceof String) || ((String) o).length() == 0)
            sb.append((sb.length() > 0 ? ", " : "")).append(Logging.getMessage("term.fileStoreFolder"));

        o = parameters.getValue(AVKey.DATASET_NAME);
        if (o == null || !(o instanceof String) || ((String) o).length() < 1)
            sb.append((sb.length() > 0 ? ", " : "")).append(Logging.getMessage("term.datasetName"));

        if (sb.length() == 0)
            return null;

        return Logging.getMessage("DataStoreProducer.InvalidDataStoreParamters", sb.toString());
    }

    protected java.io.File installLocationFor(AVList params)
    {
        String fileStoreLocation = params.getStringValue(AVKey.FILE_STORE_LOCATION);
        String dataCacheName = params.getStringValue(AVKey.DATA_CACHE_NAME);
        if (fileStoreLocation == null || dataCacheName == null)
            return null;

        String path = WWIO.appendPathPart(fileStoreLocation, dataCacheName);
        if (path == null || path.length() == 0)
            return null;

        return new java.io.File(path);
    }

    //**************************************************************//
    //********************  LevelSet Assembly  *********************//
    //**************************************************************//

    protected abstract void initProductionParameters(AVList params);

    protected void initLevelSetParameters(AVList params)
    {
        int largeThreshold = Configuration.getIntegerValue(AVKey.TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD,
            DEFAULT_TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD);
        boolean isDataSetLarge = this.isDataSetLarge(this.dataRasterList, largeThreshold);

        Sector sector = (Sector) params.getValue(AVKey.SECTOR);
        if (sector == null)
        {
            // Compute a sector that bounds the data rasters. Make sure the sector does not exceed the limits of
            // latitude and longitude.
            sector = this.computeBoundingSector(this.dataRasterList);
            if (sector != null)
                sector = sector.intersection(Sector.FULL_SPHERE);
            params.setValue(AVKey.SECTOR, sector);
        }

        Integer tileWidth = (Integer) params.getValue(AVKey.TILE_WIDTH);
        if (tileWidth == null)
        {
            tileWidth = isDataSetLarge ? DEFAULT_TILE_WIDTH_AND_HEIGHT : DEFAULT_SINGLE_LEVEL_TILE_WIDTH_AND_HEIGHT;
            params.setValue(AVKey.TILE_WIDTH, tileWidth);
        }

        Integer tileHeight = (Integer) params.getValue(AVKey.TILE_HEIGHT);
        if (tileHeight == null)
        {
            tileHeight = isDataSetLarge ? DEFAULT_TILE_WIDTH_AND_HEIGHT : DEFAULT_SINGLE_LEVEL_TILE_WIDTH_AND_HEIGHT;
            params.setValue(AVKey.TILE_HEIGHT, tileHeight);
        }

        LatLon rasterTileDelta = this.computeRasterTileDelta(tileWidth, tileHeight, this.dataRasterList);
        LatLon desiredLevelZeroDelta = this.computeDesiredTileDelta(sector);

        Integer numLevels = (Integer) params.getValue(AVKey.NUM_LEVELS);
        if (numLevels == null)
        {
            // If the data set is large, then use compute a number of levels for the full pyramid. Otherwise use a
            // single level.
            numLevels = isDataSetLarge ? this.computeNumLevels(desiredLevelZeroDelta, rasterTileDelta) : 1;
            params.setValue(AVKey.NUM_LEVELS, numLevels);
        }

        Integer numEmptyLevels = (Integer) params.getValue(AVKey.NUM_EMPTY_LEVELS);
        if (numEmptyLevels == null)
        {
            numEmptyLevels = 0;
            params.setValue(AVKey.NUM_EMPTY_LEVELS, numEmptyLevels);
        }

        LatLon levelZeroTileDelta = (LatLon) params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA);
        if (levelZeroTileDelta == null)
        {
            double scale = Math.pow(2d, numLevels - 1);
            levelZeroTileDelta = LatLon.fromDegrees(
                scale * rasterTileDelta.getLatitude().degrees,
                scale * rasterTileDelta.getLongitude().degrees);
            params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, levelZeroTileDelta);
        }

        LatLon tileOrigin = (LatLon) params.getValue(AVKey.TILE_ORIGIN);
        if (tileOrigin == null)
        {
            tileOrigin = new LatLon(sector.getMinLatitude(), sector.getMinLongitude());
            params.setValue(AVKey.TILE_ORIGIN, tileOrigin);
        }

        // If the default or caller-specified values define a level set that does not fit in the limits of latitude
        // and longitude, then we re-define the level set parameters using values known to fit in those limits.
        if (!this.isWithinLatLonLimits(sector, levelZeroTileDelta, tileOrigin))
        {
            String message
                = "TiledRasterProducer: native tiling is outside lat/lon limits. Falling back to default tiling.";
            Logging.logger().warning(message);

            levelZeroTileDelta = LatLon.fromDegrees(DEFAULT_LEVEL_ZERO_TILE_DELTA, DEFAULT_LEVEL_ZERO_TILE_DELTA);
            params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, levelZeroTileDelta);

            tileOrigin = new LatLon(Angle.NEG90, Angle.NEG180);
            params.setValue(AVKey.TILE_ORIGIN, tileOrigin);

            numLevels = this.computeNumLevels(levelZeroTileDelta, rasterTileDelta);
            params.setValue(AVKey.NUM_LEVELS, numLevels);

            int numLevelsNeeded = isDataSetLarge ? this.computeNumLevels(desiredLevelZeroDelta, rasterTileDelta) : 1;
            numEmptyLevels = (numLevels > numLevelsNeeded) ? (numLevels - numLevelsNeeded) : 0;
            params.setValue(AVKey.NUM_EMPTY_LEVELS, numEmptyLevels);
        }
    }

    protected boolean isDataSetLarge(Iterable<? extends DataRaster> rasters, int largeThreshold)
    {
        Sector sector = this.computeBoundingSector(rasters);
        LatLon pixelSize = this.computeSmallestPixelSize(rasters);
        int sectorWidth = (int) Math.ceil(sector.getDeltaLonDegrees() / pixelSize.getLongitude().degrees);
        int sectorHeight = (int) Math.ceil(sector.getDeltaLatDegrees() / pixelSize.getLatitude().degrees);
        return (sectorWidth >= largeThreshold) || (sectorHeight >= largeThreshold);
    }

    protected boolean isWithinLatLonLimits(Sector sector, LatLon tileDelta, LatLon tileOrigin)
    {
        double minLat = Math.floor((sector.getMinLatitude().degrees - tileOrigin.getLatitude().degrees)
            / tileDelta.getLatitude().degrees);
        minLat = tileOrigin.getLatitude().degrees + minLat * tileDelta.getLatitude().degrees;
        double maxLat = Math.ceil((sector.getMaxLatitude().degrees - tileOrigin.getLatitude().degrees)
            / tileDelta.getLatitude().degrees);
        maxLat = tileOrigin.getLatitude().degrees + maxLat * tileDelta.getLatitude().degrees;
        double minLon = Math.floor((sector.getMinLongitude().degrees - tileOrigin.getLongitude().degrees)
            / tileDelta.getLongitude().degrees);
        minLon = tileOrigin.getLongitude().degrees + minLon * tileDelta.getLongitude().degrees;
        double maxLon = Math.ceil((sector.getMaxLongitude().degrees - tileOrigin.getLongitude().degrees)
            / tileDelta.getLongitude().degrees);
        maxLon = tileOrigin.getLongitude().degrees + maxLon * tileDelta.getLongitude().degrees;
        return Sector.fromDegrees(minLat, maxLat, minLon, maxLon).isWithinLatLonLimits();
    }

    protected Sector computeBoundingSector(Iterable<? extends DataRaster> rasters)
    {
        Sector sector = null;
        for (DataRaster raster : rasters)
        {
            sector = (sector != null) ? raster.getSector().union(sector) : raster.getSector();
        }
        return sector;
    }

    protected LatLon computeRasterTileDelta(int tileWidth, int tileHeight, Iterable<? extends DataRaster> rasters)
    {
        LatLon pixelSize = this.computeSmallestPixelSize(rasters);
        // Compute the tile size in latitude and longitude, given a raster's sector and dimension, and the tile
        // dimensions. In this computation a pixel is assumed to cover a finite area.
        double latDelta = tileHeight * pixelSize.getLatitude().degrees;
        double lonDelta = tileWidth * pixelSize.getLongitude().degrees;
        return LatLon.fromDegrees(latDelta, lonDelta);
    }

    protected LatLon computeDesiredTileDelta(Sector sector)
    {
        double levelZeroLat = Math.min(sector.getDeltaLatDegrees(), DEFAULT_LEVEL_ZERO_TILE_DELTA);
        double levelZeroLon = Math.min(sector.getDeltaLonDegrees(), DEFAULT_LEVEL_ZERO_TILE_DELTA);
        return LatLon.fromDegrees(levelZeroLat, levelZeroLon);
    }

    protected LatLon computeRasterPixelSize(DataRaster raster)
    {
        // Compute the raster's pixel dimension in latitude and longitude. In this computation a pixel is assumed to
        // cover a finite area.
        return LatLon.fromDegrees(
            raster.getSector().getDeltaLatDegrees() / raster.getHeight(),
            raster.getSector().getDeltaLonDegrees() / raster.getWidth());
    }

    protected LatLon computeSmallestPixelSize(Iterable<? extends DataRaster> rasters)
    {
        // Find the smallest pixel dimensions in the given rasters.
        double smallestLat = Double.MAX_VALUE;
        double smallestLon = Double.MAX_VALUE;
        for (DataRaster raster : rasters)
        {
            LatLon curSize = this.computeRasterPixelSize(raster);
            if (smallestLat > curSize.getLatitude().degrees)
                smallestLat = curSize.getLatitude().degrees;
            if (smallestLon > curSize.getLongitude().degrees)
                smallestLon = curSize.getLongitude().degrees;
        }
        return LatLon.fromDegrees(smallestLat, smallestLon);
    }

    protected int computeNumLevels(LatLon levelZeroDelta, LatLon lastLevelDelta)
    {
        // Compute the number of levels needed to achieve the given last level tile delta, starting from the given
        // level zero tile delta.
        double numLatLevels = WWMath.logBase2(levelZeroDelta.getLatitude().getDegrees())
            - WWMath.logBase2(lastLevelDelta.getLatitude().getDegrees());
        double numLonLevels = WWMath.logBase2(levelZeroDelta.getLongitude().getDegrees())
            - WWMath.logBase2(lastLevelDelta.getLongitude().getDegrees());

        // Compute the maximum number of levels needed, but limit the number of levels to positive integers greater
        // than or equal to one.
        int numLevels = (int) Math.ceil(Math.max(numLatLevels, numLonLevels));
        if (numLevels < 1)
            numLevels = 1;

        return numLevels;
    }

    //**************************************************************//
    //********************  DataRaster Assembly  *******************//
    //**************************************************************//

    protected void assembleDataRasters() throws Exception
    {
        // Exit if the caller has instructed us to stop production.
        if (this.isStopped())
            return;

        for (SourceInfo info : this.getDataSourceList())
        {
            // Exit if the caller has instructed us to stop production.
            if (this.isStopped())
                break;

            Thread.sleep(0);

            // Don't validate the data source here. Data sources are validated when they're passed to the producer in
            // offerDataSource() or offerAllDataSources().
            this.assembleDataSource(info.source, info);
        }
    }

    protected void assembleDataSource(Object source, AVList params) throws Exception
    {
        if (source instanceof DataRaster)
        {
            this.dataRasterList.add((DataRaster) source);
        }
        else
        {
            DataRasterReader reader = this.readerFactory.findReaderFor(source, params, this.getDataRasterReaders());
            this.dataRasterList.add(new CachedDataRaster(source, params, reader, this.getCache()));
        }
    }

    protected static MemoryCache createDefaultCache()
    {
        long cacheSize = Configuration.getLongValue(AVKey.TILED_RASTER_PRODUCER_CACHE_SIZE,
            DEFAULT_TILED_RASTER_PRODUCER_CACHE_SIZE);
        return new BasicMemoryCache((long) (0.8 * cacheSize), cacheSize);
    }

    //**************************************************************//
    //********************  LevelSet Installation  *****************//
    //**************************************************************//

    protected void installLevelSet(LevelSet levelSet, AVList params) throws java.io.IOException
    {
        // Exit if the caller has instructed us to stop production.
        if (this.isStopped())
            return;

        // Setup the progress parameters.
        this.calculateTileCount(levelSet, params);
        this.startProgress();

        Sector sector = levelSet.getSector();
        Level level = levelSet.getFirstLevel();

        Angle dLat = level.getTileDelta().getLatitude();
        Angle dLon = level.getTileDelta().getLongitude();
        Angle latOrigin = levelSet.getTileOrigin().getLatitude();
        Angle lonOrigin = levelSet.getTileOrigin().getLongitude();
        int firstRow = Tile.computeRow(dLat, sector.getMinLatitude(), latOrigin);
        int firstCol = Tile.computeColumn(dLon, sector.getMinLongitude(), lonOrigin);
        int lastRow = Tile.computeRow(dLat, sector.getMaxLatitude(), latOrigin);
        int lastCol = Tile.computeColumn(dLon, sector.getMaxLongitude(), lonOrigin);

        buildLoop:
        {
            Angle p1 = Tile.computeRowLatitude(firstRow, dLat, latOrigin);
            for (int row = firstRow; row <= lastRow; row++)
            {
                Angle p2 = p1.add(dLat);
                Angle t1 = Tile.computeColumnLongitude(firstCol, dLon, lonOrigin);
                for (int col = firstCol; col <= lastCol; col++)
                {
                    // Exit if the caller has instructed us to stop production.
                    Thread.yield();
                    if (this.isStopped())
                        break buildLoop;

                    Angle t2 = t1.add(dLon);

                    Tile tile = new Tile(new Sector(p1, p2, t1, t2), level, row, col);
                    DataRaster tileRaster = this.createTileRaster(levelSet, tile, params);
                    // Write the top-level tile raster to disk.
                    if (tileRaster != null)
                        this.installTileRasterLater(levelSet, tile, tileRaster, params);

                    t1 = t2;
                }
                p1 = p2;
            }
        }
    }

    protected DataRaster createTileRaster(LevelSet levelSet, Tile tile, AVList params) throws java.io.IOException
    {
        // Exit if the caller has instructed us to stop production.
        if (this.isStopped())
            return null;

        DataRaster tileRaster;

        // If we have reached the final level, then create a tile raster from the original data sources.
        if (this.isFinalLevel(levelSet, tile.getLevelNumber(), params))
        {
            tileRaster = this.drawDataSources(levelSet, tile, this.dataRasterList, params);
        }
        // Otherwise, recursively create a tile raster from the next level's tile rasters.
        else
        {
            tileRaster = this.drawDescendants(levelSet, tile, params);
        }

        this.updateProgress();

        return tileRaster;
    }

    protected DataRaster drawDataSources(LevelSet levelSet, Tile tile, Iterable<DataRaster> dataRasters, AVList params)
        throws java.io.IOException
    {
        DataRaster tileRaster = null;

        // Find the data sources that intersect this tile and intersect the LevelSet sector.
        java.util.ArrayList<DataRaster> intersectingRasters = new java.util.ArrayList<DataRaster>();
        for (DataRaster raster : dataRasters)
        {
            if (raster.getSector().intersects(tile.getSector()) && raster.getSector().intersects(levelSet.getSector()))
                intersectingRasters.add(raster);
        }

        // If any data sources intersect this tile, and the tile's level is not empty, then we attempt to read those
        // sources and render them into this tile.
        if (!intersectingRasters.isEmpty() && !tile.getLevel().isEmpty())
        {
            // Create the tile raster to render into.
            tileRaster = this.createDataRaster(tile.getLevel().getTileWidth(), tile.getLevel().getTileHeight(),
                tile.getSector(), params);
            // Render each data source raster into the tile raster.
            for (DataRaster raster : intersectingRasters)
            {
                raster.drawOnTo(tileRaster);
            }
        }

        // Make the data rasters available for garbage collection.
        intersectingRasters.clear();
        //noinspection UnusedAssignment
        intersectingRasters = null;

        return tileRaster;
    }

    protected DataRaster drawDescendants(LevelSet levelSet, Tile tile, AVList params) throws java.io.IOException
    {
        DataRaster tileRaster = null;
        boolean hasDescendants = false;

        // Recursively create sub-tile rasters.
        Tile[] subTiles = this.createSubTiles(tile, levelSet.getLevel(tile.getLevelNumber() + 1));
        DataRaster[] subRasters = new DataRaster[subTiles.length];
        for (int index = 0; index < subTiles.length; index++)
        {
            // If the sub-tile does not intersect the level set, then skip that sub-tile.
            if (subTiles[index].getSector().intersects(levelSet.getSector()))
            {
                // Recursively create the sub-tile raster.
                DataRaster subRaster = this.createTileRaster(levelSet, subTiles[index], params);
                // If creating the sub-tile raster fails, then skip that sub-tile.
                if (subRaster != null)
                {
                    subRasters[index] = subRaster;
                    hasDescendants = true;
                }
            }
        }

        // Exit if the caller has instructed us to stop production.
        if (this.isStopped())
            return null;

        // If any of the sub-tiles successfully created a data raster, then we potentially create this tile's raster,
        // then write the sub-tiles to disk.
        if (hasDescendants)
        {
            // If this tile's level is not empty, then create and render the tile's raster.
            if (!tile.getLevel().isEmpty())
            {
                // Create the tile's raster.
                tileRaster = this.createDataRaster(tile.getLevel().getTileWidth(), tile.getLevel().getTileHeight(),
                    tile.getSector(), params);

                for (int index = 0; index < subTiles.length; index++)
                {
                    if (subRasters[index] != null)
                    {
                        // Render the sub-tile raster to this this tile raster.
                        subRasters[index].drawOnTo(tileRaster);
                        // Write the sub-tile raster to disk.
                        this.installTileRasterLater(levelSet, subTiles[index], subRasters[index], params);
                    }
                }
            }
        }

        // Make the sub-tiles and sub-rasters available for garbage collection.
        for (int index = 0; index < subTiles.length; index++)
        {
            subTiles[index] = null;
            subRasters[index] = null;
        }
        //noinspection UnusedAssignment
        subTiles = null;
        //noinspection UnusedAssignment
        subRasters = null;

        return tileRaster;
    }

    protected Tile[] createSubTiles(Tile tile, Level nextLevel)
    {
        Angle p0 = tile.getSector().getMinLatitude();
        Angle p2 = tile.getSector().getMaxLatitude();
        Angle p1 = Angle.midAngle(p0, p2);

        Angle t0 = tile.getSector().getMinLongitude();
        Angle t2 = tile.getSector().getMaxLongitude();
        Angle t1 = Angle.midAngle(t0, t2);

        int row = tile.getRow();
        int col = tile.getColumn();

        Tile[] subTiles = new Tile[4];
        subTiles[0] = new Tile(new Sector(p0, p1, t0, t1), nextLevel, 2 * row, 2 * col);
        subTiles[1] = new Tile(new Sector(p0, p1, t1, t2), nextLevel, 2 * row, 2 * col + 1);
        subTiles[2] = new Tile(new Sector(p1, p2, t1, t2), nextLevel, 2 * row + 1, 2 * col + 1);
        subTiles[3] = new Tile(new Sector(p1, p2, t0, t1), nextLevel, 2 * row + 1, 2 * col);

        return subTiles;
    }

    protected boolean isFinalLevel(LevelSet levelSet, int levelNumber, AVList params)
    {
        if (levelSet.isFinalLevel(levelNumber))
            return true;

        int maxNumOfLevels = levelSet.getLastLevel().getLevelNumber();
        int limit = this.extractMaxLevelLimit( params, maxNumOfLevels );
        return (levelNumber >= limit);
    }

    /**
     * Extracts a maximum level limit from the AVList if the AVList contains AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL.
     * This method requires <code>maxNumOfLevels</code> - the actual maximum numbers of levels.
     *
     * The AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL could specify multiple things:
     *
     * If the value of the AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL is "Auto" (as String),
     * the calculated limit of levels will be 70% of the actual maximum numbers of levels <code>maxNumOfLevels</code>.
     *
     * If the type of the value of the AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL is Integer,
     * it should contain an integer number between 0 (for level 0 only) and the actual maximum
     * numbers of levels <code>maxNumOfLevels</code>.
     *
     * It is also possible to specify the limit as percents, in this case the type of the
     * AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL value must be "String", have a numeric value as text and
     * the "%" percent sign in the end. Examples: "100%", "25%", "50%", etc.
     *
     * Value of AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL could be a numeric string (for example, "3"),
     * or Integer. The value will be correctly extracted and compared with the <code>maxNumOfLevels</code>.
     * Valid values must be smaller or equal to <code>maxNumOfLevels</code>.
     *
     * @param params AVList that may contain AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL property
     * @param maxNumOfLevels The actual maximum numbers of levels
     *
     * @return A limit of numbers of levels that should producer generate.
     *
     */
    protected int extractMaxLevelLimit(AVList params, int maxNumOfLevels)
    {
        if (null != params && params.hasKey(AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL))
        {
            Object o = params.getValue(AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL);
            if (o instanceof Integer)
            {
                int limit = (Integer) o;
                return (limit <= maxNumOfLevels) ? limit : maxNumOfLevels;
            }
            else if (o instanceof String)
            {
                String strLimit = (String) o;
                if ("Auto".equalsIgnoreCase(strLimit))
                {
                    return (int)Math.floor( 0.5d * (double)maxNumOfLevels ); // 0.5 = half, 0.6 = 60%
                }
                else if( strLimit.endsWith("%"))
                {
                    try
                    {
                        float percent = Float.parseFloat( strLimit.substring(0, strLimit.length()-1) );
                        int limit = (int)Math.floor( percent * (double)maxNumOfLevels / 100d );
                        return (limit <= maxNumOfLevels) ? limit :maxNumOfLevels;
                    }
                    catch (Throwable t)
                    {
                        Logging.logger().finest( WWUtil.extractExceptionReason(t));
                    }
                }
                else
                {
                    try
                    {
                        int limit = Integer.parseInt(strLimit);
                        return (limit <= maxNumOfLevels) ? limit :maxNumOfLevels;
                    }
                    catch (Throwable t)
                    {
                        Logging.logger().finest( WWUtil.extractExceptionReason(t));
                    }
                }
            }
        }

        return maxNumOfLevels;
    }

    //**************************************************************//
    //********************  Tile Installation  *********************//
    //**************************************************************//

    protected java.util.concurrent.ExecutorService createDefaultTileWriteService(int threadPoolSize)
    {
        // TODO: comment

        // Create a fixed thread pool, but provide a callback to release a tile write permit when a task completes.
        return new java.util.concurrent.ThreadPoolExecutor(
            // Fixed size thread pool.
            threadPoolSize, threadPoolSize,
            // This value is irrelevant, as threads only terminated when the executor is shutdown.
            0L, java.util.concurrent.TimeUnit.MILLISECONDS,
            // Provide an unbounded work queue.
            new java.util.concurrent.LinkedBlockingQueue<Runnable>())
        {
            protected void afterExecute(Runnable runnable, Throwable t)
            {
                // Invoke the superclass routine, then release a tile write permit.
                super.afterExecute(runnable, t);
                TiledRasterProducer.this.installTileRasterComplete();
            }
        };
    }

    protected void installTileRasterLater(final LevelSet levelSet, final Tile tile, final DataRaster tileRaster,
        final AVList params)
    {
        // TODO: comment
        // Try to acquire a permit from the tile write semaphore.
        this.getTileWriteSemaphore().acquireUninterruptibly();
        // We've acquired the permit, now execute the installTileRaster() routine in a different thread.
        this.getTileWriteService().execute(new Runnable()
        {
            public void run()
            {
                try
                {
                    installTileRaster(tile, tileRaster, params);
                    // Dispose the data raster.
                    if (tileRaster instanceof Disposable)
                        ((Disposable) tileRaster).dispose();
                }
                catch (Throwable t)
                {
                    String message = Logging.getMessage("generic.ExceptionWhileWriting", tile);
                    Logging.logger().log(java.util.logging.Level.SEVERE, message, t);
                }
            }
        });
    }

    protected void installTileRasterComplete()
    {
        // TODO: comment
        this.getTileWriteSemaphore().release();
    }

    protected void waitForInstallTileTasks()
    {
        // TODO: comment
        try
        {
            java.util.concurrent.ExecutorService service = this.getTileWriteService();
            service.shutdown();
            // Block this thread until the executor has completed.
            while (!service.awaitTermination(1000L, java.util.concurrent.TimeUnit.MILLISECONDS))
            {
                Thread.sleep(5L);
            }
        }
        catch (InterruptedException e)
        {
            String msg = Logging.getMessage("generic.interrupted", this.getClass().getName(),
                "waitForInstallTileTasks()");
            Logging.logger().finest(msg);
            // Don't swallow interrupts; instead, restore the interrupted status
            Thread.currentThread().interrupt();
        }
    }

    protected void installTileRaster(Tile tile, DataRaster tileRaster, AVList params) throws java.io.IOException
    {
        java.io.File installLocation;

        // Compute the install location of the tile.
        Object result = this.installLocationForTile(params, tile);
        if (result instanceof java.io.File)
        {
            installLocation = (java.io.File) result;
        }
        else
        {
            String message = result.toString();
            Logging.logger().severe(message);
            throw new java.io.IOException(message);
        }

        synchronized (this.fileLock)
        {
            java.io.File dir = installLocation.getParentFile();
            if (!dir.exists())
            {
                if (!dir.mkdirs())
                {
                    String message = Logging.getMessage("generic.CannotCreateFile", dir);
                    Logging.logger().warning(message);
                }
            }
        }

        // Write the tile data to the filesystem.
        String formatSuffix = params.getStringValue(AVKey.FORMAT_SUFFIX);
        DataRasterWriter[] writers = this.getDataRasterWriters();

        Object writer = this.findWriterFor(tileRaster, formatSuffix, installLocation, writers);
        if (writer instanceof DataRasterWriter)
        {
            try
            {
                ((DataRasterWriter) writer).write(tileRaster, formatSuffix, installLocation);
            }
            catch (java.io.IOException e)
            {
                String message = Logging.getMessage("generic.ExceptionWhileWriting", installLocation);
                Logging.logger().log(java.util.logging.Level.SEVERE, message, e);
            }
        }
    }

    protected Object installLocationForTile(AVList installParams, Tile tile)
    {
        String path = null;

        String s = installParams.getStringValue(AVKey.FILE_STORE_LOCATION);
        if (s != null)
            path = WWIO.appendPathPart(path, s);

        s = tile.getPath();
        if (s != null)
            path = WWIO.appendPathPart(path, s);

        if (path == null || path.length() < 1)
            return Logging.getMessage("TiledRasterProducer.InvalidTile", tile);

        return new java.io.File(path);
    }

    protected Object findWriterFor(DataRaster raster, String formatSuffix, java.io.File destination,
        DataRasterWriter[] writers)
    {
        for (DataRasterWriter writer : writers)
        {
            if (writer.canWrite(raster, formatSuffix, destination))
                return writer;
        }

        // No writer maching this DataRaster/formatSuffix.
        return Logging.getMessage("DataRaster.CannotWrite", raster, formatSuffix, destination);
    }

    //**************************************************************//
    //********************  Config File Installation  **************//
    //**************************************************************//

    /**
     * Returns a configuration document which describes the tiled data produced by this TiledRasterProducer. The
     * document's contents are derived from the specified parameter list, and depend on the concrete subclass'
     * implementation. This returns null if the parameter list is null, or if the configuration document cannot be
     * created for any reason.
     *
     * @param params the parameters which describe the configuration document's contents.
     *
     * @return the configuration document, or null if the parameter list is null or does not contain the required
     *         parameters.
     */
    protected abstract Document createConfigDoc(AVList params);

    /**
     * Installs the configuration file which describes the tiled data produced by this TiledRasterProducer. The install
     * location, configuration filename, and configuration file contents are derived from the specified parameter list.
     * This throws an exception if the configuration file cannot be installed for any reason.
     * <p/>
     * The parameter list must contain <strong>at least</strong> the following keys: <table> <tr><th>Key</th></tr>
     * <tr><td>{@link gov.nasa.worldwind.avlist.AVKey#FILE_STORE_LOCATION}</td><td></td></tr> <tr><td>{@link
     * gov.nasa.worldwind.avlist.AVKey#DATA_CACHE_NAME}</td><td></td></tr> <tr><td>{@link
     * gov.nasa.worldwind.avlist.AVKey#DATASET_NAME}</td><td></td></tr> </table>
     *
     * @param params the parameters which describe the install location, the configuration filename, and the
     *               configuration file contents.
     *
     * @throws Exception                if the configuration file cannot be installed for any reason.
     * @throws IllegalArgumentException if the parameter list is null.
     */
    protected void installConfigFile(AVList params) throws Exception
    {
        if (params == null)
        {
            String message = Logging.getMessage("nullValue.ParametersIsNull");
            Logging.logger().severe(message);
            throw new IllegalArgumentException(message);
        }

        // Exit if the caller has instructed us to stop production.
        if (this.isStopped())
            return;

        File configFile = this.getConfigFileInstallLocation(params);
        if (configFile == null)
        {
            String message = Logging.getMessage("TiledRasterProducer.NoConfigFileInstallLocation",
                params.getValue(AVKey.DATASET_NAME));
            Logging.logger().severe(message);
            throw new WWRuntimeException(message);
        }

        // Synchronize construction of the config file's parent directories. One or more tile installation tasks may be
        // running when this code executes. This synchronizes construction of common parent directories between with the
        // tile installation tasks.
        synchronized (this.fileLock)
        {
            java.io.File dir = configFile.getParentFile();
            if (!dir.exists())
            {
                if (!dir.mkdirs())
                {
                    String message = Logging.getMessage("generic.CannotCreateFile", dir);
                    Logging.logger().warning(message);
                }
            }
        }

        Document configDoc = this.createConfigDoc(params);
        if (configDoc == null)
        {
            String message = Logging.getMessage("TiledRasterProducer.CannotCreateConfigDoc",
                params.getValue(AVKey.DATASET_NAME));
            Logging.logger().severe(message);
            throw new WWRuntimeException(message);
        }

        try
        {
            WWXML.saveDocumentToFile(configDoc, configFile.getAbsolutePath());
        }
        catch (Exception e)
        {
            String message = Logging.getMessage("TiledRasterProducer.CannotWriteConfigFile", configFile);
            Logging.logger().severe(message);
            throw new WWRuntimeException(message);
        }

        this.getProductionResultsList().add(configDoc);
    }

    /**
     * Returns the location of the configuration file which describes the tiled data produced by this
     * TiledRasterProducer. The install location is derived from the specified parameter list. This returns null if the
     * parameter list is null, or if it does not contain any of the following keys: <table> <tr><th>Key</th></tr>
     * <tr><td>{@link gov.nasa.worldwind.avlist.AVKey#FILE_STORE_LOCATION}</td><td></td></tr> <tr><td>{@link
     * gov.nasa.worldwind.avlist.AVKey#DATA_CACHE_NAME}</td><td></td></tr> <tr><td>{@link
     * gov.nasa.worldwind.avlist.AVKey#DATASET_NAME}</td><td></td></tr> </table>
     *
     * @param params the parameters which describe the install location.
     *
     * @return the configuration file install location, or null if the parameter list is null or does not contain the
     *         required parameters.
     */
    protected File getConfigFileInstallLocation(AVList params)
    {
        if (params == null)
            return null;

        String fileStoreLocation = params.getStringValue(AVKey.FILE_STORE_LOCATION);
        if (fileStoreLocation != null)
            fileStoreLocation = WWIO.stripTrailingSeparator(fileStoreLocation);

        if (WWUtil.isEmpty(fileStoreLocation))
            return null;

        String cacheName = DataConfigurationUtils.getDataConfigFilename(params, ".xml");
        if (cacheName != null)
            cacheName = WWIO.stripLeadingSeparator(cacheName);

        if (WWUtil.isEmpty(cacheName))
            return null;

        return new File(fileStoreLocation + File.separator + cacheName);
    }

    //**************************************************************//
    //********************  Progress  ******************************//
    //**************************************************************//

    protected void calculateTileCount(LevelSet levelSet, AVList params)
    {
        Sector sector = levelSet.getSector();

        this.tileCount = 0;
        for (Level level : levelSet.getLevels())
        {
            Angle dLat = level.getTileDelta().getLatitude();
            Angle dLon = level.getTileDelta().getLongitude();
            Angle latOrigin = levelSet.getTileOrigin().getLatitude();
            Angle lonOrigin = levelSet.getTileOrigin().getLongitude();
            int firstRow = Tile.computeRow(dLat, sector.getMinLatitude(), latOrigin);
            int firstCol = Tile.computeColumn(dLon, sector.getMinLongitude(), lonOrigin);
            int lastRow = Tile.computeRow(dLat, sector.getMaxLatitude(), latOrigin);
            int lastCol = Tile.computeColumn(dLon, sector.getMaxLongitude(), lonOrigin);
            this.tileCount += (lastRow - firstRow + 1) * (lastCol - firstCol + 1);

            if (this.isFinalLevel(levelSet, level.getLevelNumber(), params))
                break;
        }
    }

    protected void startProgress()
    {
        this.tile = 0;
        this.firePropertyChange(AVKey.PROGRESS, null, 0d);
    }

    protected void updateProgress()
    {
        double oldProgress = this.tile / (double) this.tileCount;
        double newProgress = ++this.tile / (double) this.tileCount;
        this.firePropertyChange(AVKey.PROGRESS, oldProgress, newProgress);
    }
}


text:
package com.amazonaws.services.iot.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * The input for the SetDefaultPolicyVersion operation.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetDefaultPolicyVersionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The policy name.
     *

     */
    private String policyName;
    /**
     *

     * The policy version ID.
     *

     */
    private String policyVersionId;

    /**
     *

     * The policy name.
     *

     *
     * @param policyName
     *        The policy name.
     */

    public void setPolicyName(String policyName) {
        this.policyName = policyName;
    }

    /**
     *

     * The policy name.
     *

     *
     * @return The policy name.
     */

    public String getPolicyName() {
        return this.policyName;
    }

    /**
     *

     * The policy name.
     *

     *
     * @param policyName
     *        The policy name.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetDefaultPolicyVersionRequest withPolicyName(String policyName) {
        setPolicyName(policyName);
        return this;
    }

    /**
     *

     * The policy version ID.
     *

     *
     * @param policyVersionId
     *        The policy version ID.
     */

    public void setPolicyVersionId(String policyVersionId) {
        this.policyVersionId = policyVersionId;
    }

    /**
     *

     * The policy version ID.
     *

     *
     * @return The policy version ID.
     */

    public String getPolicyVersionId() {
        return this.policyVersionId;
    }

    /**
     *

     * The policy version ID.
     *

     *
     * @param policyVersionId
     *        The policy version ID.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetDefaultPolicyVersionRequest withPolicyVersionId(String policyVersionId) {
        setPolicyVersionId(policyVersionId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getPolicyName() != null)
            sb.append("PolicyName: ").append(getPolicyName()).append(",");
        if (getPolicyVersionId() != null)
            sb.append("PolicyVersionId: ").append(getPolicyVersionId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SetDefaultPolicyVersionRequest == false)
            return false;
        SetDefaultPolicyVersionRequest other = (SetDefaultPolicyVersionRequest) obj;
        if (other.getPolicyName() == null ^ this.getPolicyName() == null)
            return false;
        if (other.getPolicyName() != null && other.getPolicyName().equals(this.getPolicyName()) == false)
            return false;
        if (other.getPolicyVersionId() == null ^ this.getPolicyVersionId() == null)
            return false;
        if (other.getPolicyVersionId() != null && other.getPolicyVersionId().equals(this.getPolicyVersionId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getPolicyName() == null) ? 0 : getPolicyName().hashCode());
        hashCode = prime * hashCode + ((getPolicyVersionId() == null) ? 0 : getPolicyVersionId().hashCode());
        return hashCode;
    }

    @Override
    public SetDefaultPolicyVersionRequest clone() {
        return (SetDefaultPolicyVersionRequest) super.clone();
    }

}


text:
package io.github.biezhi.wechat.api.response;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.InputStream;

/**
 * 文件响应
 *
 * @author biezhi
 * @date 2018/1/18
 */
@Data
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
public class FileResponse extends ApiResponse {

    private InputStream inputStream;

}


text:
package com.amazonaws.services.sagemaker.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.sagemaker.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * UpdateCodeRepositoryRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateCodeRepositoryRequestMarshaller {

    private static final MarshallingInfo<String> CODEREPOSITORYNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CodeRepositoryName").build();
    private static final MarshallingInfo<StructuredPojo> GITCONFIG_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("GitConfig").build();

    private static final UpdateCodeRepositoryRequestMarshaller instance = new UpdateCodeRepositoryRequestMarshaller();

    public static UpdateCodeRepositoryRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(UpdateCodeRepositoryRequest updateCodeRepositoryRequest, ProtocolMarshaller protocolMarshaller) {

        if (updateCodeRepositoryRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(updateCodeRepositoryRequest.getCodeRepositoryName(), CODEREPOSITORYNAME_BINDING);
            protocolMarshaller.marshall(updateCodeRepositoryRequest.getGitConfig(), GITCONFIG_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package de.qaware.campus.secpro.mlr01;

import java.util.Arrays;

/**
 * An improved Login component. Uses char[] to store hardcoded
 * username and password. Check parameter are method local.
 *
 * @author mario-leander.reimer
 */
public class ImprovedLogin {

    private static final char[] USERNAME = {'T', 'h', 'e', 'D', 'u', 'd', 'e'};
    private static final char[] PASSWORD = {'B', 'i', 'g', 'L', 'e', 'b', 'o', 'w', 's', 'k', 'i'};

    /**
     * Check if authenticated.
     *
     * @param username the username
     * @param password the password as char[]
     * @return true if credentials OK, otherwise false
     */
    public boolean authenticated(String username, char[] password) {
        return Arrays.equals(USERNAME, username.toCharArray()) &&
                Arrays.equals(PASSWORD, password);
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "name_printers".
 *
 * @property integer $id
 * @property string $name
 *
 * @property Printers[] $printers
 */
class NamePrinters extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'name_printers';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Название принтера',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPrinters()
    {
        return $this->hasMany(Printers::className(), ['id_name_printer' => 'id']);
    }

    /*
         * фунция getKey() сначала проверяет есть ли такие же записи, если есть то возвращает их id
         * если нет то сохраняет название принтера и возвращает id сохраненной записи
         */
    public function getKey()
    {
        if ($name = NamePrinters::find()->where(['name' => $this->name])->one()) {
            return $name['id'];
        } else {
            $this->save();
            return $this->getPrimaryKey();
        }
    }

}


text:
module.exports = function (name) {
  return `import React from 'react'
import { storiesOf } from '@storybook/react'
import { withInfo } from '@storybook/addon-info'
import ${name} from './${name}'

storiesOf('${name}', module)
  .addDecorator(withInfo({ header: false, inline: true }))
  .add('default', () => (
    <${name} />
  ))
  .add('with different color', () => (
    <${name} clicksColor='blue' />
  ))
  .add('with increment hidden', () => (
    <${name} hideButton />
  ))
`
}


text:
layout: post
unique_id: crab_hot_pot
title: Crab Hot Pot
categories: []
locations:
---

YESTERDAY:
* guitar lesson
* decided not to go out due to the air quality
* Jackie ordered thai food for dinner
* finally watched Hunt for the Wilderpeople!

TODAY:
* laundry
* went to Hankook supermarket
  * picked up some frozen crabs to experiment with
* finished the Oates Adam trilogy
* hot pot with crabs!
  * frozen crabs were ... not that great

LEARNINGS:
* need to find fresher crabs


text:
package parser // import "github.com/docker/docker/builder/dockerfile/parser"

import (
	"bufio"
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"

	"github.com/gotestyourself/gotestyourself/assert"
	is "github.com/gotestyourself/gotestyourself/assert/cmp"
)

const testDir = "testfiles"
const negativeTestDir = "testfiles-negative"
const testFileLineInfo = "testfile-line/Dockerfile"

func getDirs(t *testing.T, dir string) []string {
	f, err := os.Open(dir)
	assert.NilError(t, err)
	defer f.Close()

	dirs, err := f.Readdirnames(0)
	assert.NilError(t, err)
	return dirs
}

func TestParseErrorCases(t *testing.T) {
	for _, dir := range getDirs(t, negativeTestDir) {
		dockerfile := filepath.Join(negativeTestDir, dir, "Dockerfile")

		df, err := os.Open(dockerfile)
		assert.NilError(t, err, dockerfile)
		defer df.Close()

		_, err = Parse(df)
		assert.Check(t, is.ErrorContains(err, ""), dockerfile)
	}
}

func TestParseCases(t *testing.T) {
	for _, dir := range getDirs(t, testDir) {
		dockerfile := filepath.Join(testDir, dir, "Dockerfile")
		resultfile := filepath.Join(testDir, dir, "result")

		df, err := os.Open(dockerfile)
		assert.NilError(t, err, dockerfile)
		defer df.Close()

		result, err := Parse(df)
		assert.NilError(t, err, dockerfile)

		content, err := ioutil.ReadFile(resultfile)
		assert.NilError(t, err, resultfile)

		if runtime.GOOS == "windows" {
			// CRLF --> CR to match Unix behavior
			content = bytes.Replace(content, []byte{'\x0d', '\x0a'}, []byte{'\x0a'}, -1)
		}
		assert.Check(t, is.Equal(result.AST.Dump()+"\n", string(content)), "In "+dockerfile)
	}
}

func TestParseWords(t *testing.T) {
	tests := []map[string][]string{
		{
			"input":  {"foo"},
			"expect": {"foo"},
		},
		{
			"input":  {"foo bar"},
			"expect": {"foo", "bar"},
		},
		{
			"input":  {"foo\\ bar"},
			"expect": {"foo\\ bar"},
		},
		{
			"input":  {"foo=bar"},
			"expect": {"foo=bar"},
		},
		{
			"input":  {"foo bar 'abc xyz'"},
			"expect": {"foo", "bar", "'abc xyz'"},
		},
		{
			"input":  {`foo bar "abc xyz"`},
			"expect": {"foo", "bar", `"abc xyz"`},
		},
		{
			"input":  {"àöû"},
			"expect": {"àöû"},
		},
		{
			"input":  {`föo bàr "âbc xÿz"`},
			"expect": {"föo", "bàr", `"âbc xÿz"`},
		},
	}

	for _, test := range tests {
		words := parseWords(test["input"][0], NewDefaultDirective())
		assert.Check(t, is.DeepEqual(test["expect"], words))
	}
}

func TestParseIncludesLineNumbers(t *testing.T) {
	df, err := os.Open(testFileLineInfo)
	assert.NilError(t, err)
	defer df.Close()

	result, err := Parse(df)
	assert.NilError(t, err)

	ast := result.AST
	assert.Check(t, is.Equal(5, ast.StartLine))
	assert.Check(t, is.Equal(31, ast.endLine))
	assert.Check(t, is.Len(ast.Children, 3))
	expected := [][]int{
		{5, 5},
		{11, 12},
		{17, 31},
	}
	for i, child := range ast.Children {
		msg := fmt.Sprintf("Child %d", i)
		assert.Check(t, is.DeepEqual(expected[i], []int{child.StartLine, child.endLine}), msg)
	}
}

func TestParseWarnsOnEmptyContinutationLine(t *testing.T) {
	dockerfile := bytes.NewBufferString(`
FROM alpine:3.6

RUN something \

    following \

    more

RUN another \

    thing
RUN non-indented \
# this is a comment
   after-comment

RUN indented \
    # this is an indented comment
    comment
	`)

	result, err := Parse(dockerfile)
	assert.NilError(t, err)
	warnings := result.Warnings
	assert.Check(t, is.Len(warnings, 3))
	assert.Check(t, is.Contains(warnings[0], "Empty continuation line found in"))
	assert.Check(t, is.Contains(warnings[0], "RUN something     following     more"))
	assert.Check(t, is.Contains(warnings[1], "RUN another     thing"))
	assert.Check(t, is.Contains(warnings[2], "will become errors in a future release"))
}

func TestParseReturnsScannerErrors(t *testing.T) {
	label := strings.Repeat("a", bufio.MaxScanTokenSize)

	dockerfile := strings.NewReader(fmt.Sprintf(`
		FROM image
		LABEL test=%s
`, label))
	_, err := Parse(dockerfile)
	assert.Check(t, is.Error(err, "dockerfile line greater than max allowed size of 65535"))
}


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using MahApps.Metro.Controls;

namespace MahAppsMetroHamburgerMenuNavigation.Navigation
{
    public class FrameAnimator
    {
        public static readonly DependencyProperty FrameNavigationStoryboardProperty
            = DependencyProperty.RegisterAttached(
                "FrameNavigationStoryboard",
                typeof(Storyboard),
                typeof(FrameAnimator),
                new FrameworkPropertyMetadata(null, OnFrameNavigationStoryboardChanged));

        private static void OnFrameNavigationStoryboardChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Frame frame && e.OldValue != e.NewValue)
            {
                frame.Navigating -= Frame_Navigating;
                if (e.NewValue is Storyboard)
                {
                    frame.Navigating += Frame_Navigating;
                }
            }
        }

        private static void Frame_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (sender is Frame frame)
            {
                var sb = GetFrameNavigationStoryboard(frame);
                if (sb != null)
                {
                    var presenter = frame.FindChild<ContentPresenter>();
                    sb.Begin((FrameworkElement)presenter ?? frame);
                }
            }
        }

        /// Helper for setting <see cref="FrameNavigationStoryboardProperty"/> on <paramref name="control"/>.
        /// <param name="control"><see cref="DependencyObject"/> to set <see cref="FrameNavigationStoryboardProperty"/> on.</param>
        /// <param name="storyboard">FrameNavigationStoryboard property value.</param>
        public static void SetFrameNavigationStoryboard(DependencyObject control, Storyboard storyboard)
        {
            control.SetValue(FrameNavigationStoryboardProperty, storyboard);
        }

        /// Helper for getting <see cref="FrameNavigationStoryboardProperty"/> from <paramref name="control"/>.
        /// <param name="control"><see cref="DependencyObject"/> to read <see cref="FrameNavigationStoryboardProperty"/> from.</param>
        /// <returns>FrameNavigationStoryboard property value.</returns>
        [AttachedPropertyBrowsableForType(typeof(DependencyObject))]
        public static Storyboard GetFrameNavigationStoryboard(DependencyObject control)
        {
            return (Storyboard)control.GetValue(FrameNavigationStoryboardProperty);
        }
    }
}


text:
layout: post
title: Spring Data Repositories - Best Practices
author: Thomas Darimont
category : talk
abstract: Thomas Darimont berichtet von seinen Erfahrungen mit Spring Data Repositories
---

August 2015: Thomas Darimont: Spring Data Repositories - Best Practices

    Die Repository Abstraktion ist das zentrale Element der Spring Data Projekte.
    Es stellt ein einfaches, konsistentes und Interface basiertes Programmiermodell
    bereit mit dessen Hilfe sich Datenzugriffsschichten auf relationale und auch nicht-relationale
    Datastores leicht realisieren lassen.

    In diesem Vortrag stellen wir die Repository Abstraktion vor und berichten von Best Practices
    und unseren Erfahrungen aus zahlreichen Kundenprojekten.
    Wir betrachten auch erweiterte Features wie z.B. die Integration mit querydsl, eigene Implementierungen,
    Java 8 Support sowie auch integration mit Spring MVC und Spring HATEOS.

13.08.2015, 19:00, Fraunhofer IESE, Kaiserslautern

Sprecher:

        <emp>Thomas Darimont</emp>  ist Committer im Spring Data Projekt und arbeitet als Principal Software Engineer
        bei Pivotal, früher besser bekannt als SpringSource.
        Seit über 10 Jahren widmet er sich dem Entwickeln von Java- und .Net-basierten Enterprise-Applikationen
        und Open-Source-Projekten.
        Seine Arbeitsschwerpunkte liegen im Bereich Softwarearchitektur, Spring Ökosystem und Persistenztechnologien
        sowie Stream Processing im Big Data Umfeld.
        Er ist regelmäßiger Sprecher auf deutschen und internationalen Konferenzen sowie User Groups.

Fotos:

        Previous

        Next