<commit_before>"use strict"

var async = require('async'),
    http = require('http'),
    request = require('request'),
    Database = require('./database'),
    config = require('nconf'),
    version = 'api:' + config.get("api:version");

var pool = new http.Agent;
    pool.maxSockets = 500;

var query,
    count,
    tweets,
    MAX_TWEETS,
    insightHOST,
    schemaTweetMap,
    progress;

function TwitterInsight(searchString) {
    query = searchString;
    MAX_TWEETS = 500;
    progress = 0;
    populateSchemaTweetMap();
    getColumns();

    var services = JSON.parse(process.env.VCAP_SERVICES || "{}");
    insightHOST = services["twitterinsights"] ? services["twitterinsights"][0].credentials.url : config.get(version + ':twitterInsights').url;
}

TwitterInsight.prototype = {
	count: function(callback) {
        var url = insightHOST + '/api/v1/messages/count';
        retrieveInsight(url, query, function(err, data) {
            if(!err) {
                count = data['search']['results'];
                data.count = count;
            }
            callback(err, data);
        });
    },
    fetch: function(callback) {
        var url = insightHOST + '/api/v1/messages/search?q=' + query + '&size=' + MAX_TWEETS;
        console.log(url);
        async.timesSeries(3, function(n, next) {
            retrieveInsight(url, function(err, data) {
                url = data['related']['next']['href'];
                // count = data['search']['results'];
                // tweets.push(data['tweets']);
                //TODO: insert into database here
                next(err, data);
            });
        }, function(err, data) {
            callback(err, count);
        });
	},
    insert: function(movieName, tableName, callback) {
        //check if there is already an ajax running
        if(progress == 0) {
            //create a table with the movie name to store tweets
            var db = new Database(),
                url = insightHOST + '/api/v1/messages/search';
            createMovieTweetsTable(db, tableName, function(err, data) {
                if(!err) {
                    //retrieve the tweets and insert into table
                    //Twitter for Insight provides at max 500 tweets per request
                    //call the retrieve and insert function total number of tweets / max tweets per request
                    var times =  Math.ceil(count / MAX_TWEETS);
                    async.timesSeries(times, function(n, next) {
                    	console.log(n)
                        retrieveInsight(url, query, function(err, data) {
                            if (!err && data['tweets'].length > 0) {
                                insertTweets(db, tableName, data['tweets'], function(err, message, rows) {
                                    if(!err) {
                                        progress += rows;
                                        process.stdout.write("\rso far: " + progress);
                                    }
                                    next(err, data);
                                    console.log("twitterInsight.js: insertTweets callback")
                                });
                            } else {
                           		console.log("twitterInsight.js: retrieveInsight callback")
                           		console.log(err);
                              //callback(err, progress)
                           }
                        }, (n*MAX_TWEETS));
                    }, function(err, data) {
                        return callback(err, progress);
                    });
                } else {
                	console.log("twitterInsight.js: createMovieTable callback")
                    callback(err, progress);
                }
            });
        }
    },
    getCount: function() {
        return count;
    },
    getTweets: function() {
        return tweets;
    },
    print: function() {
        console.log("No. of Tweets found: " + count);
        console.log(tweets)
    }
}

function retrieveInsight(url, query, callback, from) {
    var params = null;
    //send query parameters as below in order to handle special characters in values such as '#'
    if(query) {
        params = {
            q: query,
            size: MAX_TWEETS,
            from: from?from:0
        }
    }
    request({
        method: "GET",
        url: url,
        qs: params,
        pool: pool,
        // auth: {
        //     'user': 'f6204541d9434de8a1363a9214fe5455',
        //     'pass': 'oUzn5yaGuq'
        // },
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        }
    }, function(err, response, data) {
        if (err) {
            console.log("ERR")
            callback(err);
        } else {
            if (response.statusCode == 200) {
                try {
                    callback(null, JSON.parse(data));
                } catch(e) {
                    callback(true, {
                        message: {
                            description: e.message
                        },
                        status_code: response.statusCode
                    });
                }
            } else {
                callback(true, {
                    message: {
                        description: data
                    },
                    status_code: response.statusCode
                });
            }
        }
    });
}

function createMovieTweetsTable (db, tableName, callback) {
    var createTableQuery = 'CREATE TABLE '
        + tableName
        + '(GENERATORDISPLAYNAME VARCHAR(1024),'
        + 'ID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),'
        + 'MSGBODY VARCHAR(2048),'
        + 'MSGHASHTAGS VARCHAR(2048),'
        + 'MSGID VARCHAR(128),'
        + 'MSGPOSTEDTIME TIMESTAMP,'
        + 'MSGTYPE VARCHAR(128),'
        + 'MSGSENTIMENT VARCHAR(128) NOT NULL WITH DEFAULT \'NEUTRAL\','
        + 'SMAAUTHORCITY VARCHAR(1024),'
        + 'SMAAUTHORCOUNTRY VARCHAR(1024),'
        + 'SMAAUTHORGENDER VARCHAR(1024),'
        + 'SMAAUTHORSTATE VARCHAR(1024),'
        + 'USERDISPLAYNAME VARCHAR(1024),'
        + 'USERFOLLOWERSCOUNT INT,'
        + 'USERFRIENDSCOUNT INT,'
        + 'USERID VARCHAR(128),'
        + 'USERLANGUAGE VARCHAR(128),'
        + 'USERLINK VARCHAR(1024),'
        + 'USERLISTEDCOUNT INT,'
        + 'USERLOCATION VARCHAR(1024),'
        + 'USERPREFERREDUSERNAME VARCHAR(1024),'
        + 'USERSTATUSESCOUNT INT,'
        + 'USERUTCOFFSET VARCHAR(1024),'
        + 'USERVERIFIED VARCHAR(1024),'
        + 'PRIMARY KEY(ID)'
        + ') ORGANIZE BY ROW';

    // db.checkTableExist(tableName, function(found) {
        // db.executeQuery(dropFirst, function(result) {
        // console.log(result);
        // if(!found) {
            db.executeQuery(createTableQuery, function(err, result) {
                if(err) console.log("Error in creating tweet table for the movie");
                callback(err, {message:"New table "+ tableName +" created"});
            });
        // } else {
            //TODO: dro table if exist logic ot beimpl
            // console.log("Table exists already");
            // callback(false, {message:"Table exists already."});
        // }
    // });
    // });
}

function insertTweets(db, tableName, tweets, callback) {
    var database = new Database();
    try {
        var insertQuery = "INSERT INTO " + tableName + " (" + getColumns() + ") VALUES ";
        for (var i = 0; i < tweets.length; i++) {
            insertQuery += "("+ getColumnsValues(tweets[i]) + "),";
        }
        insertQuery = insertQuery.slice(0,-1);
        database.executeQuery(insertQuery, function(err, result) {
            if( !err ) {
                console.log("db insert: success")
                callback(err, result.message + " IN TWEETS INSERTION.", i);
            } else {
                console.log(insertQuery)
                console.log(result)
                console.log("db insert: failure")
                result.message = result.message + " IN TWEETS INSERTION.";
                callback(err, result, i);
            }
            database = null;
        });
    } catch(e) {
        console.log('catch')
        console.log(insertQuery)
        console.log(result)
        console.log(e)
        callback(true, e)
    }
}

function populateSchemaTweetMap() {
    schemaTweetMap = {
        'GENERATORDISPLAYNAME':{
            'type':'VARCHAR',
            'mapping':'message.generator.displayName'
        },
        'MSGBODY':{
            'type':'VARCHAR',
            'mapping':'message.body'
        },
        'MSGHASHTAGS':{
            'type':'VARCHAR',
            'mapping':'message.twitter_entities.hashtags'
        },
        'MSGID':{
            'type':'VARCHAR',
            'mapping':'message.id'
        },
        'MSGPOSTEDTIME':{
            'type':'TIMESTAMP',
            'mapping':'message.postedTime'
        },
        'MSGTYPE':{
            'type':'VARCHAR',
            'mapping':'message.verb'
        },
        'MSGSENTIMENT':{
            'type':'VARCHAR',
            'mapping':'cde.content.sentiment.polarity',
            'default':'NEUTRAL'
        },
        'SMAAUTHORCITY':{
            'type':'VARCHAR',
            'mapping':'cde.author.location.city'
        },
        'SMAAUTHORCOUNTRY':{
            'type':'VARCHAR',
            'mapping':'cde.author.location.country'
        },
        'SMAAUTHORGENDER':{
            'type':'VARCHAR',
            'mapping':'cde.author.gender'
        },
        'SMAAUTHORSTATE':{
            'type':'VARCHAR',
            'mapping':'cde.author.location.state'
        },
        'USERDISPLAYNAME':{
            'type':'VARCHAR',
            'mapping':'message.actor.displayName'
        },
        'USERFOLLOWERSCOUNT':{
            'type':'INT',
            'mapping':'message.actor.followersCount'
        },
        'USERFRIENDSCOUNT':{
            'type':'INT',
            'mapping':'message.actor.friendsCount'
        },
        'USERID':{
            'type':'VARCHAR',
            'mapping':'message.actor.id'
        },
        'USERLANGUAGE':{
            'type':'VARCHAR',
            'mapping':'message.actor.languages'
        },
        'USERLINK':{
            'type':'VARCHAR',
            'mapping':'message.actor.links.href'
        },
        'USERLISTEDCOUNT':{
            'type':'INT',
            'mapping':'message.actor.listedCount'
        },
        'USERLOCATION':{
            'type':'VARCHAR',
            'mapping':'message.actor.location.displayName'
        },
        'USERPREFERREDUSERNAME':{
            'type':'VARCHAR',
            'mapping':'message.actor.preferredUsername'
        },
        'USERSTATUSESCOUNT':{
            'type':'INT',
            'mapping':'message.actor.statusesCount'
        },
        'USERUTCOFFSET':{
            'type':'VARCHAR',
            'mapping':'message.actor.utcOffset'
        },
        'USERVERIFIED':{
            'type':'VARCHAR',
            'mapping':'message.actor.verified'
        }
    }
}

function getColumns() {
    var keys = '';
    for(var key in schemaTweetMap) {
        keys += key + ',';
    }
    return keys.slice(0,-1);
}

function getColumnsValues(tweet) {
    var index, value = '', values = '';
    for(var key in schemaTweetMap) {
        index = schemaTweetMap[key].mapping;
        value = getObjectValue(tweet, index);
        if (!value) {
            value = (schemaTweetMap[key].default)? "'"+schemaTweetMap[key].default+"'" : null;
        } else if (schemaTweetMap[key].type === "VARCHAR") {
            value = "'" + value.replace(/\'/g,"''") + "'";
        } else if (schemaTweetMap[key].type === "INT") {
            value = parseInt(value) ;
        } else if (schemaTweetMap[key].type === "TIMESTAMP") {
            value = "'" + value.substring(0,10) + " " + value.substring(11,19) + "'";
        }
        values += value + ", ";
    }
    return values.slice(0,-2);
}

function getObjectValue(tweet, stringMultipleIndexes) {
    var index = stringMultipleIndexes.split('.');
    var value = tweet;
    for(var i = 0; i < index.length; i++) {

        if (value[index[i]] != null && value[index[i]] != undefined) {
            value = value[index[i]];
        } else {
            return null;
        }
    }
    return String(value);
}

module.exports = TwitterInsight;<commit_msg>something went wrong with twitter api<commit_after>"use strict"

var async = require('async'),
    http = require('http'),
    request = require('request'),
    Database = require('./database'),
    config = require('nconf'),
    version = 'api:' + config.get("api:version");

var pool = new http.Agent;
    pool.maxSockets = 500;

var query,
    count,
    tweets,
    MAX_TWEETS,
    insightHOST,
    schemaTweetMap,
    progress;

function TwitterInsight(searchString) {
    query = searchString;
    MAX_TWEETS = 500;
    progress = 0;
    populateSchemaTweetMap();
    getColumns();

    var services = JSON.parse(process.env.VCAP_SERVICES || "{}");
    insightHOST = services["twitterinsights"] ? services["twitterinsights"][0].credentials.url : config.get(version + ':twitterInsights').url;
}

TwitterInsight.prototype = {
	count: function(callback) {
        var url = insightHOST + '/api/v1/messages/count';
        retrieveInsight(url, query, function(err, data) {
            if(!err) {
                count = data['search']['results'];
                data.count = count;
            }
            callback(err, data);
        });
    },
    fetch: function(callback) {
        var url = insightHOST + '/api/v1/messages/search?q=' + query + '&size=' + MAX_TWEETS;
        console.log(url);
        async.timesSeries(3, function(n, next) {
            retrieveInsight(url, function(err, data) {
                url = data['related']['next']['href'];
                // count = data['search']['results'];
                // tweets.push(data['tweets']);
                //TODO: insert into database here
                next(err, data);
            });
        }, function(err, data) {
            callback(err, count);
        });
	},
    insert: function(movieName, tableName, callback) {
        //check if there is already an ajax running
        if(progress == 0) {
            //create a table with the movie name to store tweets
            var db = new Database(),
                url = insightHOST + '/api/v1/messages/search';
            createMovieTweetsTable(db, tableName, function(err, data) {
                if(!err) {
                    //retrieve the tweets and insert into table
                    //Twitter for Insight provides at max 500 tweets per request
                    //call the retrieve and insert function total number of tweets / max tweets per request
                    var times =  Math.ceil(count / MAX_TWEETS);
                    async.timesSeries(times, function(n, next) {
                        retrieveInsight(url, query, function(err, data) {
                            if (!err && data['tweets'].length > 0) {
                                insertTweets(db, tableName, data['tweets'], function(err, message, rows) {
                                    if(!err) {
                                        progress += rows;
                                        process.stdout.write("\rso far: " + progress);
                                    }
                                    next(err, data);
                                    console.log("twitterInsight.js: insertTweets callback")
                                });
                            } else {
                           		console.log("twitterInsight.js: retrieveInsight callback")
                           		console.log(err);
                           		console.log(data);
                              //callback(err, progress)
                           }
                        }, (n*MAX_TWEETS));
                    }, function(err, data) {
                        return callback(err, progress);
                    });
                } else {
                	console.log("twitterInsight.js: createMovieTable callback")
                    callback(err, progress);
                }
            });
        }
    },
    getCount: function() {
        return count;
    },
    getTweets: function() {
        return tweets;
    },
    print: function() {
        console.log("No. of Tweets found: " + count);
        console.log(tweets)
    }
}

function retrieveInsight(url, query, callback, from) {
    var params = null;
    //send query parameters as below in order to handle special characters in values such as '#'
    if(query) {
        params = {
            q: query,
            size: MAX_TWEETS,
            from: from?from:0
        }
    }
    request({
        method: "GET",
        url: url,
        qs: params,
        pool: pool,
        // auth: {
        //     'user': 'f6204541d9434de8a1363a9214fe5455',
        //     'pass': 'oUzn5yaGuq'
        // },
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        }
    }, function(err, response, data) {
        if (err) {
            console.log("ERR")
            callback(err);
        } else {
            if (response.statusCode == 200) {
                try {
                    callback(null, JSON.parse(data));
                } catch(e) {
                    callback(true, {
                        message: {
                            description: e.message
                        },
                        status_code: response.statusCode
                    });
                }
            } else {
                callback(true, {
                    message: {
                        description: data
                    },
                    status_code: response.statusCode
                });
            }
        }
    });
}

function createMovieTweetsTable (db, tableName, callback) {
    var createTableQuery = 'CREATE TABLE '
        + tableName
        + '(GENERATORDISPLAYNAME VARCHAR(1024),'
        + 'ID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),'
        + 'MSGBODY VARCHAR(2048),'
        + 'MSGHASHTAGS VARCHAR(2048),'
        + 'MSGID VARCHAR(128),'
        + 'MSGPOSTEDTIME TIMESTAMP,'
        + 'MSGTYPE VARCHAR(128),'
        + 'MSGSENTIMENT VARCHAR(128) NOT NULL WITH DEFAULT \'NEUTRAL\','
        + 'SMAAUTHORCITY VARCHAR(1024),'
        + 'SMAAUTHORCOUNTRY VARCHAR(1024),'
        + 'SMAAUTHORGENDER VARCHAR(1024),'
        + 'SMAAUTHORSTATE VARCHAR(1024),'
        + 'USERDISPLAYNAME VARCHAR(1024),'
        + 'USERFOLLOWERSCOUNT INT,'
        + 'USERFRIENDSCOUNT INT,'
        + 'USERID VARCHAR(128),'
        + 'USERLANGUAGE VARCHAR(128),'
        + 'USERLINK VARCHAR(1024),'
        + 'USERLISTEDCOUNT INT,'
        + 'USERLOCATION VARCHAR(1024),'
        + 'USERPREFERREDUSERNAME VARCHAR(1024),'
        + 'USERSTATUSESCOUNT INT,'
        + 'USERUTCOFFSET VARCHAR(1024),'
        + 'USERVERIFIED VARCHAR(1024),'
        + 'PRIMARY KEY(ID)'
        + ') ORGANIZE BY ROW';

    // db.checkTableExist(tableName, function(found) {
        // db.executeQuery(dropFirst, function(result) {
        // console.log(result);
        // if(!found) {
            db.executeQuery(createTableQuery, function(err, result) {
                if(err) console.log("Error in creating tweet table for the movie");
                callback(err, {message:"New table "+ tableName +" created"});
            });
        // } else {
            //TODO: dro table if exist logic ot beimpl
            // console.log("Table exists already");
            // callback(false, {message:"Table exists already."});
        // }
    // });
    // });
}

function insertTweets(db, tableName, tweets, callback) {
    var database = new Database();
    try {
        var insertQuery = "INSERT INTO " + tableName + " (" + getColumns() + ") VALUES ";
        for (var i = 0; i < tweets.length; i++) {
            insertQuery += "("+ getColumnsValues(tweets[i]) + "),";
        }
        insertQuery = insertQuery.slice(0,-1);
        database.executeQuery(insertQuery, function(err, result) {
            if( !err ) {
                console.log("db insert: success")
                callback(err, result.message + " IN TWEETS INSERTION.", i);
            } else {
                console.log(insertQuery)
                console.log(result)
                console.log("db insert: failure")
                result.message = result.message + " IN TWEETS INSERTION.";
                callback(err, result, i);
            }
            database = null;
        });
    } catch(e) {
        console.log('catch')
        console.log(insertQuery)
        console.log(result)
        console.log(e)
        callback(true, e)
    }
}

function populateSchemaTweetMap() {
    schemaTweetMap = {
        'GENERATORDISPLAYNAME':{
            'type':'VARCHAR',
            'mapping':'message.generator.displayName'
        },
        'MSGBODY':{
            'type':'VARCHAR',
            'mapping':'message.body'
        },
        'MSGHASHTAGS':{
            'type':'VARCHAR',
            'mapping':'message.twitter_entities.hashtags'
        },
        'MSGID':{
            'type':'VARCHAR',
            'mapping':'message.id'
        },
        'MSGPOSTEDTIME':{
            'type':'TIMESTAMP',
            'mapping':'message.postedTime'
        },
        'MSGTYPE':{
            'type':'VARCHAR',
            'mapping':'message.verb'
        },
        'MSGSENTIMENT':{
            'type':'VARCHAR',
            'mapping':'cde.content.sentiment.polarity',
            'default':'NEUTRAL'
        },
        'SMAAUTHORCITY':{
            'type':'VARCHAR',
            'mapping':'cde.author.location.city'
        },
        'SMAAUTHORCOUNTRY':{
            'type':'VARCHAR',
            'mapping':'cde.author.location.country'
        },
        'SMAAUTHORGENDER':{
            'type':'VARCHAR',
            'mapping':'cde.author.gender'
        },
        'SMAAUTHORSTATE':{
            'type':'VARCHAR',
            'mapping':'cde.author.location.state'
        },
        'USERDISPLAYNAME':{
            'type':'VARCHAR',
            'mapping':'message.actor.displayName'
        },
        'USERFOLLOWERSCOUNT':{
            'type':'INT',
            'mapping':'message.actor.followersCount'
        },
        'USERFRIENDSCOUNT':{
            'type':'INT',
            'mapping':'message.actor.friendsCount'
        },
        'USERID':{
            'type':'VARCHAR',
            'mapping':'message.actor.id'
        },
        'USERLANGUAGE':{
            'type':'VARCHAR',
            'mapping':'message.actor.languages'
        },
        'USERLINK':{
            'type':'VARCHAR',
            'mapping':'message.actor.links.href'
        },
        'USERLISTEDCOUNT':{
            'type':'INT',
            'mapping':'message.actor.listedCount'
        },
        'USERLOCATION':{
            'type':'VARCHAR',
            'mapping':'message.actor.location.displayName'
        },
        'USERPREFERREDUSERNAME':{
            'type':'VARCHAR',
            'mapping':'message.actor.preferredUsername'
        },
        'USERSTATUSESCOUNT':{
            'type':'INT',
            'mapping':'message.actor.statusesCount'
        },
        'USERUTCOFFSET':{
            'type':'VARCHAR',
            'mapping':'message.actor.utcOffset'
        },
        'USERVERIFIED':{
            'type':'VARCHAR',
            'mapping':'message.actor.verified'
        }
    }
}

function getColumns() {
    var keys = '';
    for(var key in schemaTweetMap) {
        keys += key + ',';
    }
    return keys.slice(0,-1);
}

function getColumnsValues(tweet) {
    var index, value = '', values = '';
    for(var key in schemaTweetMap) {
        index = schemaTweetMap[key].mapping;
        value = getObjectValue(tweet, index);
        if (!value) {
            value = (schemaTweetMap[key].default)? "'"+schemaTweetMap[key].default+"'" : null;
        } else if (schemaTweetMap[key].type === "VARCHAR") {
            value = "'" + value.replace(/\'/g,"''") + "'";
        } else if (schemaTweetMap[key].type === "INT") {
            value = parseInt(value) ;
        } else if (schemaTweetMap[key].type === "TIMESTAMP") {
            value = "'" + value.substring(0,10) + " " + value.substring(11,19) + "'";
        }
        values += value + ", ";
    }
    return values.slice(0,-2);
}

function getObjectValue(tweet, stringMultipleIndexes) {
    var index = stringMultipleIndexes.split('.');
    var value = tweet;
    for(var i = 0; i < index.length; i++) {

        if (value[index[i]] != null && value[index[i]] != undefined) {
            value = value[index[i]];
        } else {
            return null;
        }
    }
    return String(value);
}

module.exports = TwitterInsight;<|endoftext|>


<commit_before>/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		// score
		score : 0,
		//enemy's health
		enemyBaseHealth: 1,
		//players health
		playerBaseHealth: 1,
		enemyCreepHealth: 10,
		playerHealth: 10,
		enemyCreepAttack: 1,
		playerAttack: 1,
		playerAttackTimer: 1000,
		enemyCreepAttackTimer: 1000,
		playerMoveSpeed: 5,
		creepMoveSpeed: 5,
		gameTimerManager: "",
		HeroDeathManager: "",
		player: "",
		exp: 0,
		gold: 0,
		exp1: 0,
		exp2: 0,
		exp3: 0,
		exp4: 0,
		win: ""
		pausePos: "",
		buyscreen: "",
		buytext: ""
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	if (!me.video.init("screen",  me.video.CANVAS, 1067, 600, true, '1.0')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	me.save.add({exp: 0, exp1: 0, exp2: 0, exp3: 0, exp4: 0});

	me.state.SPENDEXP = 112;
	// Initialize the audio.
	me.audio.init("mp3,ogg");

	// Set a callback to run when loading is complete.
	me.loader.onload = this.loaded.bind(this);

	// Load the resources.
	me.loader.preload(game.resources);

	// Initialize melonJS and display a loading screen.
	me.state.change(me.state.LOADING);
},

	// Run on game resources loaded.
	"loaded" : function () {
		//registering the player
		me.pool.register("player", game.PlayerEntity, true);
		me.pool.register("PlayerBase", game.PlayerBaseEntity);
		//registering the enemy base
		me.pool.register("EnemyBase", game.EnemyBaseEntity);
		//registering the creep
		me.pool.register("EnemyCreep", game.EnemyCreep, true);
		//registering the GameManager
		me.pool.register("GameTimerManager", game.GameTimerManager);
		me.pool.register("HeroDeathManager", game.HeroDeathManager);
		me.pool.register("ExperienceManager", game.ExperienceManager);
		me.pool.register("SpendGold", game.SpendGold);

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());
		me.state.set(me.state.SPENDEXP, new game.SpendExp());
		// Start the game.
		me.state.change(me.state.MENU);
	}
};<commit_msg>Video 49, finishing setting up the buy menu<commit_after>/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		// score
		score : 0,
		//enemy's health
		enemyBaseHealth: 1,
		//players health
		playerBaseHealth: 1,
		enemyCreepHealth: 10,
		playerHealth: 10,
		enemyCreepAttack: 1,
		playerAttack: 1,
		playerAttackTimer: 1000,
		enemyCreepAttackTimer: 1000,
		playerMoveSpeed: 5,
		creepMoveSpeed: 5,
		gameTimerManager: "",
		HeroDeathManager: "",
		player: "",
		exp: 0,
		gold: 0,
		ability1: 0,
		ability2: 0,
		ability3: 0,
		skill1: 0,
		skill2: 0,
		skill3: 0,
		exp1: 0,
		exp2: 0,
		exp3: 0,
		exp4: 0,
		win: ""
		pausePos: "",
		buyscreen: "",
		buytext: ""
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	if (!me.video.init("screen",  me.video.CANVAS, 1067, 600, true, '1.0')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	me.save.add({exp: 0, exp1: 0, exp2: 0, exp3: 0, exp4: 0});

	me.state.SPENDEXP = 112;
	// Initialize the audio.
	me.audio.init("mp3,ogg");

	// Set a callback to run when loading is complete.
	me.loader.onload = this.loaded.bind(this);

	// Load the resources.
	me.loader.preload(game.resources);

	// Initialize melonJS and display a loading screen.
	me.state.change(me.state.LOADING);
},

	// Run on game resources loaded.
	"loaded" : function () {
		//registering the player
		me.pool.register("player", game.PlayerEntity, true);
		me.pool.register("PlayerBase", game.PlayerBaseEntity);
		//registering the enemy base
		me.pool.register("EnemyBase", game.EnemyBaseEntity);
		//registering the creep
		me.pool.register("EnemyCreep", game.EnemyCreep, true);
		//registering the GameManager
		me.pool.register("GameTimerManager", game.GameTimerManager);
		me.pool.register("HeroDeathManager", game.HeroDeathManager);
		me.pool.register("ExperienceManager", game.ExperienceManager);
		me.pool.register("SpendGold", game.SpendGold);

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());
		me.state.set(me.state.SPENDEXP, new game.SpendExp());
		// Start the game.
		me.state.change(me.state.MENU);
	}
};<|endoftext|>


<commit_before>(function() {
/* globals define, Ember, DS, jQuery */

  function processEmberShims() {
    var shims = {
      'ember': {
        'default': Ember
      },
      'ember-application': {
        'default': Ember.Application
      },
      'ember-array': {
        'default': Ember.Array
      },
      'ember-array/mutable': {
        'default': Ember.MutableArray
      },
      'ember-array/utils': {
        'A':            Ember.A,
        'isEmberArray': Ember.isArray,
        'wrap':         Ember.makeArray
      },
      'ember-component': {
        'default': Ember.Component
      },
      'ember-components/checkbox': {
        'default': Ember.Checkbox
      },
      'ember-components/text-area': {
        'default': Ember.TextArea
      },
      'ember-components/text-field': {
        'default': Ember.TextField
      },
      'ember-controller': {
        'default': Ember.Controller
      },
      'ember-controller/inject': {
        'default': Ember.inject.controller
      },
      'ember-controller/proxy': {
        'default': Ember.ArrayProxy
      },
      'ember-controllers/sortable': {
        'default': Ember.SortableMixin
      },
      'ember-debug': {
        'log':      Ember.debug,
        'inspect':  Ember.inspect,
        'run':      Ember.runInDebug,
        'warn':     Ember.warn
      },
      'ember-debug/container-debug-adapter': {
        'default': Ember.ContainerDebugAdapter
      },
      'ember-debug/data-adapter': {
        'default': Ember.DataAdapter
      },
      'ember-deprecations': {
        'deprecate':      Ember.deprecate,
        'deprecateFunc':  Ember.deprecateFunc
      },
      'ember-enumerable': {
        'default': Ember.Enumerable
      },
      'ember-evented': {
        'default': Ember.Evented
      },
      'ember-evented/on': {
        'default': Ember.on
      },
      'ember-globals-resolver': {
        'default': Ember.DefaultResolver
      },
      'ember-helper': {
        'default':  Ember.Helper,
        'helper':   Ember.Helper && Ember.Helper.helper
      },
      'ember-instrumentation': {
        'instrument':   Ember.Instrumentation.instrument,
        'reset':        Ember.Instrumentation.reset,
        'subscribe':    Ember.Instrumentation.subscribe,
        'unsubscribe':  Ember.Instrumentation.unsubscribe
      },
      'ember-locations/hash': {
        'default': Ember.HashLocation
      },
      'ember-locations/history': {
        'default': Ember.HistoryLocation
      },
      'ember-locations/none': {
        'default': Ember.NoneLocation
      },
      'ember-map': {
        'default':      Ember.Map,
        'withDefault':  Ember.MapWithDefault
      },
      'ember-metal/destroy': {
        'default': Ember.destroy
      },
      'ember-metal/events': {
        'addListener':    Ember.addListener,
        'removeListener': Ember.removeListener,
        'send':           Ember.sendEvent
      },
      'ember-metal/get': {
        'default': Ember.get
      },
      'ember-metal/mixin': {
        'default': Ember.Mixin
      },
      'ember-metal/observer': {
        'default':        Ember.observer,
        'addObserver':    Ember.addObserver,
        'removeObserver': Ember.removeObserver
      },
      'ember-metal/on-load': {
        'default':  Ember.onLoad,
        'run':      Ember.runLoadHooks
      },
      'ember-metal/set': {
        'default':        Ember.set,
        'setProperties':  Ember.setProperties,
        'trySet':         Ember.trySet
      },
      'ember-metal/utils': {
        'aliasMethod':  Ember.aliasMethod,
        'assert':       Ember.assert,
        'cacheFor':     Ember.cacheFor,
        'copy':         Ember.copy,
      },
      'ember-object': {
        'default': Ember.Object
      },
      'ember-platform': {
        'assign':         Ember.merge,
        'create':         Ember.create,
        'defineProperty': Ember.platform.defineProperty,
        'hasAccessors':   Ember.platform.hasPropertyAccessors,
        'keys':           Ember.keys
      },
      'ember-route': {
        'default': Ember.Route
      },
      'ember-router': {
        'default': Ember.Router
      },
      'ember-runloop': {
        'default':      Ember.run,
        'begin':        Ember.run.begin,
        'bind':         Ember.run.bind,
        'cancel':       Ember.run.cancel,
        'debounce':     Ember.run.debounce,
        'end':          Ember.run.end,
        'join':         Ember.run.join,
        'later':        Ember.run.later,
        'next':         Ember.run.next,
        'once':         Ember.run.once,
        'schedule':     Ember.run.schedule,
        'scheduleOnce': Ember.run.scheduleOnce,
        'throttle':     Ember.run.throttle
      },
      'ember-service': {
        'default': Ember.Service
      },
      'ember-service/inject': {
        'default': Ember.inject.service
      },
      'ember-set/ordered': {
        'default': Ember.OrderedSet
      },
      'ember-string': {
        'camelize':     Ember.String.camelize,
        'capitalize':   Ember.String.capitalize,
        'classify':     Ember.String.classify,
        'dasherize':    Ember.String.dasherize,
        'decamelize':   Ember.String.decamelize,
        'fmt':          Ember.String.fmt,
        'htmlSafe':     Ember.String.htmlSafe,
        'loc':          Ember.String.loc,
        'underscore':   Ember.String.underscore,
        'w':            Ember.String.w
      },
      'ember-utils': {
        'isBlank':    Ember.isBlank,
        'isEmpty':    Ember.isEmpty,
        'isNone':     Ember.isNone,
        'isPresent':  Ember.isPresent,
        'tryInvoke':  Ember.tryInvoke,
        'typeOf':     Ember.typeOf
      }
    };

    // populate `ember/computed` named exports
    shims['ember-computed'] = {
      'default': Ember.computed
    };
    var computedMacros = [
      "empty","notEmpty", "none", "not", "bool", "match",
      "equal", "gt", "gte", "lt", "lte", "alias", "oneWay",
      "reads", "readOnly", "deprecatingAlias",
      "and", "or", "collect", "sum", "min", "max",
      "map", "sort", "setDiff", "mapBy", "mapProperty",
      "filter", "filterBy", "filterProperty", "uniq",
      "union", "intersect"
    ];
    for (var i = 0, l = computedMacros.length; i < l; i++) {
      var key = computedMacros[i];
      shims['ember-computed'][key] = Ember.computed[key];
    }

    for (var moduleName in shims) {
      generateModule(moduleName, shims[moduleName]);
    }
  }

  function processEmberDataShims() {
    var shims = {
      'ember-data':                          '',
      'ember-data/model':                    'Model',
      'ember-data/serializers/rest':         'RESTSerializer',
      'ember-data/serializers/active-model': 'ActiveModelSerializer',
      'ember-data/serializers/json':         'JSONSerializer',
      'ember-data/serializers/json-api':     'JSONAPISerializer',
      'ember-data/adapters/json-api':        'JSONAPIAdapter',
      'ember-data/adapters/rest':            'RESTAdapter',
      'ember-data/adapter':                  'Adapter',
      'ember-data/adapters/active-model':    'ActiveModelAdapter',
      'ember-data/store':                    'Store',
      'ember-data/transform':                'Transform',
      'ember-data/attr':                     'attr',
      'ember-data/relationships':            ['hasMany', 'belongsTo']
    };

    for (var moduleName in shims) {
      generateLazyModule('DS', moduleName, shims[moduleName]);
    }

    if (Ember.Test) {
      var testShims = {
        'ember-test': {
          'default': Ember.Test
        },
        'ember-test/adapter': {
          'default': Ember.Test.Adapter
        },
        'ember-test/qunit-adapter': {
          'default': Ember.Test.QUnitAdapter
        }
      };

      for (var moduleName in testShims) {
        generateModule(moduleName, testShims[moduleName]);
      }
    }
  }

  function generateModule(name, values) {
    define(name, [], function() {
      'use strict';

      return values;
    });
  }

  function generateLazyModule(namespace, name, globalName) {
    define(name, [], function() {
      'use strict';

      var exportObject = {};

      if (typeof globalName === 'object') {
        for (var i = 0, l = globalName.length; i < l; i++) {
          exportObject[globalName[i]] = window[namespace][globalName[i]];
        }
      } else {
        exportObject['default'] = (globalName !== '') ? window[namespace][globalName] : window[namespace];
      }

      return exportObject;
    });
  }

  processEmberShims();
  processEmberDataShims();
  generateModule('jquery', { 'default': self.jQuery });
  generateModule('rsvp', { 'default': Ember.RSVP });
})();
<commit_msg>Remove ember-data shims.<commit_after>(function() {
/* globals define, Ember, DS, jQuery */

  function processEmberShims() {
    var shims = {
      'ember': {
        'default': Ember
      },
      'ember-application': {
        'default': Ember.Application
      },
      'ember-array': {
        'default': Ember.Array
      },
      'ember-array/mutable': {
        'default': Ember.MutableArray
      },
      'ember-array/utils': {
        'A':            Ember.A,
        'isEmberArray': Ember.isArray,
        'wrap':         Ember.makeArray
      },
      'ember-component': {
        'default': Ember.Component
      },
      'ember-components/checkbox': {
        'default': Ember.Checkbox
      },
      'ember-components/text-area': {
        'default': Ember.TextArea
      },
      'ember-components/text-field': {
        'default': Ember.TextField
      },
      'ember-controller': {
        'default': Ember.Controller
      },
      'ember-controller/inject': {
        'default': Ember.inject.controller
      },
      'ember-controller/proxy': {
        'default': Ember.ArrayProxy
      },
      'ember-controllers/sortable': {
        'default': Ember.SortableMixin
      },
      'ember-debug': {
        'log':      Ember.debug,
        'inspect':  Ember.inspect,
        'run':      Ember.runInDebug,
        'warn':     Ember.warn
      },
      'ember-debug/container-debug-adapter': {
        'default': Ember.ContainerDebugAdapter
      },
      'ember-debug/data-adapter': {
        'default': Ember.DataAdapter
      },
      'ember-deprecations': {
        'deprecate':      Ember.deprecate,
        'deprecateFunc':  Ember.deprecateFunc
      },
      'ember-enumerable': {
        'default': Ember.Enumerable
      },
      'ember-evented': {
        'default': Ember.Evented
      },
      'ember-evented/on': {
        'default': Ember.on
      },
      'ember-globals-resolver': {
        'default': Ember.DefaultResolver
      },
      'ember-helper': {
        'default':  Ember.Helper,
        'helper':   Ember.Helper && Ember.Helper.helper
      },
      'ember-instrumentation': {
        'instrument':   Ember.Instrumentation.instrument,
        'reset':        Ember.Instrumentation.reset,
        'subscribe':    Ember.Instrumentation.subscribe,
        'unsubscribe':  Ember.Instrumentation.unsubscribe
      },
      'ember-locations/hash': {
        'default': Ember.HashLocation
      },
      'ember-locations/history': {
        'default': Ember.HistoryLocation
      },
      'ember-locations/none': {
        'default': Ember.NoneLocation
      },
      'ember-map': {
        'default':      Ember.Map,
        'withDefault':  Ember.MapWithDefault
      },
      'ember-metal/destroy': {
        'default': Ember.destroy
      },
      'ember-metal/events': {
        'addListener':    Ember.addListener,
        'removeListener': Ember.removeListener,
        'send':           Ember.sendEvent
      },
      'ember-metal/get': {
        'default': Ember.get
      },
      'ember-metal/mixin': {
        'default': Ember.Mixin
      },
      'ember-metal/observer': {
        'default':        Ember.observer,
        'addObserver':    Ember.addObserver,
        'removeObserver': Ember.removeObserver
      },
      'ember-metal/on-load': {
        'default':  Ember.onLoad,
        'run':      Ember.runLoadHooks
      },
      'ember-metal/set': {
        'default':        Ember.set,
        'setProperties':  Ember.setProperties,
        'trySet':         Ember.trySet
      },
      'ember-metal/utils': {
        'aliasMethod':  Ember.aliasMethod,
        'assert':       Ember.assert,
        'cacheFor':     Ember.cacheFor,
        'copy':         Ember.copy,
      },
      'ember-object': {
        'default': Ember.Object
      },
      'ember-platform': {
        'assign':         Ember.merge,
        'create':         Ember.create,
        'defineProperty': Ember.platform.defineProperty,
        'hasAccessors':   Ember.platform.hasPropertyAccessors,
        'keys':           Ember.keys
      },
      'ember-route': {
        'default': Ember.Route
      },
      'ember-router': {
        'default': Ember.Router
      },
      'ember-runloop': {
        'default':      Ember.run,
        'begin':        Ember.run.begin,
        'bind':         Ember.run.bind,
        'cancel':       Ember.run.cancel,
        'debounce':     Ember.run.debounce,
        'end':          Ember.run.end,
        'join':         Ember.run.join,
        'later':        Ember.run.later,
        'next':         Ember.run.next,
        'once':         Ember.run.once,
        'schedule':     Ember.run.schedule,
        'scheduleOnce': Ember.run.scheduleOnce,
        'throttle':     Ember.run.throttle
      },
      'ember-service': {
        'default': Ember.Service
      },
      'ember-service/inject': {
        'default': Ember.inject.service
      },
      'ember-set/ordered': {
        'default': Ember.OrderedSet
      },
      'ember-string': {
        'camelize':     Ember.String.camelize,
        'capitalize':   Ember.String.capitalize,
        'classify':     Ember.String.classify,
        'dasherize':    Ember.String.dasherize,
        'decamelize':   Ember.String.decamelize,
        'fmt':          Ember.String.fmt,
        'htmlSafe':     Ember.String.htmlSafe,
        'loc':          Ember.String.loc,
        'underscore':   Ember.String.underscore,
        'w':            Ember.String.w
      },
      'ember-utils': {
        'isBlank':    Ember.isBlank,
        'isEmpty':    Ember.isEmpty,
        'isNone':     Ember.isNone,
        'isPresent':  Ember.isPresent,
        'tryInvoke':  Ember.tryInvoke,
        'typeOf':     Ember.typeOf
      }
    };

    // populate `ember/computed` named exports
    shims['ember-computed'] = {
      'default': Ember.computed
    };
    var computedMacros = [
      "empty","notEmpty", "none", "not", "bool", "match",
      "equal", "gt", "gte", "lt", "lte", "alias", "oneWay",
      "reads", "readOnly", "deprecatingAlias",
      "and", "or", "collect", "sum", "min", "max",
      "map", "sort", "setDiff", "mapBy", "mapProperty",
      "filter", "filterBy", "filterProperty", "uniq",
      "union", "intersect"
    ];
    for (var i = 0, l = computedMacros.length; i < l; i++) {
      var key = computedMacros[i];
      shims['ember-computed'][key] = Ember.computed[key];
    }

    for (var moduleName in shims) {
      generateModule(moduleName, shims[moduleName]);
    }
  }

  function processTestShims() {
    if (Ember.Test) {
      var testShims = {
        'ember-test': {
          'default': Ember.Test
        },
        'ember-test/adapter': {
          'default': Ember.Test.Adapter
        },
        'ember-test/qunit-adapter': {
          'default': Ember.Test.QUnitAdapter
        }
      };

      for (var moduleName in testShims) {
        generateModule(moduleName, testShims[moduleName]);
      }
    }
  }

  function generateModule(name, values) {
    define(name, [], function() {
      'use strict';

      return values;
    });
  }

  function generateLazyModule(namespace, name, globalName) {
    define(name, [], function() {
      'use strict';

      var exportObject = {};

      if (typeof globalName === 'object') {
        for (var i = 0, l = globalName.length; i < l; i++) {
          exportObject[globalName[i]] = window[namespace][globalName[i]];
        }
      } else {
        exportObject['default'] = (globalName !== '') ? window[namespace][globalName] : window[namespace];
      }

      return exportObject;
    });
  }

  processEmberShims();
  processTestShims();
  generateModule('jquery', { 'default': self.jQuery });
  generateModule('rsvp', { 'default': Ember.RSVP });
})();
<|endoftext|>


<commit_before>/**
 * Helpers for working with responses from the SmartyStreets API.
 */

var changeCaseKeys = require('change-case-keys');
var filter = require('lodash.filter');
var isEmpty = require('lodash.isempty');
var us = require('us');

var models = require('../../../../models');

var makeCanonicalAddressFromSSResponse = function(rawAddress) {
  var addressBits = [
    rawAddress['delivery_line_1'],
    rawAddress['delivery_line_2'],
    rawAddress['last_line']
  ];
  var filteredBits = /** @type {Array} */ filter(addressBits, function(addressBit) {
    return !isEmpty(addressBit);
  });
  var address = filteredBits.join(', ');

  var components = rawAddress['components'];
  var usRegion = us.lookup(components['state_abbreviation']);
  components.stateName = usRegion !== undefined ? usRegion.name : '';

  return new models.CanonicalAddress({
    inputId: rawAddress['input_id'],
    inputIndex: rawAddress['input_index'],
    address: address,
    longitude: rawAddress['metadata']['longitude'],
    latitude: rawAddress['metadata']['latitude'],
    district: rawAddress['metadata']['congressional_district'],
    county: rawAddress['metadata']['county_name'],
    components: changeCaseKeys(components, 'camelize')
  });

};

module.exports.makeCanonicalAddressFromSSResponse = makeCanonicalAddressFromSSResponse;
<commit_msg>Treat at-large districts as though they were 0<commit_after>/**
 * Helpers for working with responses from the SmartyStreets API.
 */

var changeCaseKeys = require('change-case-keys');
var filter = require('lodash.filter');
var isEmpty = require('lodash.isempty');
var us = require('us');

var models = require('../../../../models');

var makeCanonicalAddressFromSSResponse = function(rawAddress) {
  var addressBits = [
    rawAddress['delivery_line_1'],
    rawAddress['delivery_line_2'],
    rawAddress['last_line']
  ];
  var filteredBits = /** @type {Array} */ filter(addressBits, function(addressBit) {
    return !isEmpty(addressBit);
  });
  var address = filteredBits.join(', ');

  var components = rawAddress['components'];
  var usRegion = us.lookup(components['state_abbreviation']);
  components.stateName = usRegion !== undefined ? usRegion.name : '';

  var district = rawAddress['metadata']['congressional_district'];

  return new models.CanonicalAddress({
    inputId: rawAddress['input_id'],
    inputIndex: rawAddress['input_index'],
    address: address,
    longitude: rawAddress['metadata']['longitude'],
    latitude: rawAddress['metadata']['latitude'],
    district: (district == "AL" ? "0" : district),
    county: rawAddress['metadata']['county_name'],
    components: changeCaseKeys(components, 'camelize')
  });

};

module.exports.makeCanonicalAddressFromSSResponse = makeCanonicalAddressFromSSResponse;
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('blocks.exception')
        .factory('exception', exception);

    exception.$inject = ['$q', 'logger'];
    function exception($q, logger) {
        var service = {
            catcher: catcher
        };
        return service;

        function catcher(message) {
            return function(e) {
                var thrownDescription;
                var newMessage;
                if (e.data && e.data.description) {
                    thrownDescription = '\n' + e.data.description;
                    newMessage = message + thrownDescription;
                }
                e.data.description = newMessage;
                logger.error(newMessage);
                return $q.reject(e);
            };
        }
    }
})();
<commit_msg>Fix bug exception.service.<commit_after>(function() {
    'use strict';

    angular
        .module('blocks.exception')
        .factory('exception', exception);

    exception.$inject = ['$q', 'logger'];
    function exception($q, logger) {
        var service = {
            catcher: catcher
        };
        return service;

        function catcher(message) {
            return function(e) {
                logger.error(message, e);
            };
        }
    }
})();
<|endoftext|>


<commit_before>
//if this seems like it will work, move to random tables. based on recursiveSlacker's idea.
var comedyInterestNouns = ["joke","clown","fun", "folk", "bloke"];
var comedyInterestVerbs = ["joke", "frown", "stun", "soak", "choke", "scrunch"];

var athleticInterestNouns = ["sun","lunch","crown","yolk"];
var athleticInterestVerbs = ["run","punch", "down", "drown", "soak", "won"];
//http://www.rhymezone.com/r/rhyme.cgi?Word=sun&typeofrhyme=perfect&org1=syl&org2=l&org3=y
var wordsRhymeTown = ["town", "down", "frown", "clown", "brown", "crown", "drown","noun"];
var wordsRhymeJoke = ["bloke","broke","croak","choke","folk","oak","smoke","soak","woke","yolk","yoke","coke", "spoke"];

var wordsRhymeSun = ["bun","fun","gun","son","hun","none","nun","stun","spun","shun","run","won"];
var wordsRhymePunch = ["brunch","punch","lunch","bunch","crunch","hunch","munch","scrunch"];

//would be so dope to rap about what's happened in the session.
//could read session summary?
//worry about this LATER, and definitely not in this stand alone page.
window.onload = function() {
		rapper1Line("Hello World")
		rapper2Line("Goodbye World");
		//and it don't stop till a rhyme isn't found. points on how many lines you manage. then opponent turn. they try to rhyme their first rhyme with your last.
}

//red text
function rapper1Line(line){
	$("#rap").append(""+line+"
")
}

//blue text
function rapper2Line(line){
	$("#rap").append(""+line+"
")
}
<commit_msg>rap engine is coming together<commit_after>
//if this seems like it will work, move to random tables. based on recursiveSlacker's idea.
var comedyInterestNouns = ["joke","clown","fun", "folk", "bloke"];
var comedyInterestVerbs = ["joke", "frown", "stun", "soak", "choke", "scrunch"];

var athleticInterestNouns = ["sun","lunch","crown","yolk"];
var athleticInterestVerbs = ["run","punch", "down", "drown", "soak", "won"];
//http://www.rhymezone.com/r/rhyme.cgi?Word=sun&typeofrhyme=perfect&org1=syl&org2=l&org3=y
var wordsRhymeTown = ["town", "down", "frown", "clown", "brown", "crown", "drown","noun"];
var wordsRhymeJoke = ["bloke","broke","croak","choke","folk","oak","smoke","soak","woke","yolk","yoke","coke", "spoke"];

var wordsRhymeSun = ["bun","fun","gun","son","hun","none","nun","stun","spun","shun","run","won"];
var wordsRhymePunch = ["brunch","punch","lunch","bunch","crunch","hunch","munch","scrunch"];

var noun = "noun";
var verb = "verb";
var rapTemplates = [new RapTemplate("Yo, you must be some kind of ",noun, " sitting there like you think you can ", verb) ];
rapTemplates.push(new RapTemplate("Your ass is grass, you ain't got that ",noun, " you have the worst skills that i ever did ", verb) );

//would be so dope to rap about what's happened in the session.
//could read session summary?
//worry about this LATER, and definitely not in this stand alone page.
window.onload = function() {
		rapper1Line("Hello World")
		rapper2Line("Goodbye World");
		//and it don't stop till a rhyme isn't found. points on how many lines you manage. then opponent turn. they try to rhyme their first rhyme with your last.
}

//red text
function rapper1Line(line){
	$("#rap").append(""+line+"
")
}

//blue text
function rapper2Line(line){
	$("#rap").append(""+line+"
")
}

function RapTemplate(part1, p1Type, part2, p2Type){
	this.part1 = part1;
	this.part1Type = p1Type;
	this.part2 = part2
	this.part2Type = p2Type;

	this.findWordBasedOnPart1AndInterest = function(interest){
		var wordTypeArray = this.matchInterestToWordTypeArray(interest);
		if(wordTypeArray){
				return getRandomElementFromArray(wordTypeArray);
		}
		return null;
	}

	this.matchInterestToWordTypeArray = function(interest){
		var ret = null;
		if(comedy_interests.indexOf(interest) != -1 && this.part1Type == noun){
				ret = comedyInterestNouns;
		}else if(comedy_interests.indexOf(interest) != -1 && this.part1Type == verb){
			ret = comedyInterestVerbs;
		}else if(athletic_interests.indexOf(interest) != -1 && this.part1Type == noun){
			ret = athleticInterestNouns;
		}else if(athletic_interests.indexOf(interest) != -1 && this.part1Type == verb){
			ret = athleticInterestVerbs;
		}
		return ret;
	}

	this.matchWordWithRhymeArray = function(word){
		var ret = null;
		if(wordsRhymeTown.indexOf(word) != -1){
			return wordsRhymeTown;
		}else if(wordsRhymeJoke.indexOf(word) != -1){
			return wordsRhymeJoke;
		}else if(wordsRhymeSun.indexOf(word) != -1){
			return wordsRhymeSun;
		}else if(wordsRhymePunch.indexOf(word) != -1){
			return wordsRhymePunch;
		}
	}

	this.findWordBasedOnPart2AndInterestAndPart1Word = function(interest,word){
		//first, I need to know which set of rhyming words the word falls in.
		var rhyme_array = this.matchWordWithRhymeArray(word);
		console.log("Rhyme Array: ")
		console.log(rhyme_array)
		//once I know that, see if I can find one of the rhyming words in the interest verb/noun list.
		var wordTypeArray =  this.matchInterestToWordTypeArray(interest);
		if(rhyme_array){
			var results = intersection(rhyme_array, wordTypeArray);
		}
		if(results && results.length > 0){
			return getRandomElementFromArray(results);
		}
		return null;

	}

}

//http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
//really was a good idea on recursiveSlacker's part.
function intersection (a, b) {
  var seen = a.reduce(function (h, k) {
    h[k] = true;
    return h;
  }, {});

  return b.filter(function (k) {
    var exists = seen[k];
    delete seen[k];
    return exists;
  });
}
<|endoftext|>


<commit_before>/**
 * StarField.js
 *
 * FooFighter.js — StarField entity
 *
 * This class represents the display object that renders the moving
 * starfield background in the game world.
 */

;(function( FooFighter ){

'use strict';

function StarField ( gameState, group ) {
    var d = new Date();

    this.gameState = gameState;
    this.game = gameState.game;
    this.group = group;
    // Background
    this.gameState.game.load.image(
        'background',
        'assets/img/background.png'
    );
    this.gameState.game.load.image(
        'speedLine',
        'assets/img/speedLine.png'
    );
    // Star tile
    this.gameState.game.load.image(
        'starBackground',
        'assets/img/starBackground.png'
    );
    this.config = {
        field: {
            lineSpeed: 800,
            starSpeed: 500,
            lineOpacity: 0.08,
            starOpacity: 0.15,
            lineThrottle: 100,
            starThrottle: 10
        }
    };
    this.shouldAddStar = true;
    this.shouldAddSpeedLine = true;
    this.lastCreated = {
        line: d.getTime(),
        star: d.getTime()
    };
    this.bindEvents();
}

var proto = StarField.prototype;

proto.bindEvents = function(){
    var vent = this.gameState.vent;
    vent.on('create', this.create.bind(this));
    vent.on('update', this.moveField.bind(this));
    return this;
};

proto.create = function(){
    var gs = this.gameState,
        game = gs.game,
        stars,
        tile;

    // Add the solid background sprite entity
    // this.gameState.groups.background.add(
    //     game.add.tileSprite(
    //         0, 0, game.world.width, game.world.height, 'background'
    //     )
    // );
    // Commenting this out for now, kind of like the darker game world

    // In another group, use our star tile png to create
    // the starfield background
    stars = this.group;
    for (var x = -8; x < 8; x++) {
        for (var y = -6; y < 6; y++) {
            tile = stars.create(x*254, y*256, 'starBackground');
            tile.alpha = 0.35;
        }
    };

    this.game.time.events.repeat(100, 10, this.addSpeedLine.bind(this), this);
    this.game.time.events.repeat(10, 100, this.addStar.bind(this), this);

    return this;
};

proto.moveField = function(){
    var stars = this.group;

    // This is a bit of a hack, we're just moving the background
    // group along the Y axis and starting over when we go too far
    stars.y = stars.y > 768 ? 0 : stars.y;
    stars.y += 6.0;

    return this;
};

proto.addSpeedLine = function(){
    var field = this.config.field,
        randInRange = FooFighter.Util.randInRange,
        game = this.game,
        line;

    line = this.game.add.sprite(
        game.world.width * Math.random(),
        -100,
        'speedLine'
    );
    line.alpha = field.lineOpacity;
    line.events.onOutOfBounds.add(function(){
        this.y = -100;
        this.x = game.world.width * Math.random();
    }, line);
    line.body.velocity.y = randInRange(field.lineSpeed*0.8, field.lineSpeed);

    return line;
};

proto.addStar = function(){
    var field = this.config.field,
        randInRange = FooFighter.Util.randInRange,
        starType = 'Background/starSmall.png',
        game = this.game,
        star;

    if ( Math.random() >= 0.9 ) {
        starType = 'Background/starBig.png'
    }
    star = this.game.add.sprite(
        game.world.width * Math.random(),
        0,
        'sprites',
        starType
    );
    star.alpha = field.starOpacity;
    star.events.onOutOfBounds.add(function(){
        this.y = 0;
        this.x = game.world.width * Math.random();
    }, star);
    star.body.velocity.y = randInRange(field.starSpeed*0.8, field.starSpeed);

    return star;
};

FooFighter.StarField = StarField;

})(FooFighter);
<commit_msg>make previous changes configurable<commit_after>/**
 * StarField.js
 *
 * FooFighter.js — StarField entity
 *
 * This class represents the display object that renders the moving
 * starfield background in the game world.
 */

;(function( FooFighter ){

'use strict';

function StarField ( gameState, group ) {
    var d = new Date();

    this.gameState = gameState;
    this.game = gameState.game;
    this.group = group;
    // Background
    this.gameState.game.load.image(
        'background',
        'assets/img/background.png'
    );
    this.gameState.game.load.image(
        'speedLine',
        'assets/img/speedLine.png'
    );
    // Star tile
    this.gameState.game.load.image(
        'starBackground',
        'assets/img/starBackground.png'
    );
    this.config = {
        field: {
            lineSpeed: 800,
            starSpeed: 500,
            lineOpacity: 0.08,
            starOpacity: 0.15,
            lineThrottle: 100,
            starThrottle: 10,
            numLines: 6,
            numStars: 100,
            velocityVariance: 0.5
        }
    };
    this.shouldAddStar = true;
    this.shouldAddSpeedLine = true;
    this.lastCreated = {
        line: d.getTime(),
        star: d.getTime()
    };
    this.bindEvents();
}

var proto = StarField.prototype;

proto.bindEvents = function(){
    var vent = this.gameState.vent;
    vent.on('create', this.create.bind(this));
    vent.on('update', this.moveField.bind(this));
    return this;
};

proto.create = function(){
    var gs = this.gameState,
        config = this.config,
        game = gs.game,
        stars,
        tile;

    // Add the solid background sprite entity
    // this.gameState.groups.background.add(
    //     game.add.tileSprite(
    //         0, 0, game.world.width, game.world.height, 'background'
    //     )
    // );
    // Commenting this out for now, kind of like the darker game world

    // In another group, use our star tile png to create
    // the starfield background
    stars = this.group;
    for (var x = -8; x < 8; x++) {
        for (var y = -6; y < 6; y++) {
            tile = stars.create(x*254, y*256, 'starBackground');
            tile.alpha = 0.35;
        }
    };

    this.game.time.events.repeat(
        config.field.lineThrottle,
        config.field.numLines,
        this.addSpeedLine.bind(this),
        this
    );
    this.game.time.events.repeat(
        config.field.starThrottle,
        config.field.numStars,
        this.addStar.bind(this),
        this
    );

    return this;
};

proto.moveField = function(){
    var stars = this.group;

    // This is a bit of a hack, we're just moving the background
    // group along the Y axis and starting over when we go too far
    stars.y = stars.y > 768 ? 0 : stars.y;
    stars.y += 6.0;

    return this;
};

proto.addSpeedLine = function(){
    var field = this.config.field,
        randInRange = FooFighter.Util.randInRange,
        game = this.game,
        variance = this.config.field.velocityVariance,
        line;

    line = this.game.add.sprite(
        game.world.width * Math.random(),
        -100,
        'speedLine'
    );
    line.alpha = field.lineOpacity;
    line.events.onOutOfBounds.add(function(){
        this.y = -100;
        this.x = game.world.width * Math.random();
    }, line);
    line.body.velocity.y = randInRange(
        field.lineSpeed * 0.5, field.lineSpeed
    );

    return line;
};

proto.addStar = function(){
    var field = this.config.field,
        randInRange = FooFighter.Util.randInRange,
        starType = 'Background/starSmall.png',
        variance = this.config.field.velocityVariance,
        game = this.game,
        star;

    if ( Math.random() >= 0.9 ) {
        starType = 'Background/starBig.png'
    }
    star = this.game.add.sprite(
        game.world.width * Math.random(),
        0,
        'sprites',
        starType
    );
    star.alpha = field.starOpacity;
    star.events.onOutOfBounds.add(function(){
        this.y = 0;
        this.x = game.world.width * Math.random();
    }, star);
    star.body.velocity.y = randInRange(
        field.starSpeed * variance, field.starSpeed
    );

    return star;
};

FooFighter.StarField = StarField;

})(FooFighter);
<|endoftext|>


<commit_before>import MeshBVH from '../src/MeshBVH.js';

export function generateAsync( geometry, options = {} ) {

	return new Promise( ( resolve, reject ) => {

		const worker = new Worker( './generateAsync.worker.js' );
		worker.onmessage = e => {

			const { serialized, position, error } = e.data;

			worker.terminate();
			if ( error ) {

				reject( new Error( error ) );

			} else {

				const bvh = MeshBVH.deserialize( serialized, geometry, false );

				// we need to replace the arrays because they're neutered entirely by the
				// webworker transfer.
				geometry.attributes.position.array = position;
				if ( geometry.index ) {

					geometry.index.array = serialized.index;

				}
				resolve( bvh );

			}

		};

		const index = geometry.index ? geometry.index.array : null;
		const position = geometry.attributes.position.array;

		if ( position.isInterleavedBufferAttribute || index && index.isInterleavedBufferAttribute ) {

			throw new Error( 'MeshBVH: InterleavedBufferAttribute are not supported for the geometry attributes.');

		}

		const transferrables = [ position ];
		if ( index ) {

			transferrables.push( index );

		}

		worker.postMessage( {

			index,
			position,
			options,

		}, transferrables.map( arr => arr.buffer ) );

	} );

}
<commit_msg>fix lint<commit_after>import MeshBVH from '../src/MeshBVH.js';

export function generateAsync( geometry, options = {} ) {

	return new Promise( ( resolve, reject ) => {

		const worker = new Worker( './generateAsync.worker.js' );
		worker.onmessage = e => {

			const { serialized, position, error } = e.data;

			worker.terminate();
			if ( error ) {

				reject( new Error( error ) );

			} else {

				const bvh = MeshBVH.deserialize( serialized, geometry, false );

				// we need to replace the arrays because they're neutered entirely by the
				// webworker transfer.
				geometry.attributes.position.array = position;
				if ( geometry.index ) {

					geometry.index.array = serialized.index;

				}
				resolve( bvh );

			}

		};

		const index = geometry.index ? geometry.index.array : null;
		const position = geometry.attributes.position.array;

		if ( position.isInterleavedBufferAttribute || index && index.isInterleavedBufferAttribute ) {

			throw new Error( 'MeshBVH: InterleavedBufferAttribute are not supported for the geometry attributes.' );

		}

		const transferrables = [ position ];
		if ( index ) {

			transferrables.push( index );

		}

		worker.postMessage( {

			index,
			position,
			options,

		}, transferrables.map( arr => arr.buffer ) );

	} );

}
<|endoftext|>


<commit_before>import { Seq } from 'immutable'

function defaults(env, app, cwd) {
	const config = Object.assign({}, env, app)
	const { port, assets, dest } = config
	return [
		group('default', ['serve', 'watch']),
		defTask('serve', 'serve', {
			port, root: dest, livereload: true
		}),
		group('build', ['assets', 'jade-prod', 'sass-prod', 'scripts']),
		defTask('prod', 'env', {
			prop: 'NODE_ENV', value: 'production'
		}),
		group('watch', ['watch-assets', 'watch-jade', 'watch-sass', 'watch-scripts']),
		defTask('watch-assets', 'watch', {
			src: assets, task: 'assets', cwd
		}, ['assets']),
		defTask('watch-jade', 'watch', {
			src: '**/*.jade', task: 'jade', cwd
		}, ['jade']),
		defTask('watch-sass', 'watch', {
			src: '*.{scss,css}', task: 'sass', cwd
		}, ['sass']),
		defTask('assets', 'assets', {
			src: assets, dest, cwd
		}),
		defTask('jade-prod', 'jade', {
			src: '*.jade', plumber: false, dest, cwd
		}),
		defTask('jade', 'jade', {
			src: '*.jade', plumber: true, dest, cwd
		}),
		defTask('sass-prod', 'sassProd', {
			src: '*.{scss,css}', dest, cwd
		}),
		defTask('sass', 'sass', {
			src: '*.{scss,css}', dest, cwd
		})
	].concat(
		scripts('script', '', ['prod'], config, cwd),
		scripts('scriptWatch', 'watch-', [], config, cwd)
	)
}

function scripts(func, prefix, depends, { scripts, paths, dest }, cwd) {
	const tasks = Seq(scripts)
		.mapEntries(([main, output]) => [
			prefix + main,
			defTask(prefix + main, func, {
				main, output, paths, dest, cwd
			}, depends)
		])
	return tasks.toArray().concat([
		group(prefix + 'scripts', tasks.keySeq().toArray())
	])
}

function defTask(name, func, options, depends) {
	return task(name, 'ferad-tasks', func, options, depends)
}
function task(name, modul, func, options, depends = []) {
	return { name, modul, func, options, depends }
}
function group(name, depends) {
	return {
		name, modul: 'ferad-configs', func: 'emptyTask',
		options: {}, depends
	}
}
function emptyTask(o, cb) {
	cb()
}

export default {
	defaults, scripts, defTask, task, group, emptyTask
}
<commit_msg>prod build cleanup<commit_after>import { Seq } from 'immutable'

function defaults(env, app, cwd) {
	const config = Object.assign({}, env, app)
	const { port, assets, dest } = config
	return [
		group('default', ['serve', 'watch']),
		defTask('serve', 'serve', {
			port, root: dest, livereload: true
		}),
		group('build', ['assets-prod', 'jade-prod', 'sass-prod', 'scripts']),
		defTask('prod', 'env', {
			prop: 'NODE_ENV', value: 'production'
		}, ['clean']),
		defTask('clean', 'clean', {
			dest, cwd
		}),
		group('watch', ['watch-assets', 'watch-jade', 'watch-sass', 'watch-scripts']),
		defTask('watch-assets', 'watch', {
			src: assets, task: 'assets', cwd
		}, ['assets']),
		defTask('watch-jade', 'watch', {
			src: '**/*.jade', task: 'jade', cwd
		}, ['jade']),
		defTask('watch-sass', 'watch', {
			src: '*.{scss,css}', task: 'sass', cwd
		}, ['sass']),
		defTask('assets-prod', 'assets', {
			src: assets, dest, cwd
		}, ['prod']),
		defTask('assets', 'assets', {
			src: assets, dest, cwd
		}),
		defTask('jade-prod', 'jade', {
			src: '*.jade', plumber: false, dest, cwd
		}, ['prod']),
		defTask('jade', 'jade', {
			src: '*.jade', plumber: true, dest, cwd
		}),
		defTask('sass-prod', 'sassProd', {
			src: '*.{scss,css}', dest, cwd
		}, ['prod']),
		defTask('sass', 'sass', {
			src: '*.{scss,css}', dest, cwd
		})
	].concat(
		scripts('script', '', ['prod'], config, cwd),
		scripts('scriptWatch', 'watch-', [], config, cwd)
	)
}

function scripts(func, prefix, depends, { scripts, paths, dest }, cwd) {
	const tasks = Seq(scripts)
		.mapEntries(([main, output]) => [
			prefix + main,
			defTask(prefix + main, func, {
				main, output, paths, dest, cwd
			}, depends)
		])
	return tasks.toArray().concat([
		group(prefix + 'scripts', tasks.keySeq().toArray())
	])
}

function defTask(name, func, options, depends) {
	return task(name, 'ferad-tasks', func, options, depends)
}
function task(name, modul, func, options, depends = []) {
	return { name, modul, func, options, depends }
}
function group(name, depends) {
	return {
		name, modul: 'ferad-configs', func: 'emptyTask',
		options: {}, depends
	}
}
function emptyTask(o, cb) {
	cb()
}

export default {
	defaults, scripts, defTask, task, group, emptyTask
}
<|endoftext|>


<commit_before>var game = null;

var GLOBAL_GAME_WIDTH = 320;
var GLOBAL_GAME_HEIGHT = 240;

var GLOBAL_SCREEN_WIDTH = 640;
var GLOBAL_SCREEN_HEIGHT = 480;

var GLOBAL_TILE_WIDTH = 32;
var GLOBAL_TILE_HEIGHT = 32;

var GLOBAL_GRAVITY = 1000;
var GLOBAL_JUMP_SPEED = 300;
var GLOBAL_MOVEMENT_SPEED = 250;

var data = {};
var pixel = { scale: GLOBAL_SCREEN_WIDTH/GLOBAL_GAME_WIDTH, canvas: null, context: null, width: 0, height: 0 };

var tmp;

$(document).ready(function() {

    // Create the phaser context.
    // --------------------------
    // for retro, always use Phaser.CANVAS
    // http://www.photonstorm.com/phaser/pixel-perfect-scaling-a-phaser-game
    game = new Phaser.Game(GLOBAL_GAME_WIDTH, GLOBAL_GAME_HEIGHT, Phaser.CANVAS, "");

    // Add all states.
    // ---------------
    game.state.add("BootState", chongdashu.BootState);
    game.state.add("PreloadState", chongdashu.PreloadState);
    game.state.add("GameState", chongdashu.GameState);

    // Start with boot sequence.
    // -------------------------
    game.state.start("BootState");

});
<commit_msg>Create GLOBAL_SCALE variable<commit_after>var game = null;

var GLOBAL_GAME_WIDTH = 320;
var GLOBAL_GAME_HEIGHT = 240;

var GLOBAL_SCREEN_WIDTH = 640;
var GLOBAL_SCREEN_HEIGHT = 480;

var GLOBAL_TILE_WIDTH = 32;
var GLOBAL_TILE_HEIGHT = 32;

var GLOBAL_GRAVITY = 1000;
var GLOBAL_JUMP_SPEED = 300;
var GLOBAL_MOVEMENT_SPEED = 250;
var GLOBAL_SCALE = GLOBAL_SCREEN_WIDTH/GLOBAL_GAME_WIDTH;

var data = {};
var pixel = { scale: GLOBAL_SCALE, canvas: null, context: null, width: 0, height: 0 };

var tmp;

$(document).ready(function() {

    // Create the phaser context.
    // --------------------------
    // for retro, always use Phaser.CANVAS
    // http://www.photonstorm.com/phaser/pixel-perfect-scaling-a-phaser-game
    game = new Phaser.Game(GLOBAL_GAME_WIDTH, GLOBAL_GAME_HEIGHT, Phaser.CANVAS, "");

    // Add all states.
    // ---------------
    game.state.add("BootState", chongdashu.BootState);
    game.state.add("PreloadState", chongdashu.PreloadState);
    game.state.add("GameState", chongdashu.GameState);

    // Start with boot sequence.
    // -------------------------
    game.state.start("BootState");

});
<|endoftext|>


<commit_before>var uuid = require('node-uuid');
var shell = require('shelljs');
var AWS = require('aws-sdk');

var cloudformation = new AWS.CloudFormation({
  "apiVersion": "2010-05-15",
  "region": "ap-southeast-2"
});

var randomString = function() {
  return Math.random().toString(36).substr(2, 6);
};

var stack = require('./cf-stack.json');
var userdata = shell.exec("python create_mime.py cloud-config.yaml:cloud-config userdata-script.sh:x-shellscript", {silent: true}).output;
userdata = userdata.replace(/\$STACK_NAME/g, stackName) // horrible - need to find a better way to include variables in the cloud-config
stack.Resources.Ec2Instance.Properties.UserData["Fn::Base64"] = userdata;
var stackName = "nodeapp-" + randomString();

cloudformation.createStack({
  "StackName": stackName,
  "TemplateBody": JSON.stringify(stack)
}, function(err, data) {
  if (err) {
    console.log(err, err.stack);  // an error occurred
  } else {
    console.log(data);
    (function pollUntilAvailable() {
       setTimeout(function() {
           cloudformation.describeStackEvents({ "StackName": stackName }, function(err, data) {
             if (err) {
               console.log(err, err.stack);  // an error occurred
             } else {
               var resourceType = data.StackEvents[0].ResourceType;
               var status = data.StackEvents[0].ResourceStatus;
               if (resourceType === "AWS::CloudFormation::Stack" && status === "CREATE_COMPLETE") {
                  console.log("CloudFormation stack [" + stackName +"] is [" + status + "]. Done!");
                  cloudformation.describeStacks({ "StackName": stackName }, function(err, data) {
                    if (err) {
                      console.log(err, err.stack);  // an error occurred
                    } else {
                      data.Stacks[0].Outputs.forEach(function(output) {
                        console.log(output.OutputKey + ": " + output.OutputValue);
                      });
                    }
                  });
               } else if (resourceType === "AWS::CloudFormation::Stack" && status === "ROLLBACK_COMPLETE") {
                  console.log("CloudFormation stack [" + stackName +"] creation failed with status [" + status + "]");
               } else {
                  console.log("CloudFormation stack status for [" + stackName +"] and resource type [" + resourceType + "] is [" + status + "], waiting...");
                  pollUntilAvailable();
               }
             }
           });
       }, 10 * 1000);
     })();
  }
});
<commit_msg>Use ini credentials<commit_after>var uuid = require('node-uuid');
var shell = require('shelljs');
var AWS = require('aws-sdk');

var creds = new AWS.SharedIniFileCredentials({
  profile: 'company'
});
AWS.config.credentials = creds;

var cloudformation = new AWS.CloudFormation({
  "apiVersion": "2010-05-15",
  "region": "ap-southeast-2"
});

var randomString = function() {
  return Math.random().toString(36).substr(2, 6);
};

var stack = require('./cf-stack.json');
var userdata = shell.exec("python create_mime.py cloud-config.yaml:cloud-config userdata-script.sh:x-shellscript", {silent: true}).output;
userdata = userdata.replace(/\$STACK_NAME/g, stackName) // horrible - need to find a better way to include variables in the cloud-config
stack.Resources.Ec2Instance.Properties.UserData["Fn::Base64"] = userdata;
var stackName = "nodeapp-" + randomString();

cloudformation.createStack({
  "StackName": stackName,
  "TemplateBody": JSON.stringify(stack)
}, function(err, data) {
  if (err) {
    console.log(err, err.stack);  // an error occurred
  } else {
    console.log(data);
    (function pollUntilAvailable() {
       setTimeout(function() {
           cloudformation.describeStackEvents({ "StackName": stackName }, function(err, data) {
             if (err) {
               console.log(err, err.stack);  // an error occurred
             } else {
               var resourceType = data.StackEvents[0].ResourceType;
               var status = data.StackEvents[0].ResourceStatus;
               if (resourceType === "AWS::CloudFormation::Stack" && status === "CREATE_COMPLETE") {
                  console.log("CloudFormation stack [" + stackName +"] is [" + status + "]. Done!");
                  cloudformation.describeStacks({ "StackName": stackName }, function(err, data) {
                    if (err) {
                      console.log(err, err.stack);  // an error occurred
                    } else {
                      data.Stacks[0].Outputs.forEach(function(output) {
                        console.log(output.OutputKey + ": " + output.OutputValue);
                      });
                    }
                  });
               } else if (resourceType === "AWS::CloudFormation::Stack" && status === "ROLLBACK_COMPLETE") {
                  console.log("CloudFormation stack [" + stackName +"] creation failed with status [" + status + "]");
               } else {
                  console.log("CloudFormation stack status for [" + stackName +"] and resource type [" + resourceType + "] is [" + status + "], waiting...");
                  pollUntilAvailable();
               }
             }
           });
       }, 10 * 1000);
     })();
  }
});
<|endoftext|>


<commit_before>module.exports = {
  src: [
    //--[ MAIN ]--//
    'web/built/openorchestrabackoffice/js/orchestraLib.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/tinyMceConf.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/bbcode2htmlConfigurator.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/html2bbcodeConfigurator.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/loadHtml2bbcodeInternalLink.js',
    'web/built/openorchestrabackoffice/js/viewConfigurator.js',
    'web/built/openorchestrabackoffice/js/setUpCallAjax.js',
    'web/built/openorchestrabackoffice/js/OrchestraView.js',
    'web/built/openorchestrabackoffice/js/OrchestraModalView.js',
    'web/built/openorchestrabackoffice/js/addPrototype.js',
    'web/built/openorchestrabackoffice/js/modelBackbone.js',
    'web/built/openorchestrabackoffice/js/FullPageFormView.js',
    'web/built/openorchestrabackoffice/js/ContentTypeFormView.js',
    'web/built/openorchestrabackoffice/js/FullPagePanelView.js',
    'web/built/openorchestrabackoffice/js/createNew.js',
    'web/built/openorchestrabackoffice/js/page/BlocksPanelView.js',
    'web/built/openorchestrabackoffice/js/security.js',
    'web/built/openorchestrabackoffice/js/SmartConfirmView.js',
    'web/built/openorchestrabackoffice/js/AdminFormView.js',
    'web/built/openorchestrabackoffice/js/FlashBagView.js',
    'web/built/openorchestrabackoffice/js/DisplayApiErrorView.js',
    'web/built/openorchestrabackoffice/js/generateId.js',

    //--[ AJAX LOADER ]--//
    'web/built/openorchestrabackoffice/js/ajaxLoader/AjaxLoaderView.js',

    //--[ BACKBONE ROUTER ]--//
    'web/built/openorchestrabackoffice/js/backboneRouter.js',
    'web/built/openorchestrabackoffice/js/page/LoadNodeConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/page/LoadTemplateConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/table/LoadTableConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/dashboard/LoadDashboardConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/underscoreTemplateLoader.js',

    //--[ EXTEND VIEWS ]--//
    'web/built/openorchestrabackoffice/js/extendView/addArea.js',
    'web/built/openorchestrabackoffice/js/extendView/commonPage.js',
    'web/built/openorchestrabackoffice/js/extendView/generateId.js',
    'web/built/openorchestrabackoffice/js/extendView/showVideo.js',
    'web/built/openorchestrabackoffice/js/extendView/deleteTree.js',
    'web/built/openorchestrabackoffice/js/extendView/submitAdmin.js',
    'web/built/openorchestrabackoffice/js/extendView/contentTypeSelector.js',

    //--[ WIDGETS ]--//
    'web/built/openorchestrabackoffice/js/widget/widgetChannel.js',
    'web/built/openorchestrabackoffice/js/widget/duplicateChannel.js',
    'web/built/openorchestrabackoffice/js/widget/DuplicateView.js',
    'web/built/openorchestrabackoffice/js/widget/languageChannel.js',
    'web/built/openorchestrabackoffice/js/widget/LanguageView.js',
    'web/built/openorchestrabackoffice/js/widget/previewLinkChannel.js',
    'web/built/openorchestrabackoffice/js/widget/PreviewLinkView.js',
    'web/built/openorchestrabackoffice/js/widget/statusChannel.js',
    'web/built/openorchestrabackoffice/js/widget/StatusView.js',
    'web/built/openorchestrabackoffice/js/widget/versionChannel.js',
    'web/built/openorchestrabackoffice/js/widget/VersionSelectView.js',
    'web/built/openorchestrabackoffice/js/widget/VersionView.js',

    //--[ DASHBOARD ]--//
    'web/built/openorchestrabackoffice/js/dashboard/DashboardView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetNodeListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetContentListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/LastNodesView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/DraftNodesView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/LastContentsView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/DraftContentsView.js',

    //--[ PAGE ]--//
    'web/built/openorchestrabackoffice/js/page/makeSortable.js',
    'web/built/openorchestrabackoffice/js/page/AreaView.js',
    'web/built/openorchestrabackoffice/js/page/GSAreaView.js',
    'web/built/openorchestrabackoffice/js/page/BlockView.js',
    'web/built/openorchestrabackoffice/js/page/NodeView.js',
    'web/built/openorchestrabackoffice/js/page/NodeFormView.js',
    'web/built/openorchestrabackoffice/js/page/TemplateView.js',
    'web/built/openorchestrabackoffice/js/page/GSTemplateView.js',
    'web/built/openorchestrabackoffice/js/page/TemplateFormView.js',
    'web/built/openorchestrabackoffice/js/page/SubElementFormView.js',
    'web/built/openorchestrabackoffice/js/page/showNode.js',
    'web/built/openorchestrabackoffice/js/page/showTemplate.js',
    'web/built/openorchestrabackoffice/js/page/orderNode.js',
    'web/built/openorchestrabackoffice/js/page/PageConfigurationButtonView.js',
    'web/built/openorchestrabackoffice/js/page/viewportChannel.js',
    'web/built/openorchestrabackoffice/js/page/FieldOptionDefaultValueView.js',

    //--[ AREA FLEX ]--//
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexChannel.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexAddRowExtendView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexFormView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexFormRowView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexToolbarView.js',

    //--[ TEMPLATE FLEX ]--//
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexFormView.js',
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexView.js',
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexRouter.js',

    //--[ TAB ]--//
    'web/built/openorchestrabackoffice/js/tab/TabView.js',
    'web/built/openorchestrabackoffice/js/tab/TabElementFormView.js',
    'web/built/openorchestrabackoffice/js/tab/tabViewFormLoader.js',

    //--[ DATATABLE ]--//
    'web/built/openorchestrabackoffice/js/dataTable/plugins/InputFullPagination.js',
    'web/built/openorchestrabackoffice/js/dataTable/header/searchField/*.js',
    'web/built/openorchestrabackoffice/js/dataTable/header/*.js',
    'web/built/openorchestrabackoffice/js/dataTable/*.js',

    //--[ TABLEVIEW ]--//
    'web/built/openorchestrabackoffice/js/table/TableOrchestraPagination.js',
    'web/built/openorchestrabackoffice/js/table/TableChannel.js',
    'web/built/openorchestrabackoffice/js/table/TableviewAction.js',
    'web/built/openorchestrabackoffice/js/table/TableviewRestoreAction.js',
    'web/built/openorchestrabackoffice/js/table/TableviewCollectionView.js',
    'web/built/openorchestrabackoffice/js/table/tableviewLoader.js',

    //--[ USER ]--//
    'web/built/openorchestrabackoffice/js/user/UserFormView.js',
    'web/built/openorchestrauseradmin/js/user/*.js',

    //--[ CONTENT TYPE ]--//
    'web/built/openorchestrabackoffice/js/contentType/TableviewCollectionView.js',
    'web/built/openorchestrabackoffice/js/contentType/TableViewAction.js',

    //--[ WEBSITE ]--//
    'web/built/openorchestrabackoffice/js/webSite/WebSiteFormView.js',

    //--[ GROUP TREE ]--//
    'web/built/openorchestrabackoffice/js/groupTree/*.js',

    //--[ INTERNAL LINK ]--//
    'web/built/openorchestrabackoffice/js/InternalLinkFormView.js',

    //--[ FORM BEHAVIOR ]--//
    'web/built/openorchestrabackoffice/js/formBehavior/AbstractFormBehavior.js',
    'web/built/openorchestrabackoffice/js/formBehavior/FormLibraryBehavior.js',
    'web/built/openorchestrabackoffice/js/formBehavior/ColorPicker.js',
    'web/built/openorchestrabackoffice/js/formBehavior/DatePicker.js',
    'web/built/openorchestrabackoffice/js/formBehavior/HelpText.js',
    'web/built/openorchestrabackoffice/js/formBehavior/NodeChoice.js',
    'web/built/openorchestrabackoffice/js/formBehavior/RefreshForm.js',
    'web/built/openorchestrabackoffice/js/formBehavior/RichText.js',
    'web/built/openorchestrabackoffice/js/formBehavior/TagCondition.js',
    'web/built/openorchestrabackoffice/js/formBehavior/TagCreator.js',
    'web/built/openorchestrabackoffice/js/formBehavior/ValidateHidden.js',

  ],
  dest: 'web/built/orchestra.js'
};
<commit_msg>refraich page after site creation<commit_after>module.exports = {
  src: [
    //--[ MAIN ]--//
    'web/built/openorchestrabackoffice/js/orchestraLib.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/tinyMceConf.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/bbcode2htmlConfigurator.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/html2bbcodeConfigurator.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/loadHtml2bbcodeInternalLink.js',
    'web/built/openorchestrabackoffice/js/viewConfigurator.js',
    'web/built/openorchestrabackoffice/js/setUpCallAjax.js',
    'web/built/openorchestrabackoffice/js/OrchestraView.js',
    'web/built/openorchestrabackoffice/js/OrchestraModalView.js',
    'web/built/openorchestrabackoffice/js/addPrototype.js',
    'web/built/openorchestrabackoffice/js/modelBackbone.js',
    'web/built/openorchestrabackoffice/js/FullPageFormView.js',
    'web/built/openorchestrabackoffice/js/ContentTypeFormView.js',
    'web/built/openorchestrabackoffice/js/FullPagePanelView.js',
    'web/built/openorchestrabackoffice/js/createNew.js',
    'web/built/openorchestrabackoffice/js/page/BlocksPanelView.js',
    'web/built/openorchestrabackoffice/js/security.js',
    'web/built/openorchestrabackoffice/js/SmartConfirmView.js',
    'web/built/openorchestrabackoffice/js/AdminFormView.js',
    'web/built/openorchestrabackoffice/js/FlashBagView.js',
    'web/built/openorchestrabackoffice/js/DisplayApiErrorView.js',
    'web/built/openorchestrabackoffice/js/generateId.js',

    //--[ AJAX LOADER ]--//
    'web/built/openorchestrabackoffice/js/ajaxLoader/AjaxLoaderView.js',

    //--[ BACKBONE ROUTER ]--//
    'web/built/openorchestrabackoffice/js/backboneRouter.js',
    'web/built/openorchestrabackoffice/js/page/LoadNodeConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/page/LoadTemplateConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/table/LoadTableConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/dashboard/LoadDashboardConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/underscoreTemplateLoader.js',

    //--[ EXTEND VIEWS ]--//
    'web/built/openorchestrabackoffice/js/extendView/addArea.js',
    'web/built/openorchestrabackoffice/js/extendView/commonPage.js',
    'web/built/openorchestrabackoffice/js/extendView/generateId.js',
    'web/built/openorchestrabackoffice/js/extendView/showVideo.js',
    'web/built/openorchestrabackoffice/js/extendView/deleteTree.js',
    'web/built/openorchestrabackoffice/js/extendView/submitAdmin.js',
    'web/built/openorchestrabackoffice/js/extendView/contentTypeSelector.js',

    //--[ WIDGETS ]--//
    'web/built/openorchestrabackoffice/js/widget/widgetChannel.js',
    'web/built/openorchestrabackoffice/js/widget/duplicateChannel.js',
    'web/built/openorchestrabackoffice/js/widget/DuplicateView.js',
    'web/built/openorchestrabackoffice/js/widget/languageChannel.js',
    'web/built/openorchestrabackoffice/js/widget/LanguageView.js',
    'web/built/openorchestrabackoffice/js/widget/previewLinkChannel.js',
    'web/built/openorchestrabackoffice/js/widget/PreviewLinkView.js',
    'web/built/openorchestrabackoffice/js/widget/statusChannel.js',
    'web/built/openorchestrabackoffice/js/widget/StatusView.js',
    'web/built/openorchestrabackoffice/js/widget/versionChannel.js',
    'web/built/openorchestrabackoffice/js/widget/VersionSelectView.js',
    'web/built/openorchestrabackoffice/js/widget/VersionView.js',

    //--[ DASHBOARD ]--//
    'web/built/openorchestrabackoffice/js/dashboard/DashboardView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetNodeListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetContentListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/LastNodesView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/DraftNodesView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/LastContentsView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/DraftContentsView.js',

    //--[ PAGE ]--//
    'web/built/openorchestrabackoffice/js/page/makeSortable.js',
    'web/built/openorchestrabackoffice/js/page/AreaView.js',
    'web/built/openorchestrabackoffice/js/page/GSAreaView.js',
    'web/built/openorchestrabackoffice/js/page/BlockView.js',
    'web/built/openorchestrabackoffice/js/page/NodeView.js',
    'web/built/openorchestrabackoffice/js/page/NodeFormView.js',
    'web/built/openorchestrabackoffice/js/page/TemplateView.js',
    'web/built/openorchestrabackoffice/js/page/GSTemplateView.js',
    'web/built/openorchestrabackoffice/js/page/TemplateFormView.js',
    'web/built/openorchestrabackoffice/js/page/SubElementFormView.js',
    'web/built/openorchestrabackoffice/js/page/showNode.js',
    'web/built/openorchestrabackoffice/js/page/showTemplate.js',
    'web/built/openorchestrabackoffice/js/page/orderNode.js',
    'web/built/openorchestrabackoffice/js/page/PageConfigurationButtonView.js',
    'web/built/openorchestrabackoffice/js/page/viewportChannel.js',
    'web/built/openorchestrabackoffice/js/page/FieldOptionDefaultValueView.js',

    //--[ AREA FLEX ]--//
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexChannel.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexAddRowExtendView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexFormView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexFormRowView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexToolbarView.js',

    //--[ TEMPLATE FLEX ]--//
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexFormView.js',
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexView.js',
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexRouter.js',

    //--[ TAB ]--//
    'web/built/openorchestrabackoffice/js/tab/TabView.js',
    'web/built/openorchestrabackoffice/js/tab/TabElementFormView.js',
    'web/built/openorchestrabackoffice/js/tab/tabViewFormLoader.js',

    //--[ DATATABLE ]--//
    'web/built/openorchestrabackoffice/js/dataTable/plugins/InputFullPagination.js',
    'web/built/openorchestrabackoffice/js/dataTable/header/searchField/*.js',
    'web/built/openorchestrabackoffice/js/dataTable/header/*.js',
    'web/built/openorchestrabackoffice/js/dataTable/*.js',

    //--[ TABLEVIEW ]--//
    'web/built/openorchestrabackoffice/js/table/TableOrchestraPagination.js',
    'web/built/openorchestrabackoffice/js/table/TableChannel.js',
    'web/built/openorchestrabackoffice/js/table/TableviewAction.js',
    'web/built/openorchestrabackoffice/js/table/TableviewRestoreAction.js',
    'web/built/openorchestrabackoffice/js/table/TableviewCollectionView.js',
    'web/built/openorchestrabackoffice/js/table/tableviewLoader.js',

    //--[ USER ]--//
    'web/built/openorchestrabackoffice/js/user/UserFormView.js',
    'web/built/openorchestrauseradmin/js/user/*.js',
<<<<<<< HEAD

=======

>>>>>>> refraich page after site creation
    //--[ CONTENT TYPE ]--//
    'web/built/openorchestrabackoffice/js/contentType/TableviewCollectionView.js',
    'web/built/openorchestrabackoffice/js/contentType/TableViewAction.js',

    //--[ WEBSITE ]--//
    'web/built/openorchestrabackoffice/js/webSite/WebSiteFormView.js',

    //--[ GROUP TREE ]--//
    'web/built/openorchestrabackoffice/js/groupTree/*.js',

    //--[ INTERNAL LINK ]--//
    'web/built/openorchestrabackoffice/js/InternalLinkFormView.js',

    //--[ FORM BEHAVIOR ]--//
    'web/built/openorchestrabackoffice/js/formBehavior/AbstractFormBehavior.js',
    'web/built/openorchestrabackoffice/js/formBehavior/FormLibraryBehavior.js',
    'web/built/openorchestrabackoffice/js/formBehavior/ColorPicker.js',
    'web/built/openorchestrabackoffice/js/formBehavior/DatePicker.js',
    'web/built/openorchestrabackoffice/js/formBehavior/HelpText.js',
    'web/built/openorchestrabackoffice/js/formBehavior/NodeChoice.js',
    'web/built/openorchestrabackoffice/js/formBehavior/RefreshForm.js',
    'web/built/openorchestrabackoffice/js/formBehavior/RichText.js',
    'web/built/openorchestrabackoffice/js/formBehavior/TagCondition.js',
    'web/built/openorchestrabackoffice/js/formBehavior/TagCreator.js',
    'web/built/openorchestrabackoffice/js/formBehavior/ValidateHidden.js',

  ],
  dest: 'web/built/orchestra.js'
};
<|endoftext|>