<commit_before>import choc, {set_content, DOM, on} from "https://rosuav.github.io/shed/chocfactory.js";
const {BR, CODE, TABLE, TR, TD, INPUT, SELECT, OPTION, SPAN} = choc;

//TODO: Crib these from the files somehow so they don't have to be updated.
const machines = {
	constructor: {
		name: "Constructor",
		input: "s",
		output: "s",
		cost: 4, //MW, or MJ/second
	},
	assembler: {
		name: "Assembler",
		input: "ss",
		output: "s",
		cost: 15,
	},
	refinery: {
		name: "Refinery",
		input: "sf",
		output: "sf",
		cost: 30,
	},
};
const solid_resources = {
	None: {sink: 0, name: "None"},
	FlowerPetals: {sink: 10, energy: 100, name: "Flower Petals"},
	Leaves: {sink: 3, energy: 15, name: "Leaves"},
	GenericBiomass: {sink: 12, energy: 180, name: "Biomass"},
	Biofuel: {sink: 48, energy: 450, name: "Solid Biofuel"},
	OreIron: {sink: 1, name: "Iron Ore"},
	IronIngot: {sink: 2, name: "Iron Ingot"},
	IronPlate: {sink: 6, name: "Iron Plate"},
	Plastic: {sink: 75, name: "Plastic"},
	SteelIngot: {sink: 8, name: "Steel Ingot"},
	CopperIngot: {sink: 6, name: "Copper Ingot"},
	GoldIngot: {sink: 42, name: "Caterium Ingot"},
	Wire: {sink: 6, name: "Wire"},
};
//Sink values of fluids are defined by their packaged equivalents, minus 60 for
//the package itself. This completely discounts any processing value from the
//package/unpackage process, since it's reversible.
const fluid_resources = {
	None: {sink: 0, name: "None"},
	Water: {sink: 70, name: "Water"},
	LiquidBiofuel: {sink: 310, energy: 750, name: "Liquid Biofuel"},
};
const resources = {...solid_resources, ...fluid_resources};
const resource_ids = {
	s: Object.keys(solid_resources),
	f: Object.keys(fluid_resources),
	a: Object.keys(resources),
};

const recipes = [
	{
		from: {IronIngot: 3},
		to: {IronPlate: 2},
		machine: "constructor",
		time: 6,
	},
	{
		name: "Coated Iron Plate",
		from: {IronIngot: 10, Plastic: 2},
		to: {IronPlate: 15},
		machine: "assembler",
		time: 12,
	},
	{
		name: "Steel Coated Plate",
		from: {SteelIngot: 3, Plastic: 2},
		to: {IronPlate: 18},
		machine: "assembler",
		time: 24,
	},
	{
		from: {CopperIngot: 1},
		to: {Wire: 2},
		machine: "constructor",
		time: 4,
	},
	{
		name: "Fused Wire",
		from: {CopperIngot: 4, GoldIngot: 1},
		to: {Wire: 30},
		machine: "assembler",
		time: 20,
	},
	{
		name: "Iron Wire",
		from: {IronIngot: 5},
		to: {Wire: 9},
		machine: "constructor",
		time: 24,
	},
	{
		name: "Caterium Wire",
		from: {GoldIngot: 1},
		to: {Wire: 8},
		machine: "constructor",
		time: 4,
	},
];

let machine = null;

function describe_ratio(value, base) {
	if (!base) return "";
	let ratio = value / base;
	if (ratio < 0.5) return " (1 : " + (1/ratio).toFixed(2) + ")";
	if (ratio < 1) return " (-" + Math.round(100 - ratio * 100) + "%)";
	if (ratio === 1.0) return " (same)";
	if (ratio < 2) return " (+" + Math.round(ratio * 100 - 100) + "%)";
	return " (" + ratio.toFixed(2) + " : 1)";
}

let recipeinfo = { };
//Call this on any change, whatsoever. The only info retained from one call to
//another is what update_totals populates into recipeinfo.
function update_recipes() {
	const rows = [];
	recipes.forEach(r => {
		//...
	});
	rows.push(TR({className: "highlight"}, [
		TD("Your Recipe"),
		TD(machine.name),
		TD([].concat(...recipeinfo.input_items.map(i => [CODE(i), BR()]))),
		TD([].concat(...recipeinfo.output_items.map(i => [CODE(i), BR()]))),
		TD(recipeinfo.input_sink + " to " + recipeinfo.output_sink + describe_ratio(recipeinfo.output_sink, recipeinfo.input_sink)),
		TD(recipeinfo.output_energy ?
		   recipeinfo.input_energy + " to " + recipeinfo.output_energy + describe_ratio(recipeinfo.output_energy, recipeinfo.input_energy)
		   : ""
		),
	]));
	set_content("#recipes tbody", rows);
}

function update_totals() {
	let base_sink = -1, base_energy = -1;
	recipeinfo = { };
	["input", "output"].forEach(kwd => {
		let sink = 0, energy = 0;
		const items = [];
		for (let i = 0; i < machine[kwd].length; ++i) {
			const res = resources[DOM("#" + kwd + i).value];
			if (!res) {console.warn("Borked " + kwd, DOM("#" + kwd + i).value); continue;}
			const qty = DOM("#" + kwd + "qty" + i).value|0;
			sink += (res.sink||0) * qty;
			energy += (res.energy||0) * qty;
			if (res.sink) items.push(qty + " " + res.name);
		}
		recipeinfo[kwd + "_items"] = items;
		recipeinfo[kwd + "_sink"] = sink;
		recipeinfo[kwd + "_energy"] = energy;
		let desc = sink + " sink value";
		if (base_sink === -1) base_sink = sink;
		else desc += describe_ratio(sink, base_sink);
		if (energy) {
			desc += `, ${energy} MJ`;
			if (base_energy === -1) base_energy = energy;
			else desc += describe_ratio(energy, base_energy);
		}
		set_content("#" + kwd + "_total", desc);
	});
	update_recipes();
}
on("input", "#recipe input,select", update_totals);

function RESOURCE(attrs, type) {
	//TODO: optgroup these as appropriate
	return SELECT(attrs, resource_ids[type || "a"].map(r => OPTION({value: r}, resources[r].name)));
}

function select_machine(id) {
	machine = machines[id];
	const rows = [];
	["Input", "Output"].forEach(lbl => {
		const kwd = lbl.toLowerCase();
		for (let i = 0; i < machine[kwd].length; ++i)
			rows.push(TR([TD(lbl), TD([RESOURCE({id: kwd + i}, machine[kwd][i]), INPUT({id: kwd + "qty" + i, type: "number", value: 1})])]));
		rows.push(TR([TD("Total"), TD({id: kwd + "_total"})]));
		rows.push(TR(TD({colSpan: 2})));
	});
	rows.push(TR([TD("Time"), TD([INPUT({id: "time", type: "number", value: 1}), " = ", SPAN({id: "timedesc"}, "60/min")])]));
	const stuff = [TABLE({border: 1}, rows)];
	set_content("#recipe", stuff);
	update_totals();
}
on("click", 'input[name="machine"]', e => select_machine(e.match.value));
select_machine("constructor");

on("input", "#time", e => {
	//TODO: Add per-minute descriptions for each input and output
	const permin = 60 / e.match.value;
	if (permin === Math.floor(permin)) set_content("#timedesc", permin + "/min");
	else set_content("#timedesc", permin.toFixed(3) + "/min");
});<commit_msg>Retain resource objects rather than descriptions (and only if there's quantity)<commit_after>import choc, {set_content, DOM, on} from "https://rosuav.github.io/shed/chocfactory.js";
const {BR, CODE, TABLE, TR, TD, INPUT, SELECT, OPTION, SPAN} = choc;

//TODO: Crib these from the files somehow so they don't have to be updated.
const machines = {
	constructor: {
		name: "Constructor",
		input: "s",
		output: "s",
		cost: 4, //MW, or MJ/second
	},
	assembler: {
		name: "Assembler",
		input: "ss",
		output: "s",
		cost: 15,
	},
	refinery: {
		name: "Refinery",
		input: "sf",
		output: "sf",
		cost: 30,
	},
};
const solid_resources = {
	None: {sink: 0, name: "None"},
	FlowerPetals: {sink: 10, energy: 100, name: "Flower Petals"},
	Leaves: {sink: 3, energy: 15, name: "Leaves"},
	GenericBiomass: {sink: 12, energy: 180, name: "Biomass"},
	Biofuel: {sink: 48, energy: 450, name: "Solid Biofuel"},
	OreIron: {sink: 1, name: "Iron Ore"},
	IronIngot: {sink: 2, name: "Iron Ingot"},
	IronPlate: {sink: 6, name: "Iron Plate"},
	Plastic: {sink: 75, name: "Plastic"},
	SteelIngot: {sink: 8, name: "Steel Ingot"},
	CopperIngot: {sink: 6, name: "Copper Ingot"},
	GoldIngot: {sink: 42, name: "Caterium Ingot"},
	Wire: {sink: 6, name: "Wire"},
};
//Sink values of fluids are defined by their packaged equivalents, minus 60 for
//the package itself. This completely discounts any processing value from the
//package/unpackage process, since it's reversible.
const fluid_resources = {
	None: {sink: 0, name: "None"},
	Water: {sink: 70, name: "Water"},
	LiquidBiofuel: {sink: 310, energy: 750, name: "Liquid Biofuel"},
};
const resources = {...solid_resources, ...fluid_resources};
const resource_ids = {
	s: Object.keys(solid_resources),
	f: Object.keys(fluid_resources),
	a: Object.keys(resources),
};

const recipes = [
	{
		from: {IronIngot: 3},
		to: {IronPlate: 2},
		machine: "constructor",
		time: 6,
	},
	{
		name: "Coated Iron Plate",
		from: {IronIngot: 10, Plastic: 2},
		to: {IronPlate: 15},
		machine: "assembler",
		time: 12,
	},
	{
		name: "Steel Coated Plate",
		from: {SteelIngot: 3, Plastic: 2},
		to: {IronPlate: 18},
		machine: "assembler",
		time: 24,
	},
	{
		from: {CopperIngot: 1},
		to: {Wire: 2},
		machine: "constructor",
		time: 4,
	},
	{
		name: "Fused Wire",
		from: {CopperIngot: 4, GoldIngot: 1},
		to: {Wire: 30},
		machine: "assembler",
		time: 20,
	},
	{
		name: "Iron Wire",
		from: {IronIngot: 5},
		to: {Wire: 9},
		machine: "constructor",
		time: 24,
	},
	{
		name: "Caterium Wire",
		from: {GoldIngot: 1},
		to: {Wire: 8},
		machine: "constructor",
		time: 4,
	},
];

let machine = null;

function describe_ratio(value, base) {
	if (!base) return "";
	let ratio = value / base;
	if (ratio < 0.5) return " (1 : " + (1/ratio).toFixed(2) + ")";
	if (ratio < 1) return " (-" + Math.round(100 - ratio * 100) + "%)";
	if (ratio === 1.0) return " (same)";
	if (ratio < 2) return " (+" + Math.round(ratio * 100 - 100) + "%)";
	return " (" + ratio.toFixed(2) + " : 1)";
}

let recipeinfo = { };
//Call this on any change, whatsoever. The only info retained from one call to
//another is what update_totals populates into recipeinfo.
function update_recipes() {
	const rows = [];
	recipes.forEach(r => {
		//...
	});
	rows.push(TR({className: "highlight"}, [
		TD("Your Recipe"),
		TD(machine.name),
		TD([].concat(...recipeinfo.input_items.map(i => [CODE(i[0] + " " + i[1].name), BR()]))),
		TD([].concat(...recipeinfo.output_items.map(i => [CODE(i[0] + " " + i[1].name), BR()]))),
		TD(recipeinfo.input_sink + " to " + recipeinfo.output_sink + describe_ratio(recipeinfo.output_sink, recipeinfo.input_sink)),
		TD(recipeinfo.output_energy ?
		   recipeinfo.input_energy + " to " + recipeinfo.output_energy + describe_ratio(recipeinfo.output_energy, recipeinfo.input_energy)
		   : ""
		),
	]));
	set_content("#recipes tbody", rows);
}

function update_totals() {
	let base_sink = -1, base_energy = -1;
	recipeinfo = { };
	["input", "output"].forEach(kwd => {
		let sink = 0, energy = 0;
		const items = [];
		for (let i = 0; i < machine[kwd].length; ++i) {
			const res = resources[DOM("#" + kwd + i).value];
			if (!res) {console.warn("Borked " + kwd, DOM("#" + kwd + i).value); continue;}
			const qty = DOM("#" + kwd + "qty" + i).value|0;
			sink += (res.sink||0) * qty;
			energy += (res.energy||0) * qty;
			if (res.sink && qty) items.push([qty, res]);
		}
		recipeinfo[kwd + "_items"] = items;
		recipeinfo[kwd + "_sink"] = sink;
		recipeinfo[kwd + "_energy"] = energy;
		let desc = sink + " sink value";
		if (base_sink === -1) base_sink = sink;
		else desc += describe_ratio(sink, base_sink);
		if (energy) {
			desc += `, ${energy} MJ`;
			if (base_energy === -1) base_energy = energy;
			else desc += describe_ratio(energy, base_energy);
		}
		set_content("#" + kwd + "_total", desc);
	});
	update_recipes();
}
on("input", "#recipe input,select", update_totals);

function RESOURCE(attrs, type) {
	//TODO: optgroup these as appropriate
	return SELECT(attrs, resource_ids[type || "a"].map(r => OPTION({value: r}, resources[r].name)));
}

function select_machine(id) {
	machine = machines[id];
	const rows = [];
	["Input", "Output"].forEach(lbl => {
		const kwd = lbl.toLowerCase();
		for (let i = 0; i < machine[kwd].length; ++i)
			rows.push(TR([TD(lbl), TD([RESOURCE({id: kwd + i}, machine[kwd][i]), INPUT({id: kwd + "qty" + i, type: "number", value: 1})])]));
		rows.push(TR([TD("Total"), TD({id: kwd + "_total"})]));
		rows.push(TR(TD({colSpan: 2})));
	});
	rows.push(TR([TD("Time"), TD([INPUT({id: "time", type: "number", value: 1}), " = ", SPAN({id: "timedesc"}, "60/min")])]));
	const stuff = [TABLE({border: 1}, rows)];
	set_content("#recipe", stuff);
	update_totals();
}
on("click", 'input[name="machine"]', e => select_machine(e.match.value));
select_machine("constructor");

on("input", "#time", e => {
	//TODO: Add per-minute descriptions for each input and output
	const permin = 60 / e.match.value;
	if (permin === Math.floor(permin)) set_content("#timedesc", permin + "/min");
	else set_content("#timedesc", permin.toFixed(3) + "/min");
});<|endoftext|>


<commit_before>/**
 *  Setup Pagr
 */
var pagr = (function() {
    function init( config )
    {
        // Init pages
        initPages();

        // Set default config values
        initConfig( config );

        // Init links
        $( '.' + config.linkName ).click( function( event ) {
            event.preventDefault();
            goToPage( $( event.target ).attr( 'href' ), config );
        } );

        window.onpopstate = function( event ) {
            if( event.state )
                scrollToPage( event.state.page, config );
        };
    }

    function initPages()
    {
        $( '.pagecontainer-horiz' ).each( function( index, element ) {
            var pages = $( element ).children( '.page' );
            $( element ).width( ( 100 * pages.length ) + '%' );

            pages.each( function( index, element ) {
                $( element ).width( ( 100 / pages.length ) + '%' );
            } );
        } );

        $( '.pagecontainer-vert' ).each( function( index, element ) {
            var pages = $( element ).children( '.page' );
            $( element ).height( ( 100 * pages.length ) + '%' );

            pages.each( function( index, element ) {
                $( element ).height( ( 100 / pages.length ) + '%' );
            } );
        } );
    }

    /**
     *  Initializes config with default settings
     */
    function initConfig( config )
    {
        // Save time, scroll instantly, reload time
        var time = config.scrollTime || 400;

        if( config.initialPage !== undefined )
        {
            config.scrollTime = 0;
            goToPage( config.initialPage, config );
        }

        config.scrollTime = time;

        if( config.scrollEase === undefined )
            config.scrollEase = "easeOutQuad";

        if( config.linkName === undefined )
            config.linkName = "pagrlink";
    }

    /**
     *  Scroll to the specified page
     */
    function goToPage( pageName, config )
    {
        // If no pages, just go to home
        if( pageName.length === 0 )
            return;

        // Add current state to history
        window.history.pushState( { page: pageName }, document.title, pageName );

        // Scroll to the proper page
        scrollToPage( pageName, config );
    }

    /**
     *  Actually start the scroll to the page
     */
    function scrollToPage( pageNames, config )
    {
        /**
         *  Get the index of a jQuery object
         */
        function getPageIndex( page )
        {
            var count = 0;
            for( var elem = page[ 0 ]; ( elem = elem.previousSibling ) !== null; )
                if( $( elem ).hasClass( 'page' ) )
                    ++count;
            return count;
        }

        // Convert pageNames to array
        if( typeof pageNames === "string" )
            pageNames = pageNames.split( '/' ).filter( function( obj ) { return obj.length > 0; } );

        // Get page being scrolled to
        var scrollPage = $( '[class*="pagecontainer-"] > .page#' + pageNames[ 0 ] ),
            options = { };

        // Set which direction to scroll in, and how far to go
        if( scrollPage.parent().hasClass( 'pagecontainer-horiz' ) )
        {
            options.left = -( getPageIndex( scrollPage ) * scrollPage.width() );
        }
        else if( scrollPage.parent().hasClass( 'pagecontainer-vert' ) )
        {
            options.top = -( getPageIndex( scrollPage ) * scrollPage.height() );
        }

        // Scroll to page
        $( scrollPage.parent() ).animate(
            // Scroll container so that current view is selected
            options,
            // Scroll over 400ms
            config.scrollTime,
            // Easing
            config.scrollEase,
            // If page has special scroll, use that.
            function() {
                scrollToPage( pageNames.splice( 1, 1 ), config );
            }
        );
    }

    return init;
} )();
<commit_msg>Allowed for no config option passed.<commit_after>/**
 *  Setup Pagr
 */
var pagr = (function() {
    function init( config )
    {
        // Init pages
        initPages();

        // Init config
        if( typeof config === "undefined" )
            config = { };

        // Set default config values
        initConfig( config );

        // Init links
        $( '.' + config.linkName ).click( function( event ) {
            event.preventDefault();
            goToPage( $( event.target ).attr( 'href' ), config );
        } );

        window.onpopstate = function( event ) {
            if( event.state )
                scrollToPage( event.state.page, config );
        };
    }

    function initPages()
    {
        $( '.pagecontainer-horiz' ).each( function( index, element ) {
            var pages = $( element ).children( '.page' );
            $( element ).width( ( 100 * pages.length ) + '%' );

            pages.each( function( index, element ) {
                $( element ).width( ( 100 / pages.length ) + '%' );
            } );
        } );

        $( '.pagecontainer-vert' ).each( function( index, element ) {
            var pages = $( element ).children( '.page' );
            $( element ).height( ( 100 * pages.length ) + '%' );

            pages.each( function( index, element ) {
                $( element ).height( ( 100 / pages.length ) + '%' );
            } );
        } );
    }

    /**
     *  Initializes config with default settings
     */
    function initConfig( config )
    {
        // Save time, scroll instantly, reload time
        var time = config.scrollTime || 400;

        if( config.initialPage !== undefined )
        {
            config.scrollTime = 0;
            goToPage( config.initialPage, config );
        }

        config.scrollTime = time;

        if( config.scrollEase === undefined )
            config.scrollEase = "easeOutQuad";

        if( config.linkName === undefined )
            config.linkName = "pagrlink";
    }

    /**
     *  Scroll to the specified page
     */
    function goToPage( pageName, config )
    {
        // If no pages, just go to home
        if( pageName.length === 0 )
            return;

        // Add current state to history
        window.history.pushState( { page: pageName }, document.title, pageName );

        // Scroll to the proper page
        scrollToPage( pageName, config );
    }

    /**
     *  Actually start the scroll to the page
     */
    function scrollToPage( pageNames, config )
    {
        /**
         *  Get the index of a jQuery object
         */
        function getPageIndex( page )
        {
            var count = 0;
            for( var elem = page[ 0 ]; ( elem = elem.previousSibling ) !== null; )
                if( $( elem ).hasClass( 'page' ) )
                    ++count;
            return count;
        }

        // Convert pageNames to array
        if( typeof pageNames === "string" )
            pageNames = pageNames.split( '/' ).filter( function( obj ) { return obj.length > 0; } );

        // Get page being scrolled to
        var scrollPage = $( '[class*="pagecontainer-"] > .page#' + pageNames[ 0 ] ),
            options = { };

        // Set which direction to scroll in, and how far to go
        if( scrollPage.parent().hasClass( 'pagecontainer-horiz' ) )
        {
            options.left = -( getPageIndex( scrollPage ) * scrollPage.width() );
        }
        else if( scrollPage.parent().hasClass( 'pagecontainer-vert' ) )
        {
            options.top = -( getPageIndex( scrollPage ) * scrollPage.height() );
        }

        // Scroll to page
        $( scrollPage.parent() ).animate(
            // Scroll container so that current view is selected
            options,
            // Scroll over 400ms
            config.scrollTime,
            // Easing
            config.scrollEase,
            // If page has special scroll, use that.
            function() {
                scrollToPage( pageNames.splice( 1, 1 ), config );
            }
        );
    }

    return init;
} )();
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var Mix = require('laravel-mix').config;
var plugins = require('laravel-mix').plugins;

/*
 |--------------------------------------------------------------------------
 | Mix Initialization
 |--------------------------------------------------------------------------
 |
 | As our first step, we'll require the project's Laravel Mix file
 | and record the user's requested compilation and build steps.
 | Once those steps have been recorded, we may get to work.
 |
 */

Mix.initialize();

/*
 |--------------------------------------------------------------------------
 | Webpack Context
 |--------------------------------------------------------------------------
 |
 | This prop will determine the appropriate context, when running Webpack.
 | Since you have the option of publishing this webpack.config.js file
 | to your project root, we will dynamically set the path for you.
 |
 */

module.exports.context = Mix.Paths.root();

/*
 |--------------------------------------------------------------------------
 | Webpack Entry
 |--------------------------------------------------------------------------
 |
 | We'll first specify the entry point for Webpack. By default, we'll
 | assume a single bundled file, but you may call Mix.extract()
 | to make a separate bundle specifically for vendor libraries.
 |
 */

module.exports.entry = Mix.entry();

/*
 |--------------------------------------------------------------------------
 | Webpack Output
 |--------------------------------------------------------------------------
 |
 | Webpack naturally requires us to specify our desired output path and
 | file name. We'll simply echo what you passed to with Mix.js().
 | Note that, for Mix.version(), we'll properly hash the file.
 |
 */

module.exports.output = Mix.output();

/*
 |--------------------------------------------------------------------------
 | Rules
 |--------------------------------------------------------------------------
 |
 | Webpack rules allow us to register any number of loaders and options.
 | Out of the box, we'll provide a handful to get you up and running
 | as quickly as possible, though feel free to add to this list.
 |
 */

module.exports.module = {
    rules: [
        {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: {
                    js: 'babel-loader' + Mix.babelConfig(),
                    scss: 'vue-style-loader!css-loader!sass-loader',
                    sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
                },

                postcss: [
                    require('autoprefixer')
                ]
            }
        },

        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader' + Mix.babelConfig()
        },

        {
            test: /\.(png|jpg|gif)$/,
            loader: 'file-loader',
            options: {
                name: 'images/[name].[ext]?[hash]',
                publicPath: '/'
            }
        },

        {
            test: /\.(woff2?|ttf|eot|svg|otf)$/,
            loader: 'file-loader',
            options: {
                name: 'fonts/[name].[ext]?[hash]',
                publicPath: '/'
            }
        }
    ]
};

if (Mix.preprocessors) {
    Mix.preprocessors.forEach(toCompile => {
        let extractPlugin = new plugins.ExtractTextPlugin(
            Mix.cssOutput(toCompile)
        );

        let sourceMap = Mix.sourcemaps ? '?sourceMap' : '';

        module.exports.module.rules.push({
            test: new RegExp(toCompile.src.path.replace(/\\/g, '\\\\') + '$'),
            loader: extractPlugin.extract({
                fallbackLoader: 'style-loader',
                loader: [
                    'css-loader' + sourceMap,
                    'postcss-loader' + sourceMap
                ].concat(toCompile.type == 'sass' ? [
                    'resolve-url-loader' + sourceMap,
                    'sass-loader?sourceMap&precision=8'
                ] : [
                    'less-loader' + sourceMap
                ])
            })
        });

        module.exports.plugins = (module.exports.plugins || []).concat(extractPlugin);
    });
}

/*
 |--------------------------------------------------------------------------
 | Resolve
 |--------------------------------------------------------------------------
 |
 | Here, we may set any options/aliases that affect Webpack's resolving
 | of modules. To begin, we will provide the necessary Vue alias to
 | load the Vue common library. You may delete this, if needed.
 |
 */

module.exports.resolve = {
    extensions: ['*', '.js', '.jsx', '.vue'],

    alias: {
        'vue$': 'vue/dist/vue.common.js'
    }
};

/*
 |--------------------------------------------------------------------------
 | Stats
 |--------------------------------------------------------------------------
 |
 | By default, Webpack spits a lot of information out to the terminal,
 | each you time you compile. Let's keep things a bit more minimal
 | and hide a few of those bits and pieces. Adjust as you wish.
 |
 */

module.exports.stats = {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errors: false
};

module.exports.performance = { hints: false };

/*
 |--------------------------------------------------------------------------
 | Devtool
 |--------------------------------------------------------------------------
 |
 | Sourcemaps allow us to access our original source code within the
 | browser, even if we're serving a bundled script or stylesheet.
 | You may activate sourcemaps, by adding Mix.sourceMaps().
 |
 */

module.exports.devtool = Mix.sourcemaps;

/*
 |--------------------------------------------------------------------------
 | Webpack Dev Server Configuration
 |--------------------------------------------------------------------------
 |
 | If you want to use that flashy hot module replacement feature, then
 | we've got you covered. Here, we'll set some basic initial config
 | for the Node server. You very likely won't want to edit this.
 |
 */
module.exports.devServer = {
    historyApiFallback: true,
    noInfo: true,
    compress: true
};

/*
 |--------------------------------------------------------------------------
 | Plugins
 |--------------------------------------------------------------------------
 |
 | Lastly, we'll register a number of plugins to extend and configure
 | Webpack. To get you started, we've included a handful of useful
 | extensions, for versioning, OS notifications, and much more.
 |
 */

module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.ProvidePlugin(Mix.autoload || {
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery'
    }),

    new plugins.FriendlyErrorsWebpackPlugin(),

    new plugins.StatsWriterPlugin({
        filename: 'mix-manifest.json',
        transform: Mix.manifest.transform,
    }),

    new plugins.WebpackMd5HashPlugin(),

    new webpack.LoaderOptionsPlugin({
        minimize: Mix.inProduction,
        options: {
            postcss: [
                require('autoprefixer')
            ],
            context: __dirname,
            output: { path: './' }
        }
    })
]);

if (Mix.notifications) {
    module.exports.plugins.push(
        new plugins.WebpackNotifierPlugin({
            title: 'Laravel Mix',
            alwaysNotify: true,
            contentImage: Mix.Paths.root('node_modules/laravel-mix/icons/laravel.png')
        })
    );
}

module.exports.plugins.push(
    new plugins.WebpackOnBuildPlugin(
        stats => Mix.events.fire('build', stats)
    )
);

if (Mix.versioning) {
    Mix.versioning.record();

    module.exports.plugins.push(
        new plugins.WebpackOnBuildPlugin(() => {
            Mix.versioning.prune(Mix.publicPath);
        })
    );
}

if (Mix.combine || Mix.minify) {
    module.exports.plugins.push(
        new plugins.WebpackOnBuildPlugin(() => {
            Mix.concatenateAll().minifyAll();
        })
    );
}

if (Mix.copy) {
    Mix.copy.forEach(copy => {
        module.exports.plugins.push(
            new plugins.CopyWebpackPlugin([copy])
        );
    });
}

if (Mix.extract) {
    module.exports.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
            names: Mix.entryBuilder.extractions.concat([
                path.join(Mix.js.base, 'manifest')
            ]),
            minChunks: Infinity
        })
    );
}

if (Mix.inProduction) {
    module.exports.plugins = module.exports.plugins.concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),

        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        })
    ]);
}

/*
 |--------------------------------------------------------------------------
 | Mix Finalizing
 |--------------------------------------------------------------------------
 |
 | Now that we've declared the entirety of our Webpack configuration, the
 | final step is to scan for any custom configuration in the Mix file.
 | If mix.webpackConfig() is called, we'll merge it in, and build!
 |
 */
Mix.finalize(module.exports);
<commit_msg>Add rule for compile CSS files - closes #243<commit_after>var path = require('path');
var webpack = require('webpack');
var Mix = require('laravel-mix').config;
var plugins = require('laravel-mix').plugins;

/*
 |--------------------------------------------------------------------------
 | Mix Initialization
 |--------------------------------------------------------------------------
 |
 | As our first step, we'll require the project's Laravel Mix file
 | and record the user's requested compilation and build steps.
 | Once those steps have been recorded, we may get to work.
 |
 */

Mix.initialize();

/*
 |--------------------------------------------------------------------------
 | Webpack Context
 |--------------------------------------------------------------------------
 |
 | This prop will determine the appropriate context, when running Webpack.
 | Since you have the option of publishing this webpack.config.js file
 | to your project root, we will dynamically set the path for you.
 |
 */

module.exports.context = Mix.Paths.root();

/*
 |--------------------------------------------------------------------------
 | Webpack Entry
 |--------------------------------------------------------------------------
 |
 | We'll first specify the entry point for Webpack. By default, we'll
 | assume a single bundled file, but you may call Mix.extract()
 | to make a separate bundle specifically for vendor libraries.
 |
 */

module.exports.entry = Mix.entry();

/*
 |--------------------------------------------------------------------------
 | Webpack Output
 |--------------------------------------------------------------------------
 |
 | Webpack naturally requires us to specify our desired output path and
 | file name. We'll simply echo what you passed to with Mix.js().
 | Note that, for Mix.version(), we'll properly hash the file.
 |
 */

module.exports.output = Mix.output();

/*
 |--------------------------------------------------------------------------
 | Rules
 |--------------------------------------------------------------------------
 |
 | Webpack rules allow us to register any number of loaders and options.
 | Out of the box, we'll provide a handful to get you up and running
 | as quickly as possible, though feel free to add to this list.
 |
 */

module.exports.module = {
    rules: [
        {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
                loaders: {
                    js: 'babel-loader' + Mix.babelConfig(),
                    scss: 'vue-style-loader!css-loader!sass-loader',
                    sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
                },

                postcss: [
                    require('autoprefixer')
                ]
            }
        },

        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader' + Mix.babelConfig()
        },

        {
            test: /\.css$/,
            loaders: ['style-loader', 'css-loader']
        },

        {
            test: /\.(png|jpg|gif)$/,
            loader: 'file-loader',
            options: {
                name: 'images/[name].[ext]?[hash]',
                publicPath: '/'
            }
        },

        {
            test: /\.(woff2?|ttf|eot|svg|otf)$/,
            loader: 'file-loader',
            options: {
                name: 'fonts/[name].[ext]?[hash]',
                publicPath: '/'
            }
        }
    ]
};

if (Mix.preprocessors) {
    Mix.preprocessors.forEach(toCompile => {
        let extractPlugin = new plugins.ExtractTextPlugin(
            Mix.cssOutput(toCompile)
        );

        let sourceMap = Mix.sourcemaps ? '?sourceMap' : '';

        module.exports.module.rules.push({
            test: new RegExp(toCompile.src.path.replace(/\\/g, '\\\\') + '$'),
            loader: extractPlugin.extract({
                fallbackLoader: 'style-loader',
                loader: [
                    'css-loader' + sourceMap,
                    'postcss-loader' + sourceMap
                ].concat(toCompile.type == 'sass' ? [
                    'resolve-url-loader' + sourceMap,
                    'sass-loader?sourceMap&precision=8'
                ] : [
                    'less-loader' + sourceMap
                ])
            })
        });

        module.exports.plugins = (module.exports.plugins || []).concat(extractPlugin);
    });
}

/*
 |--------------------------------------------------------------------------
 | Resolve
 |--------------------------------------------------------------------------
 |
 | Here, we may set any options/aliases that affect Webpack's resolving
 | of modules. To begin, we will provide the necessary Vue alias to
 | load the Vue common library. You may delete this, if needed.
 |
 */

module.exports.resolve = {
    extensions: ['*', '.js', '.jsx', '.vue'],

    alias: {
        'vue$': 'vue/dist/vue.common.js'
    }
};

/*
 |--------------------------------------------------------------------------
 | Stats
 |--------------------------------------------------------------------------
 |
 | By default, Webpack spits a lot of information out to the terminal,
 | each you time you compile. Let's keep things a bit more minimal
 | and hide a few of those bits and pieces. Adjust as you wish.
 |
 */

module.exports.stats = {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errors: false
};

module.exports.performance = { hints: false };

/*
 |--------------------------------------------------------------------------
 | Devtool
 |--------------------------------------------------------------------------
 |
 | Sourcemaps allow us to access our original source code within the
 | browser, even if we're serving a bundled script or stylesheet.
 | You may activate sourcemaps, by adding Mix.sourceMaps().
 |
 */

module.exports.devtool = Mix.sourcemaps;

/*
 |--------------------------------------------------------------------------
 | Webpack Dev Server Configuration
 |--------------------------------------------------------------------------
 |
 | If you want to use that flashy hot module replacement feature, then
 | we've got you covered. Here, we'll set some basic initial config
 | for the Node server. You very likely won't want to edit this.
 |
 */
module.exports.devServer = {
    historyApiFallback: true,
    noInfo: true,
    compress: true
};

/*
 |--------------------------------------------------------------------------
 | Plugins
 |--------------------------------------------------------------------------
 |
 | Lastly, we'll register a number of plugins to extend and configure
 | Webpack. To get you started, we've included a handful of useful
 | extensions, for versioning, OS notifications, and much more.
 |
 */

module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.ProvidePlugin(Mix.autoload || {
        jQuery: 'jquery',
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery'
    }),

    new plugins.FriendlyErrorsWebpackPlugin(),

    new plugins.StatsWriterPlugin({
        filename: 'mix-manifest.json',
        transform: Mix.manifest.transform,
    }),

    new plugins.WebpackMd5HashPlugin(),

    new webpack.LoaderOptionsPlugin({
        minimize: Mix.inProduction,
        options: {
            postcss: [
                require('autoprefixer')
            ],
            context: __dirname,
            output: { path: './' }
        }
    })
]);

if (Mix.notifications) {
    module.exports.plugins.push(
        new plugins.WebpackNotifierPlugin({
            title: 'Laravel Mix',
            alwaysNotify: true,
            contentImage: Mix.Paths.root('node_modules/laravel-mix/icons/laravel.png')
        })
    );
}

module.exports.plugins.push(
    new plugins.WebpackOnBuildPlugin(
        stats => Mix.events.fire('build', stats)
    )
);

if (Mix.versioning) {
    Mix.versioning.record();

    module.exports.plugins.push(
        new plugins.WebpackOnBuildPlugin(() => {
            Mix.versioning.prune(Mix.publicPath);
        })
    );
}

if (Mix.combine || Mix.minify) {
    module.exports.plugins.push(
        new plugins.WebpackOnBuildPlugin(() => {
            Mix.concatenateAll().minifyAll();
        })
    );
}

if (Mix.copy) {
    Mix.copy.forEach(copy => {
        module.exports.plugins.push(
            new plugins.CopyWebpackPlugin([copy])
        );
    });
}

if (Mix.extract) {
    module.exports.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
            names: Mix.entryBuilder.extractions.concat([
                path.join(Mix.js.base, 'manifest')
            ]),
            minChunks: Infinity
        })
    );
}

if (Mix.inProduction) {
    module.exports.plugins = module.exports.plugins.concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),

        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        })
    ]);
}

/*
 |--------------------------------------------------------------------------
 | Mix Finalizing
 |--------------------------------------------------------------------------
 |
 | Now that we've declared the entirety of our Webpack configuration, the
 | final step is to scan for any custom configuration in the Mix file.
 | If mix.webpackConfig() is called, we'll merge it in, and build!
 |
 */
Mix.finalize(module.exports);
<|endoftext|>


<commit_before>var renderContext = require('raptor-render-context');
var Context = renderContext.Context;
var xmlUtil = require('raptor-xml/util');
var escapeXml = xmlUtil.escapeXml;
var escapeXmlAttr = xmlUtil.escapeXmlAttr;

function _getHandler(name) {
    var Handler = require(name);
    var instance;
    if (Handler.process || Handler.render) {
        instance = Handler;
    } else if (!(instance = Handler.instance)) {
        //See if an instance has already been created
        instance = Handler.instance = new Handler();    //If not, create and store a new instance
    }
    return instance;
}

function notEmpty(o) {
    if (Array.isArray(o) === true) {
        module.exports = o.length !== 0;
        return;
    }
    module.exports = o;
    return;
}

module.exports = {
    h: Context.classFunc,
    t: _getHandler,
    fv: function (array, callback) {
        if (!array) {
            return;
        }
        if (!array.forEach) {
            array = [array];
        }
        var i = 0;
        var len = array.length;
        var loopStatus = {
                getLength: function () {
                    return len;
                },
                isLast: function () {
                    return i === len - 1;
                },
                isFirst: function () {
                    return i === 0;
                },
                getIndex: function () {
                    return i;
                }
            };
        for (; i < len; i++) {
            var o = array[i];
            callback(o || '', loopStatus);
        }
    },
    f: require('raptor-util').forEach,
    fl: function (array, func) {
        if (array != null) {
            if (!Array.isArray(array)) {
                array = [array];
            }
            func(array, 0, array.length);
        }
    },
    fp: function (o, func) {
        if (!o) {
            return;
        }
        for (var k in o) {
            if (o.hasOwnProperty(k)) {
                func(k, o[k]);
            }
        }
    },
    e: function (o) {
        return !notEmpty(o);
    },
    ne: notEmpty,
    x: escapeXml,
    xa: escapeXmlAttr,
    nx: function (str) {
        return {
            toString: function () {
                return str;
            }
        };
    }
};<commit_msg>Fixed build helper after code conversion mishap<commit_after>var renderContext = require('raptor-render-context');
var Context = renderContext.Context;
var xmlUtil = require('raptor-xml/util');
var escapeXml = xmlUtil.escapeXml;
var escapeXmlAttr = xmlUtil.escapeXmlAttr;

function _getHandler(name) {
    var Handler = require(name);
    var instance;
    if (Handler.process || Handler.render) {
        instance = Handler;
    } else if (!(instance = Handler.instance)) {
        //See if an instance has already been created
        instance = Handler.instance = new Handler();    //If not, create and store a new instance
    }
    return instance;
}

function notEmpty(o) {
    if (Array.isArray(o) === true) {
        return o.length !== 0;
    }
    return o;
}

module.exports = {
    h: Context.classFunc,
    t: _getHandler,
    fv: function (array, callback) {
        if (!array) {
            return;
        }
        if (!array.forEach) {
            array = [array];
        }
        var i = 0;
        var len = array.length;
        var loopStatus = {
                getLength: function () {
                    return len;
                },
                isLast: function () {
                    return i === len - 1;
                },
                isFirst: function () {
                    return i === 0;
                },
                getIndex: function () {
                    return i;
                }
            };
        for (; i < len; i++) {
            var o = array[i];
            callback(o || '', loopStatus);
        }
    },
    f: require('raptor-util').forEach,
    fl: function (array, func) {
        if (array != null) {
            if (!Array.isArray(array)) {
                array = [array];
            }
            func(array, 0, array.length);
        }
    },
    fp: function (o, func) {
        if (!o) {
            return;
        }
        for (var k in o) {
            if (o.hasOwnProperty(k)) {
                func(k, o[k]);
            }
        }
    },
    e: function (o) {
        return !notEmpty(o);
    },
    ne: notEmpty,
    x: escapeXml,
    xa: escapeXmlAttr,
    nx: function (str) {
        return {
            toString: function () {
                return str;
            }
        };
    }
};<|endoftext|>


<commit_before>import EventEmitter from 'events';

import MessengerClient from './lib/messenger-client';

class MessengerWrapper extends EventEmitter {
  constructor(opts) {
    super();

    opts = opts || {};

    if (!opts.verifyToken || !opts.pageAccessToken) {
      throw new Error('VERIFY_TOKEN or PAGE_ACCESS_TOKEN are missing.');
    }

    this.verifyToken = opts.verifyToken;
    this.pageAccessToken = opts.pageAccessToken;
    this.messengerClient = new MessengerClient(this);
  }

  verify(req, res) {
    if (req.query['hub.verify_token'] === this.verifyToken) {
      return res.send(req.query['hub.challenge']);
    } else {
      return res.send('VERIFY_TOKEN does not match.');
    }
  }

  handle(req) {
    let entries = req.body.entry;

    entries.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message) {
          this.handleEvent('message', event);
        }
        else if (event.delivery) {
          this.handleEvent('delivery', event);
        }
        else if (event.postback) {
          this.handleEvent('postback', event);
        }
      });
    });
  }

  handleEvent(action, event) {
    this.emit(action, event);
  }

  getUser(event) {
    if (typeof event === 'object') {
      return this.messengerClient.getUserData(event.sender.id);
    } else {
      return this.messengerClient.getUserData(event);
    }
  }
}

export default MessengerWrapper;
<commit_msg>messenger-wrapper: add sendData method<commit_after>import EventEmitter from 'events';

import MessengerClient from './lib/messenger-client';

class MessengerWrapper extends EventEmitter {
  constructor(opts) {
    super();

    opts = opts || {};

    if (!opts.verifyToken || !opts.pageAccessToken) {
      throw new Error('VERIFY_TOKEN or PAGE_ACCESS_TOKEN are missing.');
    }

    this.verifyToken = opts.verifyToken;
    this.pageAccessToken = opts.pageAccessToken;
    this.messengerClient = new MessengerClient(this);
  }

  verify(req, res) {
    if (req.query['hub.verify_token'] === this.verifyToken) {
      return res.send(req.query['hub.challenge']);
    } else {
      return res.send('VERIFY_TOKEN does not match.');
    }
  }

  handle(req) {
    let entries = req.body.entry;

    entries.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message) {
          this.handleEvent('message', event);
        }
        else if (event.delivery) {
          this.handleEvent('delivery', event);
        }
        else if (event.postback) {
          this.handleEvent('postback', event);
        }
      });
    });
  }

  handleEvent(action, event) {
    this.emit(action, event);
  }

  getUser(event) {
    if (typeof event === 'object') {
      return this.messengerClient.getUserData(event.sender.id);
    } else {
      return this.messengerClient.getUserData(event);
    }
  }

  sendData(payload, event) {
    if (typeof event === 'object') {
      return this.messengerClient.sendData(payload, event.sender.id)
    } else {
      return this.messengerClient.sendData(payload, event);
    }
  }
}

export default MessengerWrapper;
<|endoftext|>


<commit_before>"use strict";

function UFOs(container){

	//scene elements, I wouldn't mess with these if you are trying to work with this
	var scene, camera, renderer, cube;
	//Mess with these if you don't want a full screen visualization
	var WIDTH  = window.innerWidth;
	var HEIGHT = window.innerHeight;

	var MAXWIDTH = 928, MAXHEIGHT = 592;
	var jsonloader = new THREE.JSONLoader();
	//SECTION INITIALIZATION
	function init(container) {
		scene = new THREE.Scene();
		initCamera();
		initRenderer();
		initCube();
		container.body.appendChild(renderer.domElement);
		addMouseHandler(renderer.domElement);
		render();
	}
	function resize(){
		WIDTH  = window.innerWidth;
		HEIGHT = window.innerHeight
		renderer.setSize(WIDTH, HEIGHT);
	}
	function initCamera() {
		camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10000);
		camera.position.set(0,-500,500);
		camera.lookAt(scene.position);
	}

	function initRenderer() {
		renderer = new THREE.WebGLRenderer({ antialias: true });
		renderer.setSize(WIDTH, HEIGHT);
		window.renderer = renderer;
	}
	function initCube() {
    var loader = new THREE.TextureLoader();

    var texture = loader.load("img/usmap.gif");
		var material = new THREE.MeshPhongMaterial({map:texture});

		material.bumpMap =texture;

		material.bumpScale = 22;
		cube = new THREE.Mesh(new THREE.CubeGeometry(MAXWIDTH,MAXHEIGHT, 2), material);

		var undermaterial = new THREE.MeshBasicMaterial({color:0x000000});
		var undermap = new THREE.Mesh(new THREE.CubeGeometry(10000,10000,1),undermaterial);
		cube.add(undermap);
		var light = new THREE.DirectionalLight( 0xffffff );
		light.position.set( 1, 1, 1).normalize();
		scene.add(light);
		scene.add(cube);
	}
	var ufos = [];
	var counter = 0;
      var ufo_geometry = new THREE.TorusGeometry(25,5,25,50);

	function addUFO(x,y){
			counter++;
      var ufo = new THREE.Mesh(ufo_geometry,ufo_material);
			var ufo_material = new THREE.MeshBasicMaterial({color: Math.random()%0xffffff,opacity:.6});
			ufo.name = counter.toString();
			cube.add(ufo);
		  ufo.position.set(-928/2 +x,592/2 -y,400);
			ufos.push(ufo);
	}
	function animateUFO(ufo){
			ufo.completelyAnimated = false;
			ufo.ival = setInterval(function(){
				ufo.position.z-=3;
				if(ufo.position.z <=75)
				{
					clearInterval(ufo.ival);
				}
			},20);
	}
	this.startAnimation = function(){
			ufos.forEach(function(ufo){
					animateUFO(ufo);
			});
	}
	function addUFOPercent(x,y){
			addUFO(x*MAXWIDTH, y*MAXHEIGHT);
	}
	function remove(ufo){
			ufo.ival2 = setInterval(function(){
					ufo.position.z+=5;
					if(ufo.position.z >=500){
						clearInterval(ufo.ival2);
						cube.remove(ufo);
					}
			},30);
	}
	function clearUFOs()
	{
			ufos.forEach(function(ufo){
				remove(ufo);
			});
			ufos.splice(0,ufos.length);
	}

	//END INITIALIZATION

	function render(){
                renderer.render(scene, camera);
                requestAnimationFrame(render);
	}

	//Function Calls

	init(container);
	this.addUFO = addUFO;
	this.clearUFOs = clearUFOs;
	this.resize = resize;
	this.addUFOPercent = addUFOPercent;

	this.destroy = function(){
			renderer.domElement.parentNode.removeChild(renderer.domElement);
	}

	var mouseDown = false,mouseX,mouseY;
	// kept all of these at the end so they're out of the way.
	function onMouseMove(e) {

        e.preventDefault();

        var deltaX = e.clientX - mouseX,
            deltaY = e.clientY - mouseY;
        mouseX = e.clientX;
        mouseY = e.clientY;

        if (mouseDown) {
			rotateScene(deltaX,deltaY);
			moveScene(deltaX, deltaY);
        }
    }
    function onMouseUp(evt) {
        evt.preventDefault();

        mouseDown = false;
    }
	function onMouseDown(evt){
		evt.preventDefault();
		mouseDown = true;
	}

    function addMouseHandler(canvas) {
    canvas.addEventListener('mousemove', function (e) {
        onMouseMove(e);
    }, false);
    canvas.addEventListener('mousedown', function (e) {
        onMouseDown(e);
    }, false);
    canvas.addEventListener('mouseup', function (e) {
        onMouseUp(e);
    }, false);
}
	function rotateScene(deltaX,deltaY){
			cube.rotation.z-= deltaX/100;
	}
    function moveScene(deltaX, deltaY) {
			console.log(camera.position.z)
			if(camera.position.z > 100 || deltaY > 0){
					camera.position.z += deltaY;
					camera.rotation.x-=deltaY/360;
				}
	}
}
<commit_msg>Touchups<commit_after>"use strict";

function UFOs(container){

	//scene elements, I wouldn't mess with these if you are trying to work with this
	var scene, camera, renderer, cube;
	//Mess with these if you don't want a full screen visualization
	var WIDTH  = window.innerWidth;
	var HEIGHT = window.innerHeight;

	var MAXWIDTH = 928, MAXHEIGHT = 592;
	var jsonloader = new THREE.JSONLoader();
	//SECTION INITIALIZATION
	function init(container) {
		scene = new THREE.Scene();
		initCamera();
		if(!window.renderer)
			initRenderer();
		renderer = window.renderer;
		initCube();
		container.body.appendChild(renderer.domElement);

		addMouseHandler(renderer.domElement);
		render();
	}
	function resize(){
		WIDTH  = window.innerWidth;
		HEIGHT = window.innerHeight
		camera.aspect = WIDTH/HEIGHT;
		camera.updateProjectionMatrix();
		renderer.setSize(WIDTH, HEIGHT);
	}
	function initCamera() {
		camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 4000);
		camera.position.set(0,-500,500);
		camera.lookAt(scene.position);
	}

	function initRenderer() {
		renderer = new THREE.WebGLRenderer({ antialias: true });
		renderer.setSize(WIDTH, HEIGHT);
		window.renderer = renderer;
	}
	function initCube() {
    var loader = new THREE.TextureLoader();

    var texture = loader.load("img/usmap.gif");
		var material = new THREE.MeshPhongMaterial({map:texture});

		material.bumpMap =texture;

		material.bumpScale = 22;
		cube = new THREE.Mesh(new THREE.CubeGeometry(MAXWIDTH,MAXHEIGHT, 2), material);
		var light = new THREE.DirectionalLight( 0xffffff );
		light.position.set( 1, 1, 1).normalize();
		scene.add(light);
		scene.add(cube);
	}
	var ufos = [];
	var counter = 0;
      var ufo_geometry = new THREE.TorusGeometry(25,5,25,50);

	function addUFO(x,y){
			counter++;
      var ufo = new THREE.Mesh(ufo_geometry,ufo_material);
			var ufo_material = new THREE.MeshBasicMaterial({color: Math.random()%0xffffff,opacity:.6});
			ufo.name = counter.toString();
			cube.add(ufo);
		  ufo.position.set(-928/2 +x,592/2 -y,400);
			ufos.push(ufo);
	}
	function animateUFO(ufo){
			ufo.completelyAnimated = false;
			ufo.ival = setInterval(function(){
				ufo.position.z-=3;
				if(ufo.position.z <=75)
				{
					clearInterval(ufo.ival);
				}
			},20);
	}
	this.startAnimation = function(){
			ufos.forEach(function(ufo){
					animateUFO(ufo);
			});
	}
	function addUFOPercent(x,y){
			addUFO(x*MAXWIDTH, y*MAXHEIGHT);
	}
	function remove(ufo){
			clearInterval(ufo.ival);
			ufo.ival2 = setInterval(function(){
					ufo.position.z+=5;
					if(ufo.position.z >=500){
						clearInterval(ufo.ival2);
						cube.remove(ufo);
					}
			},30);
	}
	function clearUFOs()
	{
			ufos.forEach(function(ufo){
				remove(ufo);
			});
			ufos.splice(0,ufos.length);
	}

	//END INITIALIZATION

	function render(){
                renderer.render(scene, camera);
                requestAnimationFrame(render);
	}

	//Function Calls

	init(container);
	this.addUFO = addUFO;
	this.clearUFOs = clearUFOs;
	this.resize = resize;
	this.addUFOPercent = addUFOPercent;

	this.destroy = function(){
			renderer.domElement.parentNode.removeChild(renderer.domElement);
	}

	var mouseDown = false,mouseX,mouseY;
	// kept all of these at the end so they're out of the way.
	function onMouseMove(e) {

        e.preventDefault();

        var deltaX = e.clientX - mouseX,
            deltaY = e.clientY - mouseY;
        mouseX = e.clientX;
        mouseY = e.clientY;

        if (mouseDown) {
			rotateScene(deltaX,deltaY);
			moveScene(deltaX, deltaY);
        }
    }
    function onMouseUp(evt) {
        evt.preventDefault();

        mouseDown = false;
    }
	function onMouseDown(evt){
		evt.preventDefault();
		mouseDown = true;
	}

    function addMouseHandler(canvas) {
    canvas.addEventListener('mousemove', function (e) {
        onMouseMove(e);
    }, false);
    canvas.addEventListener('mousedown', function (e) {
        onMouseDown(e);
    }, false);
    canvas.addEventListener('mouseup', function (e) {
        onMouseUp(e);
    }, false);
}
	function rotateScene(deltaX,deltaY){
			cube.rotation.z-= deltaX/100;
	}
    function moveScene(deltaX, deltaY) {
			if(camera.position.z > 100 || deltaY > 0){
					camera.position.z += deltaY;
					camera.rotation.x-=deltaY/360;
				}
	}
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function (language) {
  // fallback to english for unsupported languages
  console.log(language, ['es'].indexOf(language));
  if (['es'].indexOf(language) !== -1) {
    language = 'en';
  }

  var osrmTextInstructions = require('osrm-text-instructions')('v5', language);

  function stepToText(step) {
    try {
      return osrmTextInstructions.compile(step);
    } catch(err) {
      console.log('Error when compiling text instruction', err, step);
      return undefined;
    }
  }

  function stepToLanes(step) {
    var lanes = step.intersections[0].lanes;

    if (!lanes) return [];

    return lanes.map(function(l) {
      var classes = [ 'leaflet-routing-icon', 'lanes'];
      if (!l.valid) classes.push(['invalid']);

      var indication = l.indications.find(function(e) {
        return e === step.maneuver.modifier;
      }) || l.indications[0];

      var icon;
      switch (indication) {
      case 'right':
      case 'sharp right':
        icon = 'turn-right';
        break;
      case 'slight right':
        icon = 'bear-right';
        break;
      case 'left':
      case 'slight left':
        icon = 'turn-left';
        break
      case 'sharp left':
        icon = 'bear-left';
        break;
      case 'uturn':
        icon = 'u-turn';
        break;
      case 'straight':
      case 'none':
      default:
        icon = 'continue';
        break;
      }
      classes.push('leaflet-routing-icon-' + icon);

      return L.DomUtil.create('span', classes.join(' '));
    });
  }

  var L = require('leaflet');
  L.Routing = L.Routing || {};

  L.Routing.ItineraryBuilder = L.Class.extend({
    options: {
      containerClassName: ''
    },

    initialize: function(options) {
      L.setOptions(this, options);
    },

    createContainer: function(className) {
      var table = L.DomUtil.create('table', className || ''),
        colgroup = L.DomUtil.create('colgroup', '', table);

      L.DomUtil.create('col', 'leaflet-routing-instruction-icon', colgroup);
      L.DomUtil.create('col', 'leaflet-routing-instruction-text', colgroup);
      L.DomUtil.create('col', 'leaflet-routing-instruction-distance', colgroup);

      return table;
    },

    createStepsContainer: function() {
      return L.DomUtil.create('tbody', '');
    },

    createStep: function(text, distance, icon, steps) {
      var row = L.DomUtil.create('tr', '', steps),
        span,
        td;

      // icon
      td = L.DomUtil.create('td', '', row);
      span = L.DomUtil.create('span', 'leaflet-routing-icon leaflet-routing-icon-'+icon, td);
      td.appendChild(span);

      // text instruction
      td = L.DomUtil.create('td', '', row);
      td.appendChild(document.createTextNode(stepToText(text)));

      // lanes
      var l = stepToLanes(text);
      if (l) {
        td.appendChild(document.createElement('br'));
        l.forEach(function(laneIcon) {
          td.appendChild(laneIcon);
        });
      }

      // distance steps
      // filter distance after arrival
      if (distance !== '0 m') {
        td = L.DomUtil.create('td', 'distance', row);
        td.appendChild(document.createTextNode(distance));
      }

      return row;
    }
  });

  return L.Routing;
}
<commit_msg>Remove debug code<commit_after>'use strict';

module.exports = function (language) {
  // fallback to english for unsupported languages
  if (['es'].indexOf(language) !== -1) {
    language = 'en';
  }

  var osrmTextInstructions = require('osrm-text-instructions')('v5', language);

  function stepToText(step) {
    try {
      return osrmTextInstructions.compile(step);
    } catch(err) {
      console.log('Error when compiling text instruction', err, step);
      return undefined;
    }
  }

  function stepToLanes(step) {
    var lanes = step.intersections[0].lanes;

    if (!lanes) return [];

    return lanes.map(function(l) {
      var classes = [ 'leaflet-routing-icon', 'lanes'];
      if (!l.valid) classes.push(['invalid']);

      var indication = l.indications.find(function(e) {
        return e === step.maneuver.modifier;
      }) || l.indications[0];

      var icon;
      switch (indication) {
      case 'right':
      case 'sharp right':
        icon = 'turn-right';
        break;
      case 'slight right':
        icon = 'bear-right';
        break;
      case 'left':
      case 'slight left':
        icon = 'turn-left';
        break
      case 'sharp left':
        icon = 'bear-left';
        break;
      case 'uturn':
        icon = 'u-turn';
        break;
      case 'straight':
      case 'none':
      default:
        icon = 'continue';
        break;
      }
      classes.push('leaflet-routing-icon-' + icon);

      return L.DomUtil.create('span', classes.join(' '));
    });
  }

  var L = require('leaflet');
  L.Routing = L.Routing || {};

  L.Routing.ItineraryBuilder = L.Class.extend({
    options: {
      containerClassName: ''
    },

    initialize: function(options) {
      L.setOptions(this, options);
    },

    createContainer: function(className) {
      var table = L.DomUtil.create('table', className || ''),
        colgroup = L.DomUtil.create('colgroup', '', table);

      L.DomUtil.create('col', 'leaflet-routing-instruction-icon', colgroup);
      L.DomUtil.create('col', 'leaflet-routing-instruction-text', colgroup);
      L.DomUtil.create('col', 'leaflet-routing-instruction-distance', colgroup);

      return table;
    },

    createStepsContainer: function() {
      return L.DomUtil.create('tbody', '');
    },

    createStep: function(text, distance, icon, steps) {
      var row = L.DomUtil.create('tr', '', steps),
        span,
        td;

      // icon
      td = L.DomUtil.create('td', '', row);
      span = L.DomUtil.create('span', 'leaflet-routing-icon leaflet-routing-icon-'+icon, td);
      td.appendChild(span);

      // text instruction
      td = L.DomUtil.create('td', '', row);
      td.appendChild(document.createTextNode(stepToText(text)));

      // lanes
      var l = stepToLanes(text);
      if (l) {
        td.appendChild(document.createElement('br'));
        l.forEach(function(laneIcon) {
          td.appendChild(laneIcon);
        });
      }

      // distance steps
      // filter distance after arrival
      if (distance !== '0 m') {
        td = L.DomUtil.create('td', 'distance', row);
        td.appendChild(document.createTextNode(distance));
      }

      return row;
    }
  });

  return L.Routing;
}
<|endoftext|>


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

/**
 * @fileoverview RESTful based opensocial container.
 */

RestfulContainer = function(baseUrl, domain, supportedFieldsArray) {
  opensocial.Container.call(this);

  var supportedFieldsMap = {};
  for (var objectType in supportedFieldsArray) {
    if (supportedFieldsArray.hasOwnProperty(objectType)) {
      supportedFieldsMap[objectType] = {};
      for (var i = 0; i < supportedFieldsArray[objectType].length; i++) {
        var supportedField = supportedFieldsArray[objectType][i];
        supportedFieldsMap[objectType][supportedField] = true;
      }
    }
  }

  this.environment_ = new opensocial.Environment(domain, supportedFieldsMap);
  this.baseUrl_ = baseUrl;

  this.securityToken_ = shindig.auth.getSecurityToken();
};
RestfulContainer.inherits(opensocial.Container);

RestfulContainer.prototype.getEnvironment = function() {
  return this.environment_;
};

RestfulContainer.prototype.requestCreateActivity = function(activity,
    priority, opt_callback) {
  opt_callback = opt_callback || {};

  var req = opensocial.newDataRequest();
  var viewer = new opensocial.IdSpec({'userId' : 'VIEWER'});
  req.add(this.newCreateActivityRequest(viewer, activity), 'key');
  req.send(function(response) {
    opt_callback(response.get('key'));
  });
};

RestfulContainer.prototype.requestData = function(dataRequest, callback) {
  callback = callback || {};

  var requestObjects = dataRequest.getRequestObjects();
  var totalRequests = requestObjects.length;

  if (totalRequests == 0) {
    callback(new opensocial.DataResponse({}, true));
    return;
  }

  var responseMap = {};
  var globalError = false;
  var responsesReceived = 0;

  var checkIfFinished = function() {
    responsesReceived++;
    if (responsesReceived == totalRequests) {
      var dataResponse = new opensocial.DataResponse(responseMap, globalError);
      callback(dataResponse);
    }
  }

  var makeProxiedRequest = function(requestObject, baseUrl, st) {
    var makeRequestParams = {
      "CONTENT_TYPE" : "JSON",
      "METHOD" : requestObject.request.method
    };

    if (requestObject.request.postData) {
      makeRequestParams["POST_DATA"] = gadgets.json.stringify(requestObject.request.postData);
    }

    var url = requestObject.request.url;
    var separator = url.indexOf("?") != -1 ? "&" : "?";

    gadgets.io.makeNonProxiedRequest(
        baseUrl + url + separator + "st=" + st,
        function(result) {
          var error;
          if (result.errors) {
            error = RestfulContainer.translateHttpError(result.errors[0]);
          }

          // TODO: get error messages
          var processedData = requestObject.request.processResponse(
              requestObject.request, result.data, error, null);
          globalError = globalError || processedData.hadError();
          responseMap[requestObject.key] = processedData;

          checkIfFinished();
        },
        makeRequestParams,
        "application/json");
  }

  var jsonBatchData = {};

  for (var j = 0; j < totalRequests; j++) {
    var requestObject = requestObjects[j];

    jsonBatchData[requestObject.key] = {url : requestObject.request.url,
      method : requestObject.request.method};
    if (requestObject.request.postData) {
      jsonBatchData[requestObject.key].postData = requestObject.request.postData;
    }
  }

  // This is slightly different than jsonContainer
  var sendResponse = function(result) {
    result = result.data;

    if (!result || result['error']) {
      callback(new opensocial.DataResponse({}, true));
      return;
    }

    var responses = result['responses'] || [];
    var globalError = false;

    var responseMap = {};

    for (var k = 0; k < requestObjects.length; k++) {
      var request = requestObjects[k];
      var response = responses[request.key];

      var rawData = response['response'];
      var error = response['error'];
      var errorMessage = response['errorMessage'];

      var processedData = request.request.processResponse(
          request.request, rawData, error, errorMessage);
      globalError = globalError || processedData.hadError();
      responseMap[request.key] = processedData;
    }

    var dataResponse = new opensocial.DataResponse(responseMap, globalError);
    callback(dataResponse);
  };

  // TODO: get the jsonbatch url from the container config
  var makeRequestParams = {
    "CONTENT_TYPE" : "JSON",
    "METHOD" : "POST",
    "AUTHORIZATION" : "SIGNED",
    "POST_DATA" : gadgets.json.stringify(jsonBatchData)
  };

  gadgets.io.makeNonProxiedRequest(
    this.baseUrl_ + "/jsonBatch?st=" + shindig.auth.getSecurityToken(),
    sendResponse, makeRequestParams, "application/json");
};

RestfulContainer.translateHttpError = function(httpError) {
  if (httpError == "Error 501") {
    return opensocial.ResponseItem.Error.NOT_IMPLEMENTED;
  } else if (httpError == "Error 401") {
    return opensocial.ResponseItem.Error.UNAUTHORIZED;
  } else if (httpError == "Error 403") {
    return opensocial.ResponseItem.Error.FORBIDDEN;
  } else if (httpError == "Error 400") {
    return opensocial.ResponseItem.Error.BAD_REQUEST;
  } else if (httpError == "Error 500") {
    return opensocial.ResponseItem.Error.INTERNAL_ERROR;
  } else if (httpError == "Error 404") {
    return opensocial.ResponseItem.Error.BAD_REQUEST;
  // TODO: Which one should the limit exceeded error be?
  // } else if (httpError == "Error ???") {
  //   return opensocial.ResponseItem.Error.LIMIT_EXCEEDED;
  }
}

RestfulContainer.prototype.makeIdSpec = function(id) {
  return new opensocial.IdSpec({'userId' : id});
}

RestfulContainer.prototype.translateIdSpec = function(newIdSpec) {
  var userId = newIdSpec.getField('userId');
  var groupId = newIdSpec.getField('groupId');

  if (userId == 'OWNER') {
    userId = '@owner';
  } else if (userId == 'VIEWER') {
    userId = '@viewer';
  } else if (opensocial.Container.isArray(idSpec)) {
    for (var i = 0; i < idSpec.length; i++) {
      // TODO: We will need multiple urls here....don't want to think about
      // that yet
    }
  }

  if (groupId == 'FRIENDS') {
    groupId = "@friends";
  } else if (!groupId) {
    groupId = "@self";
  }

  // TODO: Network distance

  return userId + "/" + groupId;
};

RestfulContainer.prototype.newFetchPersonRequest = function(id, opt_params) {
  var peopleRequest = this.newFetchPeopleRequest(
      this.makeIdSpec(id), opt_params);

  var me = this;
  return new RestfulRequestItem(peopleRequest.url, peopleRequest.method, null,
      function(rawJson) {
        return me.createPersonFromJson(rawJson);
      });
};

RestfulContainer.prototype.newFetchPeopleRequest = function(idSpec,
    opt_params) {
  var url = "/people/" + this.translateIdSpec(idSpec);

  url += "?fields=" + (opt_params['profileDetail'].join(','));
  url += "&startIndex=" + (opt_params['first'] || 0);
  url += "&count=" + (opt_params['max'] || 20);
  url += "&orderBy=" + (opt_params['sortOrder'] || 'topFriends');
  // TODO: This filterBy isn't in the spec
  url += "&filterBy=" + (opt_params['filter'] || 'all');

  var me = this;
  return new RestfulRequestItem(url, "GET", null,
      function(rawJson) {
        var jsonPeople = rawJson['entry'];
        var people = [];
        for (var i = 0; i < jsonPeople.length; i++) {
          people.push(me.createPersonFromJson(jsonPeople[i]));
        }
        return new opensocial.Collection(people,
            rawJson['startIndex'], rawJson['totalResults']);
      });
};

RestfulContainer.prototype.createPersonFromJson = function(serverJson) {
  return new JsonPerson(serverJson);
}

RestfulContainer.prototype.getFieldsList = function(keys) {
  if (opensocial.Container.isArray(keys)) {
    return keys.join(',');
  } else {
    return keys;
  }
}

RestfulContainer.prototype.newFetchPersonAppDataRequest = function(idSpec,
    keys) {
  var url = "/appdata/" + this.translateIdSpec(idSpec) + "/@app"
      + "?fields=" + this.getFieldsList(keys);
  return new RestfulRequestItem(url, "GET", null,
      function (appData) {
        return gadgets.util.escape(appData['entry'], true);
      });
};

RestfulContainer.prototype.newUpdatePersonAppDataRequest = function(id, key,
    value) {
  var url = "/appdata/" + this.translateIdSpec(this.makeIdSpec(id))
      + "/@app?fields=" + key;
  var data = {};
  data[key] = value;
  return new RestfulRequestItem(url, "POST", data);
};

RestfulContainer.prototype.newRemovePersonAppDataRequest = function(id, keys) {
  var url = "/appdata/" + this.translateIdSpec(this.makeIdSpec(id))
      + "/@app?fields=" + this.getFieldsList(keys);
  return new RestfulRequestItem(url, "DELETE");
};

RestfulContainer.prototype.newFetchActivitiesRequest = function(idSpec,
    opt_params) {
  var url = "/activities/" + this.translateIdSpec(idSpec)
      + "?app=@app"; // TODO: Handle appId correctly
  return new RestfulRequestItem(url, "GET", null,
      function(rawJson) {
        rawJson = rawJson['entry'];
        var activities = [];
        for (var i = 0; i < rawJson.length; i++) {
          activities.push(new JsonActivity(rawJson[i]));
        }
        return new opensocial.Collection(activities);
      });
};

RestfulContainer.prototype.newActivity = function(opt_params) {
  return new JsonActivity(opt_params, true);
};

RestfulContainer.prototype.newMediaItem = function(mimeType, url, opt_params) {
  opt_params = opt_params || {};
  opt_params['mimeType'] = mimeType;
  opt_params['url'] = url;
  return new JsonMediaItem(opt_params);
};

RestfulContainer.prototype.newCreateActivityRequest = function(idSpec,
    activity) {
  var url = "/activities/" + this.translateIdSpec(idSpec)
      + "/@app"; // TODO: Handle appId correctly
  return new RestfulRequestItem(url, "POST", activity.toJsonObject());
};

RestfulRequestItem = function(url, method, postData, processData) {
  this.url = url;
  this.method = method;
  this.postData = postData;
  this.processData = processData ||
    function (rawJson) {
      return rawJson;
    };

  this.processResponse = function(originalDataRequest, rawJson, error,
      errorMessage) {

    return new opensocial.ResponseItem(originalDataRequest,
        error ? null : this.processData(rawJson), error, errorMessage);
  }
};
<commit_msg>SHINDIG-433 Patch from Adam Winer. Fixed js reference to an unknown variable in the restful container. <commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

/**
 * @fileoverview RESTful based opensocial container.
 */

RestfulContainer = function(baseUrl, domain, supportedFieldsArray) {
  opensocial.Container.call(this);

  var supportedFieldsMap = {};
  for (var objectType in supportedFieldsArray) {
    if (supportedFieldsArray.hasOwnProperty(objectType)) {
      supportedFieldsMap[objectType] = {};
      for (var i = 0; i < supportedFieldsArray[objectType].length; i++) {
        var supportedField = supportedFieldsArray[objectType][i];
        supportedFieldsMap[objectType][supportedField] = true;
      }
    }
  }

  this.environment_ = new opensocial.Environment(domain, supportedFieldsMap);
  this.baseUrl_ = baseUrl;

  this.securityToken_ = shindig.auth.getSecurityToken();
};
RestfulContainer.inherits(opensocial.Container);

RestfulContainer.prototype.getEnvironment = function() {
  return this.environment_;
};

RestfulContainer.prototype.requestCreateActivity = function(activity,
    priority, opt_callback) {
  opt_callback = opt_callback || {};

  var req = opensocial.newDataRequest();
  var viewer = new opensocial.IdSpec({'userId' : 'VIEWER'});
  req.add(this.newCreateActivityRequest(viewer, activity), 'key');
  req.send(function(response) {
    opt_callback(response.get('key'));
  });
};

RestfulContainer.prototype.requestData = function(dataRequest, callback) {
  callback = callback || {};

  var requestObjects = dataRequest.getRequestObjects();
  var totalRequests = requestObjects.length;

  if (totalRequests == 0) {
    callback(new opensocial.DataResponse({}, true));
    return;
  }

  var responseMap = {};
  var globalError = false;
  var responsesReceived = 0;

  var checkIfFinished = function() {
    responsesReceived++;
    if (responsesReceived == totalRequests) {
      var dataResponse = new opensocial.DataResponse(responseMap, globalError);
      callback(dataResponse);
    }
  }

  var makeProxiedRequest = function(requestObject, baseUrl, st) {
    var makeRequestParams = {
      "CONTENT_TYPE" : "JSON",
      "METHOD" : requestObject.request.method
    };

    if (requestObject.request.postData) {
      makeRequestParams["POST_DATA"] = gadgets.json.stringify(requestObject.request.postData);
    }

    var url = requestObject.request.url;
    var separator = url.indexOf("?") != -1 ? "&" : "?";

    gadgets.io.makeNonProxiedRequest(
        baseUrl + url + separator + "st=" + st,
        function(result) {
          var error;
          if (result.errors) {
            error = RestfulContainer.translateHttpError(result.errors[0]);
          }

          // TODO: get error messages
          var processedData = requestObject.request.processResponse(
              requestObject.request, result.data, error, null);
          globalError = globalError || processedData.hadError();
          responseMap[requestObject.key] = processedData;

          checkIfFinished();
        },
        makeRequestParams,
        "application/json");
  }

  var jsonBatchData = {};

  for (var j = 0; j < totalRequests; j++) {
    var requestObject = requestObjects[j];

    jsonBatchData[requestObject.key] = {url : requestObject.request.url,
      method : requestObject.request.method};
    if (requestObject.request.postData) {
      jsonBatchData[requestObject.key].postData = requestObject.request.postData;
    }
  }

  // This is slightly different than jsonContainer
  var sendResponse = function(result) {
    result = result.data;

    if (!result || result['error']) {
      callback(new opensocial.DataResponse({}, true));
      return;
    }

    var responses = result['responses'] || [];
    var globalError = false;

    var responseMap = {};

    for (var k = 0; k < requestObjects.length; k++) {
      var request = requestObjects[k];
      var response = responses[request.key];

      var rawData = response['response'];
      var error = response['error'];
      var errorMessage = response['errorMessage'];

      var processedData = request.request.processResponse(
          request.request, rawData, error, errorMessage);
      globalError = globalError || processedData.hadError();
      responseMap[request.key] = processedData;
    }

    var dataResponse = new opensocial.DataResponse(responseMap, globalError);
    callback(dataResponse);
  };

  // TODO: get the jsonbatch url from the container config
  var makeRequestParams = {
    "CONTENT_TYPE" : "JSON",
    "METHOD" : "POST",
    "AUTHORIZATION" : "SIGNED",
    "POST_DATA" : gadgets.json.stringify(jsonBatchData)
  };

  gadgets.io.makeNonProxiedRequest(
    this.baseUrl_ + "/jsonBatch?st=" + shindig.auth.getSecurityToken(),
    sendResponse, makeRequestParams, "application/json");
};

RestfulContainer.translateHttpError = function(httpError) {
  if (httpError == "Error 501") {
    return opensocial.ResponseItem.Error.NOT_IMPLEMENTED;
  } else if (httpError == "Error 401") {
    return opensocial.ResponseItem.Error.UNAUTHORIZED;
  } else if (httpError == "Error 403") {
    return opensocial.ResponseItem.Error.FORBIDDEN;
  } else if (httpError == "Error 400") {
    return opensocial.ResponseItem.Error.BAD_REQUEST;
  } else if (httpError == "Error 500") {
    return opensocial.ResponseItem.Error.INTERNAL_ERROR;
  } else if (httpError == "Error 404") {
    return opensocial.ResponseItem.Error.BAD_REQUEST;
  // TODO: Which one should the limit exceeded error be?
  // } else if (httpError == "Error ???") {
  //   return opensocial.ResponseItem.Error.LIMIT_EXCEEDED;
  }
}

RestfulContainer.prototype.makeIdSpec = function(id) {
  return new opensocial.IdSpec({'userId' : id});
}

RestfulContainer.prototype.translateIdSpec = function(newIdSpec) {
  var userId = newIdSpec.getField('userId');
  var groupId = newIdSpec.getField('groupId');

  if (userId == 'OWNER') {
    userId = '@owner';
  } else if (userId == 'VIEWER') {
    userId = '@viewer';
  } else if (opensocial.Container.isArray(newIdSpec)) {
    for (var i = 0; i < newIdSpec.length; i++) {
      // TODO: We will need multiple urls here....don't want to think about
      // that yet
    }
  }

  if (groupId == 'FRIENDS') {
    groupId = "@friends";
  } else if (!groupId) {
    groupId = "@self";
  }

  // TODO: Network distance

  return userId + "/" + groupId;
};

RestfulContainer.prototype.newFetchPersonRequest = function(id, opt_params) {
  var peopleRequest = this.newFetchPeopleRequest(
      this.makeIdSpec(id), opt_params);

  var me = this;
  return new RestfulRequestItem(peopleRequest.url, peopleRequest.method, null,
      function(rawJson) {
        return me.createPersonFromJson(rawJson);
      });
};

RestfulContainer.prototype.newFetchPeopleRequest = function(idSpec,
    opt_params) {
  var url = "/people/" + this.translateIdSpec(idSpec);

  url += "?fields=" + (opt_params['profileDetail'].join(','));
  url += "&startIndex=" + (opt_params['first'] || 0);
  url += "&count=" + (opt_params['max'] || 20);
  url += "&orderBy=" + (opt_params['sortOrder'] || 'topFriends');
  // TODO: This filterBy isn't in the spec
  url += "&filterBy=" + (opt_params['filter'] || 'all');

  var me = this;
  return new RestfulRequestItem(url, "GET", null,
      function(rawJson) {
        var jsonPeople = rawJson['entry'];
        var people = [];
        for (var i = 0; i < jsonPeople.length; i++) {
          people.push(me.createPersonFromJson(jsonPeople[i]));
        }
        return new opensocial.Collection(people,
            rawJson['startIndex'], rawJson['totalResults']);
      });
};

RestfulContainer.prototype.createPersonFromJson = function(serverJson) {
  return new JsonPerson(serverJson);
}

RestfulContainer.prototype.getFieldsList = function(keys) {
  if (opensocial.Container.isArray(keys)) {
    return keys.join(',');
  } else {
    return keys;
  }
}

RestfulContainer.prototype.newFetchPersonAppDataRequest = function(idSpec,
    keys) {
  var url = "/appdata/" + this.translateIdSpec(idSpec) + "/@app"
      + "?fields=" + this.getFieldsList(keys);
  return new RestfulRequestItem(url, "GET", null,
      function (appData) {
        return gadgets.util.escape(appData['entry'], true);
      });
};

RestfulContainer.prototype.newUpdatePersonAppDataRequest = function(id, key,
    value) {
  var url = "/appdata/" + this.translateIdSpec(this.makeIdSpec(id))
      + "/@app?fields=" + key;
  var data = {};
  data[key] = value;
  return new RestfulRequestItem(url, "POST", data);
};

RestfulContainer.prototype.newRemovePersonAppDataRequest = function(id, keys) {
  var url = "/appdata/" + this.translateIdSpec(this.makeIdSpec(id))
      + "/@app?fields=" + this.getFieldsList(keys);
  return new RestfulRequestItem(url, "DELETE");
};

RestfulContainer.prototype.newFetchActivitiesRequest = function(idSpec,
    opt_params) {
  var url = "/activities/" + this.translateIdSpec(idSpec)
      + "?app=@app"; // TODO: Handle appId correctly
  return new RestfulRequestItem(url, "GET", null,
      function(rawJson) {
        rawJson = rawJson['entry'];
        var activities = [];
        for (var i = 0; i < rawJson.length; i++) {
          activities.push(new JsonActivity(rawJson[i]));
        }
        return new opensocial.Collection(activities);
      });
};

RestfulContainer.prototype.newActivity = function(opt_params) {
  return new JsonActivity(opt_params, true);
};

RestfulContainer.prototype.newMediaItem = function(mimeType, url, opt_params) {
  opt_params = opt_params || {};
  opt_params['mimeType'] = mimeType;
  opt_params['url'] = url;
  return new JsonMediaItem(opt_params);
};

RestfulContainer.prototype.newCreateActivityRequest = function(idSpec,
    activity) {
  var url = "/activities/" + this.translateIdSpec(idSpec)
      + "/@app"; // TODO: Handle appId correctly
  return new RestfulRequestItem(url, "POST", activity.toJsonObject());
};

RestfulRequestItem = function(url, method, postData, processData) {
  this.url = url;
  this.method = method;
  this.postData = postData;
  this.processData = processData ||
    function (rawJson) {
      return rawJson;
    };

  this.processResponse = function(originalDataRequest, rawJson, error,
      errorMessage) {

    return new opensocial.ResponseItem(originalDataRequest,
        error ? null : this.processData(rawJson), error, errorMessage);
  }
};
<|endoftext|>


<commit_before>/**
 * Created by will on 4/6/16.
 */
var MOL = {};

MOL.units = {};  //holds all the units
MOL.unit = function(id) {
    this.id = id;
    this.instructions = {};
    this.cache = {};
    this.data = {};
    this.data_limit = 5;
    this.gates = {};

    this.add_ins = function(ins) {
        if (!this.instructions[ins.signal]) {
            this.instructions[ins.signal] = [];
        }
        this.instructions[ins.signal].push(ins);
    }

};

MOL.gate = function(id,unit_id,direction,namespace,power) {
    this.id = id;
    this.unit_id = unit_id;
    this.direction = direction;
    this.namespace = namespace;
    this.power = power;
    this.hookup = nil;
};

MOL.instruction = function(id,signal,op,oprand1,oprand2,result) {
    this.id = id;
    this.signal = signal;
    this.op = op;
    this.oprand1 = oprand1;
    this.oprand2 = oprand2;
    this.result = result;
};

MOL.out_gates = {};
MOL.in_gates = {};
MOL.ins_next = {};
MOL.active_hookups = [];

/*
Steps each cycle:
empty all out_gates,in_gates

1) for each unit in MOL get all out_gates g that are on and put their namespace (the namespace they are looking for)
        as a key into out_gates with a ref to the gate as the value
        MOL.out_gates[g.namespace] = g

2) for each unit in MOL get all in_gates go that are on and put their NS into the hash
        MOL.in_gates[go.namespace] = go

3) match all outgates to ingates, multiple hookups for one gate is okay. For each pair found,
    make a hash {in_unit: go.unit_id, in_gate:go.id, out_unit:go.unit_id,out_gate:g.id} //avoid cycle ref
     and set each gate's hookup to this, and add to MOL.active_hookups

 4) get each gate's unit, and add any instruction whose state is 'GS' + gate.id for that gate's unit, to the MOL.ins_next

 5) ADD to each unit's cache the key , 'GS' + gate.id and set it to 1 unit.cache['GS' + gate.id] = 1

 6) EXECUTE all instructions in MOL.ins_next (remove ins from ins_next as we execute them)

 7) If any of these ins move data through a gate (D1 ++ , result GO#)
        if the target unit, that is at the end of the gate hookup, has an ins for GS#,
            add to that unit   unit.cache[GD#] = data moved (overrite if already set)
            add the ins to ins_next

 7) If any of these ins change data in their own unit (D1 + D2. result D2)
     if the unit has an ins for DD2 and DD2 has changed value
     add to that unit   unit.cache['DD2'] = index of data changed (overrite if already set)
     add all ins for this DD2 to ins_next

 8) EXECUTE ALL ins_next (removing each of the ins as we do it)

 9) Go through all MOL.hookups and see if any of the pair of gates is now off, if so see if each gate's unit
        has a detach signal (GX#), if so unit.cache[GX#] = 1 (create or overrite), remove any cache keys for incoming data
        ; delete unit.cache[GD#].remove hookup info from both gates and the hookup array
        ; delete GS# from cache

 ------------------------
 instruction works by : waits on signal : does an operation with up to two registers and then write to a register
 signals are:
 Gate Start: GS: when a gate connects
 Gate Data: GD :when there is data incoming through a gate
 Gate End: GX : when a gate detaches
 Data Delta DD : when a data slot changes value

 if there is no DG GS GX or DD in an instructions two operands, then that instruction does not affect or write anything

 instruction notation State,p1 p2 op, result
 p2 can be missing

 operations:
   math: + - * / --  %
   action_logic: AND OR NOT XOR > < >= <= <> ==
                            -- if logic is false no result is written to, if logic is true result has a 1
   logic: same as action logic           -- but result is always 0 or 1
   bitwise: & | ^ ~
   GateOff#  -- turns Gate# off
   GateOn#   -- turns Gate# on

 */

$(function() {
    MOL.units[0] = new MOL.unit(0);
    MOL.units[0].gates[0] = new MOL.gate(0,0);
    MOL.units[0].add_ins( new MOL.instruction(2,'GS3','+','D1','GS4','GU5'));
    var g = MOL.units[0].gates[0];
    var mm = MOL.units[g.unit_id];

    makeBrick('first');
    makeBrick('second');
    makeBrick('third');

    $('.first .gate_house').css("background-color",'blue');
});

//create the brick on screen given an x and y
function makeBrick(parent_class) {
    $("<div/>",{
        "class" : "gate_house",
        // .. you can go on and add properties
        "css" : {
            "color" : "black"
        },
        "click" : function(){
            alert("you just clicked me!!");
        },
        "data" : {
            "foo" : "bar"
        }
    }).appendTo("."+parent_class);

    for(var i=0;i<4;i++) {
        $("<div/>",{
            "class" : "gate",
            // .. you can go on and add properties
            "css" : {
                "color" : "black"
            }
        }).appendTo("."+parent_class + ' .gate_house');
    }

    $("<div/>",{
        "class" : "cpu",
        // .. you can go on and add properties
        "css" : {
            "color" : "black"
        }
    }).appendTo("."+parent_class);

    $("<div/>",{
        "class" : "storage",
        // .. you can go on and add properties
        "css" : {
            "color" : "black"
        }
    }).appendTo("."+parent_class);
}<commit_msg>I cannot stop editing and adding tonight<commit_after>/**
 * Created by will on 4/6/16.
 */
var MOL = {};

MOL.units = {};  //holds all the units
MOL.unit = function(id) {
    this.id = id;
    this.instructions = {};
    this.cache = {};
    this.data = {};
    this.data_limit = 5;
    this.gates = {};

    this.add_ins = function(ins) {
        if (!this.instructions[ins.signal]) {
            this.instructions[ins.signal] = [];
        }
        this.instructions[ins.signal].push(ins);
    }

};

MOL.gate = function(id,unit_id,direction,namespace,power) {
    this.id = id;
    this.unit_id = unit_id;
    this.direction = direction;
    this.namespace = namespace;
    this.power = power;
    this.hookup = nil;
};

MOL.instruction = function(id,signal,op,oprand1,oprand2,result) {
    this.id = id;
    this.signal = signal;
    this.op = op;
    this.oprand1 = oprand1;
    this.oprand2 = oprand2;
    this.result = result;
};

MOL.out_gates = {};
MOL.in_gates = {};
MOL.ins_next = {};
MOL.active_hookups = [];

/*
Steps each cycle:
empty all out_gates,in_gates

1) for each unit in MOL get all out_gates g that are on and put their namespace (the namespace they are looking for)
        as a key into out_gates with a ref to the gate as the value
        MOL.out_gates[g.namespace] = g

2) for each unit in MOL get all in_gates go that are on and put their NS into the hash
        MOL.in_gates[go.namespace] = go

3) match all outgates to ingates, multiple hookups for one gate is okay. For each pair found,
    make a hash {in_unit: go.unit_id, in_gate:go.id, out_unit:go.unit_id,out_gate:g.id} //avoid cycle ref
     and set each gate's hookup to this, and add to MOL.active_hookups

 4) get each gate's unit, and add any instruction whose state is 'GS' + gate.id for that gate's unit, to the MOL.ins_next

 5) ADD to each unit's cache the key , 'GS' + gate.id and set it to 1 unit.cache['GS' + gate.id] = 1

 6) EXECUTE all instructions in MOL.ins_next (remove ins from ins_next as we execute them)

 7) If any of these ins move data through a gate (D1 ++ , result GO#)
        if the target unit, that is at the end of the gate hookup, has an ins for GS#,
            add to that unit   unit.cache[GD#] = data moved (overrite if already set)
            add the ins to ins_next

 7) If any of these ins change data in their own unit (D1 + D2. result D2)
     if the unit has an ins for DD2 and DD2 has changed value
     add to that unit   unit.cache['DD2'] = index of data changed (overrite if already set)
     add all ins for this DD2 to ins_next

 8) EXECUTE ALL ins_next (removing each of the ins as we do it)

 9) Go through all MOL.hookups and see if any of the pair of gates is now off, if so see if each gate's unit
        has a detach signal (GX#), if so unit.cache[GX#] = 1 (create or overrite), remove any cache keys for incoming data
        ; delete unit.cache[GD#].remove hookup info from both gates and the hookup array
        ; delete GS# from cache

 ------------------------
 instruction works by : waits on signal : does an operation with up to two registers and then write to a register
 signals are:
 Gate Start: GS: when a gate connects
 Gate Data: GD :when there is data incoming through a gate
 Gate End: GX : when a gate detaches
 Data Delta DD : when a data slot changes value

 if there is no DG GS GX or DD in an instructions two operands, then that instruction does not affect or write anything

 instruction notation State,p1 p2 op, result
 p2 can be missing

 operations:
   math: + - * / --  %
   action_logic: AND OR NOT XOR > < >= <= <> ==
                            -- if logic is false no result is written to, if logic is true result has a 1
   logic: same as action logic           -- but result is always 0 or 1
   bitwise: & | ^ ~
   GateOff#  -- turns Gate# off
   GateOn#   -- turns Gate# on

   COPY  copies data

   NOP  no operation

 RESULTS and OPERANDS
   the signals above and
   Gate Move: GM Move data through gate, here data is just copied
   Data: D: destination is to the data #

 Please note that all combinations of signals, operands, operators and results are legal

 */

$(function() {
    MOL.units[0] = new MOL.unit(0);
    MOL.units[0].gates[0] = new MOL.gate(0,0);
    MOL.units[0].add_ins( new MOL.instruction(2,'GS3','+','D1','GS4','GU5'));
    var g = MOL.units[0].gates[0];
    var mm = MOL.units[g.unit_id];

    makeBrick('first');
    makeBrick('second');
    makeBrick('third');

    $('.first .gate_house').css("background-color",'blue');
});

//create the brick on screen given an x and y
function makeBrick(parent_class) {
    $("<div/>",{
        "class" : "gate_house",
        // .. you can go on and add properties
        "css" : {
            "color" : "black"
        },
        "click" : function(){
            alert("you just clicked me!!");
        },
        "data" : {
            "foo" : "bar"
        }
    }).appendTo("."+parent_class);

    for(var i=0;i<4;i++) {
        $("<div/>",{
            "class" : "gate",
            // .. you can go on and add properties
            "css" : {
                "color" : "black"
            }
        }).appendTo("."+parent_class + ' .gate_house');
    }

    $("<div/>",{
        "class" : "cpu",
        // .. you can go on and add properties
        "css" : {
            "color" : "black"
        }
    }).appendTo("."+parent_class);

    $("<div/>",{
        "class" : "storage",
        // .. you can go on and add properties
        "css" : {
            "color" : "black"
        }
    }).appendTo("."+parent_class);
}<|endoftext|>