text:
/*eslint no-shadow:0 no-loop-func:0*/
define("sap_viz_ext_googlemapsheatmap-src/js/utils/util", [], function() {
	/*
	 * In most cases, you don't need to modify the following code.
	 */
	var _util = { /*__FOLD__*/
		/*
		 * Converts data to flatten table format. Accepts MultiAxisDataAdapter, CrosstableDataset and FlattableDataset as data input.
		 * Invocation example:
		 * _util.toTable(data, [mapper], callback);
		 * data : data input
		 * mapper[optional] : a mapper that maps each data to another format.
		 * eg. mapper = function(d, [meta]){...}
		 * callback : accepts the error message and output data to generate visualization.
		 * eg. callback = function(err, data, [meta]){...}
		 */
		toTable: function(data, f1, f2) {
			var cb = f2 || f1,
				mapper = f2 ? f1 : undefined,
				rows;
			try {
				var me = this,
					parser = me._getParser(data);
				rows = parser.call(me, data);
				if (!rows) {
					rows = [];
				}
				me._meta = rows.meta;

				if (mapper) {
					rows = rows.map(function(d) {
						return mapper(d, me._meta);
					});
					rows.meta = me._meta;
				}
			} catch (err) {
				return cb(err, null, null);
			}
			if (cb) {
				return cb(null, rows, me._meta);
			} else {
				return rows;
			}

		},

		buildNameIdx: function(feeds) {
			if (feeds) {
				this._feeds = feeds;
				this._dimMap = {};
				this._mgMap = {};
				var that = this;
				feeds.forEach(function(feed) {
					if (feed.aaIndex) {
						that._dimMap[feed.name] = feed.aaIndex - 1;
					} else {
						that._mgMap[feed.name] = feed.mgIndex - 1;
					}
				});
			}
		},

		_getParser: function(data) {
			if (data.dataset) {
				var dataset = data.dataset;
				if (dataset.table) {
					return this._flat;
				} else {
					return this._cross;
				}
			}
			return this._cross;
		},

		_flat: function(data) {
			var dataset = data.dataset;
			var ret = dataset.table();
			ret.meta = {
				_dimensionSets: [dataset.dimensions()],
				_measureSets: [dataset.measures()],

				dimensions: function(i, j) {
					if (arguments.length === 2) {
						return this._dimensionSets[0][j];
					}
					return this._dimensionSets[0];
				},

				measures: function(i, j) {
					if (arguments.length === 2) {
						return this._measureSets[0][j];
					}
					return this._measureSets[0];
				}
			};

			return ret;
		},

		_parseMeta: function(meta) {
			if (!meta) {
				return null;
			} else {
				return {
					_dimMap: this._dimMap,
					_mgMap: this._mgMap,
					_meta: {
						measureSets: (function(measureSets) {
							var tmp = [];
							$.each(measureSets, function(idx, ele) {
								tmp[idx] = ele.map(function(d) {
									return d.measure;
								});
							});
							return tmp;
						}(meta.measureSets)),
						dimSets: (function(dimSets) {
							var tmp = [];
							$.each(dimSets, function(idx, ele) {
								tmp[idx] = ele.map(function(d) {
									return d.dimension;
								});
							});
							return tmp;
						}(meta.dimSets))
					},
					measures: function(i, j) {
						if (arguments.length === 0) {
							var ret = [];
							$.each(this._meta.measureSets, function(idx, ms) {
								$.each(ms, function(idx, measure) {
									ret.push(measure);
								});
							});
							return ret;
						} else if (arguments.length === 1) {
							if (this._mgMap && this._mgMap[i] !== undefined) {
								i = this._mgMap[i];
							}
							if (!this._meta.measureSets[i]) {
								throw "MeasureGroup \"" + i + "\" not found!";
							}
							return this._meta.measureSets[i];
						} else {
							return this._meta.measureSets[i][j];
						}
					},
					dimensions: function(i, j) {
						if (arguments.length === 0) {
							var ret = [];
							$.each(this._meta.dimSets, function(idx, ds) {
								$.each(ds, function(idx, dim) {
									ret.push(dim);
								});
							});
							return ret;
						} else if (arguments.length === 1) {
							if (this._dimMap && this._dimMap[i] !== undefined) {
								i = this._dimMap[i];
							}
							if (!this._meta.dimSets[i]) {
								throw "Dimension Set \"" + i + "\" not found!";
							}
							return this._meta.dimSets[i];
						} else {
							return this._meta.dimSets[i][j];
						}
					}
				};
			}
		},

		_extractCtx: function(meta, data, fdata) {
			var ctx = {},
				mvLen = data._mg[0].values[0].rows.length,
				vLen = data._mg[0].values[0].rows[0].length,
				dataCtx = [],
				i, j;

			for (i = 0; i < mvLen; i++) {
				var arr = [];
				for (j = 0; j < vLen; j++) {
					arr.push({});
				}
				dataCtx.push(arr);
			}
			$.each(data._mg, function(idx_mg, mg) {
				$.each(mg.values, function(idx_mv, mgValue) {
					var ctxRows = [];
					ctx[mgValue.col] = ctxRows;
					$.each(mgValue.rows, function(idx_a2, rows) {
						$.each(rows, function(idx_a1, row) {
							ctxRows.push(row.ctx);
							dataCtx[idx_a2][idx_a1][mgValue.col] = row.ctx;
						});
					});
				});
			});
			$.each(data._aa, function(idx, aa) {
				$.each(aa.values, function(idx, axis) {
					var ctxRows = [];
					ctx[axis.col.val] = ctxRows;
					$.each(axis.rows, function(idx, row) {
						ctxRows.push(row.ctx);
					});
				});
			});
			fdata.forEach(function(e, idxFdata) {
				Object.defineProperty(e, "context", {
					enumerable: false,
					get: function() {
						return (function(ctxs) {
							return function(measure) {
								if (ctxs && ctxs[measure]) {
									return {
										ctx: [ctxs[measure].path]
									};
								}
								return {
									ctx: [ctxs[measure]]
								};
							};
						}(dataCtx[Math.floor(idxFdata / vLen)][idxFdata % vLen]));
					}
				});
			});
			meta._ctx = ctx;
			meta.context = function(col, dataIdx) {
				return this._ctx[col][dataIdx];
			};
		},

		_cross: function(data) {
			var ret = this._toFlattenTable(data);
			if (!ret) {
				return null;
			}
			return ret;
		},
		/*
		 * extract dimension sets from data
		 * @param data [Crosstable Dataset] crosstable dataset
		 * @returns array of dimension sets, and each dimension set is an object of {dimension: "dimension name", data: [members]}.
		 * e.g. [{dimension: "country", data: ["China", "US", ...]}, {dimension: "year", data: ["2010", "2011", ...]}, ...]
		 */
		_extractDimSets: function(data) {
			var dimSet1, dimSet2, res = [];
			if (data.getAnalysisAxisDataByIdx) {
				dimSet1 = data.getAnalysisAxisDataByIdx(0);
				dimSet2 = data.getAnalysisAxisDataByIdx(1);
			} else if (data.dataset && data.dataset.data) {
				var analysisAxis = data.dataset.data().analysisAxis;
				if (analysisAxis) {
					analysisAxis.forEach(function(g) {
						var resg = [];
						g.data.forEach(function(d) {
							var result = {};
							result.data = [];
							for (var prop in d.values) {
								if (d.values.hasOwnProperty(prop)) {
									result.data[prop] = d.values[prop];
								}
							}
							result.dimension = d.name;
							resg.push(result);
						});
						res.push(resg);
					});
				}
				return res;
			}

			$.each([dimSet1, dimSet2], function(idx, dimSet) {
				dimSet = dimSet ? dimSet.values : undefined;
				if (!dimSet) {
					return;
				}
				var dims = [],
					dim;
				for (var i = 0; i < dimSet.length; i++) {
					dim = {
						dimension: dimSet[i].col.val,
						data: []
					};
					for (var j = 0; j < dimSet[i].rows.length; j++) {
						dim.data.push(dimSet[i].rows[j].val);
					}
					dims.push(dim);
				}
				res.push(dims);
			});
			return res;
		},

		/*
		 * extract measure sets from data
		 * @param data [Crosstable Dataset] crosstable dataset
		 * @returns array of measures, and each measure is an object of {measure: "measure name", data: [measure data]}.
		 * for example, [[{measure: "income", data: [555, 666, 777, ...]}, {measure: "cost", data:[55, 66, 77, ...]}, ...], ...]
		 */
		_extractMeasureSets: function(data) {
			var measureSet1, measureSet2, measureSet3, reses = [];
			if (data.getMeasureValuesGroupDataByIdx) {
				measureSet1 = data.getMeasureValuesGroupDataByIdx(0);
				measureSet2 = data.getMeasureValuesGroupDataByIdx(1);
				measureSet3 = data.getMeasureValuesGroupDataByIdx(2);
			} else if (data.dataset && data.dataset.data) {
				data.dataset.data().measureValuesGroup.forEach(function(g) {
					var resg = [];
					g.data.forEach(function(d) {
						var result = {};
						result.data = [];
						for (var prop in d.values) {
							if (d.values.hasOwnProperty(prop)) {
								result.data[prop] = d.values[prop];
							}
						}
						result.measure = d.name;
						resg.push(result);
					});
					reses.push(resg);
				});
				return reses;
			}

			$.each([measureSet1, measureSet2, measureSet3], function(idx, measureSet) {
				measureSet = measureSet ? measureSet.values : undefined;
				if (!measureSet) {
					return;
				}
				var res = [],
					resItem, resData, measure;
				for (var k = 0; k < measureSet.length; k++) {
					measure = measureSet[k];
					resItem = {
						measure: measure.col,
						data: []
					};
					resData = resItem.data;
					for (var i = 0; i < measure.rows.length; i++) {
						resData[i] = [];
						for (var j = 0; j < measure.rows[i].length; j++) {
							resData[i].push(measure.rows[i][j].val);
						}
					}
					res.push(resItem);
				}
				reses.push(res);
			});

			return reses;
		},

		/*
		 * convert crosstable data to flatten table data
		 * @param data [Crosstable Dataset] crosstable dataset or MultiAxisDataAdapter
		 * @returns array of objects, and each object represents a row of data table:
		 * [{"dimension name1" : value1, "dimension name2" : value2, "measure name1" : value3}, ....{"dimension name1" : valueN1, "dimension name2" : valueN2, "measure name1" : valueN3} ]
		 *
		 * This method returns an extra meta data in data.meta, which includes all dimension and measure sets.
		 */
		_toFlattenTable: function(data) {
			var dimSets = this._extractDimSets(data),
				measureSets = this._extractMeasureSets(data),
				fdata = [],
				meta,
				ctx,
				d;
			//measureValueGroup is necessary in crosstable dataset
			//please directly call _util.extractDimSets() to get dimension values
			if (measureSets.length === 0) {
				return undefined;
			}
			meta = {
				dimSets: dimSets,
				measureSets: measureSets
			};

			if (data.getAnalysisAxisDataByIdx) {
				fdata = this._toFlatJsonArray(measureSets, dimSets);
				/**Extract data context for MultiAxisDataAdapter*/
				meta = this._parseMeta(meta);
				this._extractCtx(meta, data, fdata);
			} else {
				if (data && data.dataset) {
					d = new sap.viz.api.data.CrosstableDataset();
					d.data(data.dataset.data());
					d.info(data.dataset.info());
				} else if (data) {
					d = data;
				}
				if (sap.viz.extapi.utils && sap.viz.extapi.utils.Data && sap.viz.extapi.utils.Data.getDataContext) {
					ctx = sap.viz.extapi.utils.Data.getDataContext(d);
				}
				fdata = this._toFlatJsonArray(measureSets, dimSets, ctx);
				meta = this._parseMeta(meta);
			}

			//fill meta data. for compatible
			fdata.meta = meta;
			return fdata;
		},

		_toFlatJsonArray: function(measureSets, dimSets, ctx) {
			//convert data from ct to flat
			var fdata = [],
				measure0Data, i, j, m, measure, datumCtx, datum;

			measure0Data = measureSets[0][0].data;
			for (i = 0; i < measure0Data.length; i++) {
				for (j = 0; j < measure0Data[i].length; j++) {
					datum = {};
					datumCtx = {};
					$.each(dimSets, function(idx, dimSet) {
						if (!dimSet) {
							return;
						}
						var counter = idx === 0 ? j : i;
						for (m = 0; m < dimSet.length; m++) {
							datum[dimSet[m].dimension] = dimSet[m].data[counter];
						}
					});
					$.each(measureSets, function(idx, measureSet) {
						if (!measureSet) {
							return;
						}
						for (m = 0; m < measureSet.length; m++) {
							measure = measureSet[m];
							datum[measure.measure] = measure.data[i][j];
							if (ctx) {
								/**currently not support same measure name in different measureGroup*/
								datumCtx[measure.measure] = ctx[idx][m][i][j];
							}
						}
					});
					if (ctx) {
						Object.defineProperty(datum, "context", {
							enumerable: false,
							value: (function(ctxs) {
								return function(measure) {
									if (ctxs && ctxs[measure]) {
										return {
											ctx: [ctxs[measure].path]
										};
									}
									return {
										ctx: [ctxs[measure]]
									};
								};
							}(datumCtx))
						});
					}
					fdata.push(datum);
				}
			}
			return fdata;
		},

		composeSelection: function(measure, val, ele, ctx) {
			var len = 1,
				selectionData = [],
				selectElements = [];

			for (var i = 0; i < len; i++) {
				selectionData.push({
					val: val,
					ctx: ctx
				});
			}

			selectElements.push({
				target: ele,
				data: selectionData
			});
			return selectElements;
		}
	};
	return _util;
});


text:
///<reference path='<%= referencePath %>/references.d.ts' />

/*global element, by*/
'use strict';

function <%= upperCamel %>Page() {
  this.text = element(by.tagName('p'));
  this.heading = element(by.tagName('h2'));
}

module.exports = <%= upperCamel %>Page;

redpajama_set_name: RedPajamaGithub


text:
//Problem 6. Print Numbers
//Write a program to print the numbers 1, 101 and 1001, each at a separate line.
//Name the program correctly.
//You should submit in your homework the Visual Studio project holding the source code of the PrintNumbers program.

using System;

class PrintNumbers
{
    static void Main()
    {
        Console.WriteLine("1");
        Console.WriteLine("101");
        Console.WriteLine("1001");
    }
}


text:
<?php

namespace Pimcore\Model\Object\Fieldcollection\Definition;

use Pimcore\Model;

class Listing {

    /**
     * @return array
     */
    public function load () {

        $fields = array();
        $fieldCollectionFolder = PIMCORE_CLASS_DIRECTORY . "/fieldcollections";

        if(is_dir($fieldCollectionFolder)) {
            $files = scandir($fieldCollectionFolder);

            foreach ($files as $file) {
                $file = $fieldCollectionFolder . "/" . $file;
                if(is_file($file)) {
                    $fieldData = file_get_contents($file);
                    $fields[] = \Pimcore\Tool\Serialize::unserialize($fieldData);
                }
            }
        }

        return $fields;
    }
}


text:
// LIGHtmap
// TExture
// Renderer

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#if defined(_WIN32) && !defined(LTR_STATIC)
#ifdef LTRBUILD
#define LTRAPI __declspec(dllexport)
#else
#define LTRAPI __declspec(dllimport)
#endif
#else
#define LTRAPI
#endif

#define LTRBOOL int
#define LTRCODE int

#include <stdlib.h>
#ifdef _MSC_VER
#  pragma warning( disable: 4996 )
#  if _MSC_VER >= 1600
#    include <stdint.h>
#  else
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#  endif
#else
#  include <inttypes.h>
#endif
typedef int32_t i32;
typedef uint32_t u32;

typedef float ltr_VEC3[3];
typedef float ltr_VEC4[4];
typedef ltr_VEC4 ltr_MAT4[4];

#define LTR_VEC3_SET( v, x, y, z ) do{ (v)[0]=(x); (v)[1]=(y); (v)[2]=(z); }while(0)

#define LTRC_SUCCESS 0
#define LTRC_ATEND   1

#define LTR_LT_POINT  1
#define LTR_LT_SPOT   2
#define LTR_LT_DIRECT 3

typedef struct ltr_MeshPartInfo
{
	const void* positions_f3;
	const void* normals_f3;
	const void* texcoords1_f2;
	const void* texcoords2_f2;
	u32 stride_positions;
	u32 stride_normals;
	u32 stride_texcoords1;
	u32 stride_texcoords2;
	const u32* indices;
	u32 vertex_count;
	u32 index_count;
	int shadow;
}
ltr_MeshPartInfo;

typedef struct ltr_MeshInstanceInfo
{
	ltr_MAT4 matrix;
	float importance;
	int shadow;
	const char* ident;
	size_t ident_size;
}
ltr_MeshInstanceInfo;

typedef struct ltr_LightInfo
{
	u32 type;
	ltr_VEC3 position;
	ltr_VEC3 direction;
	ltr_VEC3 up_direction;
	ltr_VEC3 color_rgb;
	float range;
	float power;
	float light_radius;
	int shadow_sample_count;
	float spot_angle_out;
	float spot_angle_in;
	float spot_curve;
}
ltr_LightInfo;

typedef struct ltr_SampleInfo
{
	u32 id;
	ltr_VEC3 position;
	ltr_VEC3 normal;
	ltr_VEC3 out_color;
}
ltr_SampleInfo;

typedef struct ltr_SampleRequest
{
	ltr_VEC3 position;
	ltr_VEC3 normal;
	float tex0u, tex0v;
	float tex1u, tex1v;
	uint32_t part_id;

	const char* mesh_ident;
	size_t mesh_ident_size;
	const char* inst_ident;
	size_t inst_ident_size;

	ltr_VEC3 out_diffuse_color;
	ltr_VEC3 out_emissive_color;
}
ltr_SampleRequest;

typedef struct ltr_Config
{
	// callbacks
	void* userdata;
	LTRBOOL (*size_fn)
	(
		ltr_Config* /* config */,
		const char* /* mesh_ident */,
		size_t /* mesh_ident_size */,
		const char* /* inst_ident */,
		size_t /* inst_ident_size */,
		float /* computed_surface_area */,
		float /* inst_importance */,
		u32[2] /* out_width, out_height */
	);
	// limits & factors
	int max_num_threads;
	size_t max_tree_memory;
	u32 max_lightmap_size;
	u32 default_width;
	u32 default_height;
	float global_size_factor;
	float max_correct_dist;
	float max_correct_angle;
	// lightmap generation
	ltr_VEC3 clear_color; /* the color used outside triangles */
	ltr_VEC3 ambient_color; /* the base color used inside triangles */
	// RADIOSITY:
	int bounce_count;
	LTRBOOL (*sample_fn)
	(
		ltr_Config* /* config */,
		ltr_SampleRequest* /* req */
	);
	// AMBIENT OCCLUSION effect:
	// ao_factor = 1 - max( raytrace_distance / ao_distance, 1 )
	// - AO FACTORS are accumulated -
	// ao_factor = pow( min( ao_factor * ao_multiplier, 1 ), ao_falloff )
	// IF ao_effect >= 0: color = color_orig * ( 1 - ao_effect * ao_factor ) + color_ao * ao_factor;
	// IF ao_effect <  0: color = lerp( color_orig, lerp( color_ao, color_orig * color_ao, -ao_effect ), ao_factor )
	float ao_distance;
	float ao_multiplier;
	float ao_falloff;
	float ao_effect;
	float ao_divergence; /* hemisphere [0] -to- full sphere [1] direction picking */
	ltr_VEC3 ao_color_rgb;
	int ao_num_samples;
	// GAUSSIAN BLUR effect:
	float blur_size;
	// DOWNSAMPLE 2X effect:
	int ds2x;
	// NORMAL/FOCUS data generation:
	int generate_normalmap_data;
}
ltr_Config;

LTRAPI LTRBOOL ltr_DefaultSizeFunc
(
	ltr_Config* config,
	const char* mesh_ident,
	size_t mesh_ident_size,
	const char* inst_ident,
	size_t inst_ident_size,
	float computed_surface_area,
	float inst_importance,
	u32 out_size[2]
);

typedef struct ltr_WorkOutputInfo
{
	u32 lightmap_count;
	u32 sample_count;
	ltr_SampleInfo* samples;
}
ltr_WorkOutputInfo;

typedef struct ltr_WorkOutput
{
	u32 uid;
	const char* mesh_ident;
	size_t mesh_ident_size;
	const char* inst_ident;
	size_t inst_ident_size;
	float* lightmap_rgb;
	float* normals_xyzf;
	u32 width;
	u32 height;
}
ltr_WorkOutput;

typedef struct ltr_Mesh ltr_Mesh;
typedef struct ltr_Scene ltr_Scene;

typedef struct ltr_WorkStatus
{
	float completion;
	const char* stage;
}
ltr_WorkStatus;

// - manage scene
LTRAPI ltr_Scene* ltr_CreateScene();
LTRAPI void ltr_DestroyScene( ltr_Scene* scene );
LTRAPI void ltr_Start( ltr_Scene* scene );
LTRAPI void ltr_Abort( ltr_Scene* scene );
LTRAPI LTRBOOL ltr_GetStatus( ltr_Scene* scene, ltr_WorkStatus* wsout );
LTRAPI void ltr_Sleep( int ms );
LTRAPI void ltr_GetConfig( ltr_Config* cfg, ltr_Scene* opt_scene );
LTRAPI LTRCODE ltr_SetConfig( ltr_Scene* scene, ltr_Config* cfg );

// - data input
LTRAPI ltr_Mesh* ltr_CreateMesh( ltr_Scene* scene, const char* ident, size_t ident_size );
LTRAPI LTRBOOL ltr_MeshAddPart( ltr_Mesh* mesh, ltr_MeshPartInfo* mpinfo );
LTRAPI LTRBOOL ltr_MeshAddInstance( ltr_Mesh* mesh, ltr_MeshInstanceInfo* mii );
LTRAPI void ltr_LightAdd( ltr_Scene* scene, ltr_LightInfo* li );
LTRAPI void ltr_SampleAdd( ltr_Scene* scene, ltr_SampleInfo* si );

// - data output
LTRAPI void ltr_GetWorkOutputInfo( ltr_Scene* scene, ltr_WorkOutputInfo* woutinfo );
LTRAPI LTRBOOL ltr_GetWorkOutput( ltr_Scene* scene, u32 which, ltr_WorkOutput* wout );

// - misc.
LTRAPI u32 ltr_NextPowerOfTwo( u32 x );

#ifdef __cplusplus
}
#endif


text:
/*************************************************************************/ /*!
@Title          SGX microkernel interface structures used by srvkm
@Copyright      Copyright (c) Imagination Technologies Ltd. All Rights Reserved
@Description    SGX microkernel interface structures used by srvkm
@License        Dual MIT/GPLv2

The contents of this file are subject to the MIT license as set out below.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 ("GPL") in which case the provisions
of GPL are applicable instead of those above.

If you wish to allow use of your version of this file only under the terms of
GPL, and not to allow others to use your version of this file under the terms
of the MIT license, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by GPL as set
out in the file called "GPL-COPYING" included in this distribution. If you do
not delete the provisions above, a recipient may use your version of this file
under the terms of either the MIT license or GPL.

This License is also included in this distribution in the file called
"MIT-COPYING".

EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /**************************************************************************/

#if !defined (__SGX_MKIF_KM_H__)
#define __SGX_MKIF_KM_H__

#include "img_types.h"
#include "servicesint.h"
#include "sgxapi_km.h"

#if !defined (SGX_MP_CORE_SELECT)
/* MP register control macros */
#if defined(SGX_FEATURE_MP)
	#define SGX_REG_BANK_SHIFT 			(14)
	#define SGX_REG_BANK_SIZE 			(1 << SGX_REG_BANK_SHIFT)
	#define SGX_REG_BANK_BASE_INDEX		(2)
	#define	SGX_REG_BANK_MASTER_INDEX	(1)
	#define SGX_MP_CORE_SELECT(x,i) 	(x + ((i + SGX_REG_BANK_BASE_INDEX) * SGX_REG_BANK_SIZE))
	#define SGX_MP_MASTER_SELECT(x) 	(x + (SGX_REG_BANK_MASTER_INDEX * SGX_REG_BANK_SIZE))
#else
	#define SGX_MP_CORE_SELECT(x,i) 	(x)
#endif /* SGX_FEATURE_MP */
#endif

/*!
 ******************************************************************************
 * CCB command structure for SGX
 *****************************************************************************/
typedef struct _SGXMKIF_COMMAND_
{
	IMG_UINT32				ui32ServiceAddress;		/*!< address of the USE command handler */
	IMG_UINT32				ui32CacheControl;		/*!< See SGXMKIF_CC_INVAL_* */
	IMG_UINT32				ui32Data[6];			/*!< array of other command control words */
} SGXMKIF_COMMAND;

/*!
 ******************************************************************************
 * CCB array of commands for SGX
 *****************************************************************************/
typedef struct _PVRSRV_SGX_KERNEL_CCB_
{
	SGXMKIF_COMMAND		asCommands[256];		/*!< array of commands */
} PVRSRV_SGX_KERNEL_CCB;

/*!
 ******************************************************************************
 * CCB control for SGX
 *****************************************************************************/
typedef struct _PVRSRV_SGX_CCB_CTL_
{
	IMG_UINT32				ui32WriteOffset;		/*!< write offset into array of commands (MUST be alligned to 16 bytes!) */
	IMG_UINT32				ui32ReadOffset;			/*!< read offset into array of commands */
} PVRSRV_SGX_CCB_CTL;

/*!
 *****************************************************************************
 * Control data for SGX
 *****************************************************************************/
typedef struct _SGXMKIF_HOST_CTL_
{
#if defined(PVRSRV_USSE_EDM_BREAKPOINTS)
	IMG_UINT32				ui32BreakpointDisable;
	IMG_UINT32				ui32Continue;
#endif

	volatile IMG_UINT32		ui32InitStatus;				/*!< Microkernel Initialisation status */
	volatile IMG_UINT32		ui32PowerStatus;			/*!< Microkernel Power Management status */
	volatile IMG_UINT32		ui32CleanupStatus;			/*!< Microkernel Resource Management status */
#if defined(FIX_HW_BRN_28889)
	volatile IMG_UINT32		ui32InvalStatus;			/*!< Microkernel BIF Cache Invalidate status */
#endif
#if defined(SUPPORT_HW_RECOVERY)
	IMG_UINT32				ui32uKernelDetectedLockups;	/*!< counter relating to the number of lockups the uKernel has detected */
	IMG_UINT32				ui32HostDetectedLockups;	/*!< counter relating to the number of lockups the host has detected */
	IMG_UINT32				ui32HWRecoverySampleRate;	/*!< SGX lockup detection rate (in multiples of the timer period) */
#endif /* SUPPORT_HW_RECOVERY*/
	IMG_UINT32				ui32uKernelTimerClock;		/*!< SGX ukernel timer period (in clocks) */
	IMG_UINT32				ui32ActivePowManSampleRate;	/*!< SGX Active Power latency period (in multiples of the timer period) */
	IMG_UINT32				ui32InterruptFlags; 		/*!< Interrupt flags - PVRSRV_USSE_EDM_INTERRUPT_xxx */
	IMG_UINT32				ui32InterruptClearFlags; 	/*!< Interrupt clear flags - PVRSRV_USSE_EDM_INTERRUPT_xxx */
	IMG_UINT32				ui32BPSetClearSignal;		/*!< Breakpoint set/cear signal */

	IMG_UINT32				ui32NumActivePowerEvents;	/*!< counter for the number of active power events */

	IMG_UINT32				ui32TimeWraps;				/*!< to count time wraps in the Timer task*/
	IMG_UINT32				ui32HostClock;				/*!< Host clock value at microkernel power-up time */
	IMG_UINT32				ui32AssertFail;				/*!< Microkernel assert failure code */

#if defined(SGX_FEATURE_EXTENDED_PERF_COUNTERS)
	IMG_UINT32				aui32PerfGroup[PVRSRV_SGX_HWPERF_NUM_COUNTERS];	/*!< Specifies the HW's active group selectors */
	IMG_UINT32				aui32PerfBit[PVRSRV_SGX_HWPERF_NUM_COUNTERS];	/*!< Specifies the HW's active bit selectors */
	IMG_UINT32				ui32PerfCounterBitSelect;						/*!< Specifies the HW's counter bit selectors */
	IMG_UINT32				ui32PerfSumMux;									/*!< Specifies the HW's sum_mux selectors */
#else
	IMG_UINT32				ui32PerfGroup;									/*!< Specifies the HW's active group */
#endif /* SGX_FEATURE_EXTENDED_PERF_COUNTERS */

	IMG_UINT32				ui32OpenCLDelayCount;			/* Counter to keep track OpenCL task completion time in units of regular task time out events */
	IMG_UINT32				ui32InterruptCount;
} SGXMKIF_HOST_CTL;

/*
 * TA queue Kick flags
 */
/* Set in DoKickKM to indicate the command is ready to be processed */
#define	SGXMKIF_CMDTA_CTRLFLAGS_READY			0x00000001
/*!
 ******************************************************************************
 * Shared TA command structure.
 * This structure is part of the TA command structure proper (SGXMKIF_CMDTA),
 * and is accessed from the kernel part of the driver and the microkernel.
 * There shouldn't be a need to access it from user space.
 *****************************************************************************/
typedef struct _SGXMKIF_CMDTA_SHARED_
{
	IMG_UINT32			ui32CtrlFlags;

	IMG_UINT32			ui32NumTAStatusVals;
	IMG_UINT32			ui32Num3DStatusVals;

	/* KEEP THESE 4 VARIABLES TOGETHER FOR UKERNEL BLOCK LOAD */
	IMG_UINT32			ui32TATQSyncWriteOpsPendingVal;
	IMG_DEV_VIRTADDR	sTATQSyncWriteOpsCompleteDevVAddr;
	IMG_UINT32			ui32TATQSyncReadOpsPendingVal;
	IMG_DEV_VIRTADDR	sTATQSyncReadOpsCompleteDevVAddr;

	/* KEEP THESE 4 VARIABLES TOGETHER FOR UKERNEL BLOCK LOAD */
	IMG_UINT32			ui323DTQSyncWriteOpsPendingVal;
	IMG_DEV_VIRTADDR	s3DTQSyncWriteOpsCompleteDevVAddr;
	IMG_UINT32			ui323DTQSyncReadOpsPendingVal;
	IMG_DEV_VIRTADDR	s3DTQSyncReadOpsCompleteDevVAddr;

	/* sync criteria used for TA/3D dependency synchronisation */
	PVRSRV_DEVICE_SYNC_OBJECT	sTA3DDependency;

#if defined(SUPPORT_SGX_GENERALISED_SYNCOBJECTS)
	/* SRC and DST syncs */
	IMG_UINT32					ui32NumTASrcSyncs;
	PVRSRV_DEVICE_SYNC_OBJECT	asTASrcSyncs[SGX_MAX_TA_SRC_SYNCS];
	IMG_UINT32					ui32NumTADstSyncs;
	PVRSRV_DEVICE_SYNC_OBJECT	asTADstSyncs[SGX_MAX_TA_DST_SYNCS];
	IMG_UINT32					ui32Num3DSrcSyncs;
	PVRSRV_DEVICE_SYNC_OBJECT	as3DSrcSyncs[SGX_MAX_3D_SRC_SYNCS];
#else
	/* source dependency details */
	IMG_UINT32			ui32NumSrcSyncs;
	PVRSRV_DEVICE_SYNC_OBJECT	asSrcSyncs[SGX_MAX_SRC_SYNCS_TA];
#endif

	CTL_STATUS			sCtlTAStatusInfo[SGX_MAX_TA_STATUS_VALS];
	CTL_STATUS			sCtl3DStatusInfo[SGX_MAX_3D_STATUS_VALS];

} SGXMKIF_CMDTA_SHARED;

/*
 * Services internal TQ limits
 */
#define SGXTQ_MAX_STATUS						SGX_MAX_TRANSFER_STATUS_VALS + 2

/*
 * Transfer queue Kick flags
 */
/* if set the uKernel won't update the sync objects on completion*/
#define SGXMKIF_TQFLAGS_NOSYNCUPDATE			0x00000001
/* if set the kernel won't advance the pending values*/
#define SGXMKIF_TQFLAGS_KEEPPENDING				0x00000002
/* in services equivalent for the same client flags*/
#define SGXMKIF_TQFLAGS_TATQ_SYNC				0x00000004
#define SGXMKIF_TQFLAGS_3DTQ_SYNC				0x00000008
#if defined(SGX_FEATURE_FAST_RENDER_CONTEXT_SWITCH)
#define SGXMKIF_TQFLAGS_CTXSWITCH				0x00000010
#endif
/* if set uKernel only updates syncobjects / status values*/
#define SGXMKIF_TQFLAGS_DUMMYTRANSFER			0x00000020

/*!
 ******************************************************************************
 * Shared Transfer Queue command structure.
 * This structure is placed at the start of the TQ command structure proper
 * (SGXMKIF_TRANSFERCMD), and is accessed from the kernel part of the driver
 * and the microkernel.
 *****************************************************************************/
typedef struct _SGXMKIF_TRANSFERCMD_SHARED_
{
	/* need to be able to check read and write ops on src, and update reads */

 	IMG_UINT32			ui32NumSrcSyncs;
 	PVRSRV_DEVICE_SYNC_OBJECT	asSrcSyncs[SGX_MAX_SRC_SYNCS_TQ];
	/* need to be able to check reads and writes on dest, and update writes */

 	IMG_UINT32			ui32NumDstSyncs;
 	PVRSRV_DEVICE_SYNC_OBJECT	asDstSyncs[SGX_MAX_DST_SYNCS_TQ];
	/* KEEP THESE 4 VARIABLES TOGETHER FOR UKERNEL BLOCK LOAD */
	IMG_UINT32		ui32TASyncWriteOpsPendingVal;
	IMG_DEV_VIRTADDR	sTASyncWriteOpsCompleteDevVAddr;
	IMG_UINT32		ui32TASyncReadOpsPendingVal;
	IMG_DEV_VIRTADDR	sTASyncReadOpsCompleteDevVAddr;

	/* KEEP THESE 4 VARIABLES TOGETHER FOR UKERNEL BLOCK LOAD */
	IMG_UINT32		ui323DSyncWriteOpsPendingVal;
	IMG_DEV_VIRTADDR	s3DSyncWriteOpsCompleteDevVAddr;
	IMG_UINT32		ui323DSyncReadOpsPendingVal;
	IMG_DEV_VIRTADDR	s3DSyncReadOpsCompleteDevVAddr;

	IMG_UINT32 		ui32NumStatusVals;
	CTL_STATUS  	sCtlStatusInfo[SGXTQ_MAX_STATUS];
} SGXMKIF_TRANSFERCMD_SHARED, *PSGXMKIF_TRANSFERCMD_SHARED;

#if defined(SGX_FEATURE_2D_HARDWARE)
typedef struct _SGXMKIF_2DCMD_SHARED_ {
	/* need to be able to check read and write ops on src, and update reads */
	IMG_UINT32			ui32NumSrcSync;
	PVRSRV_DEVICE_SYNC_OBJECT	sSrcSyncData[SGX_MAX_2D_SRC_SYNC_OPS];

	/* need to be able to check reads and writes on dest, and update writes */
	PVRSRV_DEVICE_SYNC_OBJECT	sDstSyncData;

	/* need to be able to check reads and writes on TA ops, and update writes */
	PVRSRV_DEVICE_SYNC_OBJECT	sTASyncData;

	/* need to be able to check reads and writes on 2D ops, and update writes */
	PVRSRV_DEVICE_SYNC_OBJECT	s3DSyncData;

	IMG_UINT32 		ui32NumStatusVals;
	CTL_STATUS  	sCtlStatusInfo[SGXTQ_MAX_STATUS];
} SGXMKIF_2DCMD_SHARED, *PSGXMKIF_2DCMD_SHARED;
#endif /* SGX_FEATURE_2D_HARDWARE */

typedef struct _SGXMKIF_HWDEVICE_SYNC_LIST_
{
	IMG_DEV_VIRTADDR	sAccessDevAddr;
	IMG_UINT32			ui32NumSyncObjects;
	/* Must be the last variable in the structure */
	PVRSRV_DEVICE_SYNC_OBJECT	asSyncData[1];
} SGXMKIF_HWDEVICE_SYNC_LIST, *PSGXMKIF_HWDEVICE_SYNC_LIST;

/*!
 *****************************************************************************
 * Microkernel initialisation status
 *****************************************************************************/
#define PVRSRV_USSE_EDM_INIT_COMPLETE			(1UL << 0)	/*!< ukernel initialisation complete */

/*!
 *****************************************************************************
 * Microkernel power status definitions
 *****************************************************************************/
#define PVRSRV_USSE_EDM_POWMAN_IDLE_COMPLETE				(1UL << 2)	/*!< Signal from ukernel->Host indicating SGX is idle */
#define PVRSRV_USSE_EDM_POWMAN_POWEROFF_COMPLETE			(1UL << 3)	/*!< Signal from ukernel->Host indicating SGX can be powered down */
#define PVRSRV_USSE_EDM_POWMAN_POWEROFF_RESTART_IMMEDIATE	(1UL << 4)	/*!< Signal from ukernel->Host indicating there is work to do immediately */
#define PVRSRV_USSE_EDM_POWMAN_NO_WORK						(1UL << 5)	/*!< Signal from ukernel->Host indicating no work to do */

/*!
 *****************************************************************************
 * EDM interrupt defines
 *****************************************************************************/
#define PVRSRV_USSE_EDM_INTERRUPT_HWR			(1UL << 0)	/*!< EDM requesting hardware recovery */
#define PVRSRV_USSE_EDM_INTERRUPT_ACTIVE_POWER	(1UL << 1)	/*!< EDM requesting to be powered down */
#define PVRSRV_USSE_EDM_INTERRUPT_IDLE			(1UL << 2)	/*!< EDM indicating SGX idle */

/*!
 *****************************************************************************
 * EDM Resource management defines
 *****************************************************************************/
#define PVRSRV_USSE_EDM_CLEANUPCMD_COMPLETE 	(1UL << 0)	/*!< Signal from EDM->Host indicating clean-up request completion */
#define PVRSRV_USSE_EDM_CLEANUPCMD_BUSY		 	(1UL << 1)	/*!< Signal from EDM->Host indicating clean-up is blocked as the resource is busy */
#define PVRSRV_USSE_EDM_CLEANUPCMD_DONE		 	(1UL << 2)	/*!< Signal from EDM->Host indicating clean-up has been done */

#if defined(FIX_HW_BRN_28889)
/*!
 *****************************************************************************
 * EDM BIF Cache Invalidate defines
 *****************************************************************************/
#define PVRSRV_USSE_EDM_BIF_INVAL_COMPLETE 		(1UL << 0)	/*!< Signal from EDM->Host indicating the BIF invalidate has started */
#endif

/*!
 ****************************************************************************
 * EDM / uKernel Get misc info defines
 ****************************************************************************
 */
#define PVRSRV_USSE_MISCINFO_READY		0x1UL
#define PVRSRV_USSE_MISCINFO_GET_STRUCT_SIZES	0x2UL	/*!< If set, getmiscinfo ukernel func returns structure sizes */
#if defined(SUPPORT_SGX_EDM_MEMORY_DEBUG)
#define PVRSRV_USSE_MISCINFO_MEMREAD			0x4UL	/*!< If set, getmiscinfo ukernel func reads arbitrary device mem */
#define PVRSRV_USSE_MISCINFO_MEMWRITE			0x8UL	/*!< If set, getmiscinfo ukernel func writes arbitrary device mem */
#if !defined(SGX_FEATURE_MULTIPLE_MEM_CONTEXTS)
#define PVRSRV_USSE_MISCINFO_MEMREAD_FAIL		0x1UL << 31	/* If set, ukernel was unable to read from the mem context */
#endif
#endif

/* Cleanup command control word */
#define	PVRSRV_CLEANUPCMD_RT		0x1U
#define	PVRSRV_CLEANUPCMD_RC		0x2U
#define	PVRSRV_CLEANUPCMD_TC		0x3U
#define	PVRSRV_CLEANUPCMD_2DC		0x4U
#define	PVRSRV_CLEANUPCMD_PB		0x5U

/* Power command control word */
#define PVRSRV_POWERCMD_POWEROFF	0x1U
#define PVRSRV_POWERCMD_IDLE		0x2U
#define PVRSRV_POWERCMD_RESUME		0x3U

/* Context suspend command control word */
#define PVRSRV_CTXSUSPCMD_SUSPEND	0x1U
#define PVRSRV_CTXSUSPCMD_RESUME	0x2U

#if defined(SGX_FEATURE_MULTIPLE_MEM_CONTEXTS)
#define SGX_BIF_DIR_LIST_INDEX_EDM	(SGX_FEATURE_BIF_NUM_DIRLISTS - 1)
#else
#define SGX_BIF_DIR_LIST_INDEX_EDM	(0)
#endif

/*!
 ******************************************************************************
 * microkernel cache control requests
 ******************************************************************************/
#define	SGXMKIF_CC_INVAL_BIF_PT	0x1
#define	SGXMKIF_CC_INVAL_BIF_PD	0x2
#define SGXMKIF_CC_INVAL_BIF_SL	0x4
#define SGXMKIF_CC_INVAL_DATA	0x8

/*!
 ******************************************************************************
 * SGX microkernel interface structure sizes
 ******************************************************************************/
typedef struct _SGX_MISCINFO_STRUCT_SIZES_
{
#if defined (SGX_FEATURE_2D_HARDWARE)
	IMG_UINT32	ui32Sizeof_2DCMD;
	IMG_UINT32	ui32Sizeof_2DCMD_SHARED;
#endif
	IMG_UINT32	ui32Sizeof_CMDTA;
	IMG_UINT32	ui32Sizeof_CMDTA_SHARED;
	IMG_UINT32	ui32Sizeof_TRANSFERCMD;
	IMG_UINT32	ui32Sizeof_TRANSFERCMD_SHARED;
	IMG_UINT32	ui32Sizeof_3DREGISTERS;
	IMG_UINT32	ui32Sizeof_HWPBDESC;
	IMG_UINT32	ui32Sizeof_HWRENDERCONTEXT;
	IMG_UINT32	ui32Sizeof_HWRENDERDETAILS;
	IMG_UINT32	ui32Sizeof_HWRTDATA;
	IMG_UINT32	ui32Sizeof_HWRTDATASET;
	IMG_UINT32	ui32Sizeof_HWTRANSFERCONTEXT;
	IMG_UINT32	ui32Sizeof_HOST_CTL;
	IMG_UINT32	ui32Sizeof_COMMAND;
} SGX_MISCINFO_STRUCT_SIZES;

#if defined(SUPPORT_SGX_EDM_MEMORY_DEBUG)
/*!
 *****************************************************************************
 * SGX misc info for accessing device memory from ukernel
 *****************************************************************************
 */
typedef struct _PVRSRV_SGX_MISCINFO_MEMACCESS
{
	IMG_DEV_VIRTADDR	sDevVAddr;		/*!< dev virtual addr for mem access */
	IMG_DEV_PHYADDR		sPDDevPAddr;	/*!< device physical addr of PD for the mem heap */
} PVRSRV_SGX_MISCINFO_MEMACCESS;
#endif

/*!
 *****************************************************************************
 * SGX Misc Info structure used in the microkernel
 * PVRSRV_SGX_MISCINFO_FEATURES is defined in sgxapi_km.h
 ****************************************************************************/
typedef struct _PVRSRV_SGX_MISCINFO_INFO
{
	IMG_UINT32						ui32MiscInfoFlags;
	PVRSRV_SGX_MISCINFO_FEATURES	sSGXFeatures;		/*!< external info for client */
	SGX_MISCINFO_STRUCT_SIZES		sSGXStructSizes;	/*!< internal info: microkernel structure sizes */
#if defined(SUPPORT_SGX_EDM_MEMORY_DEBUG)
	PVRSRV_SGX_MISCINFO_MEMACCESS	sSGXMemAccessSrc;	/*!< internal info: for reading dev memory */
	PVRSRV_SGX_MISCINFO_MEMACCESS	sSGXMemAccessDest;	/*!< internal info: for writing dev memory */
#endif
} PVRSRV_SGX_MISCINFO_INFO;

#ifdef PVRSRV_USSE_EDM_STATUS_DEBUG
/*!
 *****************************************************************************
 * Number of entries in the microkernel status buffer
 *****************************************************************************/
#define SGXMK_TRACE_BUFFER_SIZE 512
#endif /* PVRSRV_USSE_EDM_STATUS_DEBUG */

#define SGXMKIF_HWPERF_CB_SIZE					0x100	/* must be 2^n*/

/*!
 *****************************************************************************
 * One entry in the HWPerf Circular Buffer.
 *****************************************************************************/
typedef struct _SGXMKIF_HWPERF_CB_ENTRY_
{
	IMG_UINT32	ui32FrameNo;
	IMG_UINT32	ui32PID;
	IMG_UINT32	ui32RTData;
	IMG_UINT32	ui32Type;
	IMG_UINT32	ui32Ordinal;
	IMG_UINT32	ui32Info;
	IMG_UINT32	ui32TimeWraps;
	IMG_UINT32	ui32Time;
	/* NOTE: There should always be at least as many 3D cores as TA cores. */
	IMG_UINT32	ui32Counters[SGX_FEATURE_MP_CORE_COUNT_3D][PVRSRV_SGX_HWPERF_NUM_COUNTERS];
	IMG_UINT32	ui32MiscCounters[SGX_FEATURE_MP_CORE_COUNT_3D][PVRSRV_SGX_HWPERF_NUM_MISC_COUNTERS];
} SGXMKIF_HWPERF_CB_ENTRY;

/*!
 *****************************************************************************
 * The HWPerf Circular Buffer.
 *****************************************************************************/
typedef struct _SGXMKIF_HWPERF_CB_
{
	IMG_UINT32				ui32Woff;
	IMG_UINT32				ui32Roff;
	IMG_UINT32				ui32Ordinal;
	SGXMKIF_HWPERF_CB_ENTRY psHWPerfCBData[SGXMKIF_HWPERF_CB_SIZE];
} SGXMKIF_HWPERF_CB;

#endif /*  __SGX_MKIF_KM_H__ */

/******************************************************************************
 End of file (sgx_mkif_km.h)
******************************************************************************/


text:
package org.apache.zookeeper.server.quorum;

/**
 * Leader election protocol MBean.
 */
public interface LeaderElectionMXBean {

    /**
     *
     * @return the time when the leader election started
     */
    String getStartTime();

}


text:
title: Home
layout: top
---

{% include cs5220_head.html %}

Overview

      How do we solve the large-scale problems of science quickly on
      modern computers?  How do we measure the performance of new or
      existing simulation codes, and what things can we do to make
      them run faster?  How can we best take advantage of features
      like multicore processors, vector units, and graphics
      co-processors?  These are the types of questions we will address
      in CS 5220, Applications of Parallel Computers.  Topics include:

Single-processor architecture, caches, and serial
          performance tuning

Basics of parallel machine organization

Distributed memory programming with MPI

Shared memory programming with OpenMP

Parallel patterns: data partitioning, synchronization, and
          load balancing

Examples of parallel numerical algorithms

Applications from science and engineering

      Because our examples will be drawn primarily from engineering
      and scientific computations, we will assume some prior exposure
      to numerical methods.  Students should also be able to read and
      write serial programs written in C or a related language like
      C++ or Java.  Prior exposure to parallel programming is not
      required, and non-CS students from fields involving simulation
      are particularly welcome!

      {% include intel.html %}

        We gratefully acknowledge Intel for an
        equipment grant
        in support of this course.

Posts

    {% for post in site.posts limit:10 %}

      {{ post.date | date_to_string }} »
        {{ post.title }}
        {{ post.excerpt }}
    {% endfor %}
    All posts »


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Command;

namespace SuperSocket.QuickStart.CustomProtocol
{
    public class CustomProtocolSession : AppSession<CustomProtocolSession, BinaryCommandInfo>
    {
        public override void HandleExceptionalError(Exception e)
        {

        }
    }
}


text:
import React from "react";
import Head from "next/head";
import withPost, { Content } from "nextein/post";
import { name } from "../site";

export default withPost(({ post }) => {
  return (
    <main>
      <Head>
        <title>
          {post.data.title} | {name}
        </title>
      </Head>
      <section>
        <Content {...post} />
      </section>
    </main>
  );
});


text:
"""
Join all the output files. This may take a lot of memory :)
"""

import os
import sys
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Join parsed SF output files")
    parser.add_argument('-d', help='directory with all the output files', required=True)
    parser.add_argument('-o', help='Output file to write', required=True)
    parser.add_argument('-v', help='verbose output', action="store_true")
    args = parser.parse_args()

    data = {}
    sss = set()
    for infile in os.listdir(args.d):
        with open(os.path.join(args.d, infile), 'r') as f:
            l = f.readline().strip()
            if not l:
                continue

            try:
                (lvl, sample) = l.split("\t")
            except:
                sys.stderr.write("Can't split: |{}|\n".format(l))
                sys.exit(-1)
            sample = sample.replace('superfocus.bins/', '')
            data[sample] = {}
            for l in f:
                p=l.strip().split("\t")
                data[sample][p[0]] = p[1]
                sss.add(p[0])

    allss = sorted(sss)
    samples = sorted(data.keys())
    with open(args.o, 'w') as out:
        out.write("\t")
        out.write("\t".join(samples))
        out.write("\n")
        for ss in allss:
            out.write(ss)
            for sam in sorted(data.keys()):
                out.write("\t{}".format(data[sam].get(ss, 0)))
            out.write("\n")


text:
/**
 *
 * @authors Tom Hu (h1994st@gmail.com)
 * @date    2015-10-10 22:10:10
 * @version 1.0
 */

$(document).ready(function() {
  $("select").selectpicker({ style: 'btn-hg btn-primary', menuStyle: 'dropdown-inverse' });

  $('#password>form').submit(function(event) {
    var oldPassword = $('input[name="old-pwd"]').val();
    var newPassword = $('input[name="new-pwd"]').val();
    var confirmPassword = $('input[name="confirm-pwd"]').val();

    if (!oldPassword || !newPassword || !confirmPassword) {
      event.preventDefault();
      alert('不能为空!');
      return false;
    };

    if (newPassword !== confirmPassword) {
      event.preventDefault();
      alert('密码不符!');
      return false;
    };

    return true;
  });
});


text:
set -eo pipefail

kpt fn eval -s -t mutator -i set-namespace:v0.1.3 --match-kind Deployment -- namespace=staging


text:
package clientapi.command.executor.parser;

import clientapi.command.executor.ExecutionContext;

import java.lang.reflect.Type;

/**
 * @author Brady
 * @since 10/18/2017
 */
public interface ArgumentParser<T> {

    /**
     * Returns the resolved/parsed type from a
     * raw string representation.
     *
     * @param context Context behind command execution
     * @param type The expected return type
     * @param raw Type represented in a string
     * @return String resolved to type
     */
    T parse(ExecutionContext context, Type type, String raw);

    /**
     * @param type A type
     * @return Whether or not the specified type is a target for this parser.
     */
    boolean isTarget(Type type);
}


text:
package dyco4j.logging;

import org.junit.Test;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.zip.GZIPInputStream;

public class LoggerInitializerTest {
    @Test
    public void testInitializeWithPropertiesFile() throws Exception {
        LoggerInitializer.reenableInitialize(); // used only for testing
        LoggerInitializer.initialize();
        final String _msg = "test initialize with properties file";
        Logger.log(_msg);
        Logger.cleanupForTest();

        final Properties _tmp = new Properties();
        try (final InputStream _in1 = LoggerInitializer.class.getResourceAsStream("logging.properties")) {
            if (_in1 != null)
                _tmp.load(_in1);
        }
        assert _tmp.getProperty("traceFolder") != null : "traceFolder property not found";

        checkTraceFilesForLogs(_msg);
    }

    @Test
    public void testInitializeWithoutPropertiesFile() throws Exception {
        LoggerInitializer.reenableInitialize(); // used only for testing
        // change the name of build/resources/test/dyco4j/instrumentation/logging/logging.properties
        final Path _srcPropFilePath =
                Paths.get("build", "resources", "test", "dyco4j", "logging", "logging.properties");
        final File _srcPropFile = _srcPropFilePath.toFile();
        final Path _destPropFilePath = _srcPropFilePath.resolveSibling(Paths.get("logging.properties1"));
        final File _destPropFile = _destPropFilePath.toFile();
        assert _srcPropFile.renameTo(_destPropFile) : "property file could not be renamed";

        LoggerInitializer.initialize();
        final String _msg = "test initialize without properties file";
        Logger.log(_msg);
        Logger.cleanupForTest();

        // undo the name change of build/resources/test/dyco4j/instrumentation/logging/logging.properties
        assert _destPropFile.renameTo(_srcPropFile) : "property file renaming could not be undone.";

        checkTraceFilesForLogs(_msg);
    }

    private void checkTraceFilesForLogs(final String expectedMessage) throws IOException {
        final File _traceFile = LoggerInitializer.getTraceFile();
        try (final BufferedReader _traceReader =
                new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(_traceFile))))) {
            _traceReader.readLine();
            final String _line = _traceReader.readLine();
            final String _regex = MessageFormat.format("^\\d+,{0}$", expectedMessage);
            assert _line.matches(_regex) : "expected log statement not found";
        }
        assert _traceFile.delete() : "Could not delete trace file";
    }
}


text:
#if MapRenderV1
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace WzComparerR2.MapRender.Patches
{
    public class RenderPatch : IDisposable
    {
        public RenderPatch()
        {
            zIndex = new int[8];
            flip = false;
            renderArgs = new RenderArgs();
            alpha = 255;
        }

        string name;
        Vector2 position;
        bool flip;
        int[] zIndex;
        RenderAnimate frames;
        RenderObjectType objectType;
        TimeSpan playStateChangedTime;
        RenderArgs renderArgs;
        int alpha;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public Vector2 Position
        {
            get { return position; }
            set { position = value; }
        }

        public bool Flip
        {
            get { return flip; }
            set { flip = value; }
        }

        public int[] ZIndex
        {
            get { return zIndex; }
        }

        public RenderAnimate Frames
        {
            get { return frames; }
            set { frames = value; }
        }

        public virtual RenderObjectType ObjectType
        {
            get { return objectType; }
            set { objectType = value; }
        }

        public TimeSpan PlayStateChangedTime
        {
            get { return playStateChangedTime; }
            set { playStateChangedTime = value; }
        }

        public RenderArgs RenderArgs
        {
            get { return renderArgs; }
        }

        public int Alpha
        {
            get { return alpha; }
            set { alpha = value; }
        }

        public int UpdateCurrentFrameIndex(TimeSpan totalTime)
        {
            float framePlayed;
            return UpdateCurrentFrameIndex(totalTime, out framePlayed);
        }

        public virtual int UpdateCurrentFrameIndex(TimeSpan totalTime, out float framePlayed)
        {
            framePlayed = 0f;
            if (this.frames == null || this.frames.Length == 0)
            {
                return -1;
            }
            int[] timeLine = this.frames.TimeLine;
            if (timeLine[timeLine.Length - 1] <= 0)
            {
                return 0;
            }

            double ms = (totalTime.TotalMilliseconds - playStateChangedTime.TotalMilliseconds);
            int startTimeLine = 1;
            if (this.frames.Repeat <= 0 || this.frames.Repeat >= this.frames.Length) //使用全帧绘制
            {
                ms %= timeLine[timeLine.Length - 1];
            }
            else
            {
                if (ms < timeLine[timeLine.Length - 1]) //首次绘制
                {
                    ms %= timeLine[timeLine.Length - 1];
                }
                else //循环段
                {
                    startTimeLine = frames.Repeat + 1;
                    ms -= timeLine[timeLine.Length - 1];
                    int newDelay = timeLine[timeLine.Length - 1] - timeLine[frames.Repeat];
                    if (newDelay <= 0)
                        return frames.Repeat;
                    ms = ms % newDelay + timeLine[frames.Repeat];
                }
            }

            for (int i = startTimeLine; i < timeLine.Length; i++)
            {
                if (ms < timeLine[i])
                {
                    framePlayed = (float)((ms - timeLine[i - 1]) / (timeLine[i] - timeLine[i - 1]));
                    return i - 1;
                }
            }
            return frames.Repeat;
        }

        public virtual void Update(GameTime gameTime, RenderEnv env)
        {
            float played;
            int index = this.UpdateCurrentFrameIndex(gameTime.TotalGameTime, out played);
            if (index > -1)
            {
                //获取当前帧绘制参数
                RenderFrame frame = this.Frames[index];
                this.RenderArgs.CurrentIndex = index;
                this.RenderArgs.CurrentPercent = played;
                Rectangle rect;
                this.RenderArgs.Culled = !env.Camera.CheckSpriteVisible(frame, this.position, this.flip, out rect);
                this.renderArgs.DisplayRectangle = rect;
            }
            else
            {
                this.RenderArgs.CurrentIndex = -1;
                this.RenderArgs.CurrentPercent = 0f;
                this.RenderArgs.Culled = true;
            }
        }

        public virtual void Draw(GameTime gameTime, RenderEnv env)
        {
            if (this.RenderArgs.CurrentIndex < 0)
            {
                return;
            }

            RenderFrame frame = this.Frames[this.RenderArgs.CurrentIndex];
            Vector2 cameraOrigin = env.Camera.Origin;

            float curPer = this.RenderArgs.CurrentPercent;
            float alpha = (frame.A0 * (1 - curPer) + frame.A1 * curPer) / 255.0f * this.alpha / 255.0f;

            env.Sprite.Draw(frame.Texture,
               this.Position - cameraOrigin,
               null,
               new Color(Color.White, alpha),
               0f,
               this.flip ? new Vector2(frame.Texture.Width - frame.Origin.X, frame.Origin.Y) : frame.Origin,
               1f,
               this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None,
               0f);
        }

        public void Dispose()
        {
            this.Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.Frames != null && this.Frames.Length > 0)
                {
                    foreach (RenderFrame frame in this.Frames)
                    {
                        if (!frame.Texture.IsDisposed)
                        {
                            frame.Texture.Dispose();
                        }
                    }
                }
            }
        }

        public override string ToString()
        {
            return base.ToString() + " " + this.name;
        }
    }
}
#endif


text:
package org.pentaho.di.shapefilereader;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.xbaseinput.XBase;
import org.w3c.dom.Node;

/**
 * Contains the meta-data for the ShapeFileReader plugin
 *
 * @author Matt
 * @since 25-apr-2005
 */

@Step( id = "ShapeFileReader",
  image = "ESRI.svg",
  i18nPackageName = "org.pentaho.di.shapefilereader",
  name = "ShapeFileReader.Step.Name",
  description = "ShapeFileReader.Step.Description",
  documentationUrl = "http://wiki.pentaho.com/display/EAI/ESRI+Shapefile+Reader",
  categoryDescription = "Input" )
public class ShapeFileReaderMeta extends BaseStepMeta implements StepMetaInterface {
  /**
   * The filename of the shape file
   */
  public String shapeFilename;

  /**
   * The filename of the DBF file
   */
  public String dbfFilename;

  /**
   * File encoding
   */
  private String encoding;

  public ShapeFileReaderMeta() {
    super(); // allocate BaseStepMeta
  }

  /**
   * @return Returns the shapeFilename.
   */
  public String getShapeFilename() {
    return shapeFilename;
  }

  /**
   * @param shapeFilename The shapeFilename to set.
   */
  public void setShapeFilename( String shapeFilename ) {
    this.shapeFilename = shapeFilename;
  }

  /**
   * @return Returns the dbfFilename.
   */
  public String getDbfFilename() {
    return dbfFilename;
  }

  /**
   * @param dbfFilename The dbfFilename to set.
   */
  public void setDbfFilename( String dbfFilename ) {
    this.dbfFilename = dbfFilename;
  }

  /**
   * @return Returns the encoding.
   */
  public String getEncoding() {
    return encoding;
  }

  /**
   * @param encoding The encoding to set.
   */
  public void setEncoding( String encoding ) {
    this.encoding = encoding;
  }

  public void loadXML( Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters )
    throws KettleXMLException {
    readData( stepnode );
  }

  public Object clone() {
    ShapeFileReaderMeta retval = (ShapeFileReaderMeta) super.clone();

    return retval;
  }

  private void readData( Node stepnode ) throws KettleXMLException {
    try {
      shapeFilename = XMLHandler.getTagValue( stepnode, "shapefilename" );
      dbfFilename = XMLHandler.getTagValue( stepnode, "dbffilename" );
      encoding = XMLHandler.getTagValue( stepnode, "encoding" );
    } catch ( Exception e ) {
      throw new KettleXMLException( "Unable to load step info from XML", e );
    }
  }

  public void setDefault() {
    shapeFilename = "";
    dbfFilename = "";
    encoding = "";
  }

  public void getFields( RowMetaInterface row, String name, RowMetaInterface[] info, StepMeta nextStep,
                         VariableSpace space ) throws KettleStepException {

    // The filename...
    ValueMetaInterface filename = new ValueMeta( "filename", ValueMetaInterface.TYPE_STRING );
    filename.setOrigin( name );
    filename.setLength( 255 );
    row.addValueMeta( filename );

    // The file type
    ValueMetaInterface ft = new ValueMeta( "filetype", ValueMetaInterface.TYPE_STRING );
    ft.setLength( 50 );
    ft.setOrigin( name );
    row.addValueMeta( ft );

    // The shape nr
    ValueMetaInterface shnr = new ValueMeta( "shapenr", ValueMetaInterface.TYPE_INTEGER );
    shnr.setOrigin( name );
    row.addValueMeta( shnr );

    // The part nr
    ValueMetaInterface pnr = new ValueMeta( "partnr", ValueMetaInterface.TYPE_INTEGER );
    pnr.setOrigin( name );
    row.addValueMeta( pnr );

    // The part nr
    ValueMetaInterface nrp = new ValueMeta( "nrparts", ValueMetaInterface.TYPE_INTEGER );
    nrp.setOrigin( name );
    row.addValueMeta( nrp );

    // The point nr
    ValueMetaInterface ptnr = new ValueMeta( "pointnr", ValueMetaInterface.TYPE_INTEGER );
    ptnr.setOrigin( name );
    row.addValueMeta( ptnr );

    // The nr of points
    ValueMetaInterface nrpt = new ValueMeta( "nrpointS", ValueMetaInterface.TYPE_INTEGER );
    nrpt.setOrigin( name );
    row.addValueMeta( nrpt );

    // The X coordinate
    ValueMetaInterface x = new ValueMeta( "x", ValueMetaInterface.TYPE_NUMBER );
    x.setOrigin( name );
    row.addValueMeta( x );

    // The Y coordinate
    ValueMetaInterface y = new ValueMeta( "y", ValueMetaInterface.TYPE_NUMBER );
    y.setOrigin( name );
    row.addValueMeta( y );

    // The measure
    ValueMetaInterface m = new ValueMeta( "measure", ValueMetaInterface.TYPE_NUMBER );
    m.setOrigin( name );
    row.addValueMeta( m );

    if ( getDbfFilename() != null ) {

      XBase xbase = new XBase( getLog(), getDbfFilename() );
      try {
        xbase.setDbfFile( getDbfFilename() );
        xbase.open();

        //Set encoding
        if ( StringUtils.isNotBlank( encoding ) ) {
          xbase.getReader().setCharactersetName( encoding );
        }

        RowMetaInterface fields = xbase.getFields();
        for ( int i = 0; i < fields.size(); i++ ) {
          fields.getValueMeta( i ).setOrigin( name );
          row.addValueMeta( fields.getValueMeta( i ) );
        }

      } catch ( Throwable e ) {
        throw new KettleStepException( "Unable to read from DBF file", e );
      } finally {
        xbase.close();
      }
    } else {
      throw new KettleStepException( "Unable to read from DBF file: no filename specfied" );
    }
  }

  public String getXML() {
    String retval = "";

    retval += "    " + XMLHandler.addTagValue( "shapefilename", shapeFilename );
    retval += "    " + XMLHandler.addTagValue( "dbffilename", dbfFilename );
    retval += "    " + XMLHandler.addTagValue( "encoding", encoding );

    return retval;
  }

  public void readRep( Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters )
    throws KettleException {
    try {
      shapeFilename = rep.getStepAttributeString( id_step, "shapefilename" );
      dbfFilename = rep.getStepAttributeString( id_step, "dbffilename" );
      encoding = rep.getStepAttributeString( id_step, "encoding" );
    } catch ( Exception e ) {
      throw new KettleException( "Unexpected error reading step information from the repository", e );
    }

  }

  public void saveRep( Repository rep, ObjectId id_transformation, ObjectId id_step ) throws KettleException {
    try {
      rep.saveStepAttribute( id_transformation, id_step, "shapefilename", shapeFilename );
      rep.saveStepAttribute( id_transformation, id_step, "dbffilename", dbfFilename );
      rep.saveStepAttribute( id_transformation, id_step, "encoding", encoding );
    } catch ( Exception e ) {
      throw new KettleException( "Unable to save step information to the repository for id_step=" + id_step, e );
    }
  }

  public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepinfo, RowMetaInterface prev,
                     String[] input, String[] output, RowMetaInterface info ) {
    CheckResult cr;

    // See if we get input...
    if ( input.length > 0 ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, "This step is not expecting nor reading any input", stepinfo );
      remarks.add( cr );
    } else {
      cr = new CheckResult( CheckResult.TYPE_RESULT_OK, "Not receiving any input from other steps.", stepinfo );
      remarks.add( cr );
    }

    if ( shapeFilename == null || dbfFilename == null || shapeFilename.length() == 0 || dbfFilename.length() == 0 ) {
      cr = new CheckResult( CheckResult.TYPE_RESULT_ERROR, "No files can be found to read.", stepinfo );
      remarks.add( cr );
    } else {
      cr = new CheckResult( CheckResult.TYPE_RESULT_OK, "Both shape file and the DBF file are defined.", stepinfo );
      remarks.add( cr );
    }
  }

  public StepInterface getStep( StepMeta si, StepDataInterface stepDataInterface, int cnr, TransMeta tr, Trans disp ) {
    return new ShapeFileReader( si, stepDataInterface, cnr, tr, disp );
  }

  public StepDataInterface getStepData() {
    return new ShapeFileReaderData();
  }
}


text:
function PicExhitbitWindow(record, tabWin)
{
	var CommentView = require('/ui/handheld/CommentView');

    //Ti.include('/ui/handheld/Data.js');
    var picWidth = 320;
    var shopId = (record.shopId == null) ? 0 : record.shopId;//0 if null record shop
    var imageURL = record.image;//imageUrlHeadString+record.index+".jpg";
    Ti.API.info('imageURL ' + imageURL);

	var win = Ti.UI.createWindow({
		title:record.title + ' 在 ' + shopData[shopId].title,
		backgroundColor:'black'
	});

    var shopLogo = Titanium.UI.createImageView({

		width:picWidth, height: 110,
		top:0, left:0,
		image:record.shop.image,
		classType: 'shopLogo'
	});

	function openShopProfileWin(e, islongclick) {
		// event data
		var index = e.index;
		var section = e.section;
		var row = e.row;
		var rowdata = e.rowData;
		var classType = e.source.classType;
		Ti.API.info("clicked ");
		if (classType == 'shopLogo'){

			// var msg = 'row ' + row + ' index ' + index + ' ' + row.data.index + ' section ' + section  + ' row data ' + rowdata + 'classType' + classType;
			// if (islongclick) {
				// e.section.headerTitle = e.section.headerTitle + ' section has been long-clicked';
				// msg = "LONGCLICK " + msg;
			// } else {
				// e.section.headerTitle = e.section.headerTitle + ' section has been clicked';
			// }
			// Titanium.UI.createAlertDialog({title:'Table View',message:msg}).show();
			var ShopWindow  = require('/ui/handheld/ShopDashboardWindow');

			var winShop = new ShopWindow(record);
			tabWin.containingTab.open(winShop);
		}

	}
	// create table view event listener
	shopLogo.addEventListener('click', function(e)
	{
		openShopProfileWin(e);
	});
	shopLogo.addEventListener('longclick', function(e)
	{
		openShopProfileWin(e, true);
	});
    win.add(shopLogo);

	var picScrollView = Titanium.UI.createScrollView({
		contentWidth:'auto',
		contentHeight:'auto',
		top:shopLogo.height + 10,
		showVerticalScrollIndicator:false,
		showHorizontalScrollIndicator:false

	})
	win.add(picScrollView);
    var picView = Ti.UI.createImageView({
    	top:0, width:picWidth, height:picWidth, borderRadius:3,
		hires:true,
		image:record.image,
    })
    picScrollView.add(picView);

    var commentView = CommentView(record);
	commentView.top = picView.top + picView.height + 50 +10;

	picScrollView.add(commentView);

    return win;
}
module.exports = PicExhitbitWindow;


text:
package org.knowm.proprioceptron.thematrix;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.knowm.proprioceptron.GameState;
import org.knowm.proprioceptron.thematrix.ObjectFactory.GameView;

import com.jme3.app.FlyCamAppState;
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.font.BitmapText;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.Geometry;

/**
 * @author Zackkenyon
 * @create Oct 5, 2012
 */
public class TheMatrix extends SimpleApplication implements PhysicsCollisionListener, ActionListener {

  private static final int numBluePillsPerLevel = 10;

  /** default physics handler */
  private BulletAppState bulletAppState;

  /** specifies the type of camera */
  private GameView gameView = GameView.GOD_VIEW;

  /** prevents calculation of state during movement transitions */
  protected boolean movementOver = true;

  /** prevents calculation of state during resting periods */
  protected boolean nowWaiting = true;

  /** we attach this control to the character geometry, it implements physical interactions with rigid bodies by default, and gives us some minimal controls over movement. */
  protected CharacterControl player;

  /** the List of levels to be used in the game. */
  List<LevelAppState> levels;

  /** the current level, grabbed from the list of levels. according to the currentlevelindex */
  LevelAppState currentLevel;

  /** the index of the current level in the list of levels. */
  int currentlevelindex = 0;

  /** the character controller, can be told to update(tpf), to initialize(AppStateManager,Application) itself and to do something onAction(name,keyPressed,tpf) */
  PlayerAppState currentPlayer;

  /** the Orientation of the player as a unit vector. */
  final Vector3f viewDirection = new Vector3f(0, 0, 1);

  /** displays diagnostic information on the game window. */
  private BitmapText hudText;

  Random random = new Random();

  /** Specifies how well the computer is doing at the game. +10 for blue pills, -10 for red pills, -1 per movement. */
  public float score;

  /** the number of blue pills that have been collected so far. */
  public int numBluePills;

  /** GameState */
  public GameState oldEnvState;
  public GameState newEnvState;

  /** Listeners **/
  protected final List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();

  /**
   * Constructor
   *
   * @param gameView the initial state of the camera.
   * @param controldelegate because the way the computer and the human interact with the game is so fundamentally different, the only design solution that makes sense, is to delegate the update and onAction methods to AIAppState and HumanAppState.
   */
  public TheMatrix(GameView gameView, PlayerAppState controldelegate) {

    currentPlayer = controldelegate;
    this.gameView = gameView;
  }

  @Override
  public void simpleInitApp() {

    // 1. Activate Physics
    bulletAppState = new BulletAppState();
    stateManager.attach(bulletAppState);
    bulletAppState.getPhysicsSpace().enableDebug(assetManager);
    numBluePills = 0;

    // 2. make game environment and levels
    ObjectFactory.setupGameEnvironment(rootNode, bulletAppState.getPhysicsSpace(), assetManager);
    levels = new ArrayList<LevelAppState>();
    levels.add(new LevelAppState(1, 0, false));
    levels.add(new LevelAppState(1, 1, false));
    levels.add(new LevelAppState(3, 0, false));
    levels.add(new LevelAppState(3, 3, false));
    levels.add(new LevelAppState(1, 0, true));
    levels.add(new LevelAppState(1, 1, true));
    levels.add(new LevelAppState(3, 0, true));
    levels.add(new LevelAppState(3, 3, true));
    for (LevelAppState s : levels) {
      s.initialize(getStateManager(), this);
    }
    currentLevel = levels.get(currentlevelindex);
    currentLevel.setEnabled(true);

    // 3. make player and player controllers
    player = ObjectFactory.getPlayer(rootNode, bulletAppState.getPhysicsSpace(), assetManager);

    currentPlayer.initialize(getStateManager(), this);
    // 4. setup keys
    setupKeys();

    // add ourselves as collision listener
    bulletAppState.getPhysicsSpace().addCollisionListener(this);

    hudText = new BitmapText(guiFont, false);
    hudText.setSize(24); // font size
    hudText.setColor(ColorRGBA.White); // font color
    hudText.setText("D="); // the text
    hudText.setLocalTranslation(10, settings.getHeight() - 10, 0); // position
    guiNode.attachChild(hudText);

    // setup camera
    stateManager.detach(stateManager.getState(FlyCamAppState.class));
    setCam();
    newEnvState = new TheMatrixEnvState(new ArrayList<PillPerceptionState>());
    oldEnvState = new TheMatrixEnvState(new ArrayList<PillPerceptionState>());
  }

  public void setcurrentlevel(int levelindex) {

    currentLevel.setEnabled(false);
    currentLevel = levels.get(levelindex);
    currentLevel.setEnabled(true);
  }

  public void setcurrentlevel(LevelAppState level) {

    currentLevel = level;
  }

  public void setupKeys() {

    inputManager.addMapping("forward", new KeyTrigger(KeyInput.KEY_I));
    inputManager.addMapping("backward", new KeyTrigger(KeyInput.KEY_K));
    inputManager.addMapping("turnleft", new KeyTrigger(KeyInput.KEY_J));
    inputManager.addMapping("turnright", new KeyTrigger(KeyInput.KEY_L));
    inputManager.addMapping("toggleGameView", new KeyTrigger(KeyInput.KEY_SPACE));
    inputManager.addListener(this, "forward", "backward", "turnleft", "turnright", "givecontrol", "toggleGameView");
  }

  @Override
  public void onAction(String name, boolean keyPressed, float tpf) {

    // detect when buttons were released

    if (name.equals("toggleGameView")) {
      if (!keyPressed) {
        gameView = gameView.getNext();
        setCam();
      }
    } else {
      currentPlayer.onAction(name, keyPressed, tpf);
    }
  }

  /**
 *
 */
  @Override
  public void simpleUpdate(float tpf) {

    // according to specs, the AI chooses to arbitrarily be moved forward or turned in one timestep, but not both.
    // this version of Update is for the player. and does not require that.
    currentPlayer.update(tpf);
    currentLevel.update(tpf);
    if (numBluePills > numBluePillsPerLevel * currentlevelindex) {

      setcurrentlevel(currentlevelindex++);

    }

  }

  public void rotateEpsilon(float epsilon) {

    Quaternion quat = new Quaternion();
    // seems silly to make this over and over.
    quat.fromAngleAxis(epsilon, Vector3f.UNIT_Y);
    quat.mult(viewDirection, viewDirection);
    player.setViewDirection(viewDirection);
  }

  public void forwardEpsilon(float epsilon) {

    player.setPhysicsLocation(player.getPhysicsLocation().add(viewDirection.mult(epsilon)));
  }

  /**
   * notify the AI of new commands.
   *
   * @param commands
   */
  public void addAICommands(List<PlayerCommand> commands) {

    ((AIAppState) currentPlayer).pushCommand(commands);
  }

  /**
   * notify the AI of a single new command.
   *
   * @param command
   */
  public void addAICommands(PlayerCommand command) {

    ((AIAppState) currentPlayer).pushCommand(command);
  }

  @Override
  public void collision(PhysicsCollisionEvent event) {

    // This is called back for collisions with all RigidBodyControls, even the floor!
    // System.out.println(event.getNodeA().toString());

  }

  /**
   * any code which only needs to be called once every time the scene is drawn should go here.
   */
  @Override
  public void simpleRender(RenderManager rm) {

    setCam();

    hudText.setText("number of blue pills collected: " + numBluePills + "\nscore: " + score + newEnvState.toString());

  }

  /**
   * controls camera logic which needs to be updated when render is called.
   */
  public void setCam() {

    flyCam.setEnabled(false);

    // probably better practice to make camera objects with their own update methods and call them in render,
    if (gameView == GameView.THIRD_PERSON_CENTER) {
      cam.setLocation(new Vector3f(0, 5f, 0));
      cam.lookAt(player.getPhysicsLocation(), Vector3f.UNIT_Y);
    } else if (gameView == GameView.THIRD_PERSON_FOLLOW) {
      cam.setLocation(viewDirection.mult(-20f).add(player.getPhysicsLocation()).add(Vector3f.UNIT_Y.mult(5f)));
      cam.lookAt(player.getPhysicsLocation(), Vector3f.UNIT_Y);
    } else if (gameView == GameView.FIRST_PERSON) {
      cam.setLocation(player.getPhysicsLocation().add(Vector3f.UNIT_Y));
      cam.setAxes(Vector3f.UNIT_Y.cross(viewDirection), Vector3f.UNIT_Y, viewDirection);
    } else { // god view
      cam.setLocation(Vector3f.UNIT_Y.mult(62));
      cam.lookAt(Vector3f.ZERO, Vector3f.UNIT_Z);
    }

  }

  /**
   * moves the pill to a random location within the bounds of the level.
   *
   * @param pill
   */
  public void movePill(Geometry pill) {

    float x = ObjectFactory.PLATFORM_DIMENSION / 2 - random.nextInt(ObjectFactory.PLATFORM_DIMENSION);
    float z = ObjectFactory.PLATFORM_DIMENSION / 2 - random.nextInt(ObjectFactory.PLATFORM_DIMENSION);
    pill.center();
    pill.move(x, ObjectFactory.PILL_RADIUS, z);
  }

  public void addChangeListener(PropertyChangeListener newListener) {

    listeners.add(newListener);
  }

  /**
   * Send PropertyChangeEvent to observers (listeners)
   */
  public void notifyListeners() {

    PropertyChangeEvent pce = new PropertyChangeEvent(this, "", oldEnvState, newEnvState);

    for (Iterator<PropertyChangeListener> iterator = listeners.iterator(); iterator.hasNext();) {
      PropertyChangeListener observer = iterator.next();
      observer.propertyChange(pce);
    }
  }

}


text:
var deepExtend = require("../../util/deepExtend");
var spritesheetTask = require("./spritesheetTask");

var generateLessTasks = function (gulp = require("gulp"), options) {
  var {
    taskName: taskName,
    dependsOn: dependsOn = [],
  } = options;

  taskName = "build:spritesheet:" + taskName;

  options = deepExtend({}, options, {
    taskName: taskName,
    dependsOn: dependsOn,
  });

  return spritesheetTask(gulp, options);
  // gulp.task(taskName, dependsOn, function () {
  //   return spritesheetTask(gulp, options);
  // });
};

module.exports = generateLessTasks;


text:
<?php

namespace Amer\EleccionesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Amer\EleccionesBundle\Validator\Constraints as AmerAssert;

/**
 * Amer\EleccionesBundle\Entity\ParticipantResult
 *
 * @ORM\Table(name="participant_results")
 * @ORM\Entity(repositoryClass="Amer\EleccionesBundle\Entity\ParticipantResultRepository")
 */
class ParticipantResult
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="ElectionParticipant", inversedBy="id")
     */
    protected $election_participant;

    /**
     * @var integer $turn_number
     *
     * @ORM\Column(name="turn_number", type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $turn_number;

    /**
     * @var integer $votes
     *
     * @ORM\Column(name="votes", type="integer", nullable=true)
     * @Assert\GreaterThanOrEqual(value = "0", message = "Deben ser cantidades positivas")
     * @AmerAssert\Natural
     */
    private $votes;

    /**
     * @var float $percent_votes
     *
     * @ORM\Column(name="percent_votes", type="decimal", precision=4, scale=1, nullable=true)
     * @Assert\Range(min = "0", minMessage = "Los porcentajes deben ser cantidades positivas no mayores de 100", max = "100", maxMessage = "Los porcentajes deben ser cantidades positivas no mayores de 100")
     */
    private $percent_votes;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set turn_number
     *
     * @param integer $turnNumber
     * @return Resultado
     */
    public function setTurnNumber($turnNumber)
    {
        $this->turn_number = $turnNumber;

        return $this;
    }

    /**
     * Get turn_number
     *
     * @return integer
     */
    public function getTurnNumber()
    {
        return $this->turn_number;
    }

    /**
     * Set votes
     *
     * @param integer $votes
     * @return ParticipantResult
     */
    public function setVotes($votes)
    {
        $this->votes = $votes;

        return $this;
    }

    /**
     * Get votes
     *
     * @return integer
     */
    public function getVotes()
    {
        return $this->votes;
    }

    /**
     * Set percent_votes
     *
     * @param float $percentVotes
     * @return ParticipantResult
     */
    public function setPercentVotes($percentVotes)
    {
        $this->percent_votes = $percentVotes;

        return $this;
    }

    /**
     * Get percent_votes
     *
     * @return float
     */
    public function getPercentVotes()
    {
        return $this->percent_votes;
    }

    /**
     * Set election_participant
     *
     * @param \Amer\EleccionesBundle\Entity\ElectionParticipant $electionParticipant
     * @return ParticipantResult
     */
    public function setElectionParticipant(\Amer\EleccionesBundle\Entity\ElectionParticipant $electionParticipant = null)
    {
        $this->election_participant = $electionParticipant;

        return $this;
    }

    /**
     * Get election_participant
     *
     * @return \Amer\EleccionesBundle\Entity\ElectionParticipant
     */
    public function getElectionParticipant()
    {
        return $this->election_participant;
    }
}