text:
package org.apache.druid.data.input.parquet.simple;

import com.jayway.jsonpath.InvalidJsonException;
import com.jayway.jsonpath.spi.json.JsonProvider;
import org.apache.parquet.example.data.Group;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Provides json path for Parquet {@link Group} objects
 */
public class ParquetGroupJsonProvider implements JsonProvider
{
  private final ParquetGroupConverter converter;

  public ParquetGroupJsonProvider(ParquetGroupConverter converter)
  {
    this.converter = converter;
  }

  @Override
  public Object createArray()
  {
    return new ArrayList<>();
  }

  @Override
  public Object createMap()
  {
    return new HashMap<>();
  }

  @Override
  public boolean isArray(final Object o)
  {
    return o instanceof List;
  }

  @Override
  public boolean isMap(final Object o)
  {
    return o == null || o instanceof Map || o instanceof Group;
  }

  @Override
  public int length(final Object o)
  {
    if (o instanceof List) {
      return ((List) o).size();
    } else if (o instanceof Group) {
      // both lists and maps are 'Group' type, but we should only have a group here in a map context
      Group g = (Group) o;
      return g.getType().getFields().size();
    } else {
      return 0;
    }
  }

  @Override
  public Iterable<?> toIterable(final Object o)
  {
    if (o instanceof List) {
      return (List) o;
    }
    throw new UnsupportedOperationException(o.getClass().getName());
  }

  @Override
  public Collection<String> getPropertyKeys(final Object o)
  {
    if (o == null) {
      return Collections.emptySet();
    } else if (o instanceof Map) {
      return ((Map<Object, Object>) o).keySet().stream().map(String::valueOf).collect(Collectors.toSet());
    } else if (o instanceof Group) {
      return ((Group) o).getType().getFields().stream().map(f -> f.getName()).collect(Collectors.toSet());
    } else {
      throw new UnsupportedOperationException(o.getClass().getName());
    }
  }

  @Override
  public Object getMapValue(final Object o, final String s)
  {
    if (o == null) {
      return null;
    } else if (o instanceof Map) {
      return ((Map) o).get(s);
    } else if (o instanceof Group) {
      Group g = (Group) o;
      return converter.convertField(g, s);
    }
    throw new UnsupportedOperationException(o.getClass().getName());
  }

  @Override
  public Object getArrayIndex(final Object o, final int i)
  {
    if (o instanceof List) {
      return ((List) o).get(i);
    }
    throw new UnsupportedOperationException(o.getClass().getName());
  }

  @Override
  public void setArrayIndex(final Object o, final int i, final Object o1)
  {
    if (o instanceof List) {
      final List list = (List) o;
      if (list.size() == i) {
        list.add(o1);
      } else {
        list.set(i, o1);
      }
    } else {
      throw new UnsupportedOperationException(o.getClass().getName());
    }
  }

  @Override
  public void setProperty(final Object o, final Object o1, final Object o2)
  {
    if (o instanceof Map) {
      ((Map) o).put(o1, o2);
    } else {
      throw new UnsupportedOperationException(o.getClass().getName());
    }
  }

  @Override
  public void removeProperty(final Object o, final Object o1)
  {
    if (o instanceof Map) {
      ((Map) o).remove(o1);
    } else {
      throw new UnsupportedOperationException(o.getClass().getName());
    }
  }

  @Override
  @Deprecated
  public Object getArrayIndex(final Object o, final int i, final boolean b)
  {
    throw new UnsupportedOperationException("Deprecated");
  }

  @Override
  public Object parse(final String s) throws InvalidJsonException
  {
    throw new UnsupportedOperationException("Unused");
  }

  @Override
  public Object parse(final InputStream inputStream, final String s) throws InvalidJsonException
  {
    throw new UnsupportedOperationException("Unused");
  }

  @Override
  public String toJson(final Object o)
  {
    throw new UnsupportedOperationException("Unused");
  }

  @Override
  public Object unwrap(final Object o)
  {
    return o;
  }
}


text:
package org.apache.kafka.connect.runtime.distributed;

import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.connect.runtime.WorkerConfig;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.apache.kafka.common.config.ConfigDef.Range.atLeast;
import static org.apache.kafka.common.config.ConfigDef.Range.between;

public class DistributedConfig extends WorkerConfig {
    private static final ConfigDef CONFIG;

    /*
     * NOTE: DO NOT CHANGE EITHER CONFIG STRINGS OR THEIR JAVA VARIABLE NAMES AS
     * THESE ARE PART OF THE PUBLIC API AND CHANGE WILL BREAK USER CODE.
     */

    /**
     * group.id
     */
    public static final String GROUP_ID_CONFIG = CommonClientConfigs.GROUP_ID_CONFIG;
    private static final String GROUP_ID_DOC = "A unique string that identifies the Connect cluster group this worker belongs to.";

    /**
     * session.timeout.ms
     */
    public static final String SESSION_TIMEOUT_MS_CONFIG = CommonClientConfigs.SESSION_TIMEOUT_MS_CONFIG;
    private static final String SESSION_TIMEOUT_MS_DOC = "The timeout used to detect worker failures. " +
            "The worker sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are " +
            "received by the broker before the expiration of this session timeout, then the broker will remove the " +
            "worker from the group and initiate a rebalance. Note that the value must be in the allowable range as " +
            "configured in the broker configuration by group.min.session.timeout.ms " +
            "and group.max.session.timeout.ms.";

    /**
     * heartbeat.interval.ms
     */
    public static final String HEARTBEAT_INTERVAL_MS_CONFIG = CommonClientConfigs.HEARTBEAT_INTERVAL_MS_CONFIG;
    private static final String HEARTBEAT_INTERVAL_MS_DOC = "The expected time between heartbeats to the group " +
            "coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the " +
            "worker's session stays active and to facilitate rebalancing when new members join or leave the group. " +
            "The value must be set lower than session.timeout.ms, but typically should be set no higher " +
            "than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances.";

    /**
     * rebalance.timeout.ms
     */
    public static final String REBALANCE_TIMEOUT_MS_CONFIG = CommonClientConfigs.REBALANCE_TIMEOUT_MS_CONFIG;
    private static final String REBALANCE_TIMEOUT_MS_DOC = CommonClientConfigs.REBALANCE_TIMEOUT_MS_DOC;

    /**
     * worker.sync.timeout.ms
     */
    public static final String WORKER_SYNC_TIMEOUT_MS_CONFIG = "worker.sync.timeout.ms";
    private static final String WORKER_SYNC_TIMEOUT_MS_DOC = "When the worker is out of sync with other workers and needs" +
            " to resynchronize configurations, wait up to this amount of time before giving up, leaving the group, and" +
            " waiting a backoff period before rejoining.";

    /**
     * group.unsync.timeout.ms
     */
    public static final String WORKER_UNSYNC_BACKOFF_MS_CONFIG = "worker.unsync.backoff.ms";
    private static final String WORKER_UNSYNC_BACKOFF_MS_DOC = "When the worker is out of sync with other workers and " +
            " fails to catch up within worker.sync.timeout.ms, leave the Connect cluster for this long before rejoining.";
    public static final int WORKER_UNSYNC_BACKOFF_MS_DEFAULT = 5 * 60 * 1000;

    /**
     * offset.storage.topic
     */
    public static final String OFFSET_STORAGE_TOPIC_CONFIG = "offset.storage.topic";
    private static final String OFFSET_STORAGE_TOPIC_CONFIG_DOC = "The name of the Kafka topic where connector offsets are stored";

    /**
     * offset.storage.partitions
     */
    public static final String OFFSET_STORAGE_PARTITIONS_CONFIG = "offset.storage.partitions";
    private static final String OFFSET_STORAGE_PARTITIONS_CONFIG_DOC = "The number of partitions used when creating the offset storage topic";

    /**
     * offset.storage.replication.factor
     */
    public static final String OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG = "offset.storage.replication.factor";
    private static final String OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG_DOC = "Replication factor used when creating the offset storage topic";

    /**
     * config.storage.topic
     */
    public static final String CONFIG_TOPIC_CONFIG = "config.storage.topic";
    private static final String CONFIG_TOPIC_CONFIG_DOC = "The name of the Kafka topic where connector configurations are stored";

    /**
     * config.storage.replication.factor
     */
    public static final String CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG = "config.storage.replication.factor";
    private static final String CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG_DOC = "Replication factor used when creating the configuration storage topic";

    /**
     * status.storage.topic
     */
    public static final String STATUS_STORAGE_TOPIC_CONFIG = "status.storage.topic";
    public static final String STATUS_STORAGE_TOPIC_CONFIG_DOC = "The name of the Kafka topic where connector and task status are stored";

    /**
     * status.storage.partitions
     */
    public static final String STATUS_STORAGE_PARTITIONS_CONFIG = "status.storage.partitions";
    private static final String STATUS_STORAGE_PARTITIONS_CONFIG_DOC = "The number of partitions used when creating the status storage topic";

    /**
     * status.storage.replication.factor
     */
    public static final String STATUS_STORAGE_REPLICATION_FACTOR_CONFIG = "status.storage.replication.factor";
    private static final String STATUS_STORAGE_REPLICATION_FACTOR_CONFIG_DOC = "Replication factor used when creating the status storage topic";

    /**
     * connect.protocol
     */
    public static final String CONNECT_PROTOCOL_CONFIG = "connect.protocol";
    public static final String CONNECT_PROTOCOL_DOC = "Compatibility mode for Kafka Connect Protocol";
    public static final String CONNECT_PROTOCOL_DEFAULT = ConnectProtocolCompatibility.COMPATIBLE.toString();

    /**
     * connect.protocol
     */
    public static final String SCHEDULED_REBALANCE_MAX_DELAY_MS_CONFIG = "scheduled.rebalance.max.delay.ms";
    public static final String SCHEDULED_REBALANCE_MAX_DELAY_MS_DOC = "Compatibility mode for Kafka Connect Protocol";
    public static final int SCHEDULED_REBALANCE_MAX_DELAY_MS_DEFAULT = Math.toIntExact(TimeUnit.SECONDS.toMillis(300));

    static {
        CONFIG = baseConfigDef()
                .define(GROUP_ID_CONFIG,
                        ConfigDef.Type.STRING,
                        ConfigDef.Importance.HIGH,
                        GROUP_ID_DOC)
                .define(SESSION_TIMEOUT_MS_CONFIG,
                        ConfigDef.Type.INT,
                        10000,
                        ConfigDef.Importance.HIGH,
                        SESSION_TIMEOUT_MS_DOC)
                .define(REBALANCE_TIMEOUT_MS_CONFIG,
                        ConfigDef.Type.INT,
                        60000,
                        ConfigDef.Importance.HIGH,
                        REBALANCE_TIMEOUT_MS_DOC)
                .define(HEARTBEAT_INTERVAL_MS_CONFIG,
                        ConfigDef.Type.INT,
                        3000,
                        ConfigDef.Importance.HIGH,
                        HEARTBEAT_INTERVAL_MS_DOC)
                .define(CommonClientConfigs.METADATA_MAX_AGE_CONFIG,
                        ConfigDef.Type.LONG,
                        5 * 60 * 1000,
                        atLeast(0),
                        ConfigDef.Importance.LOW,
                        CommonClientConfigs.METADATA_MAX_AGE_DOC)
                .define(CommonClientConfigs.CLIENT_ID_CONFIG,
                        ConfigDef.Type.STRING,
                        "",
                        ConfigDef.Importance.LOW,
                        CommonClientConfigs.CLIENT_ID_DOC)
                .define(CommonClientConfigs.SEND_BUFFER_CONFIG,
                        ConfigDef.Type.INT,
                        128 * 1024,
                        atLeast(0),
                        ConfigDef.Importance.MEDIUM,
                        CommonClientConfigs.SEND_BUFFER_DOC)
                .define(CommonClientConfigs.RECEIVE_BUFFER_CONFIG,
                        ConfigDef.Type.INT,
                        32 * 1024,
                        atLeast(0),
                        ConfigDef.Importance.MEDIUM,
                        CommonClientConfigs.RECEIVE_BUFFER_DOC)
                .define(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG,
                        ConfigDef.Type.LONG,
                        50L,
                        atLeast(0L),
                        ConfigDef.Importance.LOW,
                        CommonClientConfigs.RECONNECT_BACKOFF_MS_DOC)
                .define(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG,
                        ConfigDef.Type.LONG,
                        1000L,
                        atLeast(0L),
                        ConfigDef.Importance.LOW,
                        CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_DOC)
                .define(CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG,
                        ConfigDef.Type.LONG,
                        100L,
                        atLeast(0L),
                        ConfigDef.Importance.LOW,
                        CommonClientConfigs.RETRY_BACKOFF_MS_DOC)
                .define(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG,
                        ConfigDef.Type.INT,
                        40 * 1000,
                        atLeast(0),
                        ConfigDef.Importance.MEDIUM,
                        CommonClientConfigs.REQUEST_TIMEOUT_MS_DOC)
                        /* default is set to be a bit lower than the server default (10 min), to avoid both client and server closing connection at same time */
                .define(CommonClientConfigs.CONNECTIONS_MAX_IDLE_MS_CONFIG,
                        ConfigDef.Type.LONG,
                        9 * 60 * 1000,
                        ConfigDef.Importance.MEDIUM,
                        CommonClientConfigs.CONNECTIONS_MAX_IDLE_MS_DOC)
                // security support
                .define(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG,
                        ConfigDef.Type.STRING,
                        CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL,
                        ConfigDef.Importance.MEDIUM,
                        CommonClientConfigs.SECURITY_PROTOCOL_DOC)
                .withClientSslSupport()
                .withClientSaslSupport()
                .define(WORKER_SYNC_TIMEOUT_MS_CONFIG,
                        ConfigDef.Type.INT,
                        3000,
                        ConfigDef.Importance.MEDIUM,
                        WORKER_SYNC_TIMEOUT_MS_DOC)
                .define(WORKER_UNSYNC_BACKOFF_MS_CONFIG,
                        ConfigDef.Type.INT,
                        WORKER_UNSYNC_BACKOFF_MS_DEFAULT,
                        ConfigDef.Importance.MEDIUM,
                        WORKER_UNSYNC_BACKOFF_MS_DOC)
                .define(OFFSET_STORAGE_TOPIC_CONFIG,
                        ConfigDef.Type.STRING,
                        ConfigDef.Importance.HIGH,
                        OFFSET_STORAGE_TOPIC_CONFIG_DOC)
                .define(OFFSET_STORAGE_PARTITIONS_CONFIG,
                        ConfigDef.Type.INT,
                        25,
                        atLeast(1),
                        ConfigDef.Importance.LOW,
                        OFFSET_STORAGE_PARTITIONS_CONFIG_DOC)
                .define(OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG,
                        ConfigDef.Type.SHORT,
                        (short) 3,
                        atLeast(1),
                        ConfigDef.Importance.LOW,
                        OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG_DOC)
                .define(CONFIG_TOPIC_CONFIG,
                        ConfigDef.Type.STRING,
                        ConfigDef.Importance.HIGH,
                        CONFIG_TOPIC_CONFIG_DOC)
                .define(CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG,
                        ConfigDef.Type.SHORT,
                        (short) 3,
                        atLeast(1),
                        ConfigDef.Importance.LOW,
                        CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG_DOC)
                .define(STATUS_STORAGE_TOPIC_CONFIG,
                        ConfigDef.Type.STRING,
                        ConfigDef.Importance.HIGH,
                        STATUS_STORAGE_TOPIC_CONFIG_DOC)
                .define(STATUS_STORAGE_PARTITIONS_CONFIG,
                        ConfigDef.Type.INT,
                        5,
                        atLeast(1),
                        ConfigDef.Importance.LOW,
                        STATUS_STORAGE_PARTITIONS_CONFIG_DOC)
                .define(STATUS_STORAGE_REPLICATION_FACTOR_CONFIG,
                        ConfigDef.Type.SHORT,
                        (short) 3,
                        atLeast(1),
                        ConfigDef.Importance.LOW,
                        STATUS_STORAGE_REPLICATION_FACTOR_CONFIG_DOC)
                .define(CONNECT_PROTOCOL_CONFIG,
                        ConfigDef.Type.STRING,
                        CONNECT_PROTOCOL_DEFAULT,
                        ConfigDef.LambdaValidator.with(
                            (name, value) -> {
                                try {
                                    ConnectProtocolCompatibility.compatibility((String) value);
                                } catch (Throwable t) {
                                    throw new ConfigException(name, value, "Invalid Connect protocol "
                                            + "compatibility");
                                }
                            },
                            () -> "[" + Utils.join(ConnectProtocolCompatibility.values(), ", ") + "]"),
                        ConfigDef.Importance.LOW,
                        CONNECT_PROTOCOL_DOC)
                .define(SCHEDULED_REBALANCE_MAX_DELAY_MS_CONFIG,
                        ConfigDef.Type.INT,
                        SCHEDULED_REBALANCE_MAX_DELAY_MS_DEFAULT,
                        between(0, Integer.MAX_VALUE),
                        ConfigDef.Importance.LOW,
                        SCHEDULED_REBALANCE_MAX_DELAY_MS_DOC);
    }

    @Override
    public Integer getRebalanceTimeout() {
        return getInt(DistributedConfig.REBALANCE_TIMEOUT_MS_CONFIG);
    }

    public DistributedConfig(Map<String, String> props) {
        super(CONFIG, props);
    }

    public static void main(String[] args) {
        System.out.println(CONFIG.toHtmlTable());
    }
}

redpajama_set_name: RedPajamaGithub


text:
var ifRecorder = {
		sessionId: (new Date().getTime())+""+( Math.ceil( Math.random() * 1000 ) ),
		command: { input: '', timestamp: 0 },
		output: '',
		cache: [],
		statusline: '',
		window: 0,	// which window the transcript has been saved to

		/* Turn count is the game's internal turn counter
		 * input count is the number of actual input given by the player
		 * output count is the number of packets sent to the server
		 */
		turncount: 0,	// turncount is currently unused since we don't have means to access game's turn count.
		inputcount: 0,
		outputcount: 1,
		styles: '',
		saveUrl: '',
		story: {
		    name: '',
		    version: ''
		},
		// additional information saved with the transcript
		info: '',

		// currently Undum and Parchment are supported
		interpreter: ( typeof parchment != 'undefined' ? 'Parchment' : 'Undum' ),

		// the player can opt out by having feedback=0 in the url
		optOut: ( typeof( getUrlVars()[ 'feedback' ] ) != 'undefined' && getUrlVars()[ 'feedback' ] != '1' ),

		// is the transcript saving server offline?
		serverOffline: false,

		/*
		 * Send the transcript collected so far
		 */
		send: function( window, styles, text, cache ) {
			var self = this;

			if( !this.collectTranscripts() ) {
				return;
			}

			if( typeof( window ) != 'undefined' ) {
				self.window = window;
			}
			if( typeof( styles ) != 'undefined' ) {
				self.styles = styles;
			}
			if( typeof( text ) != 'undefined' ) {
				self.output = text;
			}

			var sendData = {
			   'session': self.sessionId,
			   'log': {
			         'inputcount': self.inputcount,
			         'outputcount': self.outputcount,
			         'input': self.command.input,
			         'output': self.output,
			         'window': self.window,
			         'styles': self.styles,
			         'timestamp': new Date().getTime()
			      }
			};

			if( cache ) {
				self.cache.push( sendData );
			}
			else {
				if( self.cache.length > 0 ) {
					self.cache.push( sendData );
					sendData = self.cache;
					self.cache = [];
				}

				jQuery.ajax( {
					type: 'POST',
					url: self.saveUrl,
					data: { data: sendData }
				} );
			}

			// clearing the buffer for next turn
			self.output = '';
			self.outputcount++;
		},

		/*
		 * Send the collected cache
		 */
		sendCache: function() {
			var self = this;

			if( this.collectTranscripts() && self.cache.length > 0 ) {
				jQuery.ajax( {
					type: 'POST',
					url: self.saveUrl,
					data: { data: self.cache }
				} );
				self.cache = [];
			}
		},

		/*
		 * Check whether we should collect transcript information.
		 * Transcripts are collected if:
		 *  - we know the url where to send the transcripts
		 *  - the player hasn't opted out with feedback=0 option
		 */
		collectTranscripts: function() {
			if( this.saveUrl == '' || this.optOut || this.serverOffline ) {
				return false;
			}
			return true;
		},

		initialize: function( url ) {
			var self = this;

			if( typeof url == 'string' ) {
				self.saveUrl = url;
			}

			// Fill story name + version from Undum variables
			if( typeof undum != 'undefined' ) {
			    if( self.story.name == '' ) {
			        self.story.name = undum.game.id;
			    }

			    if( self.story.version == '' ) {
			        self.story.version = undum.game.version;
			    }
			}

			// If story name hasn't been given, set it to the file name.
			// This will not work with the archive search thing.
			if( self.story.name == '' ) {
				if( typeof( parchment.options.default_story ) != 'undefined' && parchment.options.default_story != '' ) {
					self.story.name = parchment.options.default_story;

					if( !parchment.options.lock_story && typeof( getUrlVars()[ 'story' ] ) != 'undefined' && getUrlVars()[ 'story' ] != '' ){
						self.story.name = getUrlVars()[ 'story' ];
					}
				}
				else {
					if( !parchment.options.lock_story && typeof( getUrlVars()[ 'story' ] ) != 'undefined' && getUrlVars()[ 'story' ] != '' ){
						self.story.name = getUrlVars()[ 'story' ];
					}
				}
			}

			if( self.story.name == '' ) {
				self.story.name = '(unknown)';
			}

			if( !self.collectTranscripts() ) {
				return false;
			}

			var browserString = jQuery.browser.name+' '+jQuery.browser.version+' '+jQuery.os.name;

			// there doesn't seem to be an easy way to find out which engine
			// is or will be running at this point.
			/* var engine = '';
			if( typeof( ENGINE_DESCRIPTION ) != 'undefined' ) {
				engine = ENGINE_DESCRIPTION;
			} */

			var initString = {
					'session': self.sessionId,
					'start': {
						'story': self.story.name,
						'version': self.story.version,
                        'info': self.info,
						'interpreter': self.interpreter,
						'browser': browserString
					}
				};

			jQuery.ajax( {
				type: 'POST',
				url: self.saveUrl,
				data: { data: initString },
				// check what the server returns, flag it offline if not ok
				error: function() {
					self.serverOffline = true;
				},
				success: function( data ) {
					if( data.toLowerCase() != 'ok' ) {
						self.serverOffline = true;
					}
				}
			} );

			return true;
		},

		charName: function( keyCode ) {
			// the hex values are Glulx keycodes
			switch( keyCode ) {
		    	case Event.KEY_BACKSPACE:
					return '<backspace>';
		    	case 0xfffffff9:
		    		return '<backspace/delete>'; // apparently Glulx doesn't make a difference
			    case Event.KEY_TAB:
			    case 0xfffffff7:
					return '<tab>';
				case 13:
				case 0xfffffffa:
					return '<enter>';
			    case Event.KEY_ESC:
			    case 0xfffffff8:
					return '<esc>';
				case 32:
					return '<space>';
			    case Event.KEY_LEFT:
			    case 0xfffffffe:
					return '<left>';
			    case Event.KEY_UP:
			    case 0xfffffffc:
					return '<up>';
			    case Event.KEY_RIGHT:
			    case 0xfffffffd:
					return '<right>';
			    case Event.KEY_DOWN:
			    case 0xfffffffb:
			    	return '<down>';
				case 46:
					return '';
			    case Event.KEY_PAGEUP:
			    case 0xfffffff6:
			    	return '<pgup>';
			    case Event.KEY_PAGEDOWN:
			    case 0xfffffff5:
			    	return '<pgdown>';
			    case Event.KEY_HOME:
			    case 0xfffffff4:
			    	return '<home>';
			    case Event.KEY_END:
			    case 0xfffffff3:
			    	return '<end>';
			    case 0xffffffef:
			    	return '<F1>';
			    case 0xffffffee:
			    	return '<F2>';
			    case 0xffffffed:
			    	return '<F3>';
			    case 0xffffffec:
			    	return '<F4>';
			    case 0xffffffeb:
			    	return '<F5>';
			    case 0xffffffea:
			    	return '<F6>';
			    case 0xffffffe9:
			    	return '<F7>';
			    case 0xffffffe8:
			    	return '<F8>';
			    case 0xffffffe7:
			    	return '<F9>';
			    case 0xffffffe6:
			    	return '<F10>';
			    case 0xffffffe5:
			    	return '<F11>';
			    case 0xffffffe4:
			    	return '<F12>';
				default:
					return String.fromCharCode( keyCode );
			}

		},

		/**
		 * Undum-specific functions
		 */
		undum: {
		    oldContentLength: 0,
		    prepare: function( link ) {
		        var self = ifRecorder;
		        self.command.input = link;
		        this.oldContentLength = jQuery( '#content' ).html().length;
		    },
		    send: function( link ) {
		        var self = ifRecorder;
		        self.inputcount++;
		        self.output = jQuery( '#content' ).html().substring( this.oldContentLength );
		        self.send();
		    }
		}
};

jQuery( document ).ready(function($){

/* save commands when Parchment calls the hooks in [z]ui.js */
$( document ).bind(
		'LineInput',
		function( command ) {
//			console.log( 'cmd: '+command.toSource() );
		    ifRecorder.command = command;
		    ifRecorder.inputcount++;
		}
	);

$( document ).bind(
		'CharInput',
		function( command ) {
//			console.log( 'charcmd: '+command.toSource() );
		    ifRecorder.command = command;
		    ifRecorder.command.input = ifRecorder.charName( command.input.keyCode );
		    ifRecorder.inputcount++;
		}
	);

// Sending main game texts to the recorder.
// Status line is saved by the modified Console.renderHtml().
$( document ).bind(
		'TextOutput',
		function( data ) {
			if( data.output.window == 0 ) {
			    ifRecorder.send( data.output.window, data.output.styles, data.output.text );
			}
		}
);

// Glk text output saving
$( document ).bind(
		'GlkOutput',
		function( data ) {
			if( typeof data.output === 'undefined' ) {
				return;
			}

			for( var i = 0; i < data.output.length; ++i ) {
				if( typeof data.output[ i ].text !== 'undefined' ) {
					for( var j = 0; j < data.output[ i ].text.length; ++j ) {
						ifRecorder.styles = '';
						ifRecorder.output = "\n";

						if( typeof( data.output[ i ].text[ j ].content ) != 'undefined' ) {
							for( var k = 0; k < data.output[ i ].text[ j ].content.size(); k += 2 ) {
								ifRecorder.styles = data.output[ i ].text[ j ].content[ k ];
								ifRecorder.output = data.output[ i ].text[ j ].content[ k+1 ];
								if( k == data.output[ i ].text[ j ].content.size() - 2 ) {
									ifRecorder.output += "\n";
								}
								ifRecorder.send( ifRecorder.window, ifRecorder.styles, ifRecorder.output, true );
							}
						}
						else {
							ifRecorder.send( ifRecorder.window, ifRecorder.styles, ifRecorder.output, true );
						}
					}
				}
			}
			ifRecorder.sendCache();
		}
);

/*
 * We need to modify Gnusto runner to get the final formatting of the status line.
 * Since Parchment loads some library files asynchronously we'll have to wait until
 * the runner.js file is loaded. When we reach the TextOutput function for the first
 * time we the file has been loaded and the first status line has not yet been printed.
 *
 * As far as I can tell Console.renderHtml is called only when building the status line,
 * so we can safely (?) set the window to 1 (status line) when sending this text to
 * the transcript recorder.
 *
 * (There must be a better way to do this, but this works so it'll have to suffice.)
 */

var firstTextOutputHandler = function( data ) {
	Console.prototype.renderHtml = function() {
    var string = "";
    var currString = "";
    for (var y = 0; y < this.height; y++) {
      var currStyle = null;
      for (var x = 0; x < this.width; x++) {
        if (this._styles[y][x] !== currStyle) {
          if (currStyle !== null) {
  			ifRecorder.send( 1, currStyle, currString.replace( /\&nbsp\;/gi, ' ') );
			currString = '';
            string += "";
          }
          currStyle = this._styles[y][x];
          if (currStyle !== null) {
            string += '';
          }
        }
        string += this._characters[y][x];
        currString += this._characters[y][x];
      }
      if (currStyle !== null) {
        string += "";
		ifRecorder.send( 1, currStyle, currString.replace( /\&nbsp\;/gi, ' ' )+"\n" );
		currString = '';
      }
      string += "
";
    }
    return string;
  };

	// remove the handler, no need to run more than once
	$( document ).unbind( 'TextOutput', firstTextOutputHandler );
};

$( document ).bind( 'TextOutput', firstTextOutputHandler );

}(jQuery));

/* source: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html */
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


text:
	#pragma once // Some compilers (e.g. VC++) benefit significantly from using this. We've measured 3-4% build speed improvements in apps as a result.
#endif

namespace eastl
{

	/// EASTL_FIXED_TUPLE_VECTOR_DEFAULT_NAME
	///
	/// Defines a default container name in the absence of a user-provided name.
	/// In the case of fixed-size containers, the allocator name always refers
	/// to overflow allocations.
	///
	#ifndef EASTL_FIXED_TUPLE_VECTOR_DEFAULT_NAME
		#define EASTL_FIXED_TUPLE_VECTOR_DEFAULT_NAME EASTL_DEFAULT_NAME_PREFIX " fixed_tuple_vector" // Unless the user overrides something, this is "EASTL fixed_vector".
	#endif

	/// EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR
	///
	#ifndef EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR
		#define EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR overflow_allocator_type(EASTL_FIXED_TUPLE_VECTOR_DEFAULT_NAME)
	#endif

// External interface of fixed_tuple_vector
template <size_t nodeCount, bool bEnableOverflow, typename... Ts>
class fixed_tuple_vector : public TupleVecInternal::TupleVecImpl<fixed_vector_allocator<
	TupleVecInternal::TupleRecurser<Ts...>::GetTotalAllocationSize(nodeCount, 0), 1,
	TupleVecInternal::TupleRecurser<Ts...>::GetTotalAlignment(), 0,
	bEnableOverflow, EASTLAllocatorType>, make_index_sequence<sizeof...(Ts)>, Ts...>
{
public:
	typedef fixed_vector_allocator<
		TupleVecInternal::TupleRecurser<Ts...>::GetTotalAllocationSize(nodeCount, 0), 1,
		TupleVecInternal::TupleRecurser<Ts...>::GetTotalAlignment(), 0,
		bEnableOverflow, EASTLAllocatorType> fixed_allocator_type;
	typedef aligned_buffer<fixed_allocator_type::kNodesSize, fixed_allocator_type::kNodeAlignment> aligned_buffer_type;
	typedef fixed_tuple_vector<nodeCount, bEnableOverflow, Ts...> this_type;
	typedef EASTLAllocatorType overflow_allocator_type;

	typedef TupleVecInternal::TupleVecImpl<fixed_allocator_type, make_index_sequence<sizeof...(Ts)>, Ts...> base_type;
	typedef typename base_type::size_type size_type;

private:
	aligned_buffer_type mBuffer;

public:
	fixed_tuple_vector()
		: base_type(fixed_allocator_type(mBuffer.buffer), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{ }

	fixed_tuple_vector(const overflow_allocator_type& allocator)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{ }

	fixed_tuple_vector(this_type&& x)
		: base_type(fixed_allocator_type(mBuffer.buffer), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::get_allocator().copy_overflow_allocator(x.get_allocator());
		base_type::DoInitFromIterator(make_move_iterator(x.begin()), make_move_iterator(x.end()));
		x.clear();
	}

	fixed_tuple_vector(this_type&& x, const overflow_allocator_type& allocator)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFromIterator(make_move_iterator(x.begin()), make_move_iterator(x.end()));
		x.clear();
	}

	fixed_tuple_vector(const this_type& x)
		: base_type(fixed_allocator_type(mBuffer.buffer), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::get_allocator().copy_overflow_allocator(x.get_allocator());
		base_type::DoInitFromIterator(x.begin(), x.end());
	}

	fixed_tuple_vector(const this_type& x, const overflow_allocator_type& allocator)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFromIterator(x.begin(), x.end());
	}

	template <typename MoveIterBase>
	fixed_tuple_vector(move_iterator<MoveIterBase> begin, move_iterator<MoveIterBase> end, const overflow_allocator_type& allocator = EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFromIterator(begin, end);
	}

	template <typename Iterator>
	fixed_tuple_vector(Iterator begin, Iterator end, const overflow_allocator_type& allocator = EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFromIterator(begin, end);
	}

	fixed_tuple_vector(size_type n, const overflow_allocator_type& allocator = EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitDefaultFill(n);
	}

	fixed_tuple_vector(size_type n, const Ts&... args)
		: base_type(fixed_allocator_type(mBuffer.buffer), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFillArgs(n, args...);
	}

	fixed_tuple_vector(size_type n, const Ts&... args, const overflow_allocator_type& allocator)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFillArgs(n, args...);
	}

	fixed_tuple_vector(size_type n,
				typename base_type::const_reference_tuple tup,
				const overflow_allocator_type& allocator = EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFillTuple(n, tup);
	}

	fixed_tuple_vector(const typename base_type::value_tuple* first, const typename base_type::value_tuple* last,
		const overflow_allocator_type& allocator = EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFromTupleArray(first, last);
	}

	fixed_tuple_vector(std::initializer_list<typename base_type::value_tuple> iList,
		const overflow_allocator_type& allocator = EASTL_FIXED_TUPLE_VECTOR_DEFAULT_ALLOCATOR)
		: base_type(fixed_allocator_type(mBuffer.buffer, allocator), mBuffer.buffer, nodeCount, fixed_allocator_type::kNodeSize)
	{
		base_type::DoInitFromTupleArray(iList.begin(), iList.end());
	}

	this_type& operator=(const this_type& other)
	{
		base_type::operator=(other);
		return *this;
	}

	this_type& operator=(this_type&& other)
	{
		base_type::clear();
		// OK to call DoInitFromIterator in a non-ctor scenario because clear() reset everything, more-or-less
		base_type::DoInitFromIterator(make_move_iterator(other.begin()), make_move_iterator(other.end()));
		other.clear();
		return *this;
	}

	this_type& operator=(std::initializer_list<typename base_type::value_tuple> iList)
	{
		base_type::operator=(iList);
		return *this;
	}

	void swap(this_type& x)
	{
		// If both containers are using the heap instead of local memory
		// then we can do a fast pointer swap instead of content swap.
		if ((has_overflowed() && x.has_overflowed()) && (get_overflow_allocator() == x.get_overflow_allocator()))
		{
			base_type::swap(x);
		}
		else
		{
			// Fixed containers use a special swap that can deal with excessively large buffers.
			eastl::fixed_swap(*this, x);
		}
	}

	// Returns the max fixed size, which is the user-supplied nodeCount parameter.
	size_type max_size() const { return nodeCount; }
	// Returns true if the fixed space has been fully allocated. Note that if overflow is enabled,
	// the container size can be greater than nodeCount but full() could return true because the
	// fixed space may have a recently freed slot.
	bool full() const { return (base_type::mNumElements >= nodeCount) || ((void*)base_type::mpData != (void*)mBuffer.buffer);	}
	// Returns true if the allocations spilled over into the overflow allocator. Meaningful
	// only if overflow is enabled.
	bool has_overflowed() const { return ((void*)base_type::mpData != (void*)mBuffer.buffer); }
	// Returns the value of the bEnableOverflow template parameter.
	bool can_overflow() const { return bEnableOverflow; }

	const overflow_allocator_type& get_overflow_allocator() const { return base_type::get_allocator().get_overflow_allocator(); }
};

template <size_t nodeCount, bool bEnableOverflow, typename... Ts>
inline void swap(fixed_tuple_vector<nodeCount, bEnableOverflow, Ts...>& a,
				fixed_tuple_vector<nodeCount, bEnableOverflow, Ts...>& b)
{
	a.swap(b);
}

}  // namespace eastl

#endif  // EASTL_TUPLEVECTOR_H


text:
package com.koch.ambeth.merge.independent;

import com.koch.ambeth.service.config.ServiceConfigurationConstants;
import com.koch.ambeth.testutil.TestProperties;

@TestProperties(name = ServiceConfigurationConstants.mappingFile,
		value = "com/koch/ambeth/merge/independent/independent-orm20.xml")
public class IndependentEntityMetaDataClient20Test extends IndependentEntityMetaDataClientTest {
}


text:
require 'helper'
TEST_KEY = 'bdf79cbc8aa8d866b77dccfe9349815e'

class TestBeerMapping < Test::Unit::TestCase
  context "A new beer search" do
    setup do
      @beer = BeerMapping::API.new(TEST_KEY)
      @beer.find_by_location("chicago")
    end

    should "return a pub from chicago when searching by location, chicago" do
      assert_equal @beer.locations[0].city, 'Chicago'
    end

    should "have a geo location" do
      assert !@beer.locations[0].geo.nil?
    end

    should "have image attributes if an image is present" do
      if !@beer.locations[0].images.nil?
        assert !@beer.locations[0].images[0].url.nil?
        assert !@beer.locations[0].images[0].thumburl.nil?
        assert !@beer.locations[0].images[0].caption.nil?
        assert !@beer.locations[0].images[0].height.nil?
        assert !@beer.locations[0].images[0].width.nil?
      end
    end

    should "have rating attributes if a rating is present" do
      if !@beer.locations[0].ratings.nil?
        assert !@beer.locations[0].ratings.service.nil?
        assert !@beer.locations[0].ratings.atmosphere.nil?
        assert !@beer.locations[0].ratings.selection.nil?
        assert !@beer.locations[0].ratings.overall.nil?
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Orchid\Platform\Commands;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Orchid\Platform\Dashboard;

class LinkCommand extends Command
{
    /**
     * The console command signature.
     *
     * @var string
     */
    protected $signature = 'orchid:link';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a symbolic link from resource orchid';

    /**
     * Execute the console command.
     *
     * @param Dashboard  $dashboard
     * @param Filesystem $filesystem
     *
     * @return void
     */
    public function handle(Dashboard $dashboard, Filesystem $filesystem)
    {
        $prefix = public_path('resources');

        $filesystem->ensureDirectoryExists($prefix);

        $dashboard->getPublicDirectory()->each(function ($path, $package) use ($prefix, $filesystem) {
            $package = $prefix.'/'.$package;
            $path = rtrim($path, '/');

            if (! $filesystem->exists($package)) {
                $filesystem->link($path, $package);
                $this->line("The [$package] directory has been linked.");
            }
        });

        $this->info('Links have been created.');
    }
}


text:
import tweepy

class TwitterClass:
    '''Twitter class for use with twitter'''
    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
        self.consummer_key = consumer_key
        self.consummer_secret = consumer_secret
        self.access_token = access_token
        self.access_toke_secret = access_token_secret

        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)

        self.api = tweepy.API(auth)

    def getTweets(self, url):
        public_tweets = self.api.search([])
        for tweet in public_tweets:
            print(tweet.text)

    def searchTweets(self, hashtag, limit):
        cursor = tweepy.Cursor(self.api.search,
                               q=hashtag,
                               count=100,
                               result_type="recent").items(limit)

        for tweet in cursor:
            print(tweet.text)

    def searchTweetsWithoutRT(self, hashtag, limit):
        cursor = tweepy.Cursor(self.api.search,
                               q=hashtag + " -RT",
                               count=100,
                               result_type="recent").items(limit)

        for tweet in cursor:
            print(tweet.text)

    def getLastTweetWithoutRT(self, hashtag):
        cursor = tweepy.Cursor(self.api.search,
                               q=hashtag + " -RT",
                               count=100,
                               result_type="recent").items(1)

        return cursor.next().text


text:
@implementation AKWarpedFFT
{
    AKFSignal *fsigin;
    AKParameter *kscal;
    AKParameter *kshift;
    AKControl *klowest;
    AKControl *kmeth;
    AKControl *kgain;
    AKControl *kcoefs;
}

- (instancetype)initWithInput:(AKFSignal *)sourceSignal
                 scalingRatio:(AKParameter *)scalingRatio
                        shift:(AKParameter *)shift
{
    self = [super initWithString:[self operationName]];
    if (self) {
        fsigin = sourceSignal;
        kscal = scalingRatio;
        kshift = shift;
        klowest = akp(0);
        kmeth = akp(1);
        kgain = akp(1);
        kcoefs = akp(80);
        self.state = @"connectable";
        self.dependencies = @[fsigin, kscal, kshift];

    }
    return self;
}

- (void)setOptionalLowFrequency:(AKControl *)lowFrequency {
    klowest = lowFrequency;
}

- (void)setOptionalExtractionMethod:(AKControl *)extractionMethod {
    kmeth = extractionMethod;
}

- (void)setOptionalGain:(AKControl *)gain {
    kgain = gain;
}

- (void)setOptionalNumberOfCoefficients:(AKControl *)numberOfCoefficients {
    kcoefs = numberOfCoefficients;
}

- (NSString *)stringForCSD {
    return [NSString stringWithFormat:
            @"%@ pvswarp %@, %@, %@, %@, %@, %@, %@",
            self, fsigin, kscal, kshift, klowest, kmeth, kgain, kcoefs];
}

@end


text:
using Store.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Store.Data
{
    public class StoreSeedData : DropCreateDatabaseIfModelChanges<StoreEntities>
    {
        protected override void Seed(StoreEntities context)
        {
            GetCategories().ForEach(c => context.Categories.Add(c));
            GetGadgets().ForEach(g => context.Gadgets.Add(g));

            context.Commit();
        }

        private static List<Category> GetCategories()
        {
            return new List<Category>
            {
                new Category {
                    Name = "Tablets"
                },
                new Category {
                    Name = "Laptops"
                },
                new Category {
                    Name = "Mobiles"
                }
            };
        }

        private static List<Gadget> GetGadgets()
        {
            return new List<Gadget>
            {
                new Gadget {
                    Name = "ProntoTec 7",
                    Description = "Android 4.4 KitKat Tablet PC, Cortex A8 1.2 GHz Dual Core Processor,512MB / 4GB,Dual Camera,G-Sensor (Black)",
                    CategoryID = 1,
                    Price = 46.99m,
                    Image = "prontotec.jpg"
                },
                new Gadget {
                    Name = "Samsung Galaxy",
                    Description = "Android 4.4 Kit Kat OS, 1.2 GHz quad-core processor",
                    CategoryID = 1,
                    Price = 120.95m,
                    Image= "samsung-galaxy.jpg"
                },
                new Gadget {
                    Name = "NeuTab® N7 Pro 7",
                    Description = "NeuTab N7 Pro tablet features the amazing powerful, Quad Core processor performs approximately Double multitasking running speed, and is more reliable than ever",
                    CategoryID = 1,
                    Price = 59.99m,
                    Image= "neutab.jpg"
                },
                new Gadget {
                    Name = "Dragon Touch® Y88X 7",
                    Description = "Dragon Touch Y88X tablet featuring the incredible powerful Allwinner Quad Core A33, up to four times faster CPU, ensures faster multitasking speed than ever. With the super-portable size, you get a robust power in a device that can be taken everywhere",
                    CategoryID = 1,
                    Price = 54.99m,
                    Image= "dragon-touch.jpg"
                },
                new Gadget {
                    Name = "Alldaymall A88X 7",
                    Description = "This Alldaymall tablet featuring the incredible powerful Allwinner Quad Core A33, up to four times faster CPU, ensures faster multitasking speed than ever. With the super-portable size, you get a robust power in a device that can be taken everywhere",
                    CategoryID = 1,
                    Price = 47.99m,
                    Image= "Alldaymall.jpg"
                },
                new Gadget {
                    Name = "ASUS MeMO",
                    Description = "Pad 7 ME170CX-A1-BK 7-Inch 16GB Tablet. Dual-Core Intel Atom Z2520 1.2GHz CPU",
                    CategoryID = 1,
                    Price = 94.99m,
                    Image= "asus-memo.jpg"
                },
                new Gadget {
                    Name = "ASUS 15.6-Inch",
                    Description = "Latest Generation Intel Dual Core Celeron 2.16 GHz Processor (turbo to 2.41 GHz)",
                    CategoryID = 2,
                    Price = 249.5m,
                    Image = "asus-latest.jpg"
                },
                new Gadget {
                    Name = "HP Pavilion 15-r030wm",
                    Description = "This Certified Refurbished product is manufacturer refurbished, shows limited or no wear, and includes all original accessories plus a 90-day warranty",
                    CategoryID = 2,
                    Price = 299.95m,
                    Image = "hp-pavilion.jpg"
                },
                new Gadget {
                    Name = "Dell Inspiron 15.6-Inch",
                    Description = "Intel Celeron N2830 Processor, 15.6-Inch Screen, Intel HD Graphics",
                    CategoryID = 2,
                    Price = 308.00m,
                    Image = "dell-inspiron.jpg"
                },
                new Gadget {
                    Name = "Acer Aspire E Notebook",
                    Description = "15.6 HD Active Matrix TFT Color LED (1366 x 768) 16:9 CineCrystal Display",
                    CategoryID = 2,
                    Price = 299.95m,
                    Image = "acer-aspire.jpg"
                },
                new Gadget {
                    Name = "HP Stream 13",
                    Description = "Intel Celeron N2840 Processor. 2 GB DDR3L SDRAM, 32 GB Solid-State Drive and 1TB OneDrive Cloud Storage for one year",
                    CategoryID = 2,
                    Price = 202.99m,
                    Image = "hp-stream.jpg"
                },
                new Gadget {
                    Name = "Nokia Lumia 521",
                    Description = "T-Mobile Cell Phone 4G - White. 5MP Camera - Snap creative photos with built-in digital lenses",
                    CategoryID = 3,
                    Price = 63.99m,
                    Image = "nokia-lumia.jpg"
                },
                new Gadget {
                    Name = "HTC Desire 816",
                    Description = "13 MP Rear Facing BSI Camera / 5 MP Front Facing",
                    CategoryID = 3,
                    Price = 177.99m,
                    Image = "htc-desire.jpg"
                },
                new Gadget {
                    Name = "Sanyo Innuendo",
                    Description = "Uniquely designed 3G-enabled messaging phone with side-flipping QWERTY keyboard and external glow-thru OLED dial pad that 'disappears' when not in use",
                    CategoryID = 3,
                    Price = 54.99m,
                    Image = "sanyo-innuendo.jpg"
                },
                new Gadget {
                    Name = "Ulefone N9000",
                    Description = "Unlocked world GSM phone. 3G-850/2100, 2G -850/900/1800/1900",
                    CategoryID = 3,
                    Price = 133.99m,
                    Image = "ulefone.jpg"
                }

            };
        }
    }
}


text:
<?php

namespace Sonido\Job\Strategy;

use EBernhardson\FastCGI\Client;
use EBernhardson\FastCGI\CommunicationException;
use Sonido\Model\Worker;
use Sonido\Model\Job;
use Sonido\Exception;

class Fastcgi implements StrategyInterface
{
    public $worker;

    public $waiting = false;

    public $requestData = array(
        'GATEWAY_INTERFACE' => 'FastCGI/1.0',
        'REQUEST_METHOD' => 'GET',
        'SERVER_SOFTWARE' => 'sonido-fastcgi/0.1-dev',
        'REMOTE_ADDR' => '127.0.0.1',
        'REMOTE_PORT' => 8888,
        'SERVER_ADDR' => '127.0.0.1',
        'SERVER_PORT' => 8888,
        'SERVER_PROTOCOL' => 'HTTP/1.1'
    );

    public function __construct($location, $script, $environment = array())
    {
        $this->location = $location;

        $port = false;
        if (false !== strpos($location, ':')) {
            list($location, $port) = explode(':', $location, 2);
        }

        $this->fcgi = new Client($location, $port);
        $this->fcgi->setKeepAlive(true);

        $this->requestData = $environment + $this->requestData + array(
            'SCRIPT_FILENAME' => $script,
            'SERVER_NAME' => php_uname('n'),
            'SONIDO_DIR' => __DIR__.'/../../../',
        );
    }

    public function setWorker(Worker $worker)
    {
        $this->worker = $worker;
    }

    public function perform(Job $job)
    {
        $status = 'Requested fcgi job execution from ' . $this->location . ' at ' . strftime('%F %T');
        $this->worker->log($status);

        $this->waiting = true;

        try {
            $this->fcgi->request(array(
                'SONIDO_JOB' => urlencode(serialize($job)),
            ) + $this->requestData, '');

            $response = $this->fcgi->response();
            $this->waiting = false;
        } catch (CommunicationException $e) {
            $this->waiting = false;
            $job->fail($e);

            return;
        }

        if ($response['statusCode'] !== 200) {
            $job->fail(new Exception(sprintf(
                'FastCGI job returned non-200 status code: %s Stdout: %s Stderr: %s',
                $response['headers']['status'],
                $response['body'],
                $response['stderr']
            )));
        }
    }

    public function shutdown()
    {
        if ($this->waiting === false) {
            $this->worker->log('No child to kill.');
        } else {
            $this->worker->log('Closing fcgi connection with job in progress.');
        }
        $this->fcgi->close();
    }
}


text:
package org.kie.workbench.common.services.backend.builder;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.compiler.kie.builder.impl.KieBuilderImpl;
import org.drools.compiler.kie.builder.impl.KieContainerImpl;
import org.drools.compiler.kie.builder.impl.KieModuleKieProject;
import org.drools.compiler.kproject.xml.PomModel;
import org.drools.workbench.models.datamodel.imports.Import;
import org.drools.workbench.models.datamodel.imports.Imports;
import org.drools.workbench.models.datamodel.oracle.TypeSource;
import org.guvnor.common.services.backend.file.DotFileFilter;
import org.guvnor.common.services.backend.file.JavaFileFilter;
import org.guvnor.common.services.project.builder.model.BuildResults;
import org.guvnor.common.services.project.builder.model.IncrementalBuildResults;
import org.guvnor.common.services.project.builder.service.BuildValidationHelper;
import org.guvnor.common.services.project.model.GAV;
import org.guvnor.common.services.project.model.Package;
import org.guvnor.common.services.project.model.Project;
import org.guvnor.common.services.project.model.ProjectImports;
import org.guvnor.common.services.shared.validation.model.ValidationMessage;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.Results;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.builder.IncrementalResults;
import org.kie.internal.builder.InternalKieBuilder;
import org.kie.scanner.KieModuleMetaData;
import org.kie.workbench.common.services.shared.project.KieProject;
import org.kie.workbench.common.services.shared.project.KieProjectService;
import org.kie.workbench.common.services.shared.project.ProjectImportsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.file.DirectoryStream;
import org.uberfire.java.nio.file.Files;
import org.uberfire.java.nio.file.Path;
import org.uberfire.workbench.events.ResourceChange;
import org.uberfire.workbench.events.ResourceChangeType;

import static org.kie.workbench.common.services.backend.builder.BaseFileNameResolver.*;
import static org.kie.workbench.common.services.backend.builder.BuildMessageBuilder.*;
import static org.kie.workbench.common.services.backend.builder.MessageConverter.*;
import static org.uberfire.commons.validation.PortablePreconditions.*;

public class Builder {

    private static final Logger logger = LoggerFactory.getLogger( Builder.class );

    //TODO internationalize error messages?.
    private final static String ERROR_EXTERNAL_CLASS_VERIFICATON = "Verification of class {0} failed and will not be available for authoring.\n" +
            "Please check the necessary external dependencies for this project are configured correctly.";

    private final static String ERROR_CLASS_NOT_FOUND = "Definition of class \"{0}\" was not found.\n" +
            "Please check the necessary external dependencies for this project are configured correctly.";

    private KieBuilder kieBuilder;
    private final KieServices kieServices;
    private final KieFileSystem kieFileSystem;

    private final Project project;
    private final GAV projectGAV;
    private final Path projectRoot;
    private final String projectPrefix;

    private final Handles handles = new Handles();

    private final IOService ioService;
    private final KieProjectService projectService;
    private final ProjectImportsService importsService;
    private final List<BuildValidationHelper> buildValidationHelpers;
    private final PackageNameWhiteList packageNameWhiteList;

    private final Map<Path, BuildValidationHelper> nonKieResourceValidationHelpers = new HashMap<Path, BuildValidationHelper>();
    private final Map<Path, List<ValidationMessage>> nonKieResourceValidationHelperMessages = new HashMap<Path, List<ValidationMessage>>();

    private final DirectoryStream.Filter<Path> javaResourceFilter = new JavaFileFilter();
    private final DirectoryStream.Filter<Path> dotFileFilter = new DotFileFilter();

    private Set<String> javaResources = new HashSet<String>();

    private LRUProjectDependenciesClassLoaderCache dependenciesClassLoaderCache;

    private LRUPomModelCache pomModelCache;

    public Builder( final Project project,
                    final IOService ioService,
                    final KieProjectService projectService,
                    final ProjectImportsService importsService,
                    final List<BuildValidationHelper> buildValidationHelpers,
                    final PackageNameWhiteList packageNameWhiteList,
                    final LRUProjectDependenciesClassLoaderCache dependenciesClassLoaderCache,
                    final LRUPomModelCache pomModelCache ) {
        this.project = project;
        this.ioService = ioService;
        this.projectService = projectService;
        this.importsService = importsService;
        this.buildValidationHelpers = buildValidationHelpers;
        this.packageNameWhiteList = packageNameWhiteList;
        this.projectGAV = project.getPom().getGav();
        this.projectRoot = Paths.convert( project.getRootPath() );
        this.projectPrefix = projectRoot.toUri().toString();
        this.kieServices = KieServices.Factory.get();
        this.kieFileSystem = kieServices.newKieFileSystem();
        this.dependenciesClassLoaderCache = dependenciesClassLoaderCache;
        this.pomModelCache = pomModelCache;

        DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = Files.newDirectoryStream( projectRoot );
        visitPaths( directoryStream );
    }

    public BuildResults build() {
        synchronized ( kieFileSystem ) {
            //KieBuilder is not re-usable for successive "full" builds
            kieBuilder = createKieBuilder( kieFileSystem );

            //Record RTEs from KieBuilder - that can fail if a rule uses an inaccessible class
            final BuildResults results = new BuildResults( projectGAV );
            try {
                final Results kieResults = kieBuilder.buildAll().getResults();
                results.addAllBuildMessages( convertMessages( kieResults.getMessages(),
                                                              handles ) );

            } catch ( LinkageError e ) {
                final String msg = MessageFormat.format( ERROR_CLASS_NOT_FOUND,
                                                         e.getLocalizedMessage() );
                logger.warn( msg );
                results.addBuildMessage( makeWarningMessage( msg ) );

            } catch ( Throwable e ) {
                final String msg = e.getLocalizedMessage();
                logger.error( msg,
                              e );
                results.addBuildMessage( makeErrorMessage( msg ) );

            } finally {
                pomModelCache.setEntry( project,
                                        ( (KieBuilderImpl) kieBuilder ).getPomModel() );
            }

            //Add validate messages from external helpers
            for ( Map.Entry<Path, BuildValidationHelper> e : nonKieResourceValidationHelpers.entrySet() ) {
                final org.uberfire.backend.vfs.Path vfsPath = Paths.convert( e.getKey() );
                final List<ValidationMessage> validationMessages = e.getValue().validate( vfsPath );
                nonKieResourceValidationHelperMessages.put( e.getKey(),
                                                            validationMessages );
                results.addAllBuildMessages( convertValidationMessages( validationMessages ) );
            }

            //Check external imports are available. These are loaded when a DMO is requested, but it's better to report them early
            final org.uberfire.java.nio.file.Path nioExternalImportsPath = projectRoot.resolve( "project.imports" );
            if ( Files.exists( nioExternalImportsPath ) ) {
                final org.uberfire.backend.vfs.Path externalImportsPath = Paths.convert( nioExternalImportsPath );
                final ProjectImports projectImports = importsService.load( externalImportsPath );
                final Imports imports = projectImports.getImports();
                for ( final Import item : imports.getImports() ) {
                    final String fullyQualifiedClassName = item.getType();
                    try {
                        Class clazz = this.getClass().getClassLoader().loadClass( item.getType() );

                    } catch ( ClassNotFoundException cnfe ) {
                        logger.warn( cnfe.getMessage() );
                        final String msg = MessageFormat.format( ERROR_CLASS_NOT_FOUND,
                                                                 fullyQualifiedClassName );
                        results.addBuildMessage( makeWarningMessage( msg ) );
                    }
                }
            }

            //At the end we are interested to ensure that external .jar files referenced as dependencies don't have
            // referential inconsistencies. We will at least provide a basic algorithm to ensure that if an external class
            // X references another external class Y, Y is also accessible by the class loader.
            final KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData( ( (InternalKieBuilder) kieBuilder ).getKieModuleIgnoringErrors() );
            final Set<String> packageNamesWhiteList = packageNameWhiteList.filterPackageNames( project,
                                                                                kieModuleMetaData.getPackages() );
            //store the project dependencies ClassLoader for optimization purposes.
            updateDependenciesClassLoader( project, kieModuleMetaData );

            for ( final String packageName : kieModuleMetaData.getPackages() ) {
                if ( packageNamesWhiteList.contains( packageName ) ) {
                    for ( final String className : kieModuleMetaData.getClasses( packageName ) ) {
                        final String fullyQualifiedClassName = packageName + "." + className;
                        try {
                            final Class clazz = kieModuleMetaData.getClass( packageName,
                                                                            className );
                            if ( clazz != null ) {
                                final TypeSource typeSource = getClassSource( kieModuleMetaData,
                                                                              clazz );
                                if ( TypeSource.JAVA_DEPENDENCY == typeSource ) {
                                    verifyExternalClass( clazz );
                                }
                            } else {
                                final String msg = MessageFormat.format( ERROR_EXTERNAL_CLASS_VERIFICATON,
                                                                         fullyQualifiedClassName );
                                logger.warn( msg );
                            }

                        } catch ( Throwable e ) {
                            final String msg = MessageFormat.format( ERROR_EXTERNAL_CLASS_VERIFICATON,
                                                                     fullyQualifiedClassName );
                            logger.warn( msg );
                            results.addBuildMessage( makeWarningMessage( msg ) );
                        }
                    }
                }
            }

            return results;
        }
    }

    private KieBuilder createKieBuilder( final KieFileSystem kieFileSystem ) {
        PomModel pomModel;
        final KieBuilderImpl kieBuilder = (KieBuilderImpl) kieServices.newKieBuilder( kieFileSystem );
        if ( ( pomModel = pomModelCache.getEntry( project ) ) != null ) {
            kieBuilder.setPomModel( pomModel );
        }
        return kieBuilder;
    }

    private void updateDependenciesClassLoader( final Project project,
                                                final KieModuleMetaData kieModuleMetaData ) {
        KieProject kieProject = projectService.resolveProject( project.getPomXMLPath() );
        if ( kieProject != null ) {
            dependenciesClassLoaderCache.setDependenciesClassLoader( kieProject,
                                                                     LRUProjectDependenciesClassLoaderCache.buildClassLoader( kieProject,
                                                                                kieModuleMetaData ) );
        }
    }

    private void verifyExternalClass( final Class clazz ) {
        //don't recommended to instantiate the class doing clazz.newInstance().
        clazz.getDeclaredConstructors();
        clazz.getDeclaredFields();
        clazz.getDeclaredMethods();
        clazz.getDeclaredClasses();
        clazz.getDeclaredAnnotations();
    }

    public IncrementalBuildResults addResource( final Path resource ) {
        synchronized ( kieFileSystem ) {
            checkNotNull( "resource",
                          resource );

            //Only files can be processed
            if ( !Files.isRegularFile( resource ) ) {
                return new IncrementalBuildResults( projectGAV );
            }

            checkAFullBuildHasBeenPerformed();

            //Resource Type might require "external" validation (i.e. it's not covered by Kie)
            final IncrementalBuildResults results = new IncrementalBuildResults( projectGAV );
            final BuildValidationHelper validator = getBuildValidationHelper( resource );
            if ( validator != null ) {
                final List<ValidationMessage> addedValidationMessages = validator.validate( Paths.convert( resource ) );

                results.addAllAddedMessages( convertValidationMessages( addedValidationMessages ) );
                results.addAllRemovedMessages( convertValidationMessages( nonKieResourceValidationHelperMessages.remove( resource ) ) );

                nonKieResourceValidationHelpers.put( resource,
                                                     validator );
                nonKieResourceValidationHelperMessages.put( resource,
                                                            addedValidationMessages );
            }

            //Add new resource
            final String destinationPath = resource.toUri().toString().substring( projectPrefix.length() + 1 );
            final InputStream is = ioService.newInputStream( resource );
            final BufferedInputStream bis = new BufferedInputStream( is );
            kieFileSystem.write( destinationPath,
                                 KieServices.Factory.get().getResources().newInputStreamResource( bis ) );
            addJavaClass( resource );
            handles.put( getBaseFileName( destinationPath ),
                         Paths.convert( resource ) );

            buildIncrementally( results,
                                destinationPath );

            return results;
        }
    }

    public IncrementalBuildResults deleteResource( final Path resource ) {
        synchronized ( kieFileSystem ) {
            checkNotNull( "resource",
                          resource );
            //The file has already been deleted so we can't check if the Path is a file or folder :(

            checkAFullBuildHasBeenPerformed();

            //Resource Type might have been validated "externally" (i.e. it's not covered by Kie). Clear any errors.
            final IncrementalBuildResults results = new IncrementalBuildResults( projectGAV );
            final BuildValidationHelper validator = getBuildValidationHelper( resource );
            if ( validator != null ) {
                nonKieResourceValidationHelpers.remove( resource );
                results.addAllRemovedMessages( convertValidationMessages( nonKieResourceValidationHelperMessages.remove( resource ) ) );
            }

            //Delete resource
            final String destinationPath = resource.toUri().toString().substring( projectPrefix.length() + 1 );
            kieFileSystem.delete( destinationPath );
            removeJavaClass( resource );

            buildIncrementally( results,
                                destinationPath );

            return results;
        }
    }

    public IncrementalBuildResults updateResource( final Path resource ) {
        synchronized ( kieFileSystem ) {
            return addResource( resource );
        }
    }

    public IncrementalBuildResults applyBatchResourceChanges( final Map<org.uberfire.backend.vfs.Path, Collection<ResourceChange>> changes ) {
        synchronized ( kieFileSystem ) {
            checkNotNull( "changes",
                          changes );

            checkAFullBuildHasBeenPerformed();

            //Add all changes to KieFileSystem before executing the build
            final List<String> changedFilesKieBuilderPaths = new ArrayList<String>();
            final List<ValidationMessage> nonKieResourceValidatorAddedMessages = new ArrayList<ValidationMessage>();
            final List<ValidationMessage> nonKieResourceValidatorRemovedMessages = new ArrayList<ValidationMessage>();

            for ( final Map.Entry<org.uberfire.backend.vfs.Path, Collection<ResourceChange>> pathCollectionEntry : changes.entrySet() ) {
                for ( final ResourceChange change : pathCollectionEntry.getValue() ) {
                    final ResourceChangeType type = change.getType();
                    final Path resource = Paths.convert( pathCollectionEntry.getKey() );

                    checkNotNull( "type",
                                  type );
                    checkNotNull( "resource",
                                  resource );

                    final String destinationPath = resource.toUri().toString().substring( projectPrefix.length() + 1 );
                    changedFilesKieBuilderPaths.add( destinationPath );
                    switch ( type ) {
                        case ADD:
                        case UPDATE:
                            //Only files can be processed
                            if ( !Files.isRegularFile( resource ) ) {
                                continue;
                            }

                            update( nonKieResourceValidatorAddedMessages,
                                    nonKieResourceValidatorRemovedMessages,
                                    resource,
                                    destinationPath );

                            break;
                        case DELETE:
                            delete( nonKieResourceValidatorRemovedMessages,
                                    resource,
                                    destinationPath );

                    }
                }
            }

            //Perform the Incremental build and get messages from incremental build
            final IncrementalBuildResults results = new IncrementalBuildResults( projectGAV );
            buildIncrementally( results,
                                toArray( changedFilesKieBuilderPaths ) );

            //Copy in BuildMessages for non-KIE resources
            results.addAllAddedMessages( convertValidationMessages( nonKieResourceValidatorAddedMessages ) );
            results.addAllRemovedMessages( convertValidationMessages( nonKieResourceValidatorRemovedMessages ) );

            return results;
        }
    }

    private String[] toArray( List<String> stringList ) {
        final String[] stringArray = new String[ stringList.size() ];
        stringList.toArray( stringArray );
        return stringArray;
    }

    private void delete( final List<ValidationMessage> nonKieResourceValidatorRemovedMessages,
                         final Path resource,
                         final String destinationPath ) {
        //Resource Type might have been validated "externally" (i.e. it's not covered by Kie). Clear any errors.
        nonKieResourceValidationHelpers.remove( resource );
        final List<ValidationMessage> removedValidationMessages = nonKieResourceValidationHelperMessages.remove( resource );
        if ( !( removedValidationMessages == null || removedValidationMessages.isEmpty() ) ) {
            for ( ValidationMessage validationMessage : removedValidationMessages ) {
                nonKieResourceValidatorRemovedMessages.add( validationMessage );
            }
        }

        //The file has already been deleted so we can't check if the Path is a file or folder :(
        kieFileSystem.delete( destinationPath );
        removeJavaClass( resource );
    }

    private void update( final List<ValidationMessage> nonKieResourceValidatorAddedMessages,
                         final List<ValidationMessage> nonKieResourceValidatorRemovedMessages,
                         final Path resource,
                         final String destinationPath ) {
        //Resource Type might require "external" validation (i.e. it's not covered by Kie)
        final BuildValidationHelper validator = getBuildValidationHelper( resource );
        if ( validator != null ) {
            final List<ValidationMessage> addedValidationMessages = validator.validate( Paths.convert( resource ) );

            if ( !( addedValidationMessages == null || addedValidationMessages.isEmpty() ) ) {
                for ( ValidationMessage validationMessage : addedValidationMessages ) {
                    nonKieResourceValidatorAddedMessages.add( validationMessage );
                }
            }

            final List<ValidationMessage> removedValidationMessages = nonKieResourceValidationHelperMessages.remove( resource );
            if ( !( removedValidationMessages == null || removedValidationMessages.isEmpty() ) ) {
                for ( ValidationMessage validationMessage : removedValidationMessages ) {
                    nonKieResourceValidatorRemovedMessages.add( validationMessage );
                }
            }
            nonKieResourceValidationHelpers.put( resource,
                                                 validator );
            nonKieResourceValidationHelperMessages.put( resource,
                                                        addedValidationMessages );
        }

        //Add new resource
        final InputStream is = ioService.newInputStream( resource );
        final BufferedInputStream bis = new BufferedInputStream( is );
        kieFileSystem.write( destinationPath,
                             KieServices.Factory.get().getResources().newInputStreamResource( bis ) );
        addJavaClass( resource );
        handles.put( getBaseFileName( destinationPath ),
                     Paths.convert( resource ) );
    }

    private void buildIncrementally( final IncrementalBuildResults results,
                                     final String... destinationPath ) {
        try {
            final IncrementalResults incrementalResults = ( (InternalKieBuilder) kieBuilder ).createFileSet( destinationPath ).build();
            results.addAllAddedMessages( convertMessages( incrementalResults.getAddedMessages(), handles ) );
            results.addAllRemovedMessages( convertMessages( incrementalResults.getRemovedMessages(), handles ) );

            //Tidy-up removed message handles
            for ( Message message : incrementalResults.getRemovedMessages() ) {
                handles.remove( Handles.RESOURCE_PATH + "/" + getBaseFileName( message.getPath() ) );
            }

        } catch ( LinkageError e ) {
            final String msg = MessageFormat.format( ERROR_CLASS_NOT_FOUND,
                                                     e.getLocalizedMessage() );
            logger.warn( msg );
            results.addAddedMessage( makeWarningMessage( msg ) );

        } catch ( Throwable e ) {
            final String msg = e.getLocalizedMessage();
            logger.error( msg,
                          e );
            results.addAddedMessage( makeErrorMessage( msg ) );
        }
    }

    private void checkAFullBuildHasBeenPerformed() {
        if ( !isBuilt() ) {
            throw new IllegalStateException( "A full build needs to be performed before any incremental operations." );
        }
    }

    public KieModule getKieModule() {
        //Kie classes are only available once built
        if ( !isBuilt() ) {
            build();
        }
        synchronized ( kieFileSystem ) {
            return kieBuilder.getKieModule();
        }
    }

    public KieModule getKieModuleIgnoringErrors() {
        //Kie classes are only available once built
        if ( !isBuilt() ) {
            build();
        }
        synchronized ( kieFileSystem ) {
            return ( (InternalKieBuilder) kieBuilder ).getKieModuleIgnoringErrors();
        }
    }

    public KieContainer getKieContainer() {
        BuildResults results = null;

        //Kie classes are only available once built
        if ( !isBuilt() ) {
            results = build();
        } else {
            results = new BuildResults();
            results.addAllBuildMessages( convertMessages( kieBuilder.getResults().getMessages(), handles ) );
        }
        //It's impossible to retrieve a KieContainer if the KieModule contains errors
        if ( results.getErrorMessages().isEmpty() ) {
            // Do not retrieve the KieContainer with KieServices.newKieContainer(releaseId) since this looks-up the KieModule to
            // create the KieContainer from KieRepository. This holds the most recent KieModule (for the ReleaseId) that was built with
            // kieBuilder.buildAll() which *may* be a KieModule created during asset validation and hence will lack many assets.
            // See https://bugzilla.redhat.com/show_bug.cgi?id=1202551
            final KieModule kieModule = kieBuilder.getKieModule();
            final ReleaseId releaseId = kieModule.getReleaseId();
            final org.drools.compiler.kie.builder.impl.KieProject kieProject = new KieModuleKieProject( (InternalKieModule) kieBuilder.getKieModule(), null );
            final KieContainer kieContainer = new KieContainerImpl( kieProject,
                                                                    KieServices.Factory.get().getRepository(),
                                                                    releaseId );
            return kieContainer;
        } else {
            return null;
        }
    }

    public boolean isBuilt() {
        synchronized ( kieFileSystem ) {
            return kieBuilder != null;
        }
    }

    private void visitPaths( final DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream ) {
        for ( final org.uberfire.java.nio.file.Path path : directoryStream ) {
            if ( Files.isDirectory( path ) ) {
                visitPaths( Files.newDirectoryStream( path ) );

            } else {
                //Don't process dotFiles
                if ( !dotFileFilter.accept( path ) ) {

                    //Resource Type might require "external" validation (i.e. it's not covered by Kie)
                    final BuildValidationHelper validator = getBuildValidationHelper( path );
                    if ( validator != null ) {
                        nonKieResourceValidationHelpers.put( path,
                                                             validator );
                    }

                    //Add new resource
                    final String destinationPath = path.toUri().toString().substring( projectPrefix.length() + 1 );
                    final InputStream is = ioService.newInputStream( path );
                    final BufferedInputStream bis = new BufferedInputStream( is );
                    kieFileSystem.write( destinationPath,
                                         KieServices.Factory.get().getResources().newInputStreamResource( bis ) );
                    handles.put( getBaseFileName( destinationPath ),
                                 Paths.convert( path ) );

                    //Java classes are handled by KIE so we can safely post-process them here
                    addJavaClass( path );
                }
            }
        }
    }

    private void addJavaClass( final Path path ) {
        if ( !javaResourceFilter.accept( path ) ) {
            return;
        }
        final String fullyQualifiedClassName = getFullyQualifiedClassName( path );
        if ( fullyQualifiedClassName != null ) {
            javaResources.add( fullyQualifiedClassName );
        }
    }

    private void removeJavaClass( final Path path ) {
        if ( !javaResourceFilter.accept( path ) ) {
            return;
        }
        final String fullyQualifiedClassName = getFullyQualifiedClassName( path );
        if ( fullyQualifiedClassName != null ) {
            javaResources.remove( fullyQualifiedClassName );
        }
    }

    private String getFullyQualifiedClassName( final Path path ) {
        final Package pkg = projectService.resolvePackage( Paths.convert( path ) );
        final String packageName = pkg.getPackageName();
        if ( packageName == null ) {
            return null;
        }
        final String className = path.getFileName().toString().replace( ".java",
                                                                        "" );
        return ( packageName.equals( "" ) ? className : packageName + "." + className );
    }

    public TypeSource getClassSource( final KieModuleMetaData metaData,
                                      final Class<?> clazz ) {
        //Was the Type declared in DRL
        if ( metaData.getTypeMetaInfo( clazz ).isDeclaredType() ) {
            return TypeSource.DECLARED;
        }

        //Was the Type defined inside the project or within a dependency
        String fullyQualifiedClassName = clazz.getName();
        int innerClassIdentifierIndex = fullyQualifiedClassName.indexOf( "$" );
        if ( innerClassIdentifierIndex > 0 ) {
            fullyQualifiedClassName = fullyQualifiedClassName.substring( 0,
                                                                         innerClassIdentifierIndex );
        }
        if ( javaResources.contains( fullyQualifiedClassName ) ) {
            return TypeSource.JAVA_PROJECT;
        }
        return TypeSource.JAVA_DEPENDENCY;
    }

    private BuildValidationHelper getBuildValidationHelper( final Path nioResource ) {
        for ( BuildValidationHelper validator : buildValidationHelpers ) {
            final org.uberfire.backend.vfs.Path resource = Paths.convert( nioResource );
            if ( validator.accepts( resource ) ) {
                return validator;
            }
        }
        return null;
    }

}


text:
package br.com.social.model.contato;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.ForeignKey;

import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import com.fasterxml.jackson.annotation.JsonIgnore;

import br.com.social.model.contato.enums.Perfil;
import br.com.social.model.contato.enums.TipoEmail;

@Entity
public class Email implements Serializable {
	@JsonIgnore
	public static final long serialVersionUID = -7741393511974698310L;

	public Email() {
		// TODO Auto-generated constructor stub
		this.contato = null;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@JsonIgnore
	@OnDelete(action = OnDeleteAction.CASCADE)
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "id_cliente", updatable = false, foreignKey = @ForeignKey(name = "fk_email_contato"), nullable = false)
	private Contato contato;

	@Column(nullable = false, updatable = false, length = 255)
	private String email;

	@Column(columnDefinition = "ENUM('PESSOAL', 'COMERCIAL', 'OUTROS') NOT NULL")
	@Enumerated(EnumType.STRING)
	private TipoEmail tipo;

	@Enumerated(EnumType.STRING)
	@Column(columnDefinition = "ENUM('PUBLICO', 'PRIVADO') NOT NULL")
	private Perfil perfil;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Contato getContato() {
		return contato;
	}

	public void setContato(Contato contato) {
		this.contato = contato;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public TipoEmail getTipo() {
		return tipo;
	}

	public void setTipo(TipoEmail tipo) {
		this.tipo = tipo;
	}

	public Perfil getPerfil() {
		return perfil;
	}

	public void setPerfil(Perfil perfil) {
		this.perfil = perfil;
	}
}


text: included template


text:
package org.jayware.e2.event.impl;

import org.jayware.e2.context.api.Context;
import org.jayware.e2.context.api.Disposable;
import org.jayware.e2.event.api.Event;
import org.jayware.e2.event.api.EventDispatcher;
import org.jayware.e2.event.api.EventDispatcherFactory;
import org.jayware.e2.event.api.EventFilter;
import org.jayware.e2.event.api.Query;
import org.jayware.e2.event.api.ResultSet;
import org.jayware.e2.event.api.Subscription;
import org.jayware.e2.event.api.SubscriptionBookkeeper;
import org.jayware.e2.event.api.SubscriptionFactory;
import org.jayware.e2.util.ReferenceType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.atomic.AtomicInteger;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jayware.e2.util.ObjectUtil.getClassNameOf;

public class EventBus
implements Disposable
{
    private static final Logger log = LoggerFactory.getLogger(EventBus.class);

    private final Context myContext;

    private final EventDispatcherFactory myEventDispatcherFactory;
    private final SubscriptionFactory mySubscriptionFactory;

    private final SubscriptionBookkeeper myBookkeeper;

    private final ThreadPoolExecutor myWorkerPool;

    public EventBus(Context context)
    {
        myContext = context;
        myEventDispatcherFactory = new EventDispatcherFactoryImpl();
        mySubscriptionFactory = new SubscriptionFactoryImpl();
        myBookkeeper = new SubscriptionBookkeeperImpl();
        myWorkerPool = new ThreadPoolExecutor(4, 4, 0L, SECONDS, new ArrayBlockingQueue<Runnable>(256), new EventBusThreadFactory(), new CallerRunsPolicy());
    }

    public void subscribe(Object subscriber, ReferenceType referenceType, EventFilter[] filters)
    {
        final EventDispatcher eventDispatcher;
        final Subscription subscription;

        if (myBookkeeper.isSubscribed(subscriber))
        {
            return;
        }

        eventDispatcher = myEventDispatcherFactory.createEventDispatcher(subscriber.getClass());
        subscription = mySubscriptionFactory.createSubscription(subscriber, referenceType, filters, eventDispatcher);

        myBookkeeper.subscribe(subscription);

        log.debug("Subscribe: [ {} ] {} Dispatcher: {}", subscription.getReferenceType(), getClassNameOf(subscription), getClassNameOf(subscription.getEventDispatcher()));
    }

    public void unsubscribe(Object subscriber)
    {
        myBookkeeper.unsubscribe(subscriber);

        log.debug("Unsubscribe: {}", getClassNameOf(subscriber));
    }

    public void send(Event event)
    {
        final EventDispatch dispatch = createEventDispatch(event);
        dispatch.run();
    }

    public void post(Event event)
    {
        final EventDispatch dispatch = createEventDispatch(event);
        myWorkerPool.execute(dispatch);
    }

    public ResultSet query(Query query)
    {
        final QueryDispatch dispatch = createQueryDispatch(query);
        myWorkerPool.execute(dispatch);
        return dispatch.getResult();
    }

    @Override
    public void dispose(Context context)
    {
        final List<Runnable> neverCommencedRunnables = myWorkerPool.shutdownNow();

        for (Runnable runnable : neverCommencedRunnables)
        {
            log.warn("Due to disposing the event bus, never commenced the dispatch of: {}", runnable);
        }

        myBookkeeper.clear();
    }

    private EventDispatch createEventDispatch(Event event)
    {
        return new EventDispatch(myContext, event, myBookkeeper.subscriptions());
    }

    private QueryDispatch createQueryDispatch(Query query)
    {
        return new QueryDispatch(myContext, (QueryImpl) query, myBookkeeper.subscriptions());
    }

    private static class EventBusThreadFactory
    implements ThreadFactory
    {
        private final ThreadGroup myThreadGroup = new ThreadGroup("entity-essentials");
        private final AtomicInteger nextWorkerId = new AtomicInteger();

        @Override
        public Thread newThread(Runnable runnable)
        {
            return new Thread(myThreadGroup, runnable, myThreadGroup.getName() + "-worker-" + nextWorkerId.getAndIncrement());
        }
    }
}


text:
{-# LANGUAGE DeriveDataTypeable #-}
-- | Module: Network.Heartbeat
--  Author: Alexander Vershilov <alexander.vershilov@gmail.com>
--  LICENCE: BSD
--
-- Provide a basic service discovery and heartbeat interface, using
-- broadcast UDP packets.
--
--
-- Service discrovery. Is looking service instances in local network
-- it has 2 types of discovering:
--
--    * 'OneWay' - every node broadcasting it's information to the
--        network, client listenes and stores information.
--
--    * 'ReqRep' - new client sends a broadcast event to the network
--        and each service reply with information about this service.
--
-- N.B. Req-rep service is not implemented yet
--
-- N.B. IPV6 protocols is not currently ready as IPV6 has no broadcast
--  support and multicast (ff02::1) address should be used instread
--
module Network.Discovery
  ( -- * Datatypes
    Discovery(..)
  , DiscoveryHost
  , mkBroadcast
    -- * Higher level wrappers
  , discovery
  , discoveryServer
  , lookupServerT
    -- * Internal function
  , oneWayClient
  )
  where

import Data.Bits
import Data.Binary
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S8
import Data.Time
import Data.Typeable

import Network.Socket hiding (recvFrom, sendTo)
import Network.Socket.ByteString
import Control.Applicative
import Control.Concurrent
import Control.Exception
import Control.Monad (forever, replicateM_)

import System.Time.Monotonic

data DiscoverySignal = DiscoveryStop
                    deriving (Show, Typeable)

-- | DiscoveryHost abracts over different type of broadcast hosts
-- Either an IPv4 broadcast address or IPv6 multicast
data DiscoveryHost  = HostV4 Word32

instance Exception DiscoverySignal

-- | Discovery algorithm
data Discovery = OneWay {
                    disInterval :: DiffTime,            -- ^ ping interval
                    disData :: IO ByteString            -- ^ data to send
                 }
               | ReqRep {
                   disData :: IO ByteString
                }

data DiscoveryClient a = OneWayC  (ByteString -> a)       -- ^ data decoding

-- | High level server wrapper
discoveryServer :: Discovery                              -- ^ discovery algorithm
                -> DiscoveryHost                          -- ^ broadcast address
                -> Int                                    -- ^ broadcast port
                -> IO ()
discoveryServer (OneWay interval dat_) bcast port = onSocket bcast port $
               \a s -> oneWayServer dat_ interval s a
discoveryServer _ _ _ = error  "not yet implemented"

-- | Higher level wrapper for client server application
discovery ::  Discovery                                   -- ^ discoverty
          -> (ByteString -> SockAddr -> IO ())            -- ^ message event
          -> DiscoveryHost                                -- ^ discovery address
          -> Int                                          -- ^ discovery port
          -> IO ()
discovery (OneWay interval dat_) event bcast port = onSocket bcast port $
               \a s -> bracket (forkIO $ oneWayServer dat_ interval s a)
                               (killThread)
                               (\_ ->
                                  let l = SockAddrInet (fromIntegral port) (16777343 {- 127.0.0.1 -})
                                      go Nothing = do
                                            (a',b) <- recvFrom s 1024
                                            event a' b
                                            _ <- sendTo s a' l
                                            threadDelay 100
                                            go (Just a')
                                      go (Just x) = do
                                            (a',b) <- recvFrom s 1024
                                            if x == a'
                                                then go Nothing
                                                else do
                                                  event a' b
                                                  _ <- sendTo s a' l
                                                  go (Just a')
                                  in go Nothing
                               )
discovery (ReqRep dat_) event bcast port = reqRepServer dat_ bcast port event

-- | Searches for server for the given amount of time
lookupServerT :: (Eq a) => DiscoveryClient a              -- ^ discovery client
              -> Int                                      -- ^ broadcast port
              -> DiffTime                                 -- ^ time to wait
              -> IO [(a, ByteString, SockAddr)]
lookupServerT (OneWayC parse) port interval = do
    bracket (socketPrepare >>= bindBcast (HostV4 undefined) port)                      -- TODO remove stupid hardcoding
            (sClose)
            (\sock -> do
              box <- newEmptyMVar
              t <- forkIO $ oneWayClient sock parse >>= putMVar box
              delay interval
              throwTo t DiscoveryStop
              takeMVar box)

-- | run one way server on already created sockets
oneWayServer :: (IO ByteString) -> DiffTime -> Socket -> SockAddr -> IO ()
oneWayServer getData interval sock addr = forever $
    getData >>= \d -> sendTo sock d addr >> delay interval

reqRepServer :: (IO ByteString) -> DiscoveryHost -> Int -> (ByteString -> SockAddr -> IO ()) -> IO ()
reqRepServer getData bcast port event = do
    _ <- forkIO $ onSocket bcast port $ \addr sock -> do
        _ <- forkIO $ replicateM_ 10 (getData >>= \d -> sendTo sock d addr >> delay 2)
        forever $ recvFrom sock 1024 >>= \(data_,addr') -> do
           event data_ addr'
           bracket (do socket AF_INET Stream defaultProtocol)
                   (sClose)
                   (\s -> do connect s addr'
                             sendAll s =<< getData
                   )
    bracket (do sock <- socket AF_INET Stream defaultProtocol
                return sock)
            (sClose)
            (\s -> do listen s 1
                      sockHandler s
            )
  where
    sockHandler sock = do
      (s, _) <- accept sock
      _ <- forkIO $ communicate s
      sockHandler sock
    communicate s = do
      (data_, addr) <- recvFrom s 1024
      event data_ addr

-- | run one way client
oneWayClient :: Eq a
             => Socket                                        -- ^ Socket to listen on
             -> (ByteString -> a)                             -- ^ name resolve function
             -> IO [(a, ByteString, SockAddr)]
oneWayClient sock parse = do
    let go acc = (tryD (recvFrom sock 1024)) >>= \x -> -- TODO remove data len hardcoding
          case x of
            Left _ -> return acc
            Right (msg,b) -> go $! insert' (parse msg, msg, b) acc
    go []
 where
    insert' v [] = [v]
    insert' v@(a0,_,_) y@(x@(a1,_,_):xs) | a0 == a1  = y
                                         | otherwise = x : insert' v xs

-- | Prepare socket for receiving
socketPrepare :: IO Socket
socketPrepare = do
   sock <- socket AF_INET Datagram defaultProtocol
   setSocketOption sock Broadcast 1
   setSocketOption sock ReuseAddr 1
   return sock

-- | Prepare recieving bcast addresses
bindBcast ::DiscoveryHost -> Int -> Socket -> IO Socket
bindBcast (HostV4 _) port sock = bind sock (SockAddrInet (fromIntegral port) iNADDR_ANY) >> return sock

tryD :: IO a -> IO (Either DiscoverySignal a)
tryD = try

-- | Create ipv4 broadcast port
mkBroadcast :: ByteString                 -- ^ IP address
            -> Int                        -- ^ network mask
            -> IO DiscoveryHost
mkBroadcast host m =
    let m' = complement (2^m - 1)
    in (\x -> HostV4 (x .|. m')) <$> inet_addr (S8.unpack host)

addrFromHost :: DiscoveryHost -> Int -> SockAddr
addrFromHost (HostV4 b) port = SockAddrInet (fromIntegral port) b
--                HostV6 fi ha6 sc  -> SockAddrInet6 (fromIntegral port) fi ha6 sc      -- TODO support IPV6

onSocket :: DiscoveryHost -> Int -> (SockAddr -> Socket -> IO a) -> IO a
onSocket host port f =
  let addr = addrFromHost host port
  in bracket (socketPrepare >>= bindBcast host port)
             (sClose)
             (f addr)