text:
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { DevTest } from '../../../lib/collections/collections.js';

'./feng.html'

///// HELPERS /////

Template.fengPage.helpers({
    choreslogEach() {
        return DevTest.find( { choreslogitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
    chorestodoEach() {
        return DevTest.find( { chorestodoitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
    homemessEach() {
        return DevTest.find( { homemessitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
    hometightinessEach() {
        return DevTest.find( { hometightinessitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
    carmessEach() {
        return DevTest.find( { carmessitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
    cartightinessEach() {
        return DevTest.find( { cartightinessitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
    workmessEach() {
        return DevTest.find( { workmessitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
    workspacetightinessEach() {
        return DevTest.find( { workspacetightinessitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
    improveFengpageEach() {
        return DevTest.find( { improveFengpageitemName: {$exists: true}}, {sort: {createdAt: -1}}); },
});

////////* Start of choreslog Events *//////

Template.addchoreslogItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const choreslogitemName = target.choreslogitemName.value;

    // Insert a choreslog item into the collection
    Meteor.call('choreslogitemName.insert', choreslogitemName);

    // Clear form
    target.choreslogitemName.value = '';
    },
});

Template.choreslogItem.events({
    // events go here
    'click .delete-choreslogitem'(){
     Meteor.call('choreslogitemName.remove', this._id);
    },

    'keyup [name=choreslogItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var choreslogItem = $(event.target).val();
        Meteor.call('updatechoreslogItem', documentId, choreslogItem);
        }
    },
});

////////* End of choreslog Events *//////

////////* Start of chorestodo Events *//////

Template.addchorestodoItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const chorestodoitemName = target.chorestodoitemName.value;

    // Insert a chorestodo item into the collection
    Meteor.call('chorestodoitemName.insert', chorestodoitemName);

    // Clear form
    target.chorestodoitemName.value = '';
    },
});

Template.chorestodoItem.events({
    // events go here
    'click .delete-chorestodoitem'(){
     Meteor.call('chorestodoitemName.remove', this._id);
    },

    'keyup [name=chorestodoItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var chorestodoItem = $(event.target).val();
        Meteor.call('updatechorestodoItem', documentId, chorestodoItem);
        }
    },
});

////////* End of chorestodo Events *//////

////////* Start of homemess Events *//////

Template.addhomemessItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const homemessitemName = target.homemessitemName.value;

    // Insert a homemess item into the collection
    Meteor.call('homemessitemName.insert', homemessitemName);

    // Clear form
    target.homemessitemName.value = '';
    },
});

Template.homemessItem.events({
    // events go here
    'click .delete-homemessitem'(){
     Meteor.call('homemessitemName.remove', this._id);
    },

    'keyup [name=homemessItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var homemessItem = $(event.target).val();
        Meteor.call('updatehomemessItem', documentId, homemessItem);
        }
    },
});

////////* End of homemess Events *//////

////////* Start of hometightiness Events *//////

Template.addhometightinessItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const hometightinessitemName = target.hometightinessitemName.value;

    // Insert a hometightiness item into the collection
    Meteor.call('hometightinessitemName.insert', hometightinessitemName);

    // Clear form
    target.hometightinessitemName.value = '';
    },
});

Template.hometightinessItem.events({
    // events go here
    'click .delete-hometightinessitem'(){
     Meteor.call('hometightinessitemName.remove', this._id);
    },

    'keyup [name=hometightinessItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var hometightinessItem = $(event.target).val();
        Meteor.call('updatehometightinessItem', documentId, hometightinessItem);
        }
    },
});

////////* End of hometightiness Events *//////

////////* Start of carmess Events *//////

Template.addcarmessItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const carmessitemName = target.carmessitemName.value;

    // Insert a carmess item into the collection
    Meteor.call('carmessitemName.insert', carmessitemName);

    // Clear form
    target.carmessitemName.value = '';
    },
});

Template.carmessItem.events({
    // events go here
    'click .delete-carmessitem'(){
     Meteor.call('carmessitemName.remove', this._id);
    },

    'keyup [name=carmessItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var carmessItem = $(event.target).val();
        Meteor.call('updatecarmessItem', documentId, carmessItem);
        }
    },
});

////////* End of carmess Events *//////

////////* Start of cartightiness Events *//////

Template.addcartightinessItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const cartightinessitemName = target.cartightinessitemName.value;

    // Insert a cartightiness item into the collection
    Meteor.call('cartightinessitemName.insert', cartightinessitemName);

    // Clear form
    target.cartightinessitemName.value = '';
    },
});

Template.cartightinessItem.events({
    // events go here
    'click .delete-cartightinessitem'(){
     Meteor.call('cartightinessitemName.remove', this._id);
    },

    'keyup [name=cartightinessItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var cartightinessItem = $(event.target).val();
        Meteor.call('updatecartightinessItem', documentId, cartightinessItem);
        }
    },
});

////////* End of cartightiness Events *//////

////////* Start of workmess Events *//////

Template.addworkmessItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const workmessitemName = target.workmessitemName.value;

    // Insert a workmess item into the collection
    Meteor.call('workmessitemName.insert', workmessitemName);

    // Clear form
    target.workmessitemName.value = '';
    },
});

Template.workmessItem.events({
    // events go here
    'click .delete-workmessitem'(){
     Meteor.call('workmessitemName.remove', this._id);
    },

    'keyup [name=workmessItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var workmessItem = $(event.target).val();
        Meteor.call('updateworkmessItem', documentId, workmessItem);
        }
    },
});

////////* End of workmess Events *//////

////////* Start of workspacetightiness Events *//////

Template.addworkspacetightinessItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const workspacetightinessitemName = target.workspacetightinessitemName.value;

    // Insert a workspacetightiness item into the collection
    Meteor.call('workspacetightinessitemName.insert', workspacetightinessitemName);

    // Clear form
    target.workspacetightinessitemName.value = '';
    },
});

Template.workspacetightinessItem.events({
    // events go here
    'click .delete-workspacetightinessitem'(){
     Meteor.call('workspacetightinessitemName.remove', this._id);
    },

    'keyup [name=workspacetightinessItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var workspacetightinessItem = $(event.target).val();
        Meteor.call('updateworkspacetightinessItem', documentId, workspacetightinessItem);
        }
    },
});

////////* End of workspacetightiness Events *//////

////////* Start of improveFengpage Events *//////

Template.addimproveFengpageItem.events({
  'submit form': function(event){
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const improveFengpageitemName = target.improveFengpageitemName.value;

    // Insert a improveFengpage item into the collection
    Meteor.call('improveFengpageitemName.insert', improveFengpageitemName);

    // Clear form
    target.improveFengpageitemName.value = '';
    },
});

Template.improveFengpageItem.events({
    // events go here
    'click .delete-improveFengpageitem'(){
     Meteor.call('improveFengpageitemName.remove', this._id);
    },

    'keyup [name=improveFengpageItem]': function(event){
    if(event.which == 13 || event.which == 27){
        $(event.target).blur();
    } else {
        var documentId = this._id;
        var improveFengpageItem = $(event.target).val();
        Meteor.call('updateimproveFengpageItem', documentId, improveFengpageItem);
        }
    },
});

////////* End of improveFengpage Events *//////


text:
package org.apache.kafka.common.utils;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

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

import org.junit.jupiter.api.Test;

public class AbstractIteratorTest {

    @Test
    public void testIterator() {
        int max = 10;
        List<Integer> l = new ArrayList<Integer>();
        for (int i = 0; i < max; i++)
            l.add(i);
        ListIterator<Integer> iter = new ListIterator<Integer>(l);
        for (int i = 0; i < max; i++) {
            Integer value = i;
            assertEquals(value, iter.peek());
            assertTrue(iter.hasNext());
            assertEquals(value, iter.next());
        }
        assertFalse(iter.hasNext());
    }

    @Test
    public void testEmptyIterator() {
        Iterator<Object> iter = new ListIterator<>(Collections.emptyList());
        assertThrows(NoSuchElementException.class, iter::next);
    }

    static class ListIterator<T> extends AbstractIterator<T> {
        private List<T> list;
        private int position = 0;

        public ListIterator(List<T> l) {
            this.list = l;
        }

        public T makeNext() {
            if (position < list.size())
                return list.get(position++);
            else
                return allDone();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.river.tool.envcheck;

import org.apache.river.resource.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;

import java.lang.reflect.Modifier;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.ResourceBundle;

import net.jini.config.Configuration;
import net.jini.config.ConfigurationException;
import net.jini.config.ConfigurationProvider;

import org.apache.river.start.ServiceDescriptor;
import org.apache.river.start.NonActivatableServiceDescriptor;
import org.apache.river.start.SharedActivatableServiceDescriptor;
import org.apache.river.start.SharedActivationGroupDescriptor;

import org.apache.river.tool.envcheck.Reporter.Message;
import org.apache.river.api.net.RFC3986URLClassLoader;

/**
 * Tool used to perform validity checks on the run-time environment of a client
 * or service. The output of this tool is a report; command-line options
 * control the verbosity and severity level at which report entries are
 * generated. A simple plugin architecture is implemented; a set of plugins
 * implementing a variety of checks is bundled with the tool, and support is
 * provided to allow additional plugins to be supplied by the user.
 *

 * The following items are discussed below:
 *

 *
Running the Tool
 *
Processing Options
 *
Examples
 *
Bundled Plugins
 *

 *
 *
 *
Running the Tool

 *
 * This tool primarily validates the system properties and configuration
 * files used when starting the target client or service. This is accomplished
 * by providing the unmodified command line for launching the component as
 * arguments to the tool. Thus, for a service designed to be run by the
 * service starter having the hypothetical original command line:
 *

 * java -Djava.security.policy=<var>my_policy</var> \
 *      -jar <var>install_dir</var>/lib/start.jar mystart.config
 *

 * the simplest invocation of the tool would be:
 *

 * java -jar <var>install_dir</var>/lib/envcheck.jar \
 *      java -Djava.security.policy=<var>my_policy</var> \
 *           -jar <var>install_dir</var>/lib/start.jar mystart.config
 *

 * Note that the entire command line, including the java command,
 * is supplied as arguments to the tool. The java command used to
 * run the tool may be different than the java command invoked by
 * the command line under test. The first token in the command line being
 * analyzed must not begin with a '-' and must end with the string "java".
 *
 *
 *
Processing Options

 *

 *

 *
-traces
 *
The implementation of a validity check may detect success or failure by
 *     handling an expected exception. By default, an error message will be
 *     generated in these cases, but the stack trace will be inhibited. This
 *     option is a hint that stack traces are desired. It is the responsibility
 *     of the individual plugin implementation to honor this option.
 *

 *
 *
-explain
 *
By default, the output of a validity check will be a short message with
 *     enough detail to allow a knowledgeable user to interpret it; however, it
 *     may not be understandable to a novice user. The -explain
 *     option is a hint that may result in the generation of additional output
 *     describing the purpose and context of the check. An explanation is output
 *     the first time its associated message is output, and is not repeated. It
 *     is the responsibility of the individual plugin implementation to honor
 *     this option.
 *

 *
 *
-level <var>info|warning|error</var>
 *
The tool supports three severity levels for message generation.
 *

 *

 *
<var>info</var>
 *
'success' messages or other non-failure oriented configuration data
 *
<var>warning</var>
 *
a condition or value has been detected that is 'legal', but which
 *         could result in unintended behavior. An example is the use of
 *         localhost in a codebase annotation.
 *
<var>error</var>
 *
a condition has been detected that is likely due to an error
 *         on the command line or in a configuration file. An example is
 *         assigning the value of a non-existant file name to the
 *         java.util.logging.config.file system property.
 *

 *

 *     This option is used to set the level at which message records are
 *     generated. The default value is <var>warning</var>.
 *

 *
 *
-plugin <var>file</var>

 *
Identifies a JAR file containing user supplied plugins that will be run
 *     after the standard plugins are run. All of the necessary support classes
 *     and resources required to support the plugins must be included in this
 *     file. The file must also include a resource named
 *     META-INF/services/org.apache.river.tool.envcheck.Plugin, which
 *     contains the class names of the plugins to run listed one per line.
 *     Every class listed must implement the
 *     org.apache.river.tool.envcheck.Plugin interface. This option
 *     may be supplied zero or more times.
 *

 *
 *
-security
 *
A plugin specific option that is recognized by one of the bundled
 *     plugins.  Specifying this option will activate a number of JAAS and JSSE
 *     checks. User supplied plugins wishing to recognize this option must
 *     implement the isPlugOption method of the
 *     Plugin interface.
 *

 *

 *

 *
 *
Examples

 * The following example will analyze a command line used to start a user
 * service. The command being analyzed defines a classpath and two system
 * properties, and names a class containing a main method:

 *

 *

 * java -jar <var>install_dir</var>/lib/envcheck.jar -level info -explain -traces \
 *      java -cp <var>mylib_dir</var>/myservice.jar:/jini/lib/jsk-platform.jar \
 *           -Djava.security.policy=<var>my_policy</var> \
 *           -Djava.server.rmi.codebase=http://myhost/myservice-dl.jar \
 *           myservice.MyServiceImpl
 *

 * In this case, the tool is limited to performing validity checks on the
 * classpath, policy, and codebase values identified by the system properties
 * and options provided on the service command line. The -level,
 * -explain, and -traces options supplied will result
 * in the most verbose output possible from the tool.
 *

 * The following example will analyze a command line used to start reggie using
 * the service starter. The command being analyzed uses a policy and service
 * starter configuration located in the working directory:
 *

 *

 * java -jar <var>install_dir</var>/lib/envcheck.jar -level error \
 *      java -Djava.security.policy=<var>my_starterpolicy</var> \
 *           -jar <var>install_dir</var>/lib/start.jar reggie.config
 *

 * The tool can perform many more checks in this case because the
 * bundled plugins include built-in knowledge about the service starter
 * and its public configuration entries. The tool options used will minimize
 * the output produced by the tool.
 *

 *
 *
Bundled Plugins

 * A set of plugins are loaded automatically by the tool to perform some
 * basic analysis.
 *

 * If the command line being analyzed invokes the service starter, the tool will
 * create a Configuration from the arguments of the command line
 * being analyzed. Failure to create the Configuration will result
 * in termination of the tool, otherwise the
 * org.apache.river.start.ServiceDescriptors provided by the
 * Configuration are examined. The following checks are done for
 * each ServiceDescriptor:
 *

 *
Verify that the getPolicy method returns a reference to a
 *      policy file that is valid and accessible
 *
Check whether that policy grants AllPermissions to all
 *      protection domains
 *

 * The following checks are done for each
 * NonActivatableServiceDescriptor and each
 * SharedActivatableServiceDescriptor
 *

 *
Verify that calling getServerConfigArgs does not return
 *      null or an empty array
 *
Verify that a Configuration can be constructed from those
 *      args
 *
Verify that any entry in that Configuration named
 *      initialLookupGroups does not have a value of
 *      ALL_GROUPS
 *
Verify that the export codebase is defined. For each component in the
 *      export codebase:
 *

 *
Verify that the URL is not malformed
 *
If it is an HTTPMD URL, verify that the necessary protocol handler
 *         is installed
 *
Check that domain names are fully qualified
 *
Warn if an md5 HTTPMD URL is being used (md5 has a security hole)
 *
Verify that the host name in the URL can be resolved
 *
Verify that the host name does not resolve to a loopback address
 *
Verify that it's possible to open a connection using the URL
 *

 *
If the -security option was specified:
 *

 *
Verify that javax.net.ssl.trustStore is defined and
 *            that the trust store it references is accessible
 *
Check whether org.apache.river.discovery.x500.trustStore
 *            is defined, and if so that the trust store it references is
 *            accessible
 *
Check whether javax.net.ssl.keyStore is defined, and
 *            if so that the key store it references is accessible
 *
Verify that a login configuration is defined and that it is
 *            accessible and syntactically correct
 *

 *

 * The following checks are done for each
 * SharedActivatableServiceDescriptor:
 *

 *
Verify that any entry in that Configuration named
 *       persistenceDirectory refers to either an empty directory
 *       or a non-existant directory
 *

 * The following checks are done for each
 * SharedActivationGroupDescriptor:
 *

 *
Verify that the activation system is running
 *
Verify that the virtual machine (VM) created by that command is at
 *       least version 1.4
 *
Verify that jsk-policy.jar is loaded from the extensions
 *       directory
 *
 *
Verify that jsk-platform.jar is in the classpath
 *
 *
 *
If java.util.logging.config.file is defined in the
 *       properties returned by calling getServerProperties then
 *       verify that the file it references is accessible
 *

 *  A subset of these checks are performed on the command line being analyzed:
 *

 *
Codebase/URL checks based on the value of
 *        java.rmi.server.codebase
 *
Policy file checks based on the value of
 *        java.security.policy
 *
Check for jsk-policy being loaded by the extension
 *        class loader
 *
Check for jsk-platform in the classpath
 *
Security checks if -security was specified
 *
The logging config file check
 *

 * In all cases, check that the local host name does not resolve to the
 * loopback address.
 */

public class EnvCheck {

    /** the list of plugins instances to run */
    private ArrayList pluginList = new ArrayList();

    /** flag controlling the display of stack traces in the output */
    private boolean printStackTraces = false;

    /** the command line arguments of the command being analyzed */
    private String[] args;

    /** the ServiceDescriptors obtained from the starter config */
    private ServiceDescriptor[] descriptors = new  ServiceDescriptor[0];

    /** the localization resource bundle */
    private static ResourceBundle bundle;

    /** the java command on the command line being checked */
    private String javaCmd;

    /** the options on the command line being checked (never null) */
    String[] options = new String[0];

    /** the properties on the command line being checked (never null) */
    Properties properties = new Properties();

    /** the classpath on the command line being checked */
    String classpath = null;

    /** the main class on the command line being checked */
    String mainClass = null;

    /** the executable JAR file on the command line being checked */
    String jarToRun = null;

    /** the list of plugins supplied via the -plugin option */
    static ArrayList pluginJarList = new ArrayList();

    /** the class loader for loading plugins */
    ClassLoader pluginLoader = EnvCheck.class.getClassLoader();

    /** the classpath of the tool, including the plugins (updated in run) */
    static String combinedClasspath = System.getProperty("java.class.path");

    /**
     * The entry point for the tool. The localization resource bundle is
     * located, the plugins are loaded, and the checks are performed. The system
     * property java.protocol.handler.pkgs for the tool VM is set
     * to net.jini.url to ensure that the tool can manipulate
     * HTTPMD URLs.
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
	System.setProperty("java.protocol.handler.pkgs", "net.jini.url");
	bundle = Util.getResourceBundle(EnvCheck.class);
	if (args.length == 0) {
	    usage();
	    System.exit(1);
	}
        findPlugins(args);
	new EnvCheck().run(args);
    }

    /**
     * Output the usage message.
     */
    private static void usage(){
	System.err.println(Util.getString("envcheck.usage", bundle));
    }

    /**
     * Helper to print a localized string
     *
     * @param key the resource key
     */
    private String getString(String key) {
	return Util.getString(key, bundle);
    }

    /**
     * Helper to print a localized string
     *
     * @param key the resource key
     * @param val the value parameter expected by the message
     */
    private String getString(String key, String val) {
	return Util.getString(key, bundle, val);
    }

    /**
     * Search the command line for user supplied plugin definitions
     * and place them in the internal plugin list.
     *
     * @param cmdLine the original command line args
     */
    private static void findPlugins(String[] cmdLine) {
	int index = 0;
	String arg;
	while ((arg = cmdLine[index++]).startsWith("-")) {
	    if (arg.equals("-plugin")) {
		String pluginName = cmdLine[index++];
		if (!(new File(pluginName).exists())) {
		    System.err.println(Util.getString("envcheck.noplugin",
				       bundle,
				       pluginName));
		    System.exit(1);
		}
		combinedClasspath += File.pathSeparator + pluginName;
		try {
		    pluginJarList.add(new URL("file:" + pluginName));
		} catch (MalformedURLException e) { // should never happen
		    e.printStackTrace();
		    System.exit(1);
		}
	    } else if (arg.equals("-level")) {
		index++;
	    }
	}
    }

    /**
     * Parse the command line, identifying options for the tool and parsing
     * the VM, system properties, options, JAR/main class and arguments
     * for the command line being tested. The -plugin option
     * is ignored by this parser since they must have been processed
     * earlier.
     *
     * @param cmdLine the original command line arguments
     */
    private void parseArgs(String[] cmdLine) {
	int index = 0;
	try {
	    while (true) {
		String arg = cmdLine[index++];
		if (arg.equals("-traces")) {
		    printStackTraces = true;
		    Reporter.setPrintTraces(true);
		} else if (arg.equals("-explain")) {
		    Reporter.setExplanation(true);
		} else if (arg.equals("-level")) {
		    String val = cmdLine[index++];
		    if (val.equals("info")) {
			Reporter.setLevel(Reporter.INFO);
		    } else if (val.equals("warning")) {
			Reporter.setLevel(Reporter.WARNING);
		    } else if (val.equals("error")) {
			Reporter.setLevel(Reporter.ERROR);
		    } else {
			System.err.println(getString("envcheck.badlevel"));
			usage();
			System.exit(1);
		    }
	        } else if (arg.equals("-plugin")) {
		    index++; // already processed the plugin
		} else if (isPluginOption(arg)) { //no additional work to do
		} else if (arg.startsWith("-")) {
		    System.err.println(getString("envcheck.illegalopt", arg));
		    usage();
		    System.exit(1);
		} else if (arg.endsWith("java")) {
		    javaCmd = arg;
		    break;
		} else {
		    System.err.println(getString("envcheck.nojavacmd"));
		    usage();
		    System.exit(1);
		}
	    }
	} catch (ArrayIndexOutOfBoundsException e) {
	    System.err.println(getString("envcheck.nocmdargs"));
	    usage();
	    System.exit(1);
	}
	try {
	    ArrayList optList = new ArrayList();
	    while (true) {
		String opt = cmdLine[index++];
		if (!opt.startsWith("-")) {
		    mainClass = opt;
		    break;
		} else if (opt.startsWith("-D")) {
		    int valueIndex = opt.indexOf("=");
		    String key = opt.substring(2, valueIndex);
		    String value = opt.substring(valueIndex + 1);
		    properties.put(key, value);
		} else if (opt.equals("-cp") || opt.equals("-classpath")) {
		    classpath = cmdLine[index++];
		} else if (opt.equals("-jar")) {
		    jarToRun = cmdLine[index++];
		    break;
		} else {
		    optList.add(opt);
		}
	    }
	    options =
		(String[])  optList.toArray(new String[optList.size()]);
	} catch (ArrayIndexOutOfBoundsException e) {
	    System.err.println(getString("noexecutable"));
	    usage();
	    System.exit(1);
	}
	ArrayList argList = new ArrayList();
	while (index < cmdLine.length) {
	    argList.add(cmdLine[index++]);
	}
	args = (String[]) argList.toArray(new String[argList.size()]);
    }

    /**
     * Return the ServiceDescriptors contained in the service
     * starter configuration. If the command being analyzed does not invoke the
     * service starter, a zero-length array will be returned.
     *
     * @return the descriptors in the starter configuration or an empty array
     */
    public ServiceDescriptor[] getDescriptors() {
	return descriptors;
    }

    /**
     * Return the SharedActivationGroupDescriptor contained in the
     * service starter configuration. Returns null if there is no
     * such descriptor, or if the command being analyzed does not invoke the
     * service starter.
     *
     * @return the SharedActivationGroupDescriptor or
     *         null
     */
    public SharedActivationGroupDescriptor getGroupDescriptor() {
	for (int i = 0; i < descriptors.length; i++) {
	    if (descriptors[i] instanceof SharedActivationGroupDescriptor) {
		return (SharedActivationGroupDescriptor) descriptors[i];
	    }
	}
	return null;
    }

    /**
     * Perform the runtime checks. If any user plugins were supplied, construct
     * a class loader capable of loading them and modify
     * combinedClasspath to make the classes available to subtasks.
     * Load the plugins and parse the command line. The plugins must be
     * available to the parser so that plugin specific options can be checked
     * for. Load the service starter configuration if the service starter is
     * being invoked. Execute all of the plugin classes in the order loaded.
     *
     * @param cmdLine the original command line arguments
     */
    private void run(String[] cmdLine) {
	if (pluginJarList.size() > 0) {
	    URL[] urls =
		(URL[]) pluginJarList.toArray(new URL[pluginJarList.size()]);
	    pluginLoader = new RFC3986URLClassLoader(urls, pluginLoader);
	}
	loadPlugins();
	parseArgs(cmdLine);
	if (jarToRun == null && classpath == null) {
	    System.err.println(getString("envcheck.missingclasspath"));
	    System.exit(1);
	}
	loadConfiguration();
	Iterator plugins = pluginList.iterator();
	while (plugins.hasNext()) {
	    Plugin plugin = (Plugin) plugins.next();
	    try {
		plugin.run(this);
	    } catch (SecurityException e) { // limp on if permission check fails
		e.printStackTrace();
	    }
	}
	int warningCount = Reporter.getWarningCount();
	int errorCount = Reporter.getErrorCount();
	if ((warningCount + errorCount) > 0) {
	    System.out.println();
	    System.out.println();
	    System.out.println(getString("envcheck.summaryseparator"));
	}
	if (warningCount > 0) {
	    System.out.println(getString("envcheck.warningheader")
			       + warningCount);
	}
	if (errorCount > 0) {
	    System.out.println(getString("envcheck.errorheader") + errorCount);
	}

    }

    /**
     * Check whether arg is a plugin specific option. The
     * isPluginOption method of every plugin is called in
     * case an option is shared among multiple plugins.
     *
     * @param arg the argument to check
     * @return true if any plugin's isPluginOption
     *         method returns true
     */
    private boolean isPluginOption(String arg) {
	boolean gotOne = false;
	Iterator plugins = pluginList.iterator();
	while (plugins.hasNext()) {
	    Plugin plugin = (Plugin) plugins.next();
	    if (plugin.isPluginOption(arg)) {
		gotOne = true;
	    }
	}
	return gotOne;
    }

    /**
     * Instantiate the service starter configuration if the command line being
     * analyzed runs the service starter.  This is assumed to be true if the
     * command line specified an executable JAR file named start.jar and
     * if that file resides in the same directory as a file named
     * jsk-platform.jar. Extract and save all of the service
     * descriptors and service destructors from the configuration. If a
     * ConfigurationException is thrown the tool will exit. If
     * there are no ServiceDescriptor or
     * ServiceDestructor entries supplied by the configuration a
     * error is generated and a normal return is done. The instantiation of
     * the configuration is done in a child process using the VM, properties,
     * options and arguments supplied in the command line under test.
     */
    private void loadConfiguration() {
	if (jarToRun != null) {
	    if (!jarToRun.endsWith("start.jar")) {
		return;
	    }
	    //XXX do existence check in parser
	    File starterFile = new File(jarToRun);
	    File jskLibDir = starterFile.getParentFile();
	    File jskplatform = new File(jskLibDir, "jsk-platform.jar");
	    if (!jskplatform.exists()) {
		return; // presumably a user file coincidentally named start.jar
	    }
	} else {
	    if (!mainClass.equals("org.apache.river.start.ServiceStarter")) {
		return;
	    }
	}
	//XXX need to check validity of javaCmd and arg list length
	Object lobj =
	    launch("org.apache.river.tool.envcheck.EnvCheck$GetDescriptors", args);
	if (lobj instanceof ServiceDescriptor[]) {
	    descriptors = (ServiceDescriptor[]) lobj;
	    if (descriptors.length == 0) {
		Reporter.print(new Message(Reporter.ERROR,
					   getString("envcheck.emptyconfig"),
					   null));
	    }
	} else if (lobj instanceof ConfigurationException) {
	    System.err.println(getString("envcheck.ssdescfailed"));
	    ((Throwable) lobj).printStackTrace();
	    System.exit(1);
	} else {
	    System.err.println(getString("envcheck.subtaskex", lobj.toString()));
	    ((Throwable) lobj).printStackTrace();
	    System.exit(1);
	}
    }

    /**
     * Load the plugin classes. All of the resources named
     * META-INF/services/org.apache.river.tool.envcheck.Plugin are
     * read; each such resource is expected to contain a list of plugin class
     * names, one per line (white space is trimmed). The corresponding classes
     * are loaded and saved. Any other exceptions thrown while processing
     * the plugin JAR files will cause the tool to exit.
     */
    private void loadPlugins() {
	Package pkg = getClass().getPackage();
	String pkgName = "";
	if (pkg != null) {
	    pkgName = pkg.getName();
	}
	pkgName = pkgName.replace('.', '/');
	if (pkgName.length() > 0) {
	    pkgName += "/";
	}
	Iterator plugins =
	    Service.providers(org.apache.river.tool.envcheck.Plugin.class,
			      pluginLoader);
	while (plugins.hasNext()) {
	    pluginList.add(plugins.next());
	}
    }

    /**
     * Get the command line arguments of the command being analyzed.
     *
     * @return the args
     */
    // unused, but supplied to support user developed plugins
    public String[] getArgs() {
	return args;
    }

    /**
     * Return the flag indicating whether to output stack traces that
     * result from a check.
     */
    public boolean printStacks() {
	return printStackTraces;
    }

    /**
     * Launch a child VM using the java command, properties, and
     * options supplied on the command line being analyzed. If an executable JAR
     * file was specified, the classpath of the child VM consists of the JAR
     * file name augmented with the classpath of the tool and plugins. If a main
     * class was specified, the classpath of the child VM consists of the
     * -cp/-classpath option value of the command line being
     * analyzed augmented with the classpath of the tool and plugins.
     *
     * @param task the class name of the task to launch, which must implement
     *             the SubVMTask interface
     * @param args the arguments to pass to the main method of the task
     * @return the result or exception returned by the subtask supplied as a
     *         serialized object written on the subtask's
     *         System.out stream.
     */
    public Object launch(String task, String[] args) {
	String cp;
	if (jarToRun != null) {
	    cp = jarToRun + File.pathSeparator;
	} else {
	    cp = classpath + File.pathSeparator;
	}
	cp += combinedClasspath;
	String[] opts = new String[options.length + 2];
	opts[0] = "-cp";
	opts[1] = cp;
	System.arraycopy(options, 0, opts, 2, options.length);
	if (args == null) {
	    args = new String[0];
	}
	String[] subvmArgs = new String[args.length + 1];
	subvmArgs[0] = task;
	System.arraycopy(args, 0, subvmArgs, 1, args.length);
	return launch(javaCmd, properties, opts, subvmArgs);
    }

    /**
     * Launch a child VM using the java command, properties, and
     * options supplied on the command line. If an executable JAR file was
     * specified, the classpath of the child VM consists of the JAR file name
     * augmented with the classpath of the tool and plugins. If a main class was
     * specified, the classpath of the child VM consists of the
     * -cp/-classpath option value of the command line being
     * analyzed augmented with the classpath of the tool and plugins.
     *
     * @param task the class name of the task to launch, which must implement
     *             the SubVMTask interface
     * @return the result or exception returned by the subtask supplied as a
     *         serialized object written on the subtask's
     *         System.out stream.
     */
    public Object launch(String task) {
	return launch(task, null);
    }

    /**
     * Return a property value that was specified on the command line being
     * analyzed. Only properties explicitly defined on the command line will
     * resolve to a value.
     *
     * @param key the name of the property
     * @return the property value, or null if undefined
     */
    public String getProperty(String key) {
	return properties.getProperty(key);
    }

    /**
     * Return a copy of the properties that were specified on the
     * command line being analyzed. The caller may modify the returned
     * properties object.
     *
     * @return the properties, which may be empty
     */
    public Properties getProperties() {
	return (Properties) properties.clone();
    }

    /**
     * Launch a subtask VM using the java command given by
     * javaCmd.  If javaCmd is null, the
     * command to run is derived from the value of the java.home
     * property of the tool VM.  The first value in args must name
     * a class that implements the SubVMTask interface. The
     * props and opts arrays must contain fully
     * formatted command line values for properties and options
     * (i.e. "-Dfoo=bar" or "-opt"). opts must include a
     * -cp or -classpath option and its value must
     * completely specify the classpath required to run the subtask.
     *
     * @param javaCmd the java command to execute, or
     *                null to create another instance of the
     *                tool VM
     * @param props   properties to define, which may be null or
     *                empty
     * @param opts    options to define, which must include a classpath
     *                definition
     * @param args    arguments to pass to the child VM
     * @return        the result or exception returned by the subtask supplied
     *                as a serialized object written on the subtask's
     *                System.out stream.
     *
     * @throws IllegalArgumentException if opts does not
     *         include a classpath definition, or if args[0]
     *         does not contain the name of a class that implements
     *         SubVMTask
     */
    public Object launch(String javaCmd,
			 Properties props,
			 String[] opts,
			 String[] args)
    {
	if (args == null || args.length == 0) {
	    throw new IllegalArgumentException("No class name in args[0]");
	}
	// make sure subtask is valid to avoid obscure failures at exec time
	String taskName = args[0];
	try {
	    Class taskClass = Class.forName(taskName, true, pluginLoader);
	    if (!SubVMTask.class.isAssignableFrom(taskClass)) {
		throw new IllegalArgumentException(taskName
						   + " does not implement "
						   + "SubVMTask");
	    }
	    // make sure inner classes are static
	    if (taskClass.getDeclaringClass() != null) {
		if ((taskClass.getModifiers() & Modifier.STATIC) == 0) {
		    throw new IllegalArgumentException(taskName
						   + " must be a static class");
		}
	    }
	} catch (ClassNotFoundException e) {
	    throw new IllegalArgumentException("Class not found: " + taskName);
	}
	if (javaCmd == null) {
	    javaCmd = System.getProperty("java.home");
	    javaCmd += File.separator + "bin" + File.separator + "java";
	}
	ArrayList cmdList = new ArrayList();
	cmdList.add(javaCmd);
	boolean gotClasspath = false;
	if (opts != null) {
	    for (int i = 0; i < opts.length; i++) {
		if (opts[i].equals("-cp") || opts[i].equals("-classpath"))
		    if (i + 1 == opts.length) {
			throw new IllegalArgumentException("classpath option "
							   + "does not have "
							   + "a value");
		    }
		gotClasspath = true;
		cmdList.add(opts[i]);
	    }
	}
	if (!gotClasspath) {
	    throw new IllegalArgumentException("no classpath defined");
	}
	if (props != null) {
	    Enumeration en = props.propertyNames();
	    while (en.hasMoreElements()) {
		String key = (String) en.nextElement();
		String value = props.getProperty(key);
		cmdList.add("-D" + key + "=" + value);
	    }
	}
	cmdList.add("org.apache.river.tool.envcheck.SubVM");
	for (int i = 0; i < args.length; i++) {
	    cmdList.add(args[i]);
	}
	try {
	    String[] argList =
		(String[]) cmdList.toArray(new String[cmdList.size()]);
//  	    for (int i = 0; i < argList.length; i++) {
//  		System.out.print(argList[i] + " ");
//  	    }
//  	    System.out.println();
	    Process p = Runtime.getRuntime().exec(argList);
	    Pipe pipe = new Pipe("errorPipe",
				 p.getErrorStream(),
				 System.err,
				 "Child VM: ");
	    ObjectInputStream s = new ObjectInputStream(p.getInputStream());
	    Object o = s.readObject();
	    pipe.waitTillEmpty(5000);
	    return o;
	} catch (Exception e) {
	    return e;
	}
    }

    /**
     * Launch a subtask using the environment defined by the given service
     * descriptors. Calling this method is equivalent to calling
     * launch(d, g, taskName, null).
     *
     * @param d the services descriptor, which may be null
     * @param gd the group descriptor, which may be null
     * @param taskName the name of the subtask to run
     * @return the result or exception returned by the subtask supplied as a
     *         serialized object written on the subtask's
     *         System.out stream.
     */
    public Object launch(NonActivatableServiceDescriptor d,
			 SharedActivationGroupDescriptor gd,
			 String taskName)
    {
	return launch(d, gd, taskName, null);
    }

    /**
     * Launch a subtask using the environment defined by the given service
     * descriptors.
     *

     * If d and gd are both null, then
     * calling this method is equivalent to calling
     * launch(taskName, args).
     *

     * If d is null and gd is
     * non-null then the properties are taken from
     * gd.getServerProperties() and the
     * java.security.policy property is added or replaced with the
     * value of gd.getPolicy().  The options are taken from
     * gd.getServerOptions(), but any -cp/-classpath
     * option is discarded; a -cp option is added that is the value
     * of gd.getClasspath() augmented with the classpath of the
     * tool and plugins.  If gd.getServerCommand() is
     * non-null, its value is used to invoke the child VM;
     * otherwise the java command of the command line being
     * analyzed is used. The arguments passed to the child VM consist of an
     * array whose first element is taskName and whose remaining
     * elements are taken from args.

     *

     * If d is not null, but gd is
     * null, then if d is an instance of
     * SharedActivatableServiceDescriptor an
     * IllegalArgumentException is thrown. Otherwise the properties
     * and options are taken from the command line being analyzed. The
     * java.security.policy property is added or replaced using the
     * value of d.getPolicy().  The -cp/-classpath
     * option is replaced with the value of d.getImportCodebase()
     * augmented with the classpath of the tool and plugins.  The arguments
     * passed to the child VM consist of taskName followed by
     * args if args is non-null, or
     * followed by d.getServerConfigArgs() otherwise.  The VM is
     * invoked using the java command of the command line being
     * analyzed.

     *

     * if d and gd are both non-null then
     * if d is an instance of
     * SharedActivatableServiceDescriptor then the properties,
     * options, and java command are taken from
     * gd.getServerProperties(),
     * gd.getServerOptions(), and
     * gd.getServerCommand(); however, if the value of
     * gd.getServerCommand() is null, the
     * java command is taken from the command line being
     * analysed. If d is not an instance of
     * SharedActivatableServiceDescriptor then the properties,
     * options, and java command are taken from the command line
     * being analyzed.  In all cases the java.security.policy
     * property is added or replaced using the value of
     * d.getPolicy().  The -cp/-classpath option is
     * added or replaced with the value of d.getImportCodebase()
     * augmented with the value of the classpath of the tool and plugins.  The
     * arguments passed to the child VM consist of taskName
     * followed by args if args is
     * non-null, or followed by
     * d.getServerConfigArgs() otherwise.

     *

     *
     * @param d the service descriptor, which may be null
     * @param gd the group descriptor, which may be null
     * @param taskName the name of the subtask to run
     * @param args the arguments to pass to the child VM, which may be
     *             null
     * @return the result or exception returned by the subtask supplied as a
     *         serialized object written on the subtask's
     *         System.out stream.
     */
    public Object launch(NonActivatableServiceDescriptor d,
			 SharedActivationGroupDescriptor gd,
			 String taskName,
			 String[] args)
    {
	if (d == null && gd == null) {
	    return launch(taskName, args);
	}
	//build taskArgs array
	if (args == null) {
	    if (d != null) {
		args = d.getServerConfigArgs();
		if (args == null || args.length == 0) {
		    return new IllegalArgumentException("No configuration args "
							+ "in descriptor");
		}
	    } else {
		args = new String[0];
	    }
	}
	String[] taskArgs = new String[args.length + 1];
	taskArgs[0] = taskName;
	System.arraycopy(args, 0, taskArgs, 1, args.length);

	if (d == null && gd != null) {
	    Properties props = gd.getServerProperties();
	    props.put("java.security.policy", gd.getPolicy());
	    ArrayList l = new ArrayList();
	    String[] opts = gd.getServerOptions();
	    if (opts != null) {
		for (int i = 0; i < opts.length; i++ ) {
		    if (opts[i].equals("-cp")) {
			i++; // bump past value
		    } else {
			l.add(opts[i]);
		    }
		}
	    }
	    l.add("-cp");
	    l.add(gd.getClasspath() + File.pathSeparator + combinedClasspath);
	    opts = (String[]) l.toArray(new String[l.size()]);
	    String cmd = gd.getServerCommand();
	    if (cmd == null) {
		cmd = javaCmd;
	    }
	    return launch(cmd, props, opts, taskArgs);
	} else if (d != null && gd == null) {
	    if (d instanceof SharedActivatableServiceDescriptor) {
		throw new IllegalArgumentException("no group for service");
	    }
	    Properties props = getProperties();
	    props.put("java.security.policy", d.getPolicy());
	    ArrayList l = new ArrayList();
	    for (int i = 0; i < options.length; i++ ) {
		if (options[i].equals("-cp")
		    || options[i].equals("-classpath")) {
		    i++; // bump past value
		} else {
		    l.add(options[i]);
		}
	    }
	    l.add("-cp");
	    l.add(d.getImportCodebase()
		    + File.pathSeparator
		    + combinedClasspath);
	    String[] opts = (String[]) l.toArray(new String[l.size()]);
	    return launch(javaCmd, props, opts, taskArgs);
	} else if (d != null && gd != null) {
	    Properties props = getProperties();
	    String[] opts = options;
	    String vm = null;
	    if (d instanceof SharedActivatableServiceDescriptor) {
		props = gd.getServerProperties();
		if (props == null) {
		    props = new Properties();
		}
		opts = gd.getServerOptions();
		vm = gd.getServerCommand();
	    }
	    if (vm == null) {
		vm = javaCmd;
	    }
	    props.put("java.security.policy", d.getPolicy());
	    ArrayList l = new ArrayList();
	    if (opts != null) {
		for (int i = 0; i < opts.length; i++ ) {
		    if (opts[i].equals("-cp")
		     || opts[i].equals("-classpath")) {
			i++; // bump past value
		    } else {
			l.add(opts[i]);
		    }
		}
	    }
	    l.add("-cp");
	    l.add(d.getImportCodebase()
		  + File.pathSeparator
		  + combinedClasspath);
	    opts = (String[]) l.toArray(new String[l.size()]);
	    return launch(vm, props, opts, taskArgs);
	} else {
	    throw new IllegalStateException("Should never get here");
	}
    }

    /**
     * Return the java command for the command line being analyzed.
     *
     * @return the java command
     */
    public String getJavaCmd() {
	return javaCmd;
    }

    /**
     * Check for the existence of a file identified by a property
     * supplied on the command line being analyzed.
     *
     * @param prop the name of the property
     * @param desc a brief description of the file
     * @return the property value, or null if undefined
     */
    public String checkFile(String prop, String desc) {
	String name = getProperty(prop);
	if (name == null) {
	    return getString("util.undef", desc);
	}
	return Util.checkFileName(name, desc);
    }

    /**
     * Return the name of the executable JAR file supplied on the
     * command line being analyzed.
     *
     * @return the JAR file name, or null if the command line
     *         did not specify one.
     */
    public String getJarToRun() {
        return jarToRun;
    }

    /**
     * Get the classpath provided by the command line being analyzed.  If
     * getJarToRun() returns a non-null value then
     * its value is returned. Otherwise the value supplied by the command
     * line -cp/-classpath option is returned.
     *
     * @return the classpath supplied on the command line being analyzed.
     */
    public String getClasspath() {
	if (jarToRun != null) {
	    return jarToRun;
	}
	return classpath;
    }

    /**
     * A subtask which returns the service descriptors and service
     * destructors supplied by the service starter configuration constructed
     * from args.
     */
     static class GetDescriptors implements SubVMTask {

	public Object run(String[] args) {
	    Configuration starterConfig = null;
	    try {
		starterConfig = ConfigurationProvider.getInstance(args);
	    } catch (ConfigurationException e) {
		return e;
	    }
	    try {
		ServiceDescriptor[] d1 =  (ServiceDescriptor[])
		    starterConfig.getEntry("org.apache.river.start",
					   "serviceDescriptors",
					   ServiceDescriptor[].class,
					   new ServiceDescriptor[0]);
		ServiceDescriptor[] d2 =  (ServiceDescriptor[])
		    starterConfig.getEntry("org.apache.river.start",
					   "serviceDestructors",
					   ServiceDescriptor[].class,
					   new ServiceDescriptor[0]);
		ServiceDescriptor[] descriptors =
		    new ServiceDescriptor[d1.length + d2.length];
		System.arraycopy(d1, 0, descriptors, 0, d1.length);
		System.arraycopy(d2, 0, descriptors, d1.length, d2.length);
		return descriptors;
	    } catch (ConfigurationException e) {
		return e;
	    }
	}
    }

    /**
     * An I/O redirection pipe. A daemon thread copies data from an input
     * stream to an output stream. An optional annotation may be provided
     * which will prefix each line of the copied data with a label which
     * can be used to identify the source.
     */
    private class Pipe implements Runnable {

	/** the line separator character */
	private final static byte SEPARATOR = (byte) '\n';

	/** output line buffer */
	private ByteArrayOutputStream bufOut = new ByteArrayOutputStream();

	/** the input stream */
	private InputStream in;

	/** the output PrintStream */
	private PrintStream stream;

	/** the output stream annotation */
	private String annotation;

	/** the thread to process the data */
	private Thread outThread;

	/**
	 * Create a new Pipe object and start the thread to handle the data.
	 *
	 * @param name the name to assign to the thread
	 * @param in input stream from which pipe input flows
	 * @param stream the stream to which output will be sent
	 * @param a the annotation for prepending text to logged lines
	 */
	Pipe(String name,
		    InputStream in,
		    PrintStream stream,
		    String a)
	{
	    this.in = in;
	    this.stream = stream;
	    this.annotation = a;
	    outThread = new Thread(this, name);
	    outThread.setDaemon(true);
	    outThread.start();
	}

	/**
	 * Wait until the run method terminates due to reading EOF on input
	 *
	 * @param timeout max time to wait for the thread to terminate
	 */
	void waitTillEmpty(int timeout) {
	    try {
		outThread.join(timeout);
	    } catch (InterruptedException ignore) {
	    }
	}

	/**
	 * Read and write data until EOF is detected. Flush any remaining data to
	 * the output steam and return, terminating the thread.
	 */
	public void run() {
	    byte[] buf = new byte[256];
	    int count;
	    try {
		/* read bytes till there are no more. */
		while ((count = in.read(buf)) != -1) {
		    write(buf, count);
		}

		/*  If annotating, flush internal buffer... may not have ended on a
		 *  line separator, we also need a last annotation if
		 *  something was left.
		 */
		String lastInBuffer = bufOut.toString();
		bufOut.reset();
		if (lastInBuffer.length() > 0) {
		    if (annotation != null) {
			stream.print(annotation);
		    }
		    stream.println(lastInBuffer);
		}
	    } catch (IOException e) {
	    }
	}

	/**
	 * Write each byte in the give byte array.
	 *
	 * @param b the array of input bytes
	 * @param len the number data bytes in the array
	 */
	private void write(byte b[], int len) throws IOException {
	    if (len < 0) {
		throw new ArrayIndexOutOfBoundsException(len);
	    }
	    for (int i = 0; i < len; i++) {
		write(b[i]);
	    }
	}

	/**
	 * If not annotated, write the byte to the stream immediately. Otherwise,
	 * write a byte of data to the internal buffer. If we have matched a line
	 * separator, then the currently buffered line is sent to the output writer
	 * with a prepended annotation string.
	 */
	private void write(byte b) throws IOException {

	    bufOut.write(b);

	    // write buffered line if line separator detected
	    if (b == SEPARATOR) {
		String s = bufOut.toString();
		bufOut.reset();
		if (annotation != null) {
		    stream.print(annotation);
		}
		stream.print(s);
	    }
	}
    }
}


text:
package org.spongepowered.api.text.format;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.reflect.TypeToken;
import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.TextElement;
import org.spongepowered.api.text.serializer.TextFormatConfigSerializer;

/**
 * Represents a pair of {@link TextStyle} and {@link TextColor}.
 */
public final class TextFormat implements TextElement {

    static {
        TypeSerializers.getDefaultSerializers().registerType(TypeToken.of(TextFormat.class), new TextFormatConfigSerializer());
    }

    /**
     * An empty {@link TextFormat} with no {@link TextColor} and no {@link TextStyle}.
     */
    public static final TextFormat NONE = new TextFormat(TextColors.NONE, TextStyles.NONE);

    /**
     * The text color.
     */
    private final TextColor color;

    /**
     * The text style.
     */
    private final TextStyle style;

    /**
     * Gets the {@link TextFormat} with the default style and color.
     *
     * @return The empty text format
     */
    public static TextFormat of() {
        return NONE;
    }

    /**
     * Constructs a new {@link TextFormat} with the specific style.
     *
     * @param style The style
     * @return The new text format
     */
    public static TextFormat of(TextStyle style) {
        return new TextFormat(TextColors.NONE, style);
    }

    /**
     * Constructs a new {@link TextFormat} with the specific color.
     *
     * @param color The color
     * @return The new text format
     */
    public static TextFormat of(TextColor color) {
        return new TextFormat(color, TextStyles.NONE);
    }

    /**
     * Constructs a new {@link TextFormat} with the specific color and style.
     *
     * @param color The color
     * @param style The style
     * @return The new text format
     */
    public static TextFormat of(TextColor color, TextStyle style) {
        return new TextFormat(color, style);
    }

    /**
     * Constructs a new {@link TextFormat}.
     *
     * @param color The color
     * @param style The style
     */
    private TextFormat(TextColor color, TextStyle style) {
        this.color = checkNotNull(color, "color");
        this.style = checkNotNull(style, "style");
    }

    /**
     * Returns the {@link TextColor} in this format.
     *
     * @return The color
     */
    public TextColor getColor() {
        return this.color;
    }

    /**
     * Returns the {@link TextStyle} in this format.
     *
     * @return The style
     */
    public TextStyle getStyle() {
        return this.style;
    }

    /**
     * Returns a new {@link TextFormat} with the given color.
     *
     * @param color The color
     * @return The new text format
     */
    public TextFormat color(TextColor color) {
        return new TextFormat(color, this.style);
    }

    /**
     * Returns a new {@link TextFormat} with the given style.
     *
     * @param style The style
     * @return The new text format
     */
    public TextFormat style(TextStyle style) {
        return new TextFormat(this.color, style);
    }

    /**
     * Returns a new {@link TextFormat} that combines this and the given format.
     * The given format takes higher priority than this one. Due to this the
     * color will only fallback to this one if the given format's color is
     * {@link TextColors#NONE}. If the given format's color is
     * {@link TextColors#RESET} then {@link TextColors#NONE} will be used.
     * Styles are combined using {@link TextStyle#and(TextStyle...)}.
     *
     * @param format The format to merge
     * @return The new text format
     */
    public TextFormat merge(TextFormat format) {
        TextColor color = format.color;
        // If the given format's color is NONE use this ones
        if (color == TextColors.NONE) {
            color = this.color;
            // If the given format's color is RESET use NONE
        } else if (color == TextColors.RESET) {
            color = TextColors.NONE;
        }
        return new TextFormat(color, this.style.and(format.style));
    }

    /**
     * Returns whether this {@link TextFormat} has no color and format
     * specified.
     *
     * @return If the format does not contain a color or any styles
     */
    public boolean isEmpty() {
        return this.color == TextColors.NONE && this.style.isEmpty();
    }

    @Override
    public void applyTo(Text.Builder builder) {
        builder.format(this);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof TextFormat)) {
            return false;
        }

        TextFormat that = (TextFormat) o;
        return this.color.equals(that.color) && this.style.equals(that.style);

    }

    @Override
    public int hashCode() {
        return Objects.hashCode(this.color, this.style);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("color", this.color)
                .add("style", this.style)
                .toString();
    }

}


text:
package com.growthpush;

import android.util.Log;

public class Logger {

	private static final String TAG = "GrowthPush";

	private boolean debug = false;

	public Logger() {
		super();
	}

	public void debug(String message) {

		if (debug)
			Log.d(TAG, message);

	}

	public void info(String message) {

		if (debug)
			Log.i(TAG, message);

	}

	public void warning(String message) {

		if (debug)
			Log.w(TAG, message);

	}

	public void error(String message) {

		if (debug)
			Log.e(TAG, message);

	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}

}


text:
import { expect } from 'chai';
import express from 'express';
import supertest from 'supertest';
import sinon from 'sinon';
import createServer from '../../../server/createServer';

describe('createServer', () => {
    let request;
    let logger;

    beforeEach(() => {
        logger = { info: sinon.spy() };

        request = supertest(createServer(express(), logger));
    });

    const responseContainsExpectedTitle = (expectedTitle, response) => {
        expect(response.text.indexOf(expectedTitle) !== -1).to.be.true;
    };

    it('should respond with html containing the expected title for the home page', () => {
        const expectedTitle = '<title>Home page</title>';

        return request.get('/')
            .expect(200)
            .expect(responseContainsExpectedTitle.bind(null, expectedTitle));
    });

    it('should respond with html containing the expected title for the any page', () => {
        const expectedTitle = '<title>Any page</title>';

        return request.get('/any-page')
            .expect(200)
            .expect(responseContainsExpectedTitle.bind(null, expectedTitle));
    });

    it('should respond with html containing the expected title for the dropdown page', () => {
        const expectedTitle = '<title>Dropdown page</title>';

        return request.get('/dropdown-page/any-of-it')
            .expect(200)
            .expect(responseContainsExpectedTitle.bind(null, expectedTitle));
    });
});


text:
package org.goldonship.designpattern.behavioral.memento;

import org.junit.Test;

public class ApplicationTest {
    @Test
    public void test() throws Exception {
        Application.main(new String[]{});
    }
}


text:
using System;
using System.Net.Http;
using System.Web.Http;
using AutoMapper;
using Core.Commands.LeadCommands;
using Dto.ApiRequests;
using Dto.ApiRequests.LeadForms;
using NServiceBus;
using WebApp.ModelService;

namespace WebApp.Controllers
{
    public class LeadController : SmartApiController
    {
        public IBus Bus { get; set; }
        private readonly ILeadModelService _leadModelService;

        public LeadController(ILeadModelService leadModelService)
        {
            _leadModelService = leadModelService;
        }

        public HttpResponseMessage Get([FromUri] SearchSpecification form)
        {
            var response = _leadModelService.GetPageBySpecification(form);
            return Content(response);
        }

        public HttpResponseMessage Post(AddLeadForm form)
        {
            var command = Mapper.Map<AddLeadForm, AddLead>(form);
            return ExecuteCommand(command);
        }

        public HttpResponseMessage Put(UpdateLeadForm form)
        {
            var command = Mapper.Map<UpdateLeadForm, UpdateLead>(form);
            return ExecuteCommand(command);
        }

        public HttpResponseMessage Delete(Guid id)
        {
            var command = new DeleteLead(id);
            return ExecuteCommand(command);
        }
    }
}


text:
Simple conference central demo using Google Cloud Endpoints

## Language
- [Python 2.7](http://python.org)

## APIs
- [Google Cloud Endpoints](https://developers.google.com/appengine/docs/python/endpoints/)

## Demo
- Check [Live Version](https://udacity-conference-1131.appspot.com/)
- Check [API Explorer](https://udacity-conference-1131.appspot.com/_ah/api/explorer)

## Setup Instructions
1. Update the value of `application` in `app.yaml` to the app ID you
   have registered in the App Engine admin console and would like to use to host
   your instance of this sample.
2. Update the values at the top of `settings.py` to
   reflect the respective client IDs you have registered in the
   Developer Console.
3. Update the value of CLIENT_ID in `static/js/app.js` to the Web client ID
4. (Optional) Mark the configuration files as unchanged as follows:
   `$ git update-index --assume-unchanged app.yaml settings.py static/js/app.js`
5. Run the app with the devserver using `dev_appserver.py DIR`, and ensure it's running by visiting your local server's address (by default **localhost:8080**)
6. (Optional) Generate your client library with the endpoints tool.
7. Deploy your application.

## To Run (Local)
1. Install and Open Google App Engine Launcher
2. Add project folder by press '+' on the bottom left
3. Select the newly added project and click 'Run'
4. Click 'Browse' to see the application
5. Click 'Logs' to see the feedback from backend
6. Click 'SDK Console' to manage datastore, memcache, and so on

## Tasks' Questions
#### Task 1: Add Sessions to conference
A conference consists several sessions.
Given the requirement that session should have the following variables
- Session name
- highlights
- speaker
- duration
- typeOfSession
- date
- startTime

Session object inherits from ndb.Model. For simplicity, speaker is made with StringProperty that allows only one speaker associated with one session object. For future improvement, it should allow association with multiple speakers, and each speaker is a full fledged entity. The rest of variables are pretty straight forward. 'Highlights' is repeated StringProperty records multiple string tags. 'Duration' is IntegerProperty that records the minutes of the session.

To create a session, the conference key is required since each session object is associated with one conference as it's parent. Another requirement is that current user has to be the conference's organizer in order to create the session. Lastly, the name of the session has to present. The rest of fields will be filled with default values if not provided.

For Task#4, after creating the session object, it will check if the speaker has more than one sessions in the given conference. If so, it will create a task and push to the task queue to feature the speaker.

#### Task 3.1: Two additional queries
1. Get all types of sessions
```python
@endpoints.method(message_types.VoidMessage, SessionTypes,
                  path='sessions/types',
                  http_method='GET',
                  name='getSessionsTypes')
```
User can use this endpoint to get a list of types of sessions in a array.
eg. ['Type 1', 'Type 2', 'Type 3']

2. Get Sessions that is not given type and before given time
```python
@endpoints.method(SESSION_GET_BEFORE_TIME_REQUEST, SessionForms,
                  path='sessions/notTypebeforeTime',
                  http_method='GET',
                  name='getSessionsNotTypeBeforeTime')
```
User can use this endpoint to get list of sessions that excludes given type of session before certain time.
For future improvement, it should allow user to specific a list of types for exclusion.

#### Task 3.2: Query Problem
Q: Let's say that you don't like workshops and you don't like sessions after 7 pm. How would you handle a query for all non-workshop sessions before 7 pm? What is the problem for implementing this query? What ways to solve it did you think of?

A: The solution is presented at Task 3.1 #2. Since inequality filter can not be applied to multiple properties. We first generate a list of types that excludes the given type. Use the collection and IN operator to get all the sessions that is not the given type. Then, we use inequality filter to find sessions before given time.


text:
void ginit(int*, int*, int);
void gclose();


text: <mv-usuarios-administracion class="control"></mv-usuarios-administracion>


text: * 2.0.1 - Added custom styling and class uses


text:
layout: page
title: 404 - Back in 10 minutes
---

The monkey that is responsible for this page is currently on a break. It will be back shortly, but till then you can chill @ [the homepage]({{ site.baseurl }}/).

[<img src="{{ site.baseurl }}/images/404.jpg" alt="Constructocat by https://github.com/jasoncostello" style="width: 400px;"/>]({{ site.baseurl }}/)


text:
package com.tle.web.bulk.metadata;

import com.dytech.devlib.PropBagEx;
import com.dytech.devlib.PropBagEx.PropBagThoroughIterator;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.tle.beans.item.ItemKey;
import com.tle.beans.item.ItemPack;
import com.tle.core.guice.Bind;
import com.tle.core.guice.BindFactory;
import com.tle.core.item.operations.WorkflowOperation;
import com.tle.core.item.service.ItemService;
import com.tle.core.item.standard.ItemOperationFactory;
import com.tle.core.plugins.BeanLocator;
import com.tle.core.plugins.FactoryMethodLocator;
import com.tle.web.bulk.metadata.model.BulkEditMetadataModel;
import com.tle.web.bulk.metadata.model.Modification;
import com.tle.web.bulk.metadata.model.Modification.ModificationKeys;
import com.tle.web.bulk.metadata.operations.EditMetadataBulkFactory;
import com.tle.web.bulk.metadata.section.BulkEditMetadataSection;
import com.tle.web.bulk.operation.BulkOperationExecutor;
import com.tle.web.bulk.operation.BulkOperationExtension;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.equella.annotation.PlugKey;
import com.tle.web.sections.equella.utils.KeyOption;
import com.tle.web.sections.events.RenderContext;
import com.tle.web.sections.render.Label;
import com.tle.web.sections.render.SectionRenderable;
import com.tle.web.sections.standard.Button;
import com.tle.web.sections.standard.model.Option;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Bind
public class BulkEditMetadataOperation extends BulkEditMetadataSection
    implements BulkOperationExtension {
  private static final String BULK_METADATA_VAL = "editmetadata"; // $NON-NLS-1$

  @PlugKey("bulkop.editmetadata")
  private static String LABEL_METADATA;

  @PlugKey("bulkop.editmetadata.title")
  private static Label LABEL_METADATA_TITLE;

  @Inject private ItemService itemService;

  @BindFactory
  public interface EditMetadataBulkExecutorFactory {
    EditMetadataBulkExecutor create(@Assisted("mods") List<Modification> mods);
  }

  @Override
  public void register(SectionTree tree, String parentId) {
    tree.registerInnerSection(this, parentId);
  }

  @Override
  public void registered(String id, SectionTree tree) {
    super.registered(id, tree);
  }

  @Override
  public void addOptions(SectionInfo info, List<Option<OperationInfo>> options) {
    options.add(
        new KeyOption<BulkOperationExtension.OperationInfo>(
            LABEL_METADATA, BULK_METADATA_VAL, new OperationInfo(this, BULK_METADATA_VAL)));
  }

  @Override
  public BeanLocator<EditMetadataBulkExecutor> getExecutor(SectionInfo info, String operationId) {
    return new FactoryMethodLocator<EditMetadataBulkExecutor>(
        EditMetadataBulkExecutorFactory.class,
        "create",
        Lists.newArrayList(getModel(info).getModifications()));
  }

  @Override
  public void prepareDefaultOptions(SectionInfo info, String operationId) {
    // nada
  }

  @Override
  public SectionRenderable renderOptions(RenderContext context, String operationId) {
    return renderSection(context, this);
  }

  @Override
  public Label getStatusTitleLabel(SectionInfo info, String operationId) {

    return LABEL_METADATA_TITLE;
  }

  @Override
  public boolean validateOptions(SectionInfo info, String operationId) {
    BulkEditMetadataModel model = getModel(info);
    return (model.getModifications().size() > 0)
        && !(model.isSchemaSelection() || model.isActionSelection());
  }

  @Override
  public boolean areOptionsFinished(SectionInfo info, String operationId) {
    return validateOptions(info, operationId);
  }

  @Override
  public boolean hasExtraOptions(SectionInfo info, String operationId) {
    return true;
  }

  public static class EditMetadataBulkExecutor implements BulkOperationExecutor {
    List<List<String>> nodes = new ArrayList<List<String>>();
    List<Map<ModificationKeys, String>> params = new ArrayList<Map<ModificationKeys, String>>();

    @Inject private EditMetadataBulkFactory metadataFactory;
    @Inject private ItemOperationFactory workflowFactory;

    @Inject
    public EditMetadataBulkExecutor(@Assisted("mods") List<Modification> mods) {
      for (Modification mod : mods) {
        nodes.add(mod.getNodes());
        params.add(mod.getParmas());
      }
    }

    @Override
    public WorkflowOperation[] getOperations() {
      return new WorkflowOperation[] {
        workflowFactory.startEdit(true),
        metadataFactory.editMetada(nodes, params),
        workflowFactory.save()
      };
    }

    @Override
    public String getTitleKey() {
      return "com.tle.web.bulk.metadata.bulk.editmetadata.title";
    }
  }

  @Override
  public boolean hasExtraNavigation(SectionInfo info, String operationId) {
    return true;
  }

  @Override
  public Collection<Button> getExtraNavigation(SectionInfo info, String operationId) {
    return Lists.newArrayList(
        getModificationReturnButton(),
        getChooseActionButton(),
        getEditNodesButton(),
        getSaveActionButton());
  }

  @Override
  public boolean hasPreview(SectionInfo info, String operationId) {
    return true;
  }

  @SuppressWarnings("nls")
  @Override
  public ItemPack runPreview(SectionInfo info, String operationId, long itemId) throws Exception {
    ItemKey itemKey = itemService.getItemIdKey(itemId);
    PropBagEx itemXml = itemService.getItemXmlPropBag(itemKey);
    List<Modification> mods = getModel(info).getModifications();

    for (int x = 0; x < mods.size(); x++) {
      Modification currentMod = mods.get(x);
      Map<ModificationKeys, String> op = currentMod.getParmas();
      for (String nodePath : currentMod.getNodes()) {
        String action = op.get(ModificationKeys.ACTION);
        if (!action.equalsIgnoreCase("set")) {
          PropBagThoroughIterator nodeIterator = itemXml.iterateAll(nodePath);
          while (nodeIterator.hasNext()) {
            PropBagEx currentNode = nodeIterator.next();
            if (action.equalsIgnoreCase("replace")) {
              String nodeText = currentNode.getNode();
              nodeText =
                  nodeText.replace(
                      op.get(ModificationKeys.REPLACE_FIND), op.get(ModificationKeys.REPLACE_WITH));
              currentNode.setNode("/", nodeText);
            } else if (action.equalsIgnoreCase("add")) {
              PropBagEx addedXml = new PropBagEx(op.get(ModificationKeys.ADD_XML));
              currentNode.append("/", addedXml);
            }
          }
        } else {
          // SET
          String setOption = op.get(ModificationKeys.SET_TEXT_OPTION);
          String setText = op.get(ModificationKeys.SET_TEXT);
          if (setOption.equalsIgnoreCase("always")
              || (setOption.equalsIgnoreCase("exists") && itemXml.nodeExists(nodePath))) {
            PropBagThoroughIterator nodeIterator = itemXml.iterateAll(nodePath);
            while (nodeIterator.hasNext()) {
              PropBagEx currentNode = nodeIterator.next();
              currentNode.setNode("/", setText);
            }
          }
          if (setOption.equalsIgnoreCase("always")
              || (setOption.equalsIgnoreCase("create") && !itemXml.nodeExists(nodePath))) {
            itemXml.setNode(nodePath, setText);
          }
        }
      }
    }
    ItemPack itemPack = itemService.getItemPack(itemKey);
    itemPack.setXml(itemXml);
    return itemPack;
  }

  @Override
  public boolean showPreviousButton(SectionInfo info, String opererationId) {
    BulkEditMetadataModel model = getModel(info);
    return !(model.isSchemaSelection() || model.isActionSelection());
  }
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals

from c7n.actions import Action
from c7n.manager import resources
from c7n.query import QueryResourceManager
from c7n.utils import local_session, type_schema

@resources.register('kinesis')
class KinesisStream(QueryResourceManager):

    class resource_type(object):
        service = 'kinesis'
        type = 'stream'
        enum_spec = ('list_streams', 'StreamNames', None)
        detail_spec = (
            'describe_stream', 'StreamName', None, 'StreamDescription')
        name = id = 'StreamName'
        filter_name = None
        filter_type = None
        date = None
        dimension = 'StreamName'

@KinesisStream.action_registry.register('delete')
class Delete(Action):

    schema = type_schema('delete')
    permissions = ("kinesis:DeleteStream",)

    def process(self, resources):
        client = local_session(self.manager.session_factory).client('kinesis')
        not_active = [r['StreamName'] for r in resources
                      if r['StreamStatus'] != 'ACTIVE']
        self.log.warning(
            "The following streams cannot be deleted (wrong state): %s" % (
                ", ".join(not_active)))
        for r in resources:
            if not r['StreamStatus'] == 'ACTIVE':
                continue
            client.delete_stream(
                StreamName=r['StreamName'])

@resources.register('firehose')
class DeliveryStream(QueryResourceManager):

    class resource_type(object):
        service = 'firehose'
        type = 'deliverystream'
        enum_spec = ('list_delivery_streams', 'DeliveryStreamNames', None)
        detail_spec = (
            'describe_delivery_stream', 'DeliveryStreamName', None,
            'DeliveryStreamDescription')
        name = id = 'DeliveryStreamName'
        filter_name = None
        filter_type = None
        date = 'CreateTimestamp'
        dimension = 'DeliveryStreamName'

@DeliveryStream.action_registry.register('delete')
class FirehoseDelete(Action):

    schema = type_schema('delete')
    permissions = ("firehose:DeleteDeliveryStream",)

    def process(self, resources):
        client = local_session(self.manager.session_factory).client('firehose')
        creating = [r['DeliveryStreamName'] for r in resources
                    if r['DeliveryStreamStatus'] == 'CREATING']
        if creating:
            self.log.warning(
                "These delivery streams can't be deleted (wrong state): %s" % (
                    ", ".join(creating)))
        for r in resources:
            if not r['DeliveryStreamStatus'] == 'ACTIVE':
                continue
            client.delete_delivery_stream(
                DeliveryStreamName=r['DeliveryStreamName'])

@resources.register('kinesis-analytics')
class AnalyticsApp(QueryResourceManager):

    class resource_type(object):
        service = "kinesisanalytics"
        enum_spec = ('list_applications', 'ApplicationSummaries', None)
        detail_spec = ('describe_application', 'ApplicationName',
                       'ApplicationName', 'ApplicationDetail')
        name = "ApplicationName"
        id = "ApplicationARN"
        dimension = None
        filter_name = None
        filter_type = None

@AnalyticsApp.action_registry.register('delete')
class AppDelete(Action):

    schema = type_schema('delete')
    permissions = ("kinesisanalytics:DeleteApplication",)

    def process(self, resources):
        client = local_session(
            self.manager.session_factory).client('kinesisanalytics')
        for r in resources:
            client.delete_application(
                ApplicationName=r['ApplicationName'],
                CreateTimestamp=r['CreateTimestamp'])


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

namespace FlatRedBall.Glue.CodeGeneration.CodeBuilder
{
    public interface ICode
    {
        string TabCharacter { get; set; }
        int TabCount { get; set; }

        void AddToStringBuilder(StringBuilder pBldr);
        void AddToStringBuilder(StringBuilder pBldr, int pTabCount, string pTabCharacter);
        string ToString();
        string ToString(int pTabCount, string pTabCharacter);
        List<ICodeBlock> GetTag(string pTagName);
        void Replace(string pOldValue, string pNewValue);
    }
}


text:
package com.datastax.oss.driver.internal.core.metadata.schema.queries;

import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Filters keyspaces during schema metadata queries.
 *
 * <p>Depending on the circumstances, we do it either on the server side with a WHERE IN clause that
 * will be appended to every query, or on the client side with a predicate that will be applied to
 * every fetched row.
 */
class RuleBasedKeyspaceFilter implements KeyspaceFilter {

  private static final Logger LOG = LoggerFactory.getLogger(RuleBasedKeyspaceFilter.class);

  private static final Pattern EXACT_INCLUDE = Pattern.compile("\\w+");
  private static final Pattern EXACT_EXCLUDE = Pattern.compile("!\\s*(\\w+)");
  private static final Pattern REGEX_INCLUDE = Pattern.compile("/(.+)/");
  private static final Pattern REGEX_EXCLUDE = Pattern.compile("!\\s*/(.+)/");

  private final String logPrefix;
  private final String whereClause;
  private final Set<String> exactIncludes = new HashSet<>();
  private final Set<String> exactExcludes = new HashSet<>();
  private final List<Predicate<String>> regexIncludes = new ArrayList<>();
  private final List<Predicate<String>> regexExcludes = new ArrayList<>();

  private final boolean isDebugEnabled;
  private final Set<String> loggedKeyspaces;

  RuleBasedKeyspaceFilter(@NonNull String logPrefix, @NonNull List<String> specs) {
    assert !specs.isEmpty(); // see KeyspaceFilter#newInstance

    this.logPrefix = logPrefix;
    for (String spec : specs) {
      spec = spec.trim();
      Matcher matcher;
      if (EXACT_INCLUDE.matcher(spec).matches()) {
        exactIncludes.add(spec);
        if (exactExcludes.remove(spec)) {
          LOG.warn(
              "[{}] '{}' is both included and excluded, ignoring the exclusion", logPrefix, spec);
        }
      } else if ((matcher = EXACT_EXCLUDE.matcher(spec)).matches()) {
        String name = matcher.group(1);
        if (exactIncludes.contains(name)) {
          LOG.warn(
              "[{}] '{}' is both included and excluded, ignoring the exclusion", logPrefix, name);
        } else {
          exactExcludes.add(name);
        }
      } else if ((matcher = REGEX_INCLUDE.matcher(spec)).matches()) {
        compile(matcher.group(1)).map(regexIncludes::add);
      } else if ((matcher = REGEX_EXCLUDE.matcher(spec)).matches()) {
        compile(matcher.group(1)).map(regexExcludes::add);
      } else {
        LOG.warn(
            "[{}] Error while parsing {}: invalid element '{}', skipping",
            logPrefix,
            DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES.getPath(),
            spec);
      }
    }

    if (!exactIncludes.isEmpty() && regexIncludes.isEmpty() && regexExcludes.isEmpty()) {
      // We can filter on the server
      whereClause = buildWhereClause(exactIncludes);
      if (!exactExcludes.isEmpty()) {
        // Proceed, but this is probably a mistake
        LOG.warn(
            "[{}] {} only has exact includes and excludes, the excludes are redundant",
            logPrefix,
            DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES.getPath());
      }
      LOG.debug("[{}] Filtering server-side with '{}'", logPrefix, whereClause);
    } else {
      whereClause = "";
      LOG.debug("[{}] No server-side filtering", logPrefix);
    }

    isDebugEnabled = LOG.isDebugEnabled();
    loggedKeyspaces = isDebugEnabled ? new HashSet<>() : null;
  }

  @NonNull
  @Override
  public String getWhereClause() {
    return whereClause;
  }

  @Override
  public boolean includes(@NonNull String keyspace) {
    if (exactIncludes.contains(keyspace)) {
      log(keyspace, true, "it is included by name");
      return true;
    } else if (exactExcludes.contains(keyspace)) {
      log(keyspace, false, "it is excluded by name");
      return false;
    } else if (regexIncludes.isEmpty()) {
      if (regexExcludes.isEmpty()) {
        log(keyspace, false, "it is not included by name");
        return false;
      } else if (matchesAny(keyspace, regexExcludes)) {
        log(keyspace, false, "it matches at least one regex exclude");
        return false;
      } else {
        log(keyspace, true, "it does not match any regex exclude");
        return true;
      }
    } else { // !regexIncludes.isEmpty()
      if (regexExcludes.isEmpty()) {
        if (matchesAny(keyspace, regexIncludes)) {
          log(keyspace, true, "it matches at least one regex include");
          return true;
        } else {
          log(keyspace, false, "it does not match any regex include");
          return false;
        }
      } else {
        if (matchesAny(keyspace, regexIncludes) && !matchesAny(keyspace, regexExcludes)) {
          log(keyspace, true, "it matches at least one regex include, and no regex exclude");
          return true;
        } else {
          log(keyspace, false, "it matches either no regex include, or at least one regex exclude");
          return false;
        }
      }
    }
  }

  private void log(@NonNull String keyspace, boolean include, @NonNull String reason) {
    if (isDebugEnabled && loggedKeyspaces.add(keyspace)) {
      LOG.debug(
          "[{}] Filtering {} '{}' because {}", logPrefix, include ? "in" : "out", keyspace, reason);
    }
  }

  private boolean matchesAny(String keyspace, List<Predicate<String>> rules) {
    for (Predicate<String> rule : rules) {
      if (rule.test(keyspace)) {
        return true;
      }
    }
    return false;
  }

  private Optional<Predicate<String>> compile(String regex) {
    try {
      return Optional.of(Pattern.compile(regex).asPredicate());
    } catch (PatternSyntaxException e) {
      LOG.warn(
          "[{}] Error while parsing {}: syntax error in regex /{}/ ({}), skipping",
          this.logPrefix,
          DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES.getPath(),
          regex,
          e.getMessage());
      return Optional.empty();
    }
  }

  private static String buildWhereClause(Set<String> keyspaces) {
    StringBuilder builder = new StringBuilder(" WHERE keyspace_name IN (");
    boolean first = true;
    for (String keyspace : keyspaces) {
      if (first) {
        first = false;
      } else {
        builder.append(",");
      }
      builder.append('\'').append(keyspace).append('\'');
    }
    return builder.append(')').toString();
  }
}


text:
package ucl

import (
	"bufio"
	"fmt"
	"io"
	"sort"
	"strings"
)

//go:generate ragel -Z ucl.rl

// FormatConfig represents the formatter configuration that affects how
// data is layed out in the output file.
type FormatConfig struct {
	// Indent is a string to use for each indentation level. If not set defaults to 2 spaces.
	Indent string `json:",omitempty"`
	// MultilineObjectThreshold is the maximum length for an object to be written out on a single line.
	// Default is 0, meaning that any non-empty object will be written out with key-value pairs on separate lines.
	MultilineObjectThreshold int `json:",omitempty"`
	// MultilineObjectThreshold is the maximum length for an array to be written out on a single line.
	// Default is 0, meaning that any non-empty array will be written out with items on separate lines.
	MultilineArrayThreshold int `json:",omitempty"`
	// PreserveObjectKeysOrder must be set to true if you want to keep keys in the same order as in the input.
	// By default keys are sorted in lexicographical order.
	PreserveObjectKeysOrder bool `json:",omitempty"`
	placeholder             struct{}
}

// Value represents a UCL value.
type Value interface {
	// String returns simple string representation of the value.
	String() string
	// format returns a properly formatted representation of the value. Used internally
	// by Format function.
	format(indent string, config *FormatConfig) string
}

// Format writes v, formatted according to c, to w.
func Format(v Value, c *FormatConfig, w io.Writer) error {
	if c == nil {
		c = &FormatConfig{} // keep this empty, zero values for options should mean default format.
	}
	_, err := w.Write([]byte(v.format("", c)))
	return err
}

// Parse reads UTF-8 text from r and parses it.
func Parse(r io.Reader) (Value, error) {
	rr := bufio.NewReader(r)
	data := []rune{}
	for {
		c, _, err := rr.ReadRune()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
		data = append(data, c)
	}
	return parse(data)
}

func parse(data []rune) (Value, error) {
	v, _, err := parse_json(data)
	if err != nil {
		return nil, err
	}
	return v, nil
}

// Null represents "null" JSON value.
type Null struct{}

func (Null) String() string {
	return "null"
}

func (Null) format(indent string, config *FormatConfig) string {
	return "null"
}

// Bool represents boolean value.
type Bool struct {
	Value bool
}

func (v Bool) String() string {
	if v.Value {
		return "true"
	}
	return "false"
}

func (v Bool) format(indent string, config *FormatConfig) string {
	return v.String()
}

// Number represents a numerical value.
type Number struct {
	Value float64
}

func (v Number) String() string {
	return fmt.Sprintf("%g", v.Value)
}

func (v Number) format(indent string, config *FormatConfig) string {
	return v.String()
}

// Integer represents an integer numerical value.
type Integer struct {
	Value int64
}

func (v Integer) String() string {
	return fmt.Sprintf("%d", v.Value)
}

func (v Integer) format(indent string, config *FormatConfig) string {
	return v.String()
}

// String represents a string value.
type String struct {
	Value string
}

func (v String) String() string {
	return fmt.Sprintf("\"%s\"", jsonEscape(v.Value))
}

func (v String) format(indent string, config *FormatConfig) string {
	return v.String()
}

// Array represents an array.
type Array struct {
	Value []Value
}

func (v Array) String() string {
	t := make([]string, len(v.Value))
	for i, item := range v.Value {
		t[i] = item.String()
	}
	return "[" + strings.Join(t, ",") + "]"
}

func (v Array) format(indent string, config *FormatConfig) string {
	if len(v.Value) == 0 {
		return "[]"
	}
	newIndent := config.Indent
	if newIndent == "" {
		newIndent = "  "
	}
	items := make([]string, len(v.Value))
	for i, item := range v.Value {
		items[i] = item.format(indent+newIndent, config)
	}
	shortFormatLen := 2                    // brackets
	shortFormatLen += (len(items) - 1) * 2 // ", " between items
	for _, item := range items {
		if strings.IndexRune(item, '\n') >= 0 {
			// One of the items spans multiple lines, bail out.
			shortFormatLen = config.MultilineArrayThreshold + 1
			break
		}
		shortFormatLen += len(item)
		if shortFormatLen > config.MultilineArrayThreshold {
			break
		}
	}
	if shortFormatLen <= config.MultilineArrayThreshold {
		return "[" + strings.Join(items, ", ") + "]"
	}
	r := "[\n"
	for i := 0; i < len(items)-1; i++ {
		r += indent + newIndent + items[i] + ",\n"
	}
	r += indent + newIndent + items[len(items)-1] + "\n"
	r += indent + "]"
	return r
}

// Key represents keys in objects.
type Key struct {
	Value string
	Index int
}

func (v Key) String() string {
	return fmt.Sprintf("\"%s\"", jsonEscape(v.Value))
}

func (v Key) format(indent string, config *FormatConfig) string {
	return v.String()
}

type byValue []Key

func (s byValue) Len() int           { return len(s) }
func (s byValue) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byValue) Less(i, j int) bool { return s[i].Value < s[j].Value }

type byIndex []Key

func (s byIndex) Len() int           { return len(s) }
func (s byIndex) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byIndex) Less(i, j int) bool { return s[i].Index < s[j].Index }

// Object represents an object.
type Object struct {
	Value map[Key]Value
}

func (v Object) String() string {
	t := make([]string, 0, len(v.Value))
	for key, item := range v.Value {
		t = append(t, key.String()+":"+item.String())
	}
	return "{" + strings.Join(t, ",") + "}"
}

func (v Object) Find(key string) Value {
	val, _ := v.Lookup(key)
	return val
}

func (v Object) Lookup(key string) (Value, bool) {
	for k, v := range v.Value {
		if k.Value == key {
			return v, true
		}
	}
	return nil, false
}

func (v Object) format(indent string, config *FormatConfig) string {
	if len(v.Value) == 0 {
		return "{}"
	}
	newIndent := config.Indent
	if newIndent == "" {
		newIndent = "  "
	}
	// Make sure that order of properties is stable.
	keys := make([]Key, 0, len(v.Value))
	for k := range v.Value {
		keys = append(keys, k)
	}
	if config.PreserveObjectKeysOrder {
		sort.Sort(byIndex(keys))
	} else {
		sort.Sort(byValue(keys))
	}

	items := make([]string, len(keys))
	for i, k := range keys {
		items[i] = k.format(indent+newIndent, config) + ": " + v.Value[k].format(indent+newIndent, config)
	}
	shortFormatLen := 2                    // brackets
	shortFormatLen += (len(items) - 1) * 2 // ", " between items
	for _, item := range items {
		if strings.IndexRune(item, '\n') >= 0 {
			// One of the items spans multiple lines, bail out.
			shortFormatLen = config.MultilineObjectThreshold + 1
			break
		}
		shortFormatLen += len(item)
		if shortFormatLen > config.MultilineObjectThreshold {
			break
		}
	}
	if shortFormatLen <= config.MultilineObjectThreshold {
		return "{" + strings.Join(items, ", ") + "}"
	}

	r := "{\n"
	for i := 0; i < len(keys)-1; i++ {
		r += indent + newIndent + keys[i].format(indent+newIndent, config) + ": " + v.Value[keys[i]].format(indent+newIndent, config) + ",\n"
	}
	r += indent + newIndent + keys[len(keys)-1].format(indent+newIndent, config) + ": " + v.Value[keys[len(keys)-1]].format(indent+newIndent, config) + "\n"
	r += indent + "}"
	return r
}


text:
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.swing.SwingUtilities;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.OptionBuilder;

import com.highgo.hgdbadmin.model.Index;
import com.highgo.hgdbadmin.model.Procedure;
import com.highgo.hgdbadmin.model.Sequence;
import com.highgo.hgdbadmin.model.View;
import com.highgo.hgdbadmin.myutil.MigrateCenter;
import com.highgo.hgdbadmin.myutil.ShellEnvironment;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 1.¸ù¾Ý´«ÈëµÄÐÅÏ¢£¬´´½¨Ò»¸öxml´úÂë¶Î 2.´´½¨Ò»¸öConnection£¬¿´¿´ÐÅÏ¢ÊÇ·ñÓÐЧ 3.½«´úÂë¶ÎдÈëc3p0µÄÅäÖÃÎļþ
 *
 * @author u
 *
 */
public class MigrateProcedureFunction extends AquilaFunction {

	@SuppressWarnings("static-access")
	public MigrateProcedureFunction() {
		this.addOption(OptionBuilder.withDescription("migrate procedure.").withLongOpt("name").hasArg()
				.create("name"));
	}

	public Object executeFunction(CommandLine line) {
		if (!line.hasOption("name")) {
			ShellEnvironment.println("Required argument --name is missing.");
			return null;
		}
		try {
			String name = line.getOptionValue("name");
			migrateProcedure(name);
		} catch (IOException | SQLException | InterruptedException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private void migrateProcedure(String procedure) throws IOException, SQLException, InterruptedException {
		ShellEnvironment.println("Create Procedure:" + procedure);
		MigrateCenter.createProcedure(procedure);
		ShellEnvironment.println("Create Procedure " + procedure + " successfully!");
	}
}