text:
(function () {

    var WebSocket = require('ws');
    var async = require('async');
    var sprintf = require('sprintf-js').sprintf;

    var fadecandy = {};

    fadecandy.DEFAULT_TIMEOUT = 4000;
    fadecandy.LEDS_PER_DEVICE = 512;
    fadecandy.LEDS_PER_STRIP = 64;

    fadecandy.ledInfo = function(devSerial, index) {
        // Return verbose information about an LED, given its FC controller serial number and index

        return {
            device: devSerial,
            index: index,
            stripIndex: (index / fadecandy.LEDS_PER_STRIP)|0,
            stripPosition: (index % fadecandy.LEDS_PER_STRIP)|0,
            string: sprintf('%s-%03d', devSerial, index),
        };
    }

    fadecandy.ledsForDevice = function(devSerial) {
        // Return a list of LEDs for objects describing the potential LEDs we may find on a list of FC devices.

        var results = [];
        for (var i = 0; i < fadecandy.LEDS_PER_DEVICE; i++) {
            results.push(fadecandy.ledInfo(devSerial, i));
        }
        return results;
    }

    fadecandy.ledsForDeviceList = function(devices) {
        // Return a list of objects describing the potential LEDs we may find on a list of FC devices.

        var results = [];
        for (var i = 0; i < devices.length; i++) {
            results = results.concat(fadecandy.ledsForDevice(devices[i].serial));
        }
        return results;
    }

    fadecandy.ConfigFactory = function() {
        var config = {};

        config.json = {
            listen: [ "127.0.0.1", 7890 ],
            verbose: true,
            color: { gamma: 2.5, whitepoint: [ 1, 1, 1 ] },
            devices: []
        };

        config.opcPixelCount = 0;

        config.mapDevice = function (serial) {
            /*
             * Find or create a device entry for a Fadecandy board with the given serial.
             * Returns the JSON node.
             */

            for (var i = 0; i < config.json.devices.length; i++) {
                var node = config.json.devices[i];
                if (node.type == 'fadecandy' && node.serial == serial) {
                    return node;
                }
            }

            var node = { type: 'fadecandy', serial: serial, map: [] };
            config.json.devices.push(node);
            return node;
        }

        config.mapPixel = function (device, index) {
            /*
             * Append a single device pixel to the mapping, returning the new OPC
             * pixel index. Consolidates contiguous mappings.
             *
             * Only supports channel 0 mappings of the form:
             * [ OPC Channel, First OPC Pixel, First output pixel, Pixel count ]
             */

            var devMap = config.mapDevice(device).map;
            var opcIndex = config.opcPixelCount++;
            var last = devMap[devMap.length - 1];

            if (last && last.length == 4
                && last[1] + last[3] == opcIndex
                && last[2] + last[3] == index) {
                // We can extend the last mapping
                last[3]++;
            } else {
                // New mapping line
                devMap.push([ 0, opcIndex, index, 1 ]);
            }

            return opcIndex;
        }

        return config;
    }

    fadecandy.connect = function(url, callback) {
        var connection = {};

        connection.socket = new WebSocket(url);
        connection.devices = [];
        connection.pending = {};
        connection.sequence = 1;

        connection.message = function (obj, callback, timeout) {
            timeout = timeout || fadecandy.DEFAULT_TIMEOUT;

            obj.sequence = connection.sequence;
            connection.sequence += 1;
            var msgText = JSON.stringify(obj);

            var timer = setTimeout( function timedOut() {
                callback('Timed out waiting for fcserver to respond to this message: ' + msgText);
                delete connection.pending[obj.sequence];
            }, timeout);

            connection.pending[obj.sequence] = function (obj) {
                callback(null, obj);
                delete connection.pending[obj.sequence];
                clearTimeout(timer);
            }

            connection.socket.send(JSON.stringify(obj));
        };

        connection.socket.on('message', function message(data, err) {
            var obj = JSON.parse(data);
            connection.pending[obj.sequence](obj);
        });

        connection.socket.on('open', function open() {
            connection.message( {type: 'list_connected_devices'} , function (err, obj) {
                if (err) return callback(err);

                // Sort device list by serial number, for a stable ordering
                connection.devices = obj.devices;
                connection.devices.sort(function (a, b) {
                    return a.serial.localeCompare(b.serial);
                });

                for (var i = 0; i < connection.devices.length; i++) {
                    console.log("Found Fadecandy device " + connection.devices[i].serial)
                }

                callback(null, connection);
            });
        });

        connection.rawPixels = function (device, rgb, callback) {
            // Disable interpolation, dithering, and gamma correction.
            // Bypasses the mapping layer, and sends RGB values straight to a single FC device.

            // Convert to raw array if necessary, so JSON serialize works
            if (rgb.constructor != Array) {
                rgb = Array.prototype.slice.call(rgb);
            }

            async.series([
                async.apply(connection.message, {
                    type: 'device_options',
                    device: device,
                    options: {
                        led: null,
                        dither: false,
                        interpolate: false
                    },
                }),
                async.apply(connection.message, {
                    type: 'device_color_correction',
                    device: device,
                    color: {
                        gamma: 1.0,
                        whitepoint: [1.0, 1.0, 1.0]
                    },
                }),
                async.apply(connection.message, {
                    type: 'device_pixels',
                    device: device,
                    pixels: rgb,
                }),
            ], callback);
        }

        connection.lightsOff = function (callback) {
            // Turn all lights off, on all devices

            async.map(connection.devices, function (thisDevice, callback) {
                var array = new Uint8Array(fadecandy.LEDS_PER_DEVICE * 3);
                connection.rawPixels(thisDevice, array, callback);
            }, callback);
        }

        connection.singleLight = function (device, index, callback) {
            // Turn a single light on at full brightness, and all others off

            async.map(connection.devices, function (thisDevice, callback) {
                var array = new Uint8Array(fadecandy.LEDS_PER_DEVICE * 3);
                if (device.serial == thisDevice.serial) {
                    for (var i = 0; i < 3; i++) {
                        array[3*index + i] = 255;
                    }
                }
                connection.rawPixels(thisDevice, array, callback);
            }, callback);
        }
    }

    module.exports = fadecandy;

}());


text:
set -e

NAMESPACE=${NAMESPACE:-kubeflow}

function clean_up() {
  set +e

  echo "Stopping background jobs..."
  # jobs -l
  kill -15 %1
  kill -15 %2
  kill -15 %3
}
trap clean_up EXIT SIGINT SIGTERM

echo "Preparing dev env for KFP frontend"

echo "Compiling node server..."
pushd server
npm run build
popd

# Frontend dev server proxies api requests to node server listening to
# localhost:3001 (configured in frontend/package.json -> proxy field).
#
# Node server proxies requests further to localhost:3002 or localhost:9090
# based on what request it is.
#
# localhost:3002 port forwards to ml_pipeline api server pod.
# localhost:9090 port forwards to metadata_envoy pod.

echo "Starting to port forward backend apis..."
kubectl port-forward -n $NAMESPACE svc/metadata-envoy-service 9090:9090 &
kubectl port-forward -n $NAMESPACE svc/ml-pipeline 3002:8888 &
kubectl port-forward -n $NAMESPACE svc/minio-service 9000:9000 &
export MINIO_HOST=localhost
export MINIO_NAMESPACE=
if [ "$1" == "--inspect" ]; then
  ML_PIPELINE_SERVICE_PORT=3002 npm run mock:server:inspect 3001
else
  ML_PIPELINE_SERVICE_PORT=3002 npm run mock:server 3001
fi

redpajama_set_name: RedPajamaGithub


text:
/***************
 * PART FIVE - Finishing touches
 ***************/

/* NOTES TO REMEMBER
 * Could add
 * - hitboxes to all objects to make collision better
 * - levels
 * - bosses
 * - explosions / particles
 * - parallax background
 * - vectors for movement
 * - lirbraries! http://www.createjs.com/#!/CreateJS
 */

/* RESOURCES
 * http://www.w3schools.com/html5/html5_ref_av_dom.asp
 * http://www.superflashbros.net/as3sfxr/
 */

/**
 * Initialize the Game and start it.
 */
var game = new Game();

function init() {
	game.init();
}

/**
 * Define an object to hold all our images for the game so images
 * are only ever created once. This type of object is known as a
 * singleton.
 */
var imageRepository = new function() {
	// Define images
	this.background = new Image();
	this.spaceship = new Image();
	this.bullet = new Image();
	this.enemy = new Image();
	this.enemyBullet = new Image();

	// Ensure all images have loaded before starting the game
	var numImages = 5;
	var numLoaded = 0;
	function imageLoaded() {
		numLoaded++;
		if (numLoaded === numImages) {
			window.init();
		}
	}
	this.background.onload = function() {
		imageLoaded();
	}
	this.spaceship.onload = function() {
		imageLoaded();
	}
	this.bullet.onload = function() {
		imageLoaded();
	}
	this.enemy.onload = function() {
		imageLoaded();
	}
	this.enemyBullet.onload = function() {
		imageLoaded();
	}

	// Set images src
	this.background.src = "imgs/bg.png";
	this.spaceship.src = "imgs/ship.png";
	this.bullet.src = "imgs/bullet.png";
	this.enemy.src = "imgs/enemy.png";
	this.enemyBullet.src = "imgs/bullet_enemy.png";
}

/**
 * Creates the Drawable object which will be the base class for
 * all drawable objects in the game. Sets up defualt variables
 * that all child objects will inherit, as well as the defualt
 * functions.
 */
function Drawable() {
	this.init = function(x, y, width, height) {
		// Defualt variables
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	this.speed = 0;
	this.canvasWidth = 0;
	this.canvasHeight = 0;
	this.collidableWith = "";
	this.isColliding = false;
	this.type = "";

	// Define abstract function to be implemented in child objects
	this.draw = function() {
	};
	this.move = function() {
	};
	this.isCollidableWith = function(object) {
		return (this.collidableWith === object.type);
	};
}

/**
 * Creates the Background object which will become a child of
 * the Drawable object. The background is drawn on the "background"
 * canvas and creates the illusion of moving by panning the image.
 */
function Background() {
	this.speed = 1; // Redefine speed of the background for panning

	// Implement abstract function
	this.draw = function() {
		// Pan background
		this.y += this.speed;
		//this.context.clearRect(0,0, this.canvasWidth, this.canvasHeight);
		this.context.drawImage(imageRepository.background, this.x, this.y);

		// Draw another image at the top edge of the first image
		this.context.drawImage(imageRepository.background, this.x, this.y - this.canvasHeight);

		// If the image scrolled off the screen, reset
		if (this.y >= this.canvasHeight)
			this.y = 0;
	};
}
// Set Background to inherit properties from Drawable
Background.prototype = new Drawable();

/**
 * Creates the Bullet object which the ship fires. The bullets are
 * drawn on the "main" canvas.
 */
function Bullet(object) {
	this.alive = false; // Is true if the bullet is currently in use
	var self = object;
	/*
	 * Sets the bullet values
	 */
	this.spawn = function(x, y, speed) {
		this.x = x;
		this.y = y;
		this.speed = speed;
		this.alive = true;
	};

	/*
	 * Uses a "drity rectangle" to erase the bullet and moves it.
	 * Returns true if the bullet moved of the screen, indicating that
	 * the bullet is ready to be cleared by the pool, otherwise draws
	 * the bullet.
	 */
	this.draw = function() {
		this.context.clearRect(this.x-1, this.y-1, this.width+2, this.height+2);
		this.y -= this.speed;

		if (this.isColliding) {
			return true;
		}
		else if (self === "bullet" && this.y <= 0 - this.height) {
			return true;
		}
		else if (self === "enemyBullet" && this.y >= this.canvasHeight) {
			return true;
		}
		else {
			if (self === "bullet") {
				this.context.drawImage(imageRepository.bullet, this.x, this.y);
			}
			else if (self === "enemyBullet") {
				this.context.drawImage(imageRepository.enemyBullet, this.x, this.y);
			}

			return false;
		}
	};

	/*
	 * Resets the bullet values
	 */
	this.clear = function() {
		this.x = 0;
		this.y = 0;
		this.speed = 0;
		this.alive = false;
		this.isColliding = false;
	};
}
Bullet.prototype = new Drawable();

/**
 * QuadTree object.
 *
 * The quadrant indexes are numbered as below:
 *     |
 *  1  |  0
 * ----+----
 *  2  |  3
 *     |
 */
function QuadTree(boundBox, lvl) {
	var maxObjects = 10;
	this.bounds = boundBox || {
		x: 0,
		y: 0,
		width: 0,
		height: 0
	};
	var objects = [];
	this.nodes = [];
	var level = lvl || 0;
	var maxLevels = 5;

	/*
	 * Clears the quadTree and all nodes of objects
	 */
	this.clear = function() {
		objects = [];

		for (var i = 0; i < this.nodes.length; i++) {
			this.nodes[i].clear();
		}

		this.nodes = [];
	};

	/*
	 * Get all objects in the quadTree
	 */
	this.getAllObjects = function(returnedObjects) {
		for (var i = 0; i < this.nodes.length; i++) {
			this.nodes[i].getAllObjects(returnedObjects);
		}

		for (var i = 0, len = objects.length; i < len; i++) {
			returnedObjects.push(objects[i]);
		}

		return returnedObjects;
	};

	/*
	 * Return all objects that the object could collide with
	 */
	this.findObjects = function(returnedObjects, obj) {
		if (typeof obj === "undefined") {
			console.log("UNDEFINED OBJECT");
			return;
		}

		var index = this.getIndex(obj);
		if (index != -1 && this.nodes.length) {
			this.nodes[index].findObjects(returnedObjects, obj);
		}

		for (var i = 0, len = objects.length; i < len; i++) {
			returnedObjects.push(objects[i]);
		}

		return returnedObjects;
	};

	/*
	 * Insert the object into the quadTree. If the tree
	 * excedes the capacity, it will split and add all
	 * objects to their corresponding nodes.
	 */
	this.insert = function(obj) {
		if (typeof obj === "undefined") {
			return;
		}

		if (obj instanceof Array) {
			for (var i = 0, len = obj.length; i < len; i++) {
				this.insert(obj[i]);
			}

			return;
		}

		if (this.nodes.length) {
			var index = this.getIndex(obj);
			// Only add the object to a subnode if it can fit completely
			// within one
			if (index != -1) {
				this.nodes[index].insert(obj);

				return;
			}
		}

		objects.push(obj);

		// Prevent infinite splitting
		if (objects.length > maxObjects && level < maxLevels) {
			if (this.nodes[0] == null) {
				this.split();
			}

			var i = 0;
			while (i < objects.length) {

				var index = this.getIndex(objects[i]);
				if (index != -1) {
					this.nodes[index].insert((objects.splice(i,1))[0]);
				}
				else {
					i++;
				}
			}
		}
	};

	/*
	 * Determine which node the object belongs to. -1 means
	 * object cannot completely fit within a node and is part
	 * of the current node
	 */
	this.getIndex = function(obj) {

		var index = -1;
		var verticalMidpoint = this.bounds.x + this.bounds.width / 2;
		var horizontalMidpoint = this.bounds.y + this.bounds.height / 2;

		// Object can fit completely within the top quadrant
		var topQuadrant = (obj.y < horizontalMidpoint && obj.y + obj.height < horizontalMidpoint);
		// Object can fit completely within the bottom quandrant
		var bottomQuadrant = (obj.y > horizontalMidpoint);

		// Object can fit completely within the left quadrants
		if (obj.x < verticalMidpoint &&
				obj.x + obj.width < verticalMidpoint) {
			if (topQuadrant) {
				index = 1;
			}
			else if (bottomQuadrant) {
				index = 2;
			}
		}
		// Object can fix completely within the right quandrants
		else if (obj.x > verticalMidpoint) {
			if (topQuadrant) {
				index = 0;
			}
			else if (bottomQuadrant) {
				index = 3;
			}
		}

		return index;
	};

	/*
	 * Splits the node into 4 subnodes
	 */
	this.split = function() {
		// Bitwise or [html5rocks]
		var subWidth = (this.bounds.width / 2) | 0;
		var subHeight = (this.bounds.height / 2) | 0;

		this.nodes[0] = new QuadTree({
			x: this.bounds.x + subWidth,
			y: this.bounds.y,
			width: subWidth,
			height: subHeight
		}, level+1);
		this.nodes[1] = new QuadTree({
			x: this.bounds.x,
			y: this.bounds.y,
			width: subWidth,
			height: subHeight
		}, level+1);
		this.nodes[2] = new QuadTree({
			x: this.bounds.x,
			y: this.bounds.y + subHeight,
			width: subWidth,
			height: subHeight
		}, level+1);
		this.nodes[3] = new QuadTree({
			x: this.bounds.x + subWidth,
			y: this.bounds.y + subHeight,
			width: subWidth,
			height: subHeight
		}, level+1);
	};
}

/**
 * Custom Pool object. Holds Bullet objects to be managed to prevent
 * garbage collection.
 * The pool works as follows:
 * - When the pool is initialized, it popoulates an array with
 *   Bullet objects.
 * - When the pool needs to create a new object for use, it looks at
 *   the last item in the array and checks to see if it is currently
 *   in use or not. If it is in use, the pool is full. If it is
 *   not in use, the pool "spawns" the last item in the array and
 *   then pops it from the end and pushed it back onto the front of
 *   the array. This makes the pool have free objects on the back
 *   and used objects in the front.
 * - When the pool animates its objects, it checks to see if the
 *   object is in use (no need to draw unused objects) and if it is,
 *   draws it. If the draw() function returns true, the object is
 *   ready to be cleaned so it "clears" the object and uses the
 *   array function splice() to remove the item from the array and
 *   pushes it to the back.
 * Doing this makes creating/destroying objects in the pool
 * constant.
 */
function Pool(maxSize) {
	var size = maxSize; // Max bullets allowed in the pool
	var pool = [];

	this.getPool = function() {
		var obj = [];
		for (var i = 0; i < size; i++) {
			if (pool[i].alive) {
				obj.push(pool[i]);
			}
		}
		return obj;
	}

	/*
	 * Populates the pool array with the given object
	 */
	this.init = function(object) {
		if (object == "bullet") {
			for (var i = 0; i < size; i++) {
				// Initalize the object
				var bullet = new Bullet("bullet");
				bullet.init(0,0, imageRepository.bullet.width,
										imageRepository.bullet.height);
				bullet.collidableWith = "enemy";
				bullet.type = "bullet";
				pool[i] = bullet;
			}
		}
		else if (object == "enemy") {
			for (var i = 0; i < size; i++) {
				var enemy = new Enemy();
				enemy.init(0,0, imageRepository.enemy.width,
									 imageRepository.enemy.height);
				pool[i] = enemy;
			}
		}
		else if (object == "enemyBullet") {
			for (var i = 0; i < size; i++) {
				var bullet = new Bullet("enemyBullet");
				bullet.init(0,0, imageRepository.enemyBullet.width,
										imageRepository.enemyBullet.height);
				bullet.collidableWith = "ship";
				bullet.type = "enemyBullet";
				pool[i] = bullet;
			}
		}
	};

	/*
	 * Grabs the last item in the list and initializes it and
	 * pushes it to the front of the array.
	 */
	this.get = function(x, y, speed) {
		if(!pool[size - 1].alive) {
			pool[size - 1].spawn(x, y, speed);
			pool.unshift(pool.pop());
		}
	};

	/*
	 * Used for the ship to be able to get two bullets at once. If
	 * only the get() function is used twice, the ship is able to
	 * fire and only have 1 bullet spawn instead of 2.
	 */
	this.getTwo = function(x1, y1, speed1, x2, y2, speed2) {
		if(!pool[size - 1].alive && !pool[size - 2].alive) {
			this.get(x1, y1, speed1);
			this.get(x2, y2, speed2);
		}
	};

	/*
	 * Draws any in use Bullets. If a bullet goes off the screen,
	 * clears it and pushes it to the front of the array.
	 */
	this.animate = function() {
		for (var i = 0; i < size; i++) {
			// Only draw until we find a bullet that is not alive
			if (pool[i].alive) {
				if (pool[i].draw()) {
					pool[i].clear();
					pool.push((pool.splice(i,1))[0]);
				}
			}
			else
				break;
		}
	};
}

/**
 * Create the Ship object that the player controls. The ship is
 * drawn on the "ship" canvas and uses dirty rectangles to move
 * around the screen.
 */
function Ship() {
	this.speed = 3;
	this.bulletPool = new Pool(30);
	var fireRate = 15;
	var counter = 0;
	this.collidableWith = "enemyBullet";
	this.type = "ship";

	this.init = function(x, y, width, height) {
		// Defualt variables
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.alive = true;
		this.isColliding = false;
		this.bulletPool.init("bullet");
	}

	this.draw = function() {
		this.context.drawImage(imageRepository.spaceship, this.x, this.y);
	};
	this.move = function() {
		counter++;
		// Determine if the action is move action

		if (KEY_STATUS.left || KEY_STATUS.right ||
		KEY_STATUS.down || KEY_STATUS.up) {

			// The ship moved, so erase it's current image so it can
			// be redrawn in it's new location
			this.context.clearRect(this.x, this.y, this.width, this.height);

			// Update x and y according to the direction to move and
			// redraw the ship. Change the else if's to if statements
			// to have diagonal movement.
			if (KEY_STATUS.left) {

				this.x -= this.speed
				if (this.x <= 0) // Kep player within the screen
					this.x = 0;
			} else if (KEY_STATUS.right) {

				this.x += this.speed
				if (this.x >= this.canvasWidth - this.width)
					this.x = this.canvasWidth - this.width;
			} else if (KEY_STATUS.up) {

				this.y -= this.speed
				if (this.y <= this.canvasHeight/4*3)
					this.y = this.canvasHeight/4*3;
			} else if (KEY_STATUS.down) {

				this.y += this.speed
				if (this.y >= this.canvasHeight - this.height)
					this.y = this.canvasHeight - this.height;
			}
		}

		// Redraw the ship
		if (!this.isColliding) {
			this.draw();
		}
		else {
			this.alive = false;
			game.gameOver();
		}

		if (KEY_STATUS.space && counter >= fireRate && !this.isColliding) {
			this.fire();
			counter = 0;
		}
	};

	/*
	 * Fires two bullets
	 */
	this.fire = function() {
		this.bulletPool.getTwo(this.x+6, this.y, 3,
		                       this.x+33, this.y, 3);
		game.laser.get();
	};
}
Ship.prototype = new Drawable();

/**
 * Create the Enemy ship object.
 */
function Enemy() {
	var percentFire = .01;
	var chance = 0;
	this.alive = false;
	this.collidableWith = "bullet";
	this.type = "enemy";

	/*
	 * Sets the Enemy values
	 */
	this.spawn = function(x, y, speed) {
		this.x = x;
		this.y = y;
		this.speed = speed;
		this.speedX = 0;
		this.speedY = speed;
		this.alive = true;
		this.leftEdge = this.x - 90;
		this.rightEdge = this.x + 90;
		this.bottomEdge = this.y + 140;
	};

	/*
	 * Move the enemy
	 */
	this.draw = function() {
		this.context.clearRect(this.x-1, this.y, this.width+1, this.height);
		this.x += this.speedX;
		this.y += this.speedY;
		if (this.x <= this.leftEdge) {
			this.speedX = this.speed;
		}
		else if (this.x >= this.rightEdge + this.width) {
			this.speedX = -this.speed;
		}
		else if (this.y >= this.bottomEdge) {
			this.speed = 1.5;
			this.speedY = 0;
			this.y -= 5;
			this.speedX = -this.speed;
		}

		if (!this.isColliding) {
			this.context.drawImage(imageRepository.enemy, this.x, this.y);

			// Enemy has a chance to shoot every movement
			chance = Math.floor(Math.random()*101);
			if (chance/100 < percentFire) {
				this.fire();
			}

			return false;
		}
		else {
			game.playerScore += 10;
			game.explosion.get();
			return true;
		}
	};

	/*
	 * Fires a bullet
	 */
	this.fire = function() {
		game.enemyBulletPool.get(this.x+this.width/2, this.y+this.height, -2.5);
	};

	/*
	 * Resets the enemy values
	 */
	this.clear = function() {
		this.x = 0;
		this.y = 0;
		this.speed = 0;
		this.speedX = 0;
		this.speedY = 0;
		this.alive = false;
		this.isColliding = false;
	};
}
Enemy.prototype = new Drawable();

 /**
 * Creates the Game object which will hold all objects and data for
 * the game.
 */
function Game() {
	/*
	 * Gets canvas information and context and sets up all game
	 * objects.
	 * Returns true if the canvas is supported and false if it
	 * is not. This is to stop the animation script from constantly
	 * running on browsers that do not support the canvas.
	 */
	this.init = function() {
		// Get the canvas elements
		this.bgCanvas = document.getElementById('background');
		this.shipCanvas = document.getElementById('ship');
		this.mainCanvas = document.getElementById('main');

		// Test to see if canvas is supported. Only need to
		// check one canvas
		if (this.bgCanvas.getContext) {
			this.bgContext = this.bgCanvas.getContext('2d');
			this.shipContext = this.shipCanvas.getContext('2d');
			this.mainContext = this.mainCanvas.getContext('2d');

			// Initialize objects to contain their context and canvas
			// information
			Background.prototype.context = this.bgContext;
			Background.prototype.canvasWidth = this.bgCanvas.width;
			Background.prototype.canvasHeight = this.bgCanvas.height;

			Ship.prototype.context = this.shipContext;
			Ship.prototype.canvasWidth = this.shipCanvas.width;
			Ship.prototype.canvasHeight = this.shipCanvas.height;

			Bullet.prototype.context = this.mainContext;
			Bullet.prototype.canvasWidth = this.mainCanvas.width;
			Bullet.prototype.canvasHeight = this.mainCanvas.height;

			Enemy.prototype.context = this.mainContext;
			Enemy.prototype.canvasWidth = this.mainCanvas.width;
			Enemy.prototype.canvasHeight = this.mainCanvas.height;

			// Initialize the background object
			this.background = new Background();
			this.background.init(0,0); // Set draw point to 0,0

			// Initialize the ship object
			this.ship = new Ship();
			// Set the ship to start near the bottom middle of the canvas
			this.shipStartX = this.shipCanvas.width/2 - imageRepository.spaceship.width;
			this.shipStartY = this.shipCanvas.height/4*3 + imageRepository.spaceship.height*2;
			this.ship.init(this.shipStartX, this.shipStartY,
			               imageRepository.spaceship.width, imageRepository.spaceship.height);

			// Initialize the enemy pool object
			this.enemyPool = new Pool(30);
			this.enemyPool.init("enemy");
			this.spawnWave();

			this.enemyBulletPool = new Pool(50);
			this.enemyBulletPool.init("enemyBullet");

			// Start QuadTree
			this.quadTree = new QuadTree({x:0,y:0,width:this.mainCanvas.width,height:this.mainCanvas.height});

			this.playerScore = 0;

			// Audio files
			this.laser = new SoundPool(10);
			this.laser.init("laser");

			this.explosion = new SoundPool(20);
			this.explosion.init("explosion");

			this.backgroundAudio = new Audio("sounds/kick_shock.wav");
			this.backgroundAudio.loop = true;
			this.backgroundAudio.volume = .25;
			this.backgroundAudio.load();

			this.gameOverAudio = new Audio("sounds/game_over.wav");
			this.gameOverAudio.loop = true;
			this.gameOverAudio.volume = .25;
			this.gameOverAudio.load();

			this.checkAudio = window.setInterval(function(){checkReadyState()},1000);
		}
	};

	// Spawn a new wave of enemies
	this.spawnWave = function() {
		var height = imageRepository.enemy.height;
		var width = imageRepository.enemy.width;
		var x = 100;
		var y = -height;
		var spacer = y * 1.5;
		for (var i = 1; i <= 18; i++) {
			this.enemyPool.get(x,y,2);
			x += width + 25;
			if (i % 6 == 0) {
				x = 100;
				y += spacer
			}
		}
	}

	// Start the animation loop
	this.start = function() {
		this.ship.draw();
		this.backgroundAudio.play();
		animate();
	};

	// Restart the game
	this.restart = function() {
		this.gameOverAudio.pause();

		document.getElementById('game-over').style.display = "none";
		this.bgContext.clearRect(0, 0, this.bgCanvas.width, this.bgCanvas.height);
		this.shipContext.clearRect(0, 0, this.shipCanvas.width, this.shipCanvas.height);
		this.mainContext.clearRect(0, 0, this.mainCanvas.width, this.mainCanvas.height);

		this.quadTree.clear();

		this.background.init(0,0);
		this.ship.init(this.shipStartX, this.shipStartY,
		               imageRepository.spaceship.width, imageRepository.spaceship.height);

		this.enemyPool.init("enemy");
		this.spawnWave();
		this.enemyBulletPool.init("enemyBullet");

		this.playerScore = 0;

		this.backgroundAudio.currentTime = 0;
		this.backgroundAudio.play();

		this.start();
	};

	// Game over
	this.gameOver = function() {
		this.backgroundAudio.pause();
		this.gameOverAudio.currentTime = 0;
		this.gameOverAudio.play();
		document.getElementById('game-over').style.display = "block";
	};
}

/**
 * Ensure the game sound has loaded before starting the game
 */
function checkReadyState() {
	if (game.gameOverAudio.readyState === 4 && game.backgroundAudio.readyState === 4) {
		window.clearInterval(game.checkAudio);
		document.getElementById('loading').style.display = "none";
		game.start();
	}
}

/**
 * A sound pool to use for the sound effects
 */
function SoundPool(maxSize) {
	var size = maxSize; // Max bullets allowed in the pool
	var pool = [];
	this.pool = pool;
	var currSound = 0;

	/*
	 * Populates the pool array with the given object
	 */
	this.init = function(object) {
		if (object == "laser") {
			for (var i = 0; i < size; i++) {
				// Initalize the object
				laser = new Audio("sounds/laser.wav");
				laser.volume = .12;
				laser.load();
				pool[i] = laser;
			}
		}
		else if (object == "explosion") {
			for (var i = 0; i < size; i++) {
				var explosion = new Audio("sounds/explosion.wav");
				explosion.volume = .1;
				explosion.load();
				pool[i] = explosion;
			}
		}
	};

	/*
	 * Plays a sound
	 */
	this.get = function() {
		if(pool[currSound].currentTime == 0 || pool[currSound].ended) {
			pool[currSound].play();
		}
		currSound = (currSound + 1) % size;
	};
}

/**
 * The animation loop. Calls the requestAnimationFrame shim to
 * optimize the game loop and draws all game objects. This
 * function must be a gobal function and cannot be within an
 * object.
 */
function animate() {
	document.getElementById('score').innerHTML = game.playerScore;

	// Insert objects into quadtree
	game.quadTree.clear();
	game.quadTree.insert(game.ship);
	game.quadTree.insert(game.ship.bulletPool.getPool());
	game.quadTree.insert(game.enemyPool.getPool());
	game.quadTree.insert(game.enemyBulletPool.getPool());

	detectCollision();

	// No more enemies
	if (game.enemyPool.getPool().length === 0) {
		game.spawnWave();
	}

	// Animate game objects
	if (game.ship.alive) {
		requestAnimFrame( animate );

		game.background.draw();
		game.ship.move();
		game.ship.bulletPool.animate();
		game.enemyPool.animate();
		game.enemyBulletPool.animate();
	}
}

function detectCollision() {
	var objects = [];
	game.quadTree.getAllObjects(objects);

	for (var x = 0, len = objects.length; x < len; x++) {
		game.quadTree.findObjects(obj = [], objects[x]);

		for (y = 0, length = obj.length; y < length; y++) {

			// DETECT COLLISION ALGORITHM
			if (objects[x].collidableWith === obj[y].type &&
				(objects[x].x < obj[y].x + obj[y].width &&
			     objects[x].x + objects[x].width > obj[y].x &&
				 objects[x].y < obj[y].y + obj[y].height &&
				 objects[x].y + objects[x].height > obj[y].y)) {
				objects[x].isColliding = true;
				obj[y].isColliding = true;
			}
		}
	}
};

// The keycodes that will be mapped when a user presses a button.
// Original code by Doug McInnes
KEY_CODES = {
  32: 'space',
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
}

// Creates the array to hold the KEY_CODES and sets all their values
// to true. Checking true/flase is the quickest way to check status
// of a key press and which one was pressed when determining
// when to move and which direction.
KEY_STATUS = {};
for (code in KEY_CODES) {
  KEY_STATUS[KEY_CODES[code]] = false;
}
/**
 * Sets up the document to listen to onkeydown events (fired when
 * any key on the keyboard is pressed down). When a key is pressed,
 * it sets the appropriate direction to true to let us know which
 * key it was.
 */

document.onkeydown = function(e) {
	console.log(KEY_CODES[e.keyCode]);
	// Firefox and opera use charCode instead of keyCode to
	// return which key was pressed.
console.log(KEY_CODES[e.keyCode]);
	var keyCode = (e.keyCode) ? e.keyCode : e.charCode;

  if (KEY_CODES[keyCode]) {
		e.preventDefault();
    KEY_STATUS[KEY_CODES[keyCode]] = true;
  }
}
/**
 * Sets up the document to listen to ownkeyup events (fired when
 * any key on the keyboard is released). When a key is released,
 * it sets teh appropriate direction to false to let us know which
 * key it was.
 */
document.onkeyup = function(e) {
  var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
  if (KEY_CODES[keyCode]) {
    e.preventDefault();
    KEY_STATUS[KEY_CODES[keyCode]] = false;
  }
}

/**
 * requestAnim shim layer by Paul Irish
 * Finds the first API that works to optimize the animation loop,
 * otherwise defaults to setTimeout().
 */
window.requestAnimFrame = (function(){
	return  window.requestAnimationFrame       ||
			window.webkitRequestAnimationFrame ||
			window.mozRequestAnimationFrame    ||
			window.oRequestAnimationFrame      ||
			window.msRequestAnimationFrame     ||
			function(/* function */ callback, /* DOMElement */ element){
				window.setTimeout(callback, 1000 / 60);
			};
})();


text:
:- module(markdown,
	  [ markdown_dom/2		% +MarkDown, -DOM
	  ]).
:- use_module(library(sgml)).
:- use_module(library(process)).
:- use_module(library(error)).

/** <module> Parse markdown documents into a DOM
*/

:- create_prolog_flag(markdown_program, markdown, []).

%%	markdown_dom(+Input, -DOM) is det.
%
%	Process markdown input into an HTML  DOM structure compatible to
%	load_structure/3     and     html//1     as      provided     by
%	library(http/html_write).
%
%	@param	Input is either a term stream(+Stream) or the name of a
%		file.

markdown_dom(stream(Stream), DOM) :- !,
	must_be(stream, Stream),
	current_prolog_flag(markdown_program, Prog),
	process_create(path(Prog), [],
		       [ stdin(pipe(In)),
			 stdout(pipe(Out)),
			 process(PID)
		       ]),
	thread_create(( copy_stream_data(Stream, In),
			close(In)
		      ), _, [detached(true)]),
	load_structure(Out, DOM, [dialect(xml)]),
	process_wait(PID, _).
markdown_dom(File, DOM) :-
	current_prolog_flag(markdown_program, Prog),
	process_create(path(Prog), [file(File)],
		       [ stdout(pipe(Out)),
			 process(PID)
		       ]),
	load_structure(Out, DOM, [dialect(xml)]),
	process_wait(PID, _).


text:
package cn.xdean.jex.lang.function;

import cn.xdean.jex.lang.collection.Wrapper;
import cn.xdean.jex.lang.function.type.ActionE0;
import cn.xdean.jex.lang.function.type.ActionE1;
import cn.xdean.jex.lang.function.type.FuncE0;

import java.util.function.*;

public class FunctionAdapter {

  public static <T> Supplier<T> supplier(T t) {
    return () -> t;
  }

  public static <T> UnaryOperator<T> function(Consumer<T> c) {
    return t -> {
      c.accept(t);
      return t;
    };
  }

  public static <T> Consumer<T> consumer(Runnable r) {
    return t -> r.run();
  }

  public static <A, B> BiConsumer<A, B> consumeFirst(Consumer<A> c) {
    return (a, b) -> c.accept(a);
  }

  public static <A, B> BiConsumer<A, B> consumeSecond(Consumer<B> c) {
    return (a, b) -> c.accept(b);
  }

  public static <A, B> BiFunction<A, B, A> functionFirst(BiConsumer<A, B> bc) {
    return (a, b) -> {
      bc.accept(a, b);
      return a;
    };
  }

  public static <A, B> BiFunction<A, B, B> functionSecond(BiConsumer<A, B> bc) {
    return (a, b) -> {
      bc.accept(a, b);
      return b;
    };
  }

  /**
   * @param s
   * @param c
   * @return the supplier's product
   */
  public static <T> T supplierToRunnable(Supplier<T> s, Consumer<Runnable> c) {
    Wrapper<T> w = new Wrapper<>(null);
    c.accept(() -> w.set(s.get()));
    return w.get();
  }

  public static <T, E extends Exception, EE extends Exception> T
      supplierToRunnable(FuncE0<T, E> s, ActionE1<ActionE0<E>, EE> c) throws EE {
    Wrapper<T> w = new Wrapper<>(null);
    c.call(() -> w.set(s.call()));
    return w.get();
  }
}


text:
<?php

/**
 * User: pliebig
 * Date: 10.03.14
 * Time: 15:15
 * E-Mail: p.liebig@me.com
 */

/**
 * export helper - contains only helper function for export
 *
 * @author      Shopgate GmbH, 35510 Butzbach, DE
 * @package     Shopgate_Framework
 */
class Shopgate_Framework_Helper_Export extends Mage_Core_Helper_Abstract
{
    /**
     * if images have a height and/or width lower than this, the image will not be exported
     * as long as shopgate/export/export_lowres_image is 0
     */
    const IMAGE_EXPORT_MINRESOLUTION  = 150;
    /**
     * @var null
     */
    protected $_weightFactor = null;

    /**
     * @param float $price
     *
     * @return float
     */
    public function convertPriceCurrency($price)
    {
        $baseCurrencyCode    = Mage::app()->getStore()->getBaseCurrencyCode();
        $currentCurrencyCode = Mage::helper('shopgate')->getConfig()->getCurrency();
        $convertedPrice      = Mage::helper('directory')->currencyConvert(
                                   $price,
                                   $baseCurrencyCode,
                                   $currentCurrencyCode
        );

        return $convertedPrice;
    }

    /**
     * Get the price for catalog rules
     *
     * @param Mage_Catalog_Model_Product $product
     *
     * @return float
     */
    public function calcProductPriceRule(Mage_Catalog_Model_Product $product)
    {
        $rulePrice = null;
        if (Mage::helper("shopgate/config")->getIsMagentoVersionLower15()) {
            $pId       = $product->getId();
            $storeId   = $product->getStoreId();
            $date      = Mage::app()->getLocale()->storeTimeStamp($storeId);
            $wId       = Mage::app()->getStore($storeId)->getWebsiteId();
            $rulePrice = Mage::getResourceModel('catalogrule/rule')
                             ->getRulePrice($date, $wId, 0, $pId);

        } else {
            $rulePrice = Mage::getModel("catalogrule/rule")->calcProductPriceRule($product, $product->getPrice());
        }

        return $rulePrice;
    }

    /**
     * Helper Function to get ConvertFactor for Weight conversion to gram
     *
     * @return float|int
     */
    public function getWeightFactor()
    {
        if (!$this->_weightFactor) {
            $this->_weightFactor = 1000;
            $lbCountry           = array("US", "GB");
            $country             = Mage::getStoreConfig(
                                       "general/country/default",
                                       Mage::helper('shopgate')->getConfig()->getStoreViewId()
            );
            $weightUnit          = Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_WEIGHT_UNIT);

            if ($weightUnit == 0) {
                if (in_array($country, $lbCountry)) {
                    $this->_weightFactor = Shopgate_Framework_Model_Shopgate_Plugin::CONVERT_POUNDS_TO_GRAM_FACTOR;
                }
            } else {
                switch ($weightUnit) {
                    case Shopgate_Framework_Model_System_Config_Source_Weight_Units::WEIGHT_UNIT_KG:
                        $this->_weightFactor = 1000;
                        break;
                    case Shopgate_Framework_Model_System_Config_Source_Weight_Units::WEIGHT_UNIT_GRAMM:
                        $this->_weightFactor = 1;
                        break;
                    case Shopgate_Framework_Model_System_Config_Source_Weight_Units::WEIGHT_UNIT_POUND:
                        $this->_weightFactor = Shopgate_Framework_Model_Shopgate_Plugin::CONVERT_POUNDS_TO_GRAM_FACTOR;
                        break;
                    case Shopgate_Framework_Model_System_Config_Source_Weight_Units::WEIGHT_UNIT_OUNCE:
                        $this->_weightFactor = Shopgate_Framework_Model_Shopgate_Plugin::CONVERT_OUNCES_TO_GRAM_FACTOR;
                        break;
                }
            }
        }

        return $this->_weightFactor;
    }

    /**
     * calculates price for product options base on product and magento settings
     *
     * @param Mage_Catalog_Model_Product $product
     * @param float                      $price
     *
     * @return float
     */
    public function getOptionPrice($product, $price)
    {
        $priceInclTax = Mage::helper('tax')->getPrice($product, $price, true);
        $priceExclTax = Mage::helper('tax')->getPrice($product, $price);

        $valuePrice = (Mage::helper('tax')->displayPriceIncludingTax())
            ? $priceInclTax
            : $priceExclTax;

        return $valuePrice;
    }

    /**
     * Returns whether product has custom option of type file or not.
     * (only if option is required)
     *
     * @param Mage_Catalog_Model_Product $product
     *
     * @return bool
     */
    public function productHasRequiredFileOption($product)
    {
        $options = $product->getOptions();
        foreach ($options as $option) {
            /** @var $option Mage_Catalog_Model_Product_Option */
            if ($option->getType() === Mage_Catalog_Model_Product_Option::OPTION_TYPE_FILE && $option->getIsRequire()) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param Mage_Catalog_Model_Product $product
     * @param int                        $parentCategory
     *
     * @return string
     */
    public function getCategoryNumberForGroupProduct(Mage_Catalog_Model_Product $product, $parentCategory)
    {
        return "gp" . $product->getId() . "_" . $parentCategory;
    }

    /**
     * parse url
     *
     * @param $url
     *
     * @return mixed
     */
    public function parseUrl($url)
    {
        if (Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_DEBUG_HTUSER)
            && Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_DEBUG_HTPASS)
        ) {

            $replacement = "http://";
            $replacement .= urlencode(
                Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_DEBUG_HTUSER)
            );
            $replacement .= ":";
            $replacement .= urlencode(
                Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_DEBUG_HTPASS)
            );
            $replacement .= "@";

            $url = preg_replace("/^http:\/\//i", $replacement, $url, 1);
        }

        return $url;
    }

    /**
     * return images for a product according to settings
     *
     * @param Mage_Catalog_Model_Product $product
     *
     * @return mixed
     */
    public function getMediaImages($product)
    {
        $mediaGallery = $this->_getAllImages($product);
        $sortedGallery = array();
        if ($mediaGallery) {
            foreach ($mediaGallery as $image) {
                $imageConfig = Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_EXPORT_FIRST_PRODUCT_IMAGE);
                if ($imageConfig == 'thumbnail' && $image->getFile() == $product->getThumbnail()) {
                    $sortedGallery[-1] = $image;
                } else if ($imageConfig == 'base' && $image->getFile() == $product->getImage()) {
                    $sortedGallery[-1] = $image;
                } else if ($imageConfig == 'small' && $image->getFile() == $product->getSmallImage()) {
                    $sortedGallery[-1] = $image;
                } else {
                    if (!array_key_exists($image->getPosition(), $sortedGallery)) {
                        $sortedGallery[$image->getPosition()] = $image;
                    } else {
                        $sortedGallery[] = $image;
                    }

                }
            }
        }
        ksort($sortedGallery);

        return $sortedGallery;
    }

    /**
     * Retrieve media gallery images, depending on config settings
     * - with the possibility not to ignore the excluded ones
     * - with the possibility to ignore the small ones
     *
     * @see Mage_Catalog_Model_Product::getMediaGalleryImages()
     *
     * @param Mage_Catalog_Model_Product $product
     *
     * @return mixed
     */
    protected function _getAllImages($product)
    {
        $images = new Varien_Data_Collection();
        if (!$product->hasData('media_gallery_images') && is_array($product->getMediaGallery('images'))) {
            foreach ($product->getMediaGallery('images') as $image) {
                // ignore disabled images
                if (!Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_EXPORT_EXCLUDED_IMAGES)) {
                    if ($image['disabled']) {
                        continue;
                    }
                }
                $image['url']  = $product->getMediaConfig()->getMediaUrl($image['file']);
                $image['id'] = isset($image['value_id']) ? $image['value_id'] : null;
                $image['path'] = $product->getMediaConfig()->getMediaPath($image['file']);
                // ignore small images
                if (!Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_EXPORT_LOWRES_IMAGES)){
                    if (file_exists($image['path'])) {
                        list($width, $height) = getimagesize($image['path']);
                        if ($width < self::IMAGE_EXPORT_MINRESOLUTION || $height < self::IMAGE_EXPORT_MINRESOLUTION) {
                            continue;
                        }
                    }
                }
                $images->addItem(new Varien_Object($image));
            }
        }
        return $images;
    }

    /**
     * fills the item-array available_text field
     * Note: the function isAvailable()  on the Product-Object is only available in Magento-Version >= 1.5
     *
     * @param Mage_Catalog_Model_Product $product
     * @param int $storeViewId
     *
     * @return string
     */
    public function getAvailableText($product, $storeViewId)
    {
        $availableText = "";
        $attributeCode = Mage::getStoreConfig(
                             Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_EXPORT_AVAILABLE_TEXT_ATTRIBUTE_CODE
        );

        if ($attributeCode) {
        	$attributeInputType = $product->getResource()
        		->getAttribute($attributeCode)
        		->getFrontendInput();

            $rawValue = $product
                ->getResource()
                ->getAttributeRawValue($product->getId(), $attributeCode, $storeViewId);

        	switch($attributeInputType) {
        		case "select":
                    /** @var Mage_Eav_Model_Entity_Attribute_Option $attr */
                    $attr = Mage::getModel('eav/entity_attribute_option')
                                ->getCollection()
                                ->setStoreFilter($storeViewId)
                                ->join('attribute', 'attribute.attribute_id=main_table.attribute_id', 'attribute_code')
                                ->addFieldToFilter('main_table.option_id', array('eq' => $rawValue))
                                ->getFirstItem();

        			if($attr) {
        				$availableText = ($attr->getStoreValue()) ? $attr->getStoreValue() : $attr->getValue();
        			}
        			break;
                case "date" :
                    $availableText = Mage::helper('core')->formatDate($rawValue, 'medium', false);
                    break;
        		case "text":
        			$availableText = $rawValue;
        			break;
        		default:

        	}
        }

        if (!$availableText) {
            /** @var Mage_CatalogInventory_Model_Stock_Item $stockItem */
            $stockItem   = $product->getStockItem();
            $isAvailable = $stockItem->checkQty(1) && $product->isSaleable();
            if ($product->isComposite()) {
                $isAvailable = true;
            }

            if ($isAvailable && $stockItem->getIsInStock()) {
                if ($stockItem->getManageStock()
                    && $stockItem->getBackorders() == Mage_CatalogInventory_Model_Stock::BACKORDERS_YES_NOTIFY
                    && $stockItem->getQty() <= 0
                ) {
                    $availableText = Mage::helper('shopgate')->__('Item will be backordered');
                } else {
                    $availableText = Mage::helper('shopgate')->__('In stock');
                }
            } else {
                $availableText = Mage::helper('shopgate')->__('Out of stock');
            }

        }

        return $availableText;
    }

    /**
     * @param Mage_Catalog_Model_Product $product
     * @param Mage_Catalog_Model_Product $parentItem
     *
     * @return string
     */
    public function createFullDescription($product, $parentItem = null)
    {
        $description = $this->_getProductDescription($product);
        if ($parentItem) {
            $parentDescription = $this->_getProductDescription($parentItem);
            switch (Mage::getStoreConfig(
                        Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_EXPORT_VARIATION_DESCRIPTION
            )) {
                case 1:
                    $description = $parentDescription;
                    break;
                case 2:
                    $description = $parentDescription . "

" . $description;
                    break;
                case 3:
                    $description = $description . "

" . $parentDescription;
                    break;
            }
        }

        $processor = Mage::helper('cms')->getPageTemplateProcessor();

        return $processor->filter($description);
    }

    /**
     * @param Mage_Catalog_Model_Product $product
     *
     * @return string
     */
    protected function _getProductDescription($product)
    {
        $description      = "";
        $longDescription  = $product->getDescription();
        $shortDescription = $product->getShortDescription();

        // Convert description and/or short description with nl2br
        $convertDescription = Mage::helper('shopgate')->getConfig()->getConvertDescription(true);
        if (in_array("0", $convertDescription)) {
            $longDescription = nl2br($longDescription);
        } else {
            if (in_array("1", $convertDescription)) {
                $shortDescription = nl2br($shortDescription);
            }
        }

        switch (Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_EXPORT_DESCRIPTION_TYPE)) {
            case 0:
                $description = $longDescription;
                break;
            case 1:
                $description = $shortDescription;
                break;
            case 2:
                $description = $longDescription;
                $description .= "

";
                $description .= $shortDescription;
                break;
            case 3:
                $description = $shortDescription;
                $description .= "

";
                $description .= $longDescription;
                break;
            case 4:
                $descriptionAttribute = Mage::getStoreConfig(
                                            Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_DESCRIPTION_ATTR_CODE
                );

                $attributeCodes = explode(",", $descriptionAttribute);

                $counter = 0;
                foreach ($attributeCodes as $attributeCode) {

                    $attributeCode = trim($attributeCode);

                    if (!empty($attributeCode)) {
                        $description1 = $product->getData($attributeCode);
                        if (in_array("2", $convertDescription)) {
                            $description1 = nl2br($description1);
                        }
                        if (!empty($description1) && $counter > 0) {
                            $description .= "

";
                        }
                        $description .= $description1;
                    }
                    $counter++;
                }
        }

        return $description;
    }

    /**
     * create deep link for the product
     *
     * @param Mage_Catalog_Model_Product $product
     * @param Mage_Catalog_Model_Product $parentItem
     *
     * @return string
     */
    public function getDeepLink($product, $parentItem = null)
    {
        $deepLink = $product->getProductUrl(true);

        if ($parentItem && $product->getVisibility() == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE) {
            $deepLink = $parentItem->getProductUrl(true);
        }

        return $this->parseUrl($deepLink);
    }

    /**
     * @param Mage_Catalog_Model_Product $product
     *
     * @return string
     */
    public function getManufacturer($product)
    {
        $manufacturer = $product->getManufacturer();
        if ($manufacturer) {
            $manufacturer = $product->getResource()
                                    ->getAttribute('manufacturer')
                                    ->getSource()
                                    ->getOptionText($manufacturer);
        }

        return $manufacturer;
    }

    /**
     * @param $product Mage_Catalog_Model_Product
     * @return int
     */
    public function getParentStockQuantity($product)
    {
        /** @var Mage_CatalogInventory_Model_Stock_Item $stockItem */
        $stockItem = $product->getStockItem();
        if (!$stockItem->hasStockQty()) {
            $stockItem->setStockQty(0);  // prevent possible recursive loop
            if (!$product->isComposite()) {
                $stockQty = $stockItem->getQty();
            } else {
                $stockQty = null;
                $productsByGroups = $this->_getProductsToPurchaseByReqGroups($product);
                foreach ($productsByGroups as $productsInGroup) {
                    $qty = 0;
                    foreach ($productsInGroup as $childProduct) {
                        if ($childProduct->hasStockItem()) {
                            $qty += $childProduct->getStockItem()->getQty();
                        }
                    }
                    if (is_null($stockQty) || $qty < $stockQty) {
                        $stockQty = $qty;
                    }
                }
            }
            $stockQty = (float) $stockQty;
            if ($stockQty < 0 || !$stockItem->getManageStock()
                || !$stockItem->getIsInStock() || ($product && !$product->isSaleable())
            ) {
                $stockQty = 0;
            }
            $product->getStockItem()->setQty($stockQty);
        } else {
            $stockQty = ($product->isSalable()) ? $stockItem->getQty() : 0;
        }
        return $stockQty;
    }

    /**
     * @param $product Mage_Catalog_Model_Product
     * @return array
     */
    protected function _getProductsToPurchaseByReqGroups($product)
    {
        $type = $product->getTypeId();
        $productGroups = array();
        switch($type) {
            case Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE:
                $productGroups = array($product->getTypeInstance(true)->getUsedProducts(null, $product));
                break;
            case Mage_Catalog_Model_Product_Type::TYPE_BUNDLE:
                $productGroups = $this->_getProductGroupsForBundle($product);
                break;
            case Mage_Catalog_Model_Product_Type::TYPE_GROUPED:
                $productGroups = array($product->getTypeInstance(true)->getAssociatedProducts($product));
                break;
        }
        return $productGroups;
    }

    /**
     * Retrieve products divided into groups required to purchase
     * At least one product in each group has to be purchased
     *
     * @param  Mage_Catalog_Model_Product $product
     * @return array
     */
    public function _getProductGroupsForBundle($product)
    {
        $groups = array();
        $allProducts = array();
        $hasRequiredOptions = false;
        foreach ($product->getTypeInstance(true)->getOptions($product) as $option) {
            $groupProducts = array();
            foreach ($product->getTypeInstance()->getSelectionsCollection(array($option->getId()), $product) as $childProduct) {
                $groupProducts[] = $childProduct;
                $allProducts[] = $childProduct;
            }
            if ($option->getRequired()) {
                $groups[] = $groupProducts;
                $hasRequiredOptions = true;
            }
        }
        if (!$hasRequiredOptions) {
            $groups = array($allProducts);
        }
        return $groups;
    }

    /**
     * @param Mage_Catalog_Model_Product $product
     *
     * @return bool
     */
    public function isProductVisibleInCategories($product)
    {
        if ($product->getVisibility() != Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE
            && $product->getVisibility() != Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_SEARCH
        ) {
            return true;
        }
        if (Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_EXPORT_IS_EXPORT_STORES)) {
            $storesToExport = Mage::helper('shopgate')->getConfig()->getExportStores(true);
            foreach ($storesToExport as $storeId) {
                $value = Mage::getResourceModel('catalog/product')->getAttributeRawValue(
                    $product->getId(), 'visibility', $storeId
                );
                if (in_array(
                    $value, array(
                              Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
                              Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
                          )
                )) {
                    return true;
                }
            }
        }
        return false;
    }
}


text:
IF NOT EXISTS (select * from sys.objects where type = 'p' and name = 'testEmptyDeltaStore' and schema_id = SCHEMA_ID('RowGroups') )
	exec ('create procedure [RowGroups].[testEmptyDeltaStore] as select 1');
GO

ALTER PROCEDURE [RowGroups].[testEmptyDeltaStore] AS
BEGIN
	IF OBJECT_ID('tempdb..#ExpectedRowGroups') IS NOT NULL
		DROP TABLE #ExpectedRowGroups;

	create table #ExpectedRowGroups(
		[TableName] nvarchar(256),
		[Type] varchar(20),
		[Location] varchar(15),
		[Partition] int,
		[Compression Type] varchar(50),
		[BulkLoadRGs] int,
		[Open DeltaStores] int,
		[Closed DeltaStores] int,
		[Compressed RowGroups] int,
		[Total RowGroups] int,
		[Deleted Rows] Decimal(18,6),
		[Active Rows] Decimal(18,6),
		[Total Rows] Decimal(18,6),
		[Size in GB] Decimal(18,3),
		[Scans] int,
		[Updates] int,
		[LastScan] DateTime
	);

	select top (0) *
		into #ActualRowGroups
		from #ExpectedRowGroups;

	-- CCI
	-- Insert expected result
	insert into #ExpectedRowGroups (TableName, Type, Location, Partition, [Compression Type], [BulkLoadRGs], [Open DeltaStores], [Closed DeltaStores],
									[Compressed RowGroups], [Total RowGroups], [Deleted Rows], [Active Rows], [Total Rows], [Size in GB], [Scans], [Updates],  [LastScan])
		select '[dbo].[EmptyDeltaStoreCCI]', 'Clustered', 'Disk-Based', 1, 'COLUMNSTORE', 0, 1, 0,
				0, 1, 0.0 /*Del Rows*/, 0.000000 /*Active Rows*/, 0.000000 /*Total Rows*/, 0.0, 0, 1, NULL;

	insert into #ActualRowGroups
		exec dbo.cstore_GetRowGroups @tableName = 'EmptyDeltaStoreCCI';

	update #ExpectedRowGroups
		set Scans = NULL, Updates = NULL, LastScan = NULL;
	update #ActualRowGroups
		set Scans = NULL, Updates = NULL, LastScan = NULL;

	exec tSQLt.AssertEqualsTable '#ExpectedRowGroups', '#ActualRowGroups';

END

GO


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

using Xunit;
using SolrNet.Impl.FieldSerializers;
using SolrNet.Impl.QuerySerializers;
using System;

namespace SolrNet.Tests {

	public class SolrQueryByFieldTests {
		public class TestDocument {}

        public string Serialize(object q) {
            var serializer = new DefaultQuerySerializer(new DefaultFieldSerializer());
            return serializer.Serialize(q);
        }

        [Fact]
        public void NullField_yields_null_query() {
            var q = new SolrQueryByField(null, "123456");
            Assert.Null(Serialize(q));
        }

        [Fact]
        public void NullValue_yields_null_query() {
            var q = new SolrQueryByField("id", null);
            Assert.Null(Serialize(q));
        }

        [Fact]
        public void EmptyValue() {
            var q = new SolrQueryByField("id", "");
            Assert.Equal("id:(\"\")", Serialize(q));
        }

		[Fact]
		public void Basic() {
			var q = new SolrQueryByField("id", "123456");
            Assert.Equal("id:(123456)", Serialize(q));
		}

		[Fact]
		public void ShouldQuoteSpaces() {
			var q = new SolrQueryByField("id", "hello world");
            Assert.Equal("id:(\"hello world\")", Serialize(q));
		}

		[Fact]
		public void ShouldQuoteSpecialChar() {
			var q = new SolrQueryByField("id", "hello+world-bye&&q||w!e(r)t{y}[u]^i\"o~p:a\\s+d;;?*/");
            Assert.Equal(@"id:(hello\+world\-bye\&&q\||w\!e\(r\)t\{y\}\[u\]\^i\""o\~p\:a\\s\+d\;\;\?\*\/)", Serialize(q));
		}

        [Fact]
        public void QuotedFalse() {
            var q = new SolrQueryByField("id", "hello?wor/ld*") { Quoted = false };
            Assert.Equal("id:(hello?wor/ld*)", Serialize(q));
        }
	}
}


text:
package core

import (
	"fmt"
	"strings"
	"time"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"

	"k8s.io/apimachinery/pkg/util/clock"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apimachinery/pkg/util/validation/field"
	"k8s.io/apiserver/pkg/admission"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/helper/qos"
	k8s_api_v1 "k8s.io/kubernetes/pkg/api/v1"
	"k8s.io/kubernetes/pkg/api/validation"
	"k8s.io/kubernetes/pkg/kubeapiserver/admission/util"
	"k8s.io/kubernetes/pkg/quota"
	"k8s.io/kubernetes/pkg/quota/generic"
)

// the name used for object count quota
var podObjectCountName = generic.ObjectCountQuotaResourceNameFor(v1.SchemeGroupVersion.WithResource("pods").GroupResource())

// podResources are the set of resources managed by quota associated with pods.
var podResources = []api.ResourceName{
	podObjectCountName,
	api.ResourceCPU,
	api.ResourceMemory,
	api.ResourceEphemeralStorage,
	api.ResourceRequestsCPU,
	api.ResourceRequestsMemory,
	api.ResourceRequestsEphemeralStorage,
	api.ResourceLimitsCPU,
	api.ResourceLimitsMemory,
	api.ResourceLimitsEphemeralStorage,
	api.ResourcePods,
}

// NOTE: it was a mistake, but if a quota tracks cpu or memory related resources,
// the incoming pod is required to have those values set.  we should not repeat
// this mistake for other future resources (gpus, ephemeral-storage,etc).
// do not add more resources to this list!
var validationSet = sets.NewString(
	string(api.ResourceCPU),
	string(api.ResourceMemory),
	string(api.ResourceRequestsCPU),
	string(api.ResourceRequestsMemory),
	string(api.ResourceLimitsCPU),
	string(api.ResourceLimitsMemory),
)

// NewPodEvaluator returns an evaluator that can evaluate pods
func NewPodEvaluator(f quota.ListerForResourceFunc, clock clock.Clock) quota.Evaluator {
	listFuncByNamespace := generic.ListResourceUsingListerFunc(f, v1.SchemeGroupVersion.WithResource("pods"))
	podEvaluator := &podEvaluator{listFuncByNamespace: listFuncByNamespace, clock: clock}
	return podEvaluator
}

// podEvaluator knows how to measure usage of pods.
type podEvaluator struct {
	// knows how to list pods
	listFuncByNamespace generic.ListFuncByNamespace
	// used to track time
	clock clock.Clock
}

// Constraints verifies that all required resources are present on the pod
// In addition, it validates that the resources are valid (i.e. requests < limits)
func (p *podEvaluator) Constraints(required []api.ResourceName, item runtime.Object) error {
	pod, ok := item.(*api.Pod)
	if !ok {
		return fmt.Errorf("Unexpected input object %v", item)
	}

	// Pod level resources are often set during admission control
	// As a consequence, we want to verify that resources are valid prior
	// to ever charging quota prematurely in case they are not.
	// TODO remove this entire section when we have a validation step in admission.
	allErrs := field.ErrorList{}
	fldPath := field.NewPath("spec").Child("containers")
	for i, ctr := range pod.Spec.Containers {
		allErrs = append(allErrs, validation.ValidateResourceRequirements(&ctr.Resources, fldPath.Index(i).Child("resources"))...)
	}
	fldPath = field.NewPath("spec").Child("initContainers")
	for i, ctr := range pod.Spec.InitContainers {
		allErrs = append(allErrs, validation.ValidateResourceRequirements(&ctr.Resources, fldPath.Index(i).Child("resources"))...)
	}
	if len(allErrs) > 0 {
		return allErrs.ToAggregate()
	}

	// BACKWARD COMPATIBILITY REQUIREMENT: if we quota cpu or memory, then each container
	// must make an explicit request for the resource.  this was a mistake.  it coupled
	// validation with resource counting, but we did this before QoS was even defined.
	// let's not make that mistake again with other resources now that QoS is defined.
	requiredSet := quota.ToSet(required).Intersection(validationSet)
	missingSet := sets.NewString()
	for i := range pod.Spec.Containers {
		enforcePodContainerConstraints(&pod.Spec.Containers[i], requiredSet, missingSet)
	}
	for i := range pod.Spec.InitContainers {
		enforcePodContainerConstraints(&pod.Spec.InitContainers[i], requiredSet, missingSet)
	}
	if len(missingSet) == 0 {
		return nil
	}
	return fmt.Errorf("must specify %s", strings.Join(missingSet.List(), ","))
}

// GroupResource that this evaluator tracks
func (p *podEvaluator) GroupResource() schema.GroupResource {
	return v1.SchemeGroupVersion.WithResource("pods").GroupResource()
}

// Handles returns true if the evaluator should handle the specified attributes.
func (p *podEvaluator) Handles(a admission.Attributes) bool {
	op := a.GetOperation()
	if op == admission.Create {
		return true
	}
	initializationCompletion, err := util.IsInitializationCompletion(a)
	if err != nil {
		// fail closed, will try to give an evaluation.
		utilruntime.HandleError(err)
		return true
	}
	// only uninitialized pods might be updated.
	return initializationCompletion
}

// Matches returns true if the evaluator matches the specified quota with the provided input item
func (p *podEvaluator) Matches(resourceQuota *api.ResourceQuota, item runtime.Object) (bool, error) {
	return generic.Matches(resourceQuota, item, p.MatchingResources, podMatchesScopeFunc)
}

// MatchingResources takes the input specified list of resources and returns the set of resources it matches.
func (p *podEvaluator) MatchingResources(input []api.ResourceName) []api.ResourceName {
	return quota.Intersection(input, podResources)
}

// Usage knows how to measure usage associated with pods
func (p *podEvaluator) Usage(item runtime.Object) (api.ResourceList, error) {
	// delegate to normal usage
	return PodUsageFunc(item, p.clock)
}

// UsageStats calculates aggregate usage for the object.
func (p *podEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error) {
	return generic.CalculateUsageStats(options, p.listFuncByNamespace, podMatchesScopeFunc, p.Usage)
}

// verifies we implement the required interface.
var _ quota.Evaluator = &podEvaluator{}

// enforcePodContainerConstraints checks for required resources that are not set on this container and
// adds them to missingSet.
func enforcePodContainerConstraints(container *api.Container, requiredSet, missingSet sets.String) {
	requests := container.Resources.Requests
	limits := container.Resources.Limits
	containerUsage := podComputeUsageHelper(requests, limits)
	containerSet := quota.ToSet(quota.ResourceNames(containerUsage))
	if !containerSet.Equal(requiredSet) {
		difference := requiredSet.Difference(containerSet)
		missingSet.Insert(difference.List()...)
	}
}

// podComputeUsageHelper can summarize the pod compute quota usage based on requests and limits
func podComputeUsageHelper(requests api.ResourceList, limits api.ResourceList) api.ResourceList {
	result := api.ResourceList{}
	result[api.ResourcePods] = resource.MustParse("1")
	if request, found := requests[api.ResourceCPU]; found {
		result[api.ResourceCPU] = request
		result[api.ResourceRequestsCPU] = request
	}
	if limit, found := limits[api.ResourceCPU]; found {
		result[api.ResourceLimitsCPU] = limit
	}
	if request, found := requests[api.ResourceMemory]; found {
		result[api.ResourceMemory] = request
		result[api.ResourceRequestsMemory] = request
	}
	if limit, found := limits[api.ResourceMemory]; found {
		result[api.ResourceLimitsMemory] = limit
	}
	if request, found := requests[api.ResourceEphemeralStorage]; found {
		result[api.ResourceEphemeralStorage] = request
		result[api.ResourceRequestsEphemeralStorage] = request
	}
	if limit, found := limits[api.ResourceEphemeralStorage]; found {
		result[api.ResourceLimitsEphemeralStorage] = limit
	}
	return result
}

func toInternalPodOrError(obj runtime.Object) (*api.Pod, error) {
	pod := &api.Pod{}
	switch t := obj.(type) {
	case *v1.Pod:
		if err := k8s_api_v1.Convert_v1_Pod_To_api_Pod(t, pod, nil); err != nil {
			return nil, err
		}
	case *api.Pod:
		pod = t
	default:
		return nil, fmt.Errorf("expect *api.Pod or *v1.Pod, got %v", t)
	}
	return pod, nil
}

// podMatchesScopeFunc is a function that knows how to evaluate if a pod matches a scope
func podMatchesScopeFunc(scope api.ResourceQuotaScope, object runtime.Object) (bool, error) {
	pod, err := toInternalPodOrError(object)
	if err != nil {
		return false, err
	}
	switch scope {
	case api.ResourceQuotaScopeTerminating:
		return isTerminating(pod), nil
	case api.ResourceQuotaScopeNotTerminating:
		return !isTerminating(pod), nil
	case api.ResourceQuotaScopeBestEffort:
		return isBestEffort(pod), nil
	case api.ResourceQuotaScopeNotBestEffort:
		return !isBestEffort(pod), nil
	}
	return false, nil
}

// PodUsageFunc returns the quota usage for a pod.
// A pod is charged for quota if the following are not true.
//  - pod has a terminal phase (failed or succeeded)
//  - pod has been marked for deletion and grace period has expired
func PodUsageFunc(obj runtime.Object, clock clock.Clock) (api.ResourceList, error) {
	pod, err := toInternalPodOrError(obj)
	if err != nil {
		return api.ResourceList{}, err
	}

	// always quota the object count (even if the pod is end of life)
	// object count quotas track all objects that are in storage.
	// where "pods" tracks all pods that have not reached a terminal state,
	// count/pods tracks all pods independent of state.
	result := api.ResourceList{
		podObjectCountName: *(resource.NewQuantity(1, resource.DecimalSI)),
	}

	// by convention, we do not quota compute resources that have reached end-of life
	// note: the "pods" resource is considered a compute resource since it is tied to life-cycle.
	if !QuotaPod(pod, clock) {
		return result, nil
	}

	requests := api.ResourceList{}
	limits := api.ResourceList{}
	// TODO: ideally, we have pod level requests and limits in the future.
	for i := range pod.Spec.Containers {
		requests = quota.Add(requests, pod.Spec.Containers[i].Resources.Requests)
		limits = quota.Add(limits, pod.Spec.Containers[i].Resources.Limits)
	}
	// InitContainers are run sequentially before other containers start, so the highest
	// init container resource is compared against the sum of app containers to determine
	// the effective usage for both requests and limits.
	for i := range pod.Spec.InitContainers {
		requests = quota.Max(requests, pod.Spec.InitContainers[i].Resources.Requests)
		limits = quota.Max(limits, pod.Spec.InitContainers[i].Resources.Limits)
	}

	result = quota.Add(result, podComputeUsageHelper(requests, limits))
	return result, nil
}

func isBestEffort(pod *api.Pod) bool {
	return qos.GetPodQOS(pod) == api.PodQOSBestEffort
}

func isTerminating(pod *api.Pod) bool {
	if pod.Spec.ActiveDeadlineSeconds != nil && *pod.Spec.ActiveDeadlineSeconds >= int64(0) {
		return true
	}
	return false
}

// QuotaPod returns true if the pod is eligible to track against a quota
// A pod is eligible for quota, unless any of the following are true:
//  - pod has a terminal phase (failed or succeeded)
//  - pod has been marked for deletion and grace period has expired.
func QuotaPod(pod *api.Pod, clock clock.Clock) bool {
	// if pod is terminal, ignore it for quota
	if api.PodFailed == pod.Status.Phase || api.PodSucceeded == pod.Status.Phase {
		return false
	}
	// deleted pods that should be gone should not be charged to user quota.
	// this can happen if a node is lost, and the kubelet is never able to confirm deletion.
	// even though the cluster may have drifting clocks, quota makes a reasonable effort
	// to balance cluster needs against user needs.  user's do not control clocks,
	// but at worst a small drive in clocks will only slightly impact quota.
	if pod.DeletionTimestamp != nil && pod.DeletionGracePeriodSeconds != nil {
		now := clock.Now()
		deletionTime := pod.DeletionTimestamp.Time
		gracePeriod := time.Duration(*pod.DeletionGracePeriodSeconds) * time.Second
		if now.After(deletionTime.Add(gracePeriod)) {
			return false
		}
	}
	return true
}

// QuotaV1Pod returns true if the pod is eligible to track against a quota
// if it's not in a terminal state according to its phase.
func QuotaV1Pod(pod *v1.Pod, clock clock.Clock) bool {
	// if pod is terminal, ignore it for quota
	if v1.PodFailed == pod.Status.Phase || v1.PodSucceeded == pod.Status.Phase {
		return false
	}
	// if pods are stuck terminating (for example, a node is lost), we do not want
	// to charge the user for that pod in quota because it could prevent them from
	// scaling up new pods to service their application.
	if pod.DeletionTimestamp != nil && pod.DeletionGracePeriodSeconds != nil {
		now := clock.Now()
		deletionTime := pod.DeletionTimestamp.Time
		gracePeriod := time.Duration(*pod.DeletionGracePeriodSeconds) * time.Second
		if now.After(deletionTime.Add(gracePeriod)) {
			return false
		}
	}
	return true
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   PhysicalWire.h
 * Author: jucemar
 *
 * Created on 12 de Maio de 2017, 22:49
 */

#ifndef PHYSICALDESIGN_PHYSICALWIRE_H
#define PHYSICALDESIGN_PHYSICALWIRE_H

namespace Rsyn {

//! @brief Physical wire class stores wire segments of routed nets.
class PhysicalWire : public Proxy<PhysicalWireData> {
	friend class PhysicalDesign;
protected:
	//! @brief Constructs a Rsyn::PhysicalWire object with a pointer to Rsyn::PhysicalWireData.

	PhysicalWire(PhysicalWireData * data) : Proxy(data) {
	}
public:
	//! @brief Constructs a Rsyn::PhysicalWire object with a null pointer to Rsyn::PhysicalWireData.

	PhysicalWire() : Proxy(nullptr) {
	}
	//! @brief Constructs a Rsyn::PhysicalWire object with a null pointer to Rsyn::PhysicalWireData.

	PhysicalWire(std::nullptr_t) : Proxy(nullptr) {
	}

	//! @brief Returns a vector reference to path of the wire.
	const std::vector<Rsyn::PhysicalWireSegment> & allSegments() const;
}; // end class

} // end namespace

#endif /* PHYSICALDESIGN_PHYSICALWIRE_H */


text:
import { storiesOf } from '@storybook/angular';
import { StyledComponent } from './styled.component';

storiesOf('Custom|styleUrls', module).add('Component with styles', () => ({
  component: StyledComponent,
}));


text:
import time, sys, os, pkg_resources
import slip

from twisted.internet.serialport import SerialPort

from twisted.python import log
from twisted.internet import reactor, ssl
from twisted.application import service
from twisted.internet.protocol import Protocol, Factory

from twisted.web.server import Site
from twisted.web.static import File

from autobahn.twisted.websocket import \
    WebSocketServerProtocol, WebSocketServerFactory, listenWS

from autobahn.twisted.resource import \
    WebSocketResource, HTTPChannelHixie76Aware

class Bridge():

    def __init__(self):
        self.serialServer = None
        self.wsServer = None

    def setSerialServer(self, sServer):
        self.serialServer = sServer

    def setWebsocketServer(self, wsServer):
        self.wsServer = wsServer

    def serialToWebsocket(self, data):
        if self.wsServer is not None:
            self.wsServer.sendMessage(data, True)

    def websocketToSerial(self, data):
        if self.serialServer is not None:
            self.serialServer.cmdReceived(data)

class USBClient(Protocol):

    def __init__(self, bridge):
        self.bridge = bridge
        # self.bridge.setSerialServer(self)
        self.slip_processor = slip.slip()

    def connectionFailed(self):
        print "Connection Failed:", self

    def connectionMade(self):
        # global serialServer
        # serialServer = self
        self.bridge.setSerialServer(self)
        print 'Arduino device: ', self.bridge.serialServer, ' is connected.'

    def dataReceived(self, data):
        # print "Data received! with %d bytes!" % len(data)
        self.slip_processor.append(data)
        slip_packets = self.slip_processor.decode()
        for packet in slip_packets:
            # print packet, '- from Arduino.'
            self.bridge.serialToWebsocket(packet)

    def cmdReceived(self, data):
        # print data
        cmd = self.slip_processor.encode(data)
        self.bridge.serialServer.transport.write(cmd)
        # print cmd, ' - sent to Arduino.'

class BridgedWebSocketServerFactory(WebSocketServerFactory):

    def __init__(self, url, debug, debugCodePaths, bridge):
        WebSocketServerFactory.__init__(self, url,
                                        debug=debug,
                                        debugCodePaths=debugCodePaths)
        self.bridge = bridge

class WebSocketServer(WebSocketServerProtocol):

    def onOpen(self):
        print 'WebSocket connection open.'

    def onConnect(self, request):
        self.factory.bridge.setWebsocketServer(self)
        print 'Client connecting: {0}'.format(request.peer)

    def onMessage(self, payload, isBinary):
        self.factory.bridge.websocketToSerial(payload)

    def onClose(self, wasClean, code, reason):
        print 'WebSocket connection closed: {0}'.format(reason)

if __name__ == '__main__':

    # port = '/dev/cu.usbmodema0111'
    port = '/dev/cu.usbmodem1411'
    # port = '/dev/cu.usbmodem14141'

    baudrate = 115200
    SERVER_IP = '127.0.0.1'
    SERVER_WS_PORT = 8000
    SERVER_HTTP_PORT = 9000
    SERVER_HTTP_RESOURCES = 'web'
    bridge = Bridge()

    log.startLogging(sys.stdout)

    # websocket setup
    wsAddress = 'wss://%s:%d' % (SERVER_IP, SERVER_WS_PORT)
    contextFactory = ssl.DefaultOpenSSLContextFactory('/etc/apache2/ssl/localhost.key',
                                                    '/etc/apache2/ssl/localhost.crt')
    wsfactory = BridgedWebSocketServerFactory(wsAddress, False, False, bridge)
    wsfactory.protocol = WebSocketServer
    reactor.listenSSL(SERVER_WS_PORT, wsfactory, contextFactory)

    # http setup
    webdir = os.path.abspath(SERVER_HTTP_RESOURCES)
    site = Site(File(webdir))
    site.protocol = HTTPChannelHixie76Aware
    reactor.listenTCP(SERVER_HTTP_PORT, site)

    usbclient = USBClient(bridge)

    print('About to open serial port {0} [{1} baud] ..'.format(port, baudrate))
    try:
        SerialPort(usbclient, port, reactor, baudrate=baudrate)
    except Exception as e:
        print('Could not open serial port: {0}'.format(e))

    reactor.run()


text:
<?xml version="1.0" encoding="UTF-8" ?>
<config>
  <abortOnConfigurationError>${solr.abortOnConfigurationError:true}</abortOnConfigurationError>

  <dataDir>${solr.core.dataDir}</dataDir>

  <indexDefaults>
    <useCompoundFile>false</useCompoundFile>
    <mergeFactor>10</mergeFactor>
    <ramBufferSizeMB>32</ramBufferSizeMB>
    <maxFieldLength>10000</maxFieldLength>
    <writeLockTimeout>1000</writeLockTimeout>
    <commitLockTimeout>10000</commitLockTimeout>
    <lockType>native</lockType>
  </indexDefaults>

  <mainIndex>
    <useCompoundFile>false</useCompoundFile>
    <ramBufferSizeMB>32</ramBufferSizeMB>
    <mergeFactor>10</mergeFactor>
    <unlockOnStartup>true</unlockOnStartup>
    <reopenReaders>true</reopenReaders>
    <deletionPolicy class="solr.SolrDeletionPolicy">
      <str name="maxCommitsToKeep">1</str>
      <str name="maxOptimizedCommitsToKeep">0</str>
    </deletionPolicy>
    <infoStream file="INFOSTREAM.txt">false</infoStream>
  </mainIndex>

  <jmx />

  <updateHandler class="solr.DirectUpdateHandler2"/>

  <query>
    <maxBooleanClauses>1024</maxBooleanClauses>
    <filterCache class="solr.FastLRUCache" size="512" initialSize="512" autowarmCount="0"/>
    <queryResultCache class="solr.LRUCache" size="512" initialSize="512" autowarmCount="0"/>
    <documentCache class="solr.LRUCache" size="512" initialSize="512" autowarmCount="0"/>
    <enableLazyFieldLoading>true</enableLazyFieldLoading>
    <queryResultWindowSize>20</queryResultWindowSize>
    <queryResultMaxDocsCached>200</queryResultMaxDocsCached>
    <listener event="newSearcher" class="solr.QuerySenderListener">
      <arr name="queries">
      </arr>
    </listener>
    <listener event="firstSearcher" class="solr.QuerySenderListener">
      <arr name="queries">
        <lst> <str name="q">solr rocks</str><str name="start">0</str><str name="rows">10</str></lst>
        <lst><str name="q">static firstSearcher warming query from solrconfig.xml</str></lst>
      </arr>
    </listener>
    <useColdSearcher>false</useColdSearcher>
    <maxWarmingSearchers>2</maxWarmingSearchers>
  </query>

  <requestDispatcher handleSelect="true" >
    <requestParsers enableRemoteStreaming="true" multipartUploadLimitInKB="2048000" />
    <httpCaching lastModifiedFrom="openTime" etagSeed="Solr"/>
  </requestDispatcher>

  <requestHandler name="standard" class="solr.SearchHandler" default="true">
     <lst name="defaults">
       <str name="echoParams">explicit</str>
     </lst>
  </requestHandler>

  <requestHandler name="/update" class="solr.XmlUpdateRequestHandler" />

  <requestHandler name="/update/javabin" class="solr.BinaryUpdateRequestHandler" />

  <requestHandler name="/analysis/document" class="solr.DocumentAnalysisRequestHandler" />

  <requestHandler name="/analysis/field" class="solr.FieldAnalysisRequestHandler" />

  <requestHandler name="/update/csv" class="solr.CSVRequestHandler" startup="lazy" />

  <requestHandler name="/admin/" class="org.apache.solr.handler.admin.AdminHandlers" />

  <requestHandler name="/admin/ping" class="PingRequestHandler">
    <lst name="defaults">
      <str name="qt">standard</str>
      <str name="q">solrpingquery</str>
      <str name="echoParams">all</str>
    </lst>
  </requestHandler>

  <requestHandler name="/debug/dump" class="solr.DumpRequestHandler" >
    <lst name="defaults">
     <str name="echoParams">explicit</str> <!-- for all params (including the default etc) use: 'all' -->
     <str name="echoHandler">true</str>
    </lst>
  </requestHandler>

  <queryResponseWriter name="xslt" class="org.apache.solr.request.XSLTResponseWriter">
    <int name="xsltCacheLifetimeSeconds">5</int>
  </queryResponseWriter>

  <admin>
    <defaultQuery>solr</defaultQuery>
  </admin>

</config>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.hazelcast.queue.impl.QueueContainer (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.hazelcast.queue.impl.QueueContainer

Packages that use QueueContainer

Package
Description

com.hazelcast.queue.impl

This package contains the IQueue functionality.

 The IQueue is the distributed version of the BlockingQueue.

Uses of QueueContainer in com.hazelcast.queue.impl

Fields in com.hazelcast.queue.impl declared as QueueContainer

Modifier and Type
Field and Description

protected QueueContainer
QueueItem.container

Methods in com.hazelcast.queue.impl that return QueueContainer

Modifier and Type
Method and Description

protected QueueContainer
QueueOperation.getOrCreateContainer()

QueueContainer
QueueService.getOrCreateContainer(String name,
                    boolean fromBackup)

Methods in com.hazelcast.queue.impl with parameters of type QueueContainer

Modifier and Type
Method and Description

void
QueueService.addContainer(String name,
            QueueContainer container)

Constructors in com.hazelcast.queue.impl with parameters of type QueueContainer

Constructor and Description

QueueItem(QueueContainer container,
         long itemId,
         Data data)

TxQueueItem(QueueContainer container,
           long itemId,
           Data data)

Constructor parameters in com.hazelcast.queue.impl with type arguments of type QueueContainer

Constructor and Description

QueueReplicationOperation(Map<String,QueueContainer> migrationData,
                         int partitionId,
                         int replicaIndex)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Hazelcast, Inc.. All Rights Reserved.


text:
patron=$1			# Almacenamos en la variable patron el argumento
				# numero 1, que contiene el patrón a buscar.

shift				# Desplazamos las posiciones de los argumentos hacia
				# la izquierda, eliminando así el parámetro que
				# contenía el patron buscar, quedandonos con la
				# lista de ficheros en los cuales realizar la
				# búsqueda.

for f				# Recorremos la lista de argumentos, formada ahora
				# por los nombres de los ficheros únicamente.

do
	fgrep -q $patron $f	# El comando fgrep busca en el fichero $f las lineas
				# que contengan el patrón $patron, y nos devuelve
				# las lineas que contienen dicho patron. Pero con la
				# opción "-q", hacemos que funcione en modo
				# silencioso sin enviar resultado a su salida
				# estándar
	if [ $? = 1 ]		# Si el código de retorno del comando anterior es 1
				# (error) debemos continuar con	la siguiente
				# iteración del bucle, es decir, con el siguiente
				# fichero.
	then
		continue
	fi

	cp $f $HOME/backups	# Si se ha llegado hasta esta línea es porque se ha
				# localizado un fichero con ese	patron y no se ha
				# interrumpido la ejecución de esta iteración, y por
				# lo tanto, realizamos la copia de dicho fichero.
done


text:
package client

// TODO @jhowardmsft - This will move to Microsoft/opengcs soon

import (
	"fmt"
	"os"
	"path/filepath"
)

// LayerVhdDetails is a utility for getting a file name, size and indication of
// sandbox for a VHD(x) in a folder. A read-only layer will be layer.vhd. A
// read-write layer will be sandbox.vhdx.
func LayerVhdDetails(folder string) (string, int64, bool, error) {
	var fileInfo os.FileInfo
	isSandbox := false
	filename := filepath.Join(folder, "layer.vhd")
	var err error

	if fileInfo, err = os.Stat(filename); err != nil {
		filename = filepath.Join(folder, "sandbox.vhdx")
		if fileInfo, err = os.Stat(filename); err != nil {
			if os.IsNotExist(err) {
				return "", 0, isSandbox, fmt.Errorf("could not find layer or sandbox in %s", folder)
			}
			return "", 0, isSandbox, fmt.Errorf("error locating layer or sandbox in %s: %s", folder, err)
		}
		isSandbox = true
	}
	return filename, fileInfo.Size(), isSandbox, nil
}


text:
<?php
	Defined("BASE_PATH") or die("Dilarang Mengakses File Secara Langsung");
?>

	<link rel="stylesheet" type="text/css" href="<?= base_url."assets/plugins/DataTables/DataTables-1.10.15/css/dataTables.bootstrap.min.css"; ?>"/>
	<link rel="stylesheet" type="text/css" href="<?= base_url."assets/plugins/DataTables/Responsive-2.1.1/css/responsive.bootstrap.min.css"; ?>"/>

Admin

<a href="<?= base_url ?>"> SiSGar

<a href="<?= base_url."index.php?m=admin&p=list"; ?>">Admin

Data Admin

Data Admin

                                <button type="button" class="btn btn-default btn-flat" id="tambah_admin"> Tambah</button>

                                <button type="button" class="btn btn-success btn-flat" id="exportExcel"> Export Excel</button>

                                <button type="button" class="btn btn-danger btn-flat" id="exportPdf"> Export Pdf</button>

                                        No
                                        Username
                                        Nama
                                        Email
                                        Hak Akses
                                        Level
                                        Status
                                        Aksi

<?php include_once("form.php"); ?>


text:
require 'certificate_authority'
require 'fileutils'

if ARGV.empty?
  puts "Usage: ruby certgen.rb <domain>"
  exit 1
end

$domain = ARGV[0]

$certs_path = File.join(ENV['HOME'], '.docker')

def certificate_authority
  cert_path = File.join($certs_path, 'ca', 'cert.pem')
  ca_path = File.join($certs_path, 'ca', 'key.pem')

  key_material = if File.exist?(ca_path)
    key = OpenSSL::PKey::RSA.new(File.read(ca_path))
    mem_key = CertificateAuthority::MemoryKeyMaterial.new
    mem_key.public_key = key.public_key
    mem_key.private_key = key
    mem_key
  else
    mem_key = CertificateAuthority::MemoryKeyMaterial.new
    mem_key.generate_key
    mem_key
  end

  if File.exist?(cert_path)
    raw_cert = File.read(cert_path)
    openssl = OpenSSL::X509::Certificate.new(raw_cert)
    cert = CertificateAuthority::Certificate.from_openssl(openssl)
    cert.key_material = key_material
    cert
  else
    root = CertificateAuthority::Certificate.new
    root.subject.common_name = $domain
    root.serial_number.number = 1
    root.signing_entity = true
    root.key_material = key_material

    ca_profile = {
      "extensions" => {
        "keyUsage" => {
          "usage" => [ "critical", "keyCertSign" ]
        }
      }
    }

    root.sign!(ca_profile)
    root
  end
end

def server_certificate(root)
  server = CertificateAuthority::Certificate.new
  server.subject.common_name = $domain
  server.serial_number.number = rand(3..100000)
  server.parent = root
  server.key_material.generate_key
  server.sign!
  server
end

def client_certificate(root)
  client = CertificateAuthority::Certificate.new
  client.subject.common_name = $domain
  client.serial_number.number = 2
  client.parent = root

  client.key_material.generate_key

  signing_profile = {
    "extensions" => {
      "extendedKeyUsage" => {
        "usage" => [ "clientAuth" ]
      }
    }
  }

  client.sign!(signing_profile)
  client
end

root   = certificate_authority
server = server_certificate(root)
client = client_certificate(root)

[
  # You can reuse this file to generate more certs
  ['ca/key.pem',  root.key_material.private_key],
  ['ca/cert.pem', root.to_pem],

  # Those are default filenames expected by Docker
  ['ca.pem',   root.to_pem],
  ['key.pem',  client.key_material.private_key],
  ['cert.pem', client.to_pem],

  # Those files are supposed to be uploaded to server
  ["#{$domain}/ca.pem",   root.to_pem],
  ["#{$domain}/key.pem",  server.key_material.private_key],
  ["#{$domain}/cert.pem", server.to_pem]
].each do |name, contents|
  path = File.join($certs_path, name)
  FileUtils.mkdir_p(File.dirname(path))
  File.write(path, contents)
  File.chmod(0600, path)
end

puts "CA certificates are in #{$certs_path}/ca"
puts "Client certificates are in #{$certs_path}"
puts "Server certificates are in #{$certs_path}/#{$domain}"


text:
package org.displaytag.util;

import javax.servlet.jsp.PageContext;

/**
 * RequestHelperFactory interface.
 *

 * Users can specify a custom RequestHelperFactory implementation in displaytag.properties.
 *

 * A custom RequestHelperFactory can return a different RequestHelper implementation (the
 * {@link DefaultRequestHelperFactory}returns instaces of {@link DefaultRequestHelper})
 *
 * @author Fabrizio Giustina
 *
 * @version $Revision$ ($Author$)
 */
public interface RequestHelperFactory {

    /**
     * returns a RequestHelper instance for a given request.
     *
     * @param pageContext
     *            PageContext passed by the tag
     *
     * @return RequestHelper instance
     */
    RequestHelper getRequestHelperInstance(PageContext pageContext);

}