<commit_before>//dependencies for each module used
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require("socket.io")(http);
var path = require('path');
var session = require('express-session');
const MongoStore = require("connect-mongo")(session);
const mongoose = require("mongoose");
const handlebars = require('express-handlebars');
const passport = require("passport");
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var pg = require('pg');

dotenv.load();

var models = require("./models");
var db = mongoose.connection;

var router = {
    queryDELPH: require("./routes/queryDELPH"),
    dashboard: require('./routes/dashboard'),
    dashboardnew: require('./routes/dashboardnew')
};

var parser = {
    body: require("body-parser"),
    cookie: require("cookie-parser")
};

// Database Connection
mongoose.connect(process.env.MONGODB_URI || 'mongodb://127.0.0.1/cogs121');
db.on('error', console.error.bind(console, 'Mongo DB Connection Error:'));
db.once('open', function(callback) {
    console.log("Database connected successfully.");
});

var session_middleware = session({
    key: "session",
    secret: process.env.SESSION_SECRET,
    saveUninitialized: true,
    resave: true,
    store: new MongoStore({ mongooseConnection: db })
});

app.set('port', process.env.PORT || 8000);
app.engine('html', handlebars({
    defaultLayout: 'layout',
    extname: '.html'
}));
app.set("view engine", "html");
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'public')));
app.use(parser.cookie());
app.use(parser.body.urlencoded({ extended: true }));
app.use(parser.body.json());
app.use(require('method-override')());
app.use(session_middleware);
app.use(passport.initialize());
app.use(passport.session());

app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.use(session({
    secret: 'keyboard cat',
    saveUninitialized: true,
    resave: true
}));

/* TODO: Passport Middleware Here*/
TwitterStrategy = require('passport-twitter').Strategy;

passport.use(new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY ,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET ,
    callbackURL: "/auth/twitter/callback"
}, function(token, token_secret, profile, done) {
    // What goes here? Refer to step 4.
    //console.log(profile);
    models.User.findOne({ "twitterID": profile.id }, function(err, user) {
        // (1) Check if there is an error. If so, return done(err);
        if(err) return done(err);

        if(!user) {
            // (2) since the user is not found, create new user.
            var newUser = new models.User({
                "twitterID": profile.id,
                "token": token,
                "username": profile.username,
                "displayName": profile.displayName,
                "photo": profile.photos[0].value
            });

            // Refer to Assignment 0 to how create a new instance of a model
            return done(null, newUser);
        } else {
            // (3) since the user is found, update user's information
            process.nextTick(function() {
                return done(null, user);
            });
        }
    });
}));
/* TODO: Passport serialization here */
passport.serializeUser(function(user, done) {
    done(null, user);
});
passport.deserializeUser(function(user, done) {
    done(null, user);
});

//routes
//routes
app.get('/', function(req, res) {
    res.render('index');
});

app.get('/dashboard', router.dashboard.view);
app.get('/dashboardnew', router.dashboardnew.view);

app.get('/map_explore', function(req, res) {
    res.render('map_view_google');
});

app.get('/donut', function(req, res) {
    res.render('donut');
});

//race data for donut chart
app.get('/raceData', function(req, res) {
    //connect to DELPHI Database
    var pg = require('pg');
    var conString = process.env.DATABASE_CONNECTION_URL;

    var client = new pg.Client(conString);
    client.connect(function(err) {
        if (err) {
            return console.error('could not connect to postgres', err);

        }
        client.query('SELECT "Geography", "Race", "Year", "Hospitalization No." FROM cogs121_16_raw.hhsa_anxiety_disorder_by_race_2010_2012 AS tableData',
            function(err, result) {
                if (err) {
                    return console.error('error running query', err);
                }

                //console.log(result);

                var rawData = result.rows;
                var renderDataRace0 = {};
                var renderDataRace1 = {};
                var renderDataRace2 = {};
                var year = {
                    "2010": [],
                    "2011": [],
                    "2012": []
                };

                for (i = 0; i < rawData.length; i++) {
                    if (rawData[i].Geography === "San Diego County (Actual Rate)") {
                        if (parseInt(rawData[i]["Year"]) == "2010") {
                            renderDataRace0[(rawData[i].Race)] = rawData[i]["Hospitalization No."];
                        }
                        if (parseInt(rawData[i]["Year"]) == "2011") {
                            renderDataRace1[(rawData[i].Race)] = rawData[i]["Hospitalization No."];
                        }
                        if (parseInt(rawData[i]["Year"]) == "2012") {
                            renderDataRace2[(rawData[i].Race)] = rawData[i]["Hospitalization No."];
                        }
                    }
                }
                year["2010"].push(renderDataRace0);
                year["2011"].push(renderDataRace1);
                year["2012"].push(renderDataRace2);

                res.json(year);
                client.end();
            });
    });

    return {
        raceData: "No data present."
    }
});

app.get('/gender_graph', function(req, res) {
    res.render('gender_graph');
});

app.get('/gender_data', function(req, res) {
    //connect to DELPHI Database
    var pg = require('pg');

    var conString = process.env.DATABASE_CONNECTION_URL;

    var client = new pg.Client(conString);
    client.connect(function(err) {
        if (err) {
            return console.error('could not connect to postgres', err);

        }

        client.query('SELECT "Geography", "Year", "Gender", "Hospitalization No." FROM cogs121_16_raw.hhsa_anxiety_disorder_by_gender_2010_2012 WHERE "Geography" LIKE \'%Actual Rate%\'',
            function(err, result) {
                if (err) {
                    return console.error('error running query', err);
                }

                var rawData = result.rows;

                var renderGender0 = {};
                var renderGender1 = {};
                var renderGender2 = {};
                var year = {
                    "2010": [],
                    "2011": [],
                    "2012": []
                };

                for (i = 0; i < rawData.length; i++) {
                    if (rawData[i].Geography === "San Diego County (Actual Rate)") {
                        if (parseInt(rawData[i]["Year"]) == "2010") {
                            renderGender0[(rawData[i].Gender)] = rawData[i]["Hospitalization No."];
                        }
                        if (parseInt(rawData[i]["Year"]) == "2011") {
                            renderGender1[(rawData[i].Gender)] = rawData[i]["Hospitalization No."];
                        }
                        if (parseInt(rawData[i]["Year"]) == "2012") {
                            renderGender2[(rawData[i].Gender)] = rawData[i]["Hospitalization No."];
                        }
                    }
                }
                year["2010"].push(renderGender0);
                year["2011"].push(renderGender1);
                year["2012"].push(renderGender2);

                //console.log(year["2010"][0]);

                res.json(year);
                client.end();
                //return { delphidata: result };
            });
    });

    return {
        delphidata: "No data present."
    }
});

app.get('/age', function(req, res) {
    res.render('age');
});

app.get('/ageData', function(req, res) {
    var pg = require('pg');
    var conString = process.env.DATABASE_CONNECTION_URL;

    var client = new pg.Client(conString);
    client.connect(function(err) {
        if (err) {
            return console.error('could not connect to postgres', err);

        }
        client.query('SELECT "Geography", "Year", "Age", "Hospitalization No." FROM cogs121_16_raw.hhsa_anxiety_disorder_by_age_2010_2012 AS tableData',
            function(err, result) {
                if (err) {
                    return console.error('error running query', err);
                }

                var rawData = result.rows;

                var data = [];

                for (i = 0; i < rawData.length; i++) {

                    var eachForm =  {
                        geo: [],
                        series: [
                            {
                                label: '0-15',
                                values: []
                            },
                            {
                                label: '15-24',
                                values: []
                            },
                            {
                                label: '25-44',
                                values: []
                            },
                            {
                                label: '45-64',
                                values: []
                            },
                            {
                                label: '65+',
                                values: []
                            },]
                    }

                    var e = rawData[i].Geography;
                    eachForm["geo"] = e;
                    // if (rawData[i].Geography === "San Diego County (Actual Rate)") {
                        if (parseInt(rawData[i]["Year"]) == "2010") {
                            var a = rawData[i]["Hospitalization No."];
                            if (a == "<5") {
                                a = 5;
                            }
                            if (a == NaN) {
                                a = 0;
                            }

                            if (rawData[i]["Age"] == "0-14") {
                               eachForm["series"][0]["values"][0] = a;
                            }

                            if (rawData[i]["Age"] == "15-24") {
                                eachForm["series"][1]["values"][0] = a;
                            }

                            if (rawData[i]["Age"] == "25-44") {
                                eachForm["series"][2]["values"][0] = a;
                            }

                            if (rawData[i]["Age"] == "45-64") {
                                eachForm["series"][3]["values"][0] = a;
                            }

                            if (rawData[i]["Age"] == "65+") {
                                eachForm["series"][4]["values"][0] = a;
                            }
                        }

                        if (parseInt(rawData[i]["Year"]) == "2011") {
                            var a = rawData[i]["Hospitalization No."];
                            if (a == "<5") {
                                a = 5;
                            }

                            if (a == NaN) {
                                a = 0;
                            }
                            if (rawData[i]["Age"] == "0-14") {
                                eachForm["series"][0]["values"][0] = eachForm["series"][0]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "15-24") {
                                eachForm["series"][1]["values"][0] = eachForm["series"][1]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "25-44") {
                                eachForm["series"][2]["values"][0] = eachForm["series"][2]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "45-64") {
                                eachForm["series"][3]["values"][0] = eachForm["series"][3]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "65+") {
                                eachForm["series"][4]["values"][0] = eachForm["series"][4]["values"][0]+ a;
                            }
                        }
                        if (parseInt(rawData[i]["Year"]) == "2012") {
                            var a = rawData[i]["Hospitalization No."];
                            if (a == "<5") {
                                a = 5;
                            }
                            if (a == NaN) {
                                a = 0;
                            }
                            if (rawData[i]["Age"] == "0-14") {
                                eachForm["series"][0]["values"][0] = eachForm["series"][0]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "15-24") {
                                eachForm["series"][1]["values"][0] = eachForm["series"][1]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "25-44") {
                                eachForm["series"][2]["values"][0] = eachForm["series"][2]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "45-64") {
                                eachForm["series"][3]["values"][0] = eachForm["series"][3]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "65+") {
                                eachForm["series"][4]["values"][0] = eachForm["series"][4]["values"][0]+ a;
                            }
                        }

                       eachForm["series"][0]["values"][0] /= 3;
                       eachForm["series"][1]["values"][0] /= 3;
                       eachForm["series"][2]["values"][0] /= 3;
                       eachForm["series"][3]["values"][0] /= 3;
                       eachForm["series"][4]["values"][0] /= 3;

                    data[i] = eachForm;
                }

                res.json(data);
                client.end();
            });
    });

    return {
        raceData: "No data present."
    }
});

app.get('/map_anxiety_rate', router.queryDELPH.map_anxiety_rate);

// More routes here if needed
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback',
    passport.authenticate('twitter', {  successRedirect: '/dashboardnew',
                                        failureRedirect: '/nowhere' }));
app.get('/logout', function(req, res){
    req.logOut();

    var value = '?signout=true';
    res.redirect('/dashboardnew' + value);
});
io.use(function(socket, next) {
    session_middleware(socket.request, {}, next);
});

/* TODO: Server-side Socket.io here */
io.on('connection', function(socket) {
    socket.on('anxietyChat', function(msg) {
        try {
            var user = socket.request.session.passport.user;
        } catch(err) {

            console.log("no user authenticated");
            return;
        }

        var newAnxietyPost = new models.Newsfeed({
            'type': 'anxietyChat',
            'user': user.username,
            'photo': user.photo,
            'message': msg,
            'posted': Date().toString()
        });

        newAnxietyPost.save(saved);
        function saved(err) {
            if(err) {
                console.log(err);
                return;
            }
            io.emit('anxietyChat', JSON.stringify(newAnxietyPost));
        }
    });
});

http.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});<commit_msg>Stop the remote apache, using port 80 on node<commit_after>//dependencies for each module used
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require("socket.io")(http);
var path = require('path');
var session = require('express-session');
const MongoStore = require("connect-mongo")(session);
const mongoose = require("mongoose");
const handlebars = require('express-handlebars');
const passport = require("passport");
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var pg = require('pg');

dotenv.load();

var models = require("./models");
var db = mongoose.connection;

var router = {
    queryDELPH: require("./routes/queryDELPH"),
    dashboard: require('./routes/dashboard'),
    dashboardnew: require('./routes/dashboardnew')
};

var parser = {
    body: require("body-parser"),
    cookie: require("cookie-parser")
};

// Database Connection
mongoose.connect(process.env.MONGODB_URI || 'mongodb://127.0.0.1/cogs121');
db.on('error', console.error.bind(console, 'Mongo DB Connection Error:'));
db.once('open', function(callback) {
    console.log("Database connected successfully.");
});

var session_middleware = session({
    key: "session",
    secret: process.env.SESSION_SECRET,
    saveUninitialized: true,
    resave: true,
    store: new MongoStore({ mongooseConnection: db })
});

app.set('port', process.env.PORT || 80);
app.engine('html', handlebars({
    defaultLayout: 'layout',
    extname: '.html'
}));
app.set("view engine", "html");
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'public')));
app.use(parser.cookie());
app.use(parser.body.urlencoded({ extended: true }));
app.use(parser.body.json());
app.use(require('method-override')());
app.use(session_middleware);
app.use(passport.initialize());
app.use(passport.session());

app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.use(session({
    secret: 'keyboard cat',
    saveUninitialized: true,
    resave: true
}));

/* TODO: Passport Middleware Here*/
TwitterStrategy = require('passport-twitter').Strategy;

passport.use(new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY ,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET ,
    callbackURL: "/auth/twitter/callback"
}, function(token, token_secret, profile, done) {
    // What goes here? Refer to step 4.
    //console.log(profile);
    models.User.findOne({ "twitterID": profile.id }, function(err, user) {
        // (1) Check if there is an error. If so, return done(err);
        if(err) return done(err);

        if(!user) {
            // (2) since the user is not found, create new user.
            var newUser = new models.User({
                "twitterID": profile.id,
                "token": token,
                "username": profile.username,
                "displayName": profile.displayName,
                "photo": profile.photos[0].value
            });

            // Refer to Assignment 0 to how create a new instance of a model
            return done(null, newUser);
        } else {
            // (3) since the user is found, update user's information
            process.nextTick(function() {
                return done(null, user);
            });
        }
    });
}));
/* TODO: Passport serialization here */
passport.serializeUser(function(user, done) {
    done(null, user);
});
passport.deserializeUser(function(user, done) {
    done(null, user);
});

//routes
//routes
app.get('/', function(req, res) {
    res.render('index');
});

app.get('/dashboard', router.dashboard.view);
app.get('/dashboardnew', router.dashboardnew.view);

app.get('/map_explore', function(req, res) {
    res.render('map_view_google');
});

app.get('/donut', function(req, res) {
    res.render('donut');
});

//race data for donut chart
app.get('/raceData', function(req, res) {
    //connect to DELPHI Database
    var pg = require('pg');
    var conString = process.env.DATABASE_CONNECTION_URL;

    var client = new pg.Client(conString);
    client.connect(function(err) {
        if (err) {
            return console.error('could not connect to postgres', err);

        }
        client.query('SELECT "Geography", "Race", "Year", "Hospitalization No." FROM cogs121_16_raw.hhsa_anxiety_disorder_by_race_2010_2012 AS tableData',
            function(err, result) {
                if (err) {
                    return console.error('error running query', err);
                }

                //console.log(result);

                var rawData = result.rows;
                var renderDataRace0 = {};
                var renderDataRace1 = {};
                var renderDataRace2 = {};
                var year = {
                    "2010": [],
                    "2011": [],
                    "2012": []
                };

                for (i = 0; i < rawData.length; i++) {
                    if (rawData[i].Geography === "San Diego County (Actual Rate)") {
                        if (parseInt(rawData[i]["Year"]) == "2010") {
                            renderDataRace0[(rawData[i].Race)] = rawData[i]["Hospitalization No."];
                        }
                        if (parseInt(rawData[i]["Year"]) == "2011") {
                            renderDataRace1[(rawData[i].Race)] = rawData[i]["Hospitalization No."];
                        }
                        if (parseInt(rawData[i]["Year"]) == "2012") {
                            renderDataRace2[(rawData[i].Race)] = rawData[i]["Hospitalization No."];
                        }
                    }
                }
                year["2010"].push(renderDataRace0);
                year["2011"].push(renderDataRace1);
                year["2012"].push(renderDataRace2);

                res.json(year);
                client.end();
            });
    });

    return {
        raceData: "No data present."
    }
});

app.get('/gender_graph', function(req, res) {
    res.render('gender_graph');
});

app.get('/gender_data', function(req, res) {
    //connect to DELPHI Database
    var pg = require('pg');

    var conString = process.env.DATABASE_CONNECTION_URL;

    var client = new pg.Client(conString);
    client.connect(function(err) {
        if (err) {
            return console.error('could not connect to postgres', err);

        }

        client.query('SELECT "Geography", "Year", "Gender", "Hospitalization No." FROM cogs121_16_raw.hhsa_anxiety_disorder_by_gender_2010_2012 WHERE "Geography" LIKE \'%Actual Rate%\'',
            function(err, result) {
                if (err) {
                    return console.error('error running query', err);
                }

                var rawData = result.rows;

                var renderGender0 = {};
                var renderGender1 = {};
                var renderGender2 = {};
                var year = {
                    "2010": [],
                    "2011": [],
                    "2012": []
                };

                for (i = 0; i < rawData.length; i++) {
                    if (rawData[i].Geography === "San Diego County (Actual Rate)") {
                        if (parseInt(rawData[i]["Year"]) == "2010") {
                            renderGender0[(rawData[i].Gender)] = rawData[i]["Hospitalization No."];
                        }
                        if (parseInt(rawData[i]["Year"]) == "2011") {
                            renderGender1[(rawData[i].Gender)] = rawData[i]["Hospitalization No."];
                        }
                        if (parseInt(rawData[i]["Year"]) == "2012") {
                            renderGender2[(rawData[i].Gender)] = rawData[i]["Hospitalization No."];
                        }
                    }
                }
                year["2010"].push(renderGender0);
                year["2011"].push(renderGender1);
                year["2012"].push(renderGender2);

                //console.log(year["2010"][0]);

                res.json(year);
                client.end();
                //return { delphidata: result };
            });
    });

    return {
        delphidata: "No data present."
    }
});

app.get('/age', function(req, res) {
    res.render('age');
});

app.get('/ageData', function(req, res) {
    var pg = require('pg');
    var conString = process.env.DATABASE_CONNECTION_URL;

    var client = new pg.Client(conString);
    client.connect(function(err) {
        if (err) {
            return console.error('could not connect to postgres', err);

        }
        client.query('SELECT "Geography", "Year", "Age", "Hospitalization No." FROM cogs121_16_raw.hhsa_anxiety_disorder_by_age_2010_2012 AS tableData',
            function(err, result) {
                if (err) {
                    return console.error('error running query', err);
                }

                var rawData = result.rows;

                var data = [];

                for (i = 0; i < rawData.length; i++) {

                    var eachForm =  {
                        geo: [],
                        series: [
                            {
                                label: '0-15',
                                values: []
                            },
                            {
                                label: '15-24',
                                values: []
                            },
                            {
                                label: '25-44',
                                values: []
                            },
                            {
                                label: '45-64',
                                values: []
                            },
                            {
                                label: '65+',
                                values: []
                            },]
                    }

                    var e = rawData[i].Geography;
                    eachForm["geo"] = e;
                    // if (rawData[i].Geography === "San Diego County (Actual Rate)") {
                        if (parseInt(rawData[i]["Year"]) == "2010") {
                            var a = rawData[i]["Hospitalization No."];
                            if (a == "<5") {
                                a = 5;
                            }
                            if (a == NaN) {
                                a = 0;
                            }

                            if (rawData[i]["Age"] == "0-14") {
                               eachForm["series"][0]["values"][0] = a;
                            }

                            if (rawData[i]["Age"] == "15-24") {
                                eachForm["series"][1]["values"][0] = a;
                            }

                            if (rawData[i]["Age"] == "25-44") {
                                eachForm["series"][2]["values"][0] = a;
                            }

                            if (rawData[i]["Age"] == "45-64") {
                                eachForm["series"][3]["values"][0] = a;
                            }

                            if (rawData[i]["Age"] == "65+") {
                                eachForm["series"][4]["values"][0] = a;
                            }
                        }

                        if (parseInt(rawData[i]["Year"]) == "2011") {
                            var a = rawData[i]["Hospitalization No."];
                            if (a == "<5") {
                                a = 5;
                            }

                            if (a == NaN) {
                                a = 0;
                            }
                            if (rawData[i]["Age"] == "0-14") {
                                eachForm["series"][0]["values"][0] = eachForm["series"][0]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "15-24") {
                                eachForm["series"][1]["values"][0] = eachForm["series"][1]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "25-44") {
                                eachForm["series"][2]["values"][0] = eachForm["series"][2]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "45-64") {
                                eachForm["series"][3]["values"][0] = eachForm["series"][3]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "65+") {
                                eachForm["series"][4]["values"][0] = eachForm["series"][4]["values"][0]+ a;
                            }
                        }
                        if (parseInt(rawData[i]["Year"]) == "2012") {
                            var a = rawData[i]["Hospitalization No."];
                            if (a == "<5") {
                                a = 5;
                            }
                            if (a == NaN) {
                                a = 0;
                            }
                            if (rawData[i]["Age"] == "0-14") {
                                eachForm["series"][0]["values"][0] = eachForm["series"][0]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "15-24") {
                                eachForm["series"][1]["values"][0] = eachForm["series"][1]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "25-44") {
                                eachForm["series"][2]["values"][0] = eachForm["series"][2]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "45-64") {
                                eachForm["series"][3]["values"][0] = eachForm["series"][3]["values"][0]+ a;
                            }

                            if (rawData[i]["Age"] == "65+") {
                                eachForm["series"][4]["values"][0] = eachForm["series"][4]["values"][0]+ a;
                            }
                        }

                       eachForm["series"][0]["values"][0] /= 3;
                       eachForm["series"][1]["values"][0] /= 3;
                       eachForm["series"][2]["values"][0] /= 3;
                       eachForm["series"][3]["values"][0] /= 3;
                       eachForm["series"][4]["values"][0] /= 3;

                    data[i] = eachForm;
                }

                res.json(data);
                client.end();
            });
    });

    return {
        raceData: "No data present."
    }
});

app.get('/map_anxiety_rate', router.queryDELPH.map_anxiety_rate);

// More routes here if needed
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback',
    passport.authenticate('twitter', {  successRedirect: '/dashboardnew',
                                        failureRedirect: '/nowhere' }));
app.get('/logout', function(req, res){
    req.logOut();

    var value = '?signout=true';
    res.redirect('/dashboardnew' + value);
});
io.use(function(socket, next) {
    session_middleware(socket.request, {}, next);
});

/* TODO: Server-side Socket.io here */
io.on('connection', function(socket) {
    socket.on('anxietyChat', function(msg) {
        try {
            var user = socket.request.session.passport.user;
        } catch(err) {

            console.log("no user authenticated");
            return;
        }

        var newAnxietyPost = new models.Newsfeed({
            'type': 'anxietyChat',
            'user': user.username,
            'photo': user.photo,
            'message': msg,
            'posted': Date().toString()
        });

        newAnxietyPost.save(saved);
        function saved(err) {
            if(err) {
                console.log(err);
                return;
            }
            io.emit('anxietyChat', JSON.stringify(newAnxietyPost));
        }
    });
});

http.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var assert = require('assert-plus');
var util = require('util');

function translateAction(job) {

    if (/^provision/.test(job.name)) {
        return 'provision';
    }

    if (job.params.task !== 'update' && job.params.task !== 'snapshot') {
        return job.params.task;
    }

    if (job.params.task === 'snapshot') {
        if (/^snapshot/.test(job.name)) {
            return 'create_snapshot';
        } else if (/^rollback/.test(job.name)) {
            return 'rollback_snapshot';
        } else if (/^delete-snapshot/.test(job.name)) {
            return 'delete_snapshot';
        }
    }

    // The multiple possibilities for machine update:
    if (job.params.payload.set_customer_metadata &&
            job.params.payload.remove_customer_metadata) {
        return 'replace_metadata';
    }

    if (job.params.payload.remove_tags && job.params.payload.set_tags) {
        return 'replace_tags';
    }

    if (job.params.payload.remove_customer_metadata) {
        return 'remove_metadata';
    }

    if (job.params.payload.set_customer_metadata) {
        return 'set_metadata';
    }

    if (job.params.payload.remove_tags) {
        return 'remove_tags';
    }

    if (job.params.payload.set_tags) {
        return 'set_tags';
    }

    if (job.params.subtask === 'rename' || job.params.subtask === 'resize') {
        return job.params.subtask;
    }

    return 'unknown';
}

function translate(job) {
    var j = {
        success: (job.execution === 'succeeded') ? 'yes' : 'no',
        time: job.chain_results[job.chain_results.length - 1].finished_at
    };
    j.action = translateAction(job);
    if (job.params.context) {
        j.caller = job.params.context.caller;
        j.parameters = job.params.context.parameters;
    } else {
        j.caller = {
            type: 'operator'
        };
    }
    return j;
}

function list(req, res, next) {
    assert.ok(req.sdc);

    var customer = req.account.uuid,
        log = req.log,
        machine = req.params.machine,
        vmapi = req.sdc.vmapi;

    return vmapi.listJobs({
        vm_uuid: machine,
        owner_uuid: customer
    }, {
        log: req.log,
        headers: {
            'x-request-id': req.getId()
        }
    }, function (err, jobs) {
        if (err) {
            return next(err);
        }

        // Ignore all not finished jobs
        var actions = jobs.filter(function (j) {
            return (j.execution !== 'running' && j.execution !== 'queued');
        }).map(translate);

        log.debug('GET %s -> %j', req.path(), actions);
        res.send(actions);
        return next();
    });
}

function mount(server, before) {
    assert.object(server, 'server');
    assert.ok(before);

    server.get({
        path: '/:account/machines/:machine/audit',
        name: 'MachineAudit'
    }, before, list);

    server.head({
        path: '/:account/machines/:machine/audit',
        name: 'HeadAudit'
    }, before, list);
}

// --- API

module.exports = {
    mount: mount
};
<commit_msg>PUBAPI-1111 - check for resize jobs earlier when creating audit lists.<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var assert = require('assert-plus');
var util = require('util');

function translateAction(job) {
    if (/^provision/.test(job.name)) {
        return 'provision';
    }

    if (job.params.task !== 'update' && job.params.task !== 'snapshot') {
        return job.params.task;
    }

    if (job.params.task === 'snapshot') {
        if (/^snapshot/.test(job.name)) {
            return 'create_snapshot';
        } else if (/^rollback/.test(job.name)) {
            return 'rollback_snapshot';
        } else if (/^delete-snapshot/.test(job.name)) {
            return 'delete_snapshot';
        }
    }

    if (job.params.subtask === 'rename' || job.params.subtask === 'resize') {
        return job.params.subtask;
    }

    // The multiple possibilities for machine update:
    if (job.params.payload.set_customer_metadata &&
            job.params.payload.remove_customer_metadata) {
        return 'replace_metadata';
    }

    if (job.params.payload.remove_tags && job.params.payload.set_tags) {
        return 'replace_tags';
    }

    if (job.params.payload.remove_customer_metadata) {
        return 'remove_metadata';
    }

    if (job.params.payload.set_customer_metadata) {
        return 'set_metadata';
    }

    if (job.params.payload.remove_tags) {
        return 'remove_tags';
    }

    if (job.params.payload.set_tags) {
        return 'set_tags';
    }

    return 'unknown';
}

function translate(job) {
    var j = {
        success: (job.execution === 'succeeded') ? 'yes' : 'no',
        time: job.chain_results[job.chain_results.length - 1].finished_at
    };
    j.action = translateAction(job);
    if (job.params.context) {
        j.caller = job.params.context.caller;
        j.parameters = job.params.context.parameters;
    } else {
        j.caller = {
            type: 'operator'
        };
    }
    return j;
}

function list(req, res, next) {
    assert.ok(req.sdc);

    var customer = req.account.uuid,
        log = req.log,
        machine = req.params.machine,
        vmapi = req.sdc.vmapi;

    return vmapi.listJobs({
        vm_uuid: machine,
        owner_uuid: customer
    }, {
        log: req.log,
        headers: {
            'x-request-id': req.getId()
        }
    }, function (err, jobs) {
        if (err) {
            return next(err);
        }

        // Ignore all not finished jobs
        var actions = jobs.filter(function (j) {
            return (j.execution !== 'running' && j.execution !== 'queued');
        }).map(translate);

        log.debug('GET %s -> %j', req.path(), actions);
        res.send(actions);
        return next();
    });
}

function mount(server, before) {
    assert.object(server, 'server');
    assert.ok(before);

    server.get({
        path: '/:account/machines/:machine/audit',
        name: 'MachineAudit'
    }, before, list);

    server.head({
        path: '/:account/machines/:machine/audit',
        name: 'HeadAudit'
    }, before, list);
}

// --- API

module.exports = {
    mount: mount
};
<|endoftext|>


<commit_before>"use strict"

var format = require('python-format')
var request = require('request')

var port = +process.env.npm_package_config_webhookport
if (!port) {
    console.error("Start the bot using 'npm start'.")
    return
}

var secret = process.env.npm_package_config_secret
if (!secret) {
    console.error("Secret not defined, please use 'npm config set psdevbot:secret value'.")
    return
}

var Showdown = require('./showdown')
var parameters = {}
Object.keys(Showdown.keys).forEach(function (key) {
    parameters[key] = process.env['npm_package_config_' + key]
})
var client = new Showdown(parameters)
client.connect()

var github = require('githubhook')({
    port: port,
    secret: secret,
    logger: console
})

function shorten(url, callback) {
    function shortenCallback(error, response, body) {
        var shortenedUrl = url
        if (!error && response.headers.location) {
            shortenedUrl = response.headers.location
        }
        callback(shortenedUrl)
    }
    request.post('https://git.io', {form: {url: url}}, shortenCallback)
}

var escape = require('escape-html')

github.on('push', function push(repo, ref, result) {
    var url = result.compare
    var branch = /[^/]+$/.exec(ref)[0]
    shorten(url, function pushShortened(url) {
        var messages = []
        var message = result.commits.length === 1 ?
            "[{}] {} pushed {} new commit to {}: {4}" :
            "[{}] {} pushed {} new commits to {}: {4}"

        messages.push(format(
            message,
            escape(repo),
            escape(result.pusher.name),
            escape(result.commits.length),
            escape(branch),
            escape(url)
        ))
        result.commits.forEach(function (commit) {
            messages.push(format(
                "{}/{} {} {}: {}",
                escape(repo),
                escape(branch),
                escape(commit.id.substring(0, 8)),
                escape(commit.author.name),
                escape(/.+/.exec(commit.message)[0])
            ))
        })
        client.report('!htmlbox ' + messages.join("
"))
    })
})

github.on('pull_request', function pullRequest(repo, ref, result) {
    var url = result.pull_request.html_url
    shorten(url, function pullRequestShortened(url) {
        client.report(format(
            "!htmlbox [{}] {} {} pull request #{}: {} {}",
            escape(repo),
            escape(result.pull_request.user.login),
            escape(result.action),
            escape(result.pull_request.number),
            escape(result.pull_request.title),
            escape(url)
        ))
    })
})

github.listen()
<commit_msg>Neatly escape repo name.<commit_after>"use strict"

var format = require('python-format')
var request = require('request')

var port = +process.env.npm_package_config_webhookport
if (!port) {
    console.error("Start the bot using 'npm start'.")
    return
}

var secret = process.env.npm_package_config_secret
if (!secret) {
    console.error("Secret not defined, please use 'npm config set psdevbot:secret value'.")
    return
}

var Showdown = require('./showdown')
var parameters = {}
Object.keys(Showdown.keys).forEach(function (key) {
    parameters[key] = process.env['npm_package_config_' + key]
})
var client = new Showdown(parameters)
client.connect()

var github = require('githubhook')({
    port: port,
    secret: secret,
    logger: console
})

function shorten(url, callback) {
    function shortenCallback(error, response, body) {
        var shortenedUrl = url
        if (!error && response.headers.location) {
            shortenedUrl = response.headers.location
        }
        callback(shortenedUrl)
    }
    request.post('https://git.io', {form: {url: url}}, shortenCallback)
}

function getRepoName(repo) {
    switch (repo) {
    case 'Pokemon-Showdown':
        return 'server'
    case 'Pokemon-Showdown-Client':
        return 'client'
    default:
        return repo
    }
}

var escape = require('escape-html')

github.on('push', function push(repo, ref, result) {
    var url = result.compare
    var branch = /[^/]+$/.exec(ref)[0]
    shorten(url, function pushShortened(url) {
        var messages = []
        var message = result.commits.length === 1 ?
            "[{}] {} pushed {} new commit to {}: {4}" :
            "[{}] {} pushed {} new commits to {}: {4}"

        messages.push(format(
            message,
            escape(getRepoName(repo)),
            escape(result.pusher.name),
            escape(result.commits.length),
            escape(branch),
            escape(url)
        ))
        result.commits.forEach(function (commit) {
            messages.push(format(
                "{}/{} {} {}: {}",
                escape(getRepoName(repo)),
                escape(branch),
                escape(commit.id.substring(0, 8)),
                escape(commit.author.name),
                escape(/.+/.exec(commit.message)[0])
            ))
        })
        client.report('!htmlbox ' + messages.join("
"))
    })
})

github.on('pull_request', function pullRequest(repo, ref, result) {
    var url = result.pull_request.html_url
    shorten(url, function pullRequestShortened(url) {
        client.report(format(
            "!htmlbox [{}] {} {} pull request #{}: {} {}",
            escape(getRepoName(repo)),
            escape(result.pull_request.user.login),
            escape(result.action),
            escape(result.pull_request.number),
            escape(result.pull_request.title),
            escape(url)
        ))
    })
})

github.listen()
<|endoftext|>


<commit_before>'use strict';

import utils from './utils.js';
import bind from './helpers/bind.js';
import Axios from './core/Axios.js';
import mergeConfig from './core/mergeConfig.js';
import defaults from './defaults/index.js';
import formDataToJSON from './helpers/formDataToJSON.js';
import CanceledError from './cancel/CanceledError.js';
import CancelToken from'./cancel/CancelToken.js';
import isCancel from'./cancel/isCancel.js';
import {VERSION} from './env/data.js';
import toFormData from './helpers/toFormData.js';
import AxiosError from '../lib/core/AxiosError.js';
import spread from './helpers/spread.js';
import isAxiosError from './helpers/isAxiosError.js';

/**
 * Create an instance of Axios
 *
 * @param {Object} defaultConfig The default config for the instance
 *
 * @returns {Axios} A new instance of Axios
 */
function createInstance(defaultConfig) {
  const context = new Axios(defaultConfig);
  const instance = bind(Axios.prototype.request, context);

  // Copy axios.prototype to instance
  utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});

  // Copy context to instance
  utils.extend(instance, context, {allOwnKeys: true});

  // Factory for creating new instances
  instance.create = function create(instanceConfig) {
    return createInstance(mergeConfig(defaultConfig, instanceConfig));
  };

  return instance;
}

// Create the default instance to be exported
const axios = createInstance(defaults);

// Expose Axios class to allow class inheritance
axios.Axios = Axios;

// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;

// Expose AxiosError class
axios.AxiosError = AxiosError;

// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;

// Expose all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};

axios.spread = spread;

// Expose isAxiosError
axios.isAxiosError = isAxiosError;

axios.formToJSON = thing => {
  return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
};

export default axios;
<commit_msg>fix: the error of calling extend to pass parameters #4844 (#4857)<commit_after>'use strict';

import utils from './utils.js';
import bind from './helpers/bind.js';
import Axios from './core/Axios.js';
import mergeConfig from './core/mergeConfig.js';
import defaults from './defaults/index.js';
import formDataToJSON from './helpers/formDataToJSON.js';
import CanceledError from './cancel/CanceledError.js';
import CancelToken from'./cancel/CancelToken.js';
import isCancel from'./cancel/isCancel.js';
import {VERSION} from './env/data.js';
import toFormData from './helpers/toFormData.js';
import AxiosError from '../lib/core/AxiosError.js';
import spread from './helpers/spread.js';
import isAxiosError from './helpers/isAxiosError.js';

/**
 * Create an instance of Axios
 *
 * @param {Object} defaultConfig The default config for the instance
 *
 * @returns {Axios} A new instance of Axios
 */
function createInstance(defaultConfig) {
  const context = new Axios(defaultConfig);
  const instance = bind(Axios.prototype.request, context);

  // Copy axios.prototype to instance
  utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});

  // Copy context to instance
  utils.extend(instance, context, null, {allOwnKeys: true});

  // Factory for creating new instances
  instance.create = function create(instanceConfig) {
    return createInstance(mergeConfig(defaultConfig, instanceConfig));
  };

  return instance;
}

// Create the default instance to be exported
const axios = createInstance(defaults);

// Expose Axios class to allow class inheritance
axios.Axios = Axios;

// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;

// Expose AxiosError class
axios.AxiosError = AxiosError;

// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;

// Expose all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};

axios.spread = spread;

// Expose isAxiosError
axios.isAxiosError = isAxiosError;

axios.formToJSON = thing => {
  return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
};

export default axios;
<|endoftext|>


<commit_before>/*
 server.js
 mongodb-rest

 Created by Tom de Grunt on 2010-10-03.
 Copyright (c) 2010 Tom de Grunt.
 This file is part of mongodb-rest.
 */

var fs = require("fs"),
        sys = require("sys"),
        express = require('express');

var config = {"db": {
        'port': 27017,
        'host': "localhost"
    },
    "accessControl": {
        "allowOrigin": "*",
        "allowMethods": "GET,POST,PUT,DELETE,HEAD,OPTIONS"
    },
    'server': {
        'port': 3000,
        'address': "0.0.0.0"
    },
    'flavor': "regular",
    'debug': true
};

var app = module.exports.app = express();

try {
    config = JSON.parse(fs.readFileSync(process.cwd() + "/config.json"));
} catch (e) {
    // ignore
}

module.exports.config = config;

app.configure(function() {
    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.static(process.cwd() + '/public'));
    app.use(express.logger());

    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');

    if (config.accessControl) {
        var accesscontrol = require('./lib/accesscontrol');
        app.use(accesscontrol.handle);
    }
});

require('./lib/main');
require('./lib/command');
require('./lib/rest');
require('./lib/snomed');
require('./lib/snomed-v1');

if (!process.argv[2] || !process.argv[2].indexOf("expresso")) {
    app.listen(config.server.port, config.server.address);
}
<commit_msg>Removing old jade references<commit_after>/*
 server.js
 mongodb-rest

 Created by Tom de Grunt on 2010-10-03.
 Copyright (c) 2010 Tom de Grunt.
 This file is part of mongodb-rest.
 */

var fs = require("fs"),
        sys = require("sys"),
        express = require('express');

var config = {"db": {
        'port': 27017,
        'host': "localhost"
    },
    "accessControl": {
        "allowOrigin": "*",
        "allowMethods": "GET,POST,PUT,DELETE,HEAD,OPTIONS"
    },
    'server': {
        'port': 3000,
        'address': "0.0.0.0"
    },
    'flavor': "regular",
    'debug': true
};

var app = module.exports.app = express();

try {
    config = JSON.parse(fs.readFileSync(process.cwd() + "/config.json"));
} catch (e) {
    // ignore
}

module.exports.config = config;

app.configure(function() {
    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.static(process.cwd() + '/public'));
    app.use(express.logger());

    //app.set('views', __dirname + '/views');
    //app.set('view engine', 'jade');

    if (config.accessControl) {
        var accesscontrol = require('./lib/accesscontrol');
        app.use(accesscontrol.handle);
    }
});

require('./lib/main');
require('./lib/command');
require('./lib/rest');
require('./lib/snomed');
require('./lib/snomed-v1');

if (!process.argv[2] || !process.argv[2].indexOf("expresso")) {
    app.listen(config.server.port, config.server.address);
}
<|endoftext|>


<commit_before>/**
 * This file provided by Facebook is for non-commercial testing and evaluation
 * purposes only. Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
var app = express();

//MailChimp
var MailChimpAPI = require('mailchimp').MailChimpAPI;
var apiKey = process.env.MAILCHIMP_API;
try {
    var api = new MailChimpAPI(apiKey, { version : '1.3' });
} catch (error) {
    console.log(error.message);
}

var COMMENTS_FILE = path.join(__dirname, 'comments.json');

app.set('port', (process.env.PORT || 3000));

app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Additional middleware which will set headers that we need on each request.
app.use(function(req, res, next) {
    // Set permissive CORS header - this allows this server to be used only as
    // an API server in conjunction with something like webpack-dev-server.
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Disable caching so we'll always get the latest.
    res.setHeader('Cache-Control', 'no-cache');
    next();
});

app.get('/name/*', function(req, res) {
  // res.sendfile(path, {root: './public'});
  //res.sendFile(path.join(__dirname, 'public'))
});

app.post('/api/subscribe', function(req, res) {
  MongoClient.connect(process.env.MONGODB_URI, function(err, db) {
    if (err) {
      throw err;
    }

    var collection = db.collection('curiosity')
    collection.insert(req.body, function(err, result) {

      addToEmailList(req.body.name, req.body.email);

      if (err) {
        throw err;
      }

    });
  });
});

addToEmailList = function(name, email){
  //TODO: Dedublicate
  var merge_vars = {
      EMAIL: email,
      FNAME: name
  };

  api.listSubscribe({ id : process.env.MAILCHIMP_LIST_ID,
                      email_address : email,
                      merge_vars : merge_vars,
                      double_optin: false,
                      send_welcome: false,
                      update_existing: true }, function (error, data) {
    if (error){
      console.log(error.message);
    }
    else{
      //console.log(JSON.stringify(data));
    }
  });

}

app.listen(app.get('port'), function() {
  console.log('Server started: http://localhost:' + app.get('port') + '/');
});
<commit_msg>new relic in code<commit_after>/**
 * This file provided by Facebook is for non-commercial testing and evaluation
 * purposes only. Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
require('newrelic');
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
var app = express();

//MailChimp
var MailChimpAPI = require('mailchimp').MailChimpAPI;
var apiKey = process.env.MAILCHIMP_API;
try {
    var api = new MailChimpAPI(apiKey, { version : '1.3' });
} catch (error) {
    console.log(error.message);
}

var COMMENTS_FILE = path.join(__dirname, 'comments.json');

app.set('port', (process.env.PORT || 3000));

app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Additional middleware which will set headers that we need on each request.
app.use(function(req, res, next) {
    // Set permissive CORS header - this allows this server to be used only as
    // an API server in conjunction with something like webpack-dev-server.
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Disable caching so we'll always get the latest.
    res.setHeader('Cache-Control', 'no-cache');
    next();
});

app.get('/name/*', function(req, res) {
  // res.sendfile(path, {root: './public'});
  //res.sendFile(path.join(__dirname, 'public'))
});

app.post('/api/subscribe', function(req, res) {
  MongoClient.connect(process.env.MONGODB_URI, function(err, db) {
    if (err) {
      throw err;
    }

    var collection = db.collection('curiosity')
    collection.insert(req.body, function(err, result) {

      addToEmailList(req.body.name, req.body.email);

      if (err) {
        throw err;
      }

    });
  });
});

addToEmailList = function(name, email){
  //TODO: Dedublicate
  var merge_vars = {
      EMAIL: email,
      FNAME: name
  };

  api.listSubscribe({ id : process.env.MAILCHIMP_LIST_ID,
                      email_address : email,
                      merge_vars : merge_vars,
                      double_optin: false,
                      send_welcome: false,
                      update_existing: true }, function (error, data) {
    if (error){
      console.log(error.message);
    }
    else{
      //console.log(JSON.stringify(data));
    }
  });

}

app.listen(app.get('port'), function() {
  console.log('Server started: http://localhost:' + app.get('port') + '/');
});
<|endoftext|>


<commit_before>var $ = require("jquery");
var rowFor = require("./row-for");
var columnFor = require("./column-for");
var score = 0;
var highScore = 0;

function setUpGame() {
  var board = new Board();
  var game = new Game();
  Cell
  var cell = new Cell();
  board.addValueToAvailableCell.bind(board)();
  board.addValueToAvailableCell.bind(board)();
  board.render.bind(board)();
  document.addEventListener('keydown', board.handleKey.bind(board, game));

  renderHighScore();
  resetScore();
}

$(document).ready(function(){
  setUpGame();
});

//TODO:delete unnecessary functions
//move cell and game to other files if possible

$(".new-game-button").on("click", function(){
  location.reload ();
});

function Board() {
  this.row = 4;
  this.column = 4;
  this.cells = [];
  this.buildGrid(arguments);
}

function Cell(row, column, value) {
  this.row = row;
  this.column = column;
  this.value = value;
}

function Game () {
  this.cells =[];
  this.score = score;
  this.highScore = highScore;
}

Board.prototype = {

  addValueToAvailableCell: function() {
    var available = this.checkAvailalbeCells();
    var index = Math.floor(Math.random() * (available.length));
    return available[index].value = (Math.random() < 0.9 ? 2 : 4);
  },

  buildGrid: function(cells) {
    if (this.cells.length) {
      return this.cells;
    }
    for (var i = 0; i < 16; i++) {
      var value = cells[i] ? cells[i] : 0;
      this.cells.push(new Cell(rowFor(i), columnFor(i), value));
    }
  },

  checkAndChangeValue: function(direction) {
    var slice;
    var directionBoolean;

    if (direction === 1 || direction === 3) {
      slice = [
        [this.cells[0], this.cells[1], this.cells[2], this.cells[3]],
        [this.cells[4], this.cells[5], this.cells[6], this.cells[7]],
        [this.cells[8], this.cells[9], this.cells[10], this.cells[11]],
        [this.cells[12], this.cells[13], this.cells[14], this.cells[15]]
      ];
    } else {
      slice = [
        [this.cells[0], this.cells[4], this.cells[8], this.cells[12]],
        [this.cells[1], this.cells[5], this.cells[9], this.cells[13]],
        [this.cells[2], this.cells[6], this.cells[10], this.cells[14]],
        [this.cells[3], this.cells[7], this.cells[11], this.cells[15]]
      ];
    }

    if (direction === 1) {
      directionBoolean = true;
    } else if (direction === 2){
      directionBoolean = true;
    } else if (direction === 3) {
      directionBoolean = false;
    } else {
      directionBoolean = false;
    }

    for (var i = 0; i < 4; i++) {
      for (var j = directionBoolean ? 0 : 3; directionBoolean ? j < 4 : j >= 0; directionBoolean ? j++ : j-- ) {
        slice[i][j].update(directionBoolean, slice[i], j);
      }
    }
  },

  checkAvailalbeCells: function() {
    var available = this.cells.filter(function(item, index, array) {
      return item.value === 0;
    });
    return available;
  },

  clearBoard: function() {
    this.cells = [];
  },

  fromStorage: function () { //Function not implemented yet
    return JSON.parse(localStorage.get(value));
  },

  handleKey: function(game, event) {
    var moved = false;

    switch (event.keyCode) {
      case 37: // Left
      case 38: // Up
      case 39: // Right
      case 40: // Down
       event.preventDefault();
       break;
    }

    switch (event.keyCode) {
      case 37: // Left
        moved = this.processMove(1);
        break;
      case 38: // Up
        moved = this.processMove(2);
        break;
      case 39: // Right
       moved = this.processMove(3);
        break;
      case 40: // Down
        moved = this.processMove(4);
        break;
      }
      if (moved) {
        this.addValueToAvailableCell();
        this.render();
      }

      if (moved === false && this.checkAvailalbeCells().length === 0) {
        lose();
      }
  },

  printBoard: function() {
    for (var i = 0; i < 16; i++) {
    }
  },

  processMove: function(direction) {

    var moved = true;
    // var state = 'state';
    // var score = 'score'
    // var previousState = JSON.stringify(this.cells);
    var previousState = this.toString(this.cells);
    this.checkAndChangeValue(direction);
    // var currentState = JSON.stringify(this.cells);
    var currentState = this.toString(this.cells);
    if (previousState === currentState) {
      moved = false;
    }
    localStorage.setItem('state', currentState);
    localStorage.setItem('score', score);
    // this.toLocalStorage(state, currentState);
    // this.toLocalStorage(score, currentState);
    return moved;
  },

  render: function() {
    for (var i = 0; i < this.cells.length; i++) {
      var tile = document.getElementById(i);
      tile.innerHTML = this.cells[i].value;
      tile.className = (`tile${this.cells[i].value}`);
    }
  },

  toString: function(value) {
    return JSON.stringify(value);
  },

  toStorage: function(tag, value) { //Function not implemented yet
      localStorage.setItem(tag, value);
  }
};

Cell.prototype = {

  update: function(direction, slice, positionInSlice) {
    for (var i = positionInSlice; direction ? ++i < 4 : --i >= 0;) {
      if (this.value === slice[i].value && this.value !== 0) {
        this.value = this.value * 2;
        slice[i].value = 0;
        this.calculateScore(this.value);
        this.setHighScore();
        return;
      } else if (this.value === 0 && slice[i].value > 0){
        this.value = slice[i].value;
        slice[i].value = 0;
      } else if (slice[i].value > 0) {
        return;
      } else {
        continue;
      }
    }
  },

  calculateScore: function(value) {
    score += value;
    $('.current-score').text(score);
  },

  setHighScore: function() {
    var highScore = getHighScore();
    if (score >= highScore) {
      highScore = score;
    }
    localStorage.setItem('highScore', highScore);
    renderHighScore();
  }
};

function lose() {
 alert('you lose');
}

function getHighScore() {
  storedHighScore = JSON.parse(localStorage.getItem('highScore'));
  if (storedHighScore) {
    highScore = storedHighScore;
  }
  return highScore;
}

function renderHighScore() {
  var highScore = getHighScore();
  $('.high-score').text(highScore);
}

function resetScore() {
  score = 0;
  $('.current-score').text(score);
  localStorage.setItem('score', score);
}

module.exports = [Board, Cell, Game];
<commit_msg>WIP added part of function for checking for merge; this will replace current method of checking for lost game<commit_after>var $ = require("jquery");
var rowFor = require("./row-for");
var columnFor = require("./column-for");
var score = 0;
var highScore = 0;

function setUpGame() {
  var board = new Board();
  var game = new Game();
  Cell
  var cell = new Cell();
  board.addValueToAvailableCell.bind(board)();
  board.addValueToAvailableCell.bind(board)();
  board.render.bind(board)();
  document.addEventListener('keydown', board.handleKey.bind(board, game));

  renderHighScore();
  resetScore();
}

$(document).ready(function(){
  setUpGame();
});

//TODO:delete unnecessary functions
//move cell and game to other files if possible

$(".new-game-button").on("click", function(){
  location.reload ();
});

function Board() {
  this.row = 4;
  this.column = 4;
  this.cells = [];
  this.buildGrid(arguments);
}

function Cell(row, column, value) {
  this.row = row;
  this.column = column;
  this.value = value;
}

function Game () {
  this.cells =[];
  this.score = score;
  this.highScore = highScore;
}

Board.prototype = {

  addValueToAvailableCell: function() {
    var available = this.checkAvailalbeCells();
    var index = Math.floor(Math.random() * (available.length));
    return available[index].value = (Math.random() < 0.9 ? 2 : 4);
  },

  buildGrid: function(cells) {
    if (this.cells.length) {
      return this.cells;
    }
    for (var i = 0; i < 16; i++) {
      var value = cells[i] ? cells[i] : 0;
      this.cells.push(new Cell(rowFor(i), columnFor(i), value));
    }
  },

  checkAndChangeValue: function(direction) {
    var slice;
    var directionBoolean;

    if (direction === 1 || direction === 3) {
      slice = [
        [this.cells[0], this.cells[1], this.cells[2], this.cells[3]],
        [this.cells[4], this.cells[5], this.cells[6], this.cells[7]],
        [this.cells[8], this.cells[9], this.cells[10], this.cells[11]],
        [this.cells[12], this.cells[13], this.cells[14], this.cells[15]]
      ];
    } else {
      slice = [
        [this.cells[0], this.cells[4], this.cells[8], this.cells[12]],
        [this.cells[1], this.cells[5], this.cells[9], this.cells[13]],
        [this.cells[2], this.cells[6], this.cells[10], this.cells[14]],
        [this.cells[3], this.cells[7], this.cells[11], this.cells[15]]
      ];
    }

    if (direction === 1) {
      directionBoolean = true;
    } else if (direction === 2){
      directionBoolean = true;
    } else if (direction === 3) {
      directionBoolean = false;
    } else {
      directionBoolean = false;
    }

    for (var i = 0; i < 4; i++) {
      for (var j = directionBoolean ? 0 : 3; directionBoolean ? j < 4 : j >= 0; directionBoolean ? j++ : j-- ) {
        slice[i][j].update(directionBoolean, slice[i], j);
      }
    }
  },

  checkAvailalbeCells: function() {
    var available = this.cells.filter(function(item, index, array) {
      return item.value === 0;
    });
    return available;
  },

  checkForMerge: function() {
    var horizontalArray = [
      [this.cells[0], this.cells[1], this.cells[2], this.cells[3]],
      [this.cells[4], this.cells[5], this.cells[6], this.cells[7]],
      [this.cells[8], this.cells[9], this.cells[10], this.cells[11]],
      [this.cells[12], this.cells[13], this.cells[14], this.cells[15]]
    ];

    var verticalArray = [
      [this.cells[0], this.cells[4], this.cells[8], this.cells[12]],
      [this.cells[1], this.cells[5], this.cells[9], this.cells[13]],
      [this.cells[2], this.cells[6], this.cells[10], this.cells[14]],
      [this.cells[3], this.cells[7], this.cells[11], this.cells[15]]
    ];

    //iterate through each inner array
    //see if there are any touching cells with the same value
    //if there is then a merge is possible, return true
    //double for loop?
    //replace this function with current way of checking for lost game

  },

  clearBoard: function() {
    this.cells = [];
  },

  fromStorage: function () { //Function not implemented yet
    return JSON.parse(localStorage.get(value));
  },

  handleKey: function(game, event) {
    var moved = false;

    switch (event.keyCode) {
      case 37: // Left
      case 38: // Up
      case 39: // Right
      case 40: // Down
       event.preventDefault();
       break;
    }

    switch (event.keyCode) {
      case 37: // Left
        moved = this.processMove(1);
        break;
      case 38: // Up
        moved = this.processMove(2);
        break;
      case 39: // Right
       moved = this.processMove(3);
        break;
      case 40: // Down
        moved = this.processMove(4);
        break;
      }
      if (moved) {
        this.addValueToAvailableCell();
        this.render();
      }

      if (moved === false && this.checkAvailalbeCells().length === 0) {
        lose();
      }
  },

  printBoard: function() {
    for (var i = 0; i < 16; i++) {
    }
  },

  processMove: function(direction) {

    var moved = true;
    // var state = 'state';
    // var score = 'score'
    // var previousState = JSON.stringify(this.cells);
    var previousState = this.toString(this.cells);
    this.checkAndChangeValue(direction);
    // var currentState = JSON.stringify(this.cells);
    var currentState = this.toString(this.cells);
    if (previousState === currentState) {
      moved = false;
    }
    localStorage.setItem('state', currentState);
    localStorage.setItem('score', score);
    // this.toLocalStorage(state, currentState);
    // this.toLocalStorage(score, currentState);
    return moved;
  },

  render: function() {
    for (var i = 0; i < this.cells.length; i++) {
      var tile = document.getElementById(i);
      tile.innerHTML = this.cells[i].value;
      tile.className = (`tile${this.cells[i].value}`);
    }
  },

  toString: function(value) {
    return JSON.stringify(value);
  },

  toStorage: function(tag, value) { //Function not implemented yet
      localStorage.setItem(tag, value);
  }
};

Cell.prototype = {

  update: function(direction, slice, positionInSlice) {
    for (var i = positionInSlice; direction ? ++i < 4 : --i >= 0;) {
      if (this.value === slice[i].value && this.value !== 0) {
        this.value = this.value * 2;
        slice[i].value = 0;
        this.calculateScore(this.value);
        this.setHighScore();
        return;
      } else if (this.value === 0 && slice[i].value > 0){
        this.value = slice[i].value;
        slice[i].value = 0;
      } else if (slice[i].value > 0) {
        return;
      } else {
        continue;
      }
    }
  },

  calculateScore: function(value) {
    score += value;
    $('.current-score').text(score);
  },

  setHighScore: function() {
    var highScore = getHighScore();
    if (score >= highScore) {
      highScore = score;
    }
    localStorage.setItem('highScore', highScore);
    renderHighScore();
  }
};

function lose() {
 alert('you lose');
}

function getHighScore() {
  storedHighScore = JSON.parse(localStorage.getItem('highScore'));
  if (storedHighScore) {
    highScore = storedHighScore;
  }
  return highScore;
}

function renderHighScore() {
  var highScore = getHighScore();
  $('.high-score').text(highScore);
}

function resetScore() {
  score = 0;
  $('.current-score').text(score);
  localStorage.setItem('score', score);
}

module.exports = [Board, Cell, Game];
<|endoftext|>


<commit_before>// Load up a process to clear the build directory, build once from the Brocfile,
// and serve it on 0.0.0.0:5000 with express. Based on broccoli/lib/builder.js
var broccoli            = require('broccoli');
var copyDereferenceSync = require('copy-dereference').sync;
var express             = require('express');
var fs                  = require('fs');
var gzipStatic          = require('connect-gzip-static');
var http                = require('http');
var path                = require('path');
var Q                   = require('q');
var rimraf              = require('rimraf');

// Clean existing data
function clean(directory) {
  if (fs.existsSync(directory)) {
    rimraf.sync(directory);
  }
}

// Build application
function build(outputDir) {
  var node = broccoli.loadBrocfile();
  var builder = new broccoli.Builder(node, { tmpdir: './tmp' });

  return builder.build()
  .then(function() {
    copyDereferenceSync(builder.outputPath, outputDir);
  })
  .finally(function() {
    return builder.cleanup();
  })
  .catch(function(err) {
    // Should show file and line/col if present
    if (err.file) {
      console.error('File: ' + err.file);
    }
    console.error(err.stack);
    console.error('\nBuild failed');
    process.exit(1);
  });
}

// Start up server
function serve() {
  var app = express();
  var router = express.Router();
  router.get('/*', function(req, res, next) {
    // Check for resource requests and redirect to the index file for them
    if (path.extname(req.path).length > 0) {
      next();
    } else {
      req.url = "/index.html";
      next();
    }
  });
  app.use(router);
  app.use(gzipStatic(__dirname + "/public", {
    maxAge: 31536000 * 1000 // 1 year
  }));

  var server = app.listen(process.env.PORT || 5000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Scholar Portal app listening at http://%s:%s', host, port);
  });
}
Q(clean("public"))
.then(function() {
  return build("public");
})
.then(serve)
.done();
<commit_msg>Change tmpdir for server<commit_after>// Load up a process to clear the build directory, build once from the Brocfile,
// and serve it on 0.0.0.0:5000 with express. Based on broccoli/lib/builder.js
var broccoli            = require('broccoli');
var copyDereferenceSync = require('copy-dereference').sync;
var express             = require('express');
var fs                  = require('fs');
var gzipStatic          = require('connect-gzip-static');
var http                = require('http');
var path                = require('path');
var Q                   = require('q');
var rimraf              = require('rimraf');

// Clean existing data
function clean(directory) {
  if (fs.existsSync(directory)) {
    rimraf.sync(directory);
  }
}

// Build application
function build(outputDir) {
  fs.mkdirSync('tmp');
  var node = broccoli.loadBrocfile();
  var builder = new broccoli.Builder(node, { tmpdir: 'tmp' });

  return builder.build()
  .then(function() {
    copyDereferenceSync(builder.outputPath, outputDir);
  })
  .finally(function() {
    return builder.cleanup();
  })
  .catch(function(err) {
    // Should show file and line/col if present
    if (err.file) {
      console.error('File: ' + err.file);
    }
    console.error(err.stack);
    console.error('\nBuild failed');
    process.exit(1);
  });
}

// Start up server
function serve() {
  var app = express();
  var router = express.Router();
  router.get('/*', function(req, res, next) {
    // Check for resource requests and redirect to the index file for them
    if (path.extname(req.path).length > 0) {
      next();
    } else {
      req.url = "/index.html";
      next();
    }
  });
  app.use(router);
  app.use(gzipStatic(__dirname + "/public", {
    maxAge: 31536000 * 1000 // 1 year
  }));

  var server = app.listen(process.env.PORT || 5000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Scholar Portal app listening at http://%s:%s', host, port);
  });
}
Q(clean("public"))
.then(function() {
  return build("public");
})
.then(serve)
.done();
<|endoftext|>


<commit_before>const cfenv = require('cfenv');
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
const Cloudant = require('cloudant');
const ObjectStorage = require('bluemix-objectstorage').ObjectStorage;

// Emulating VCAP_VARIABLES if running in local mode
try { require("./vcap-local"); } catch (e) {}
var appEnv = cfenv.getAppEnv();

// AppMetrics monitoring instrumentation
require('appmetrics-dash').attach();

// Swagger instrumentation
app.use("/swagger/api", express.static("./public/swagger.yaml"));
app.use("/explorer", express.static("./public/swagger-ui"));

// Business logic
app.get("/products", function(req, res, next){

	res.json([{
		"id":0,
		"name":"IBM"
	},{
		"id":1,
		"name":"Bluemix"
	},{
		"id":2,
		"name":"Watson"
	}]);
});

app.post("/products", function(req, res, next){
	// Put your business logic here
	res.json();
});

app.get("/product/:id", function(req, res, next){
	// Put your business logic here
	res.json();
});

app.put("/product/:id", function(req, res, next){
	// Put your business logic here
	res.json();
});

app.delete("/product/:id", function(req, res, next){
	// Put your business logic here
	res.json();
});

// Starting the server
const port = 'PORT' in process.env ? process.env.PORT : 8080;
app.listen(port, function () {
	const address = (this.address().address === '::') ? 'http://localhost' : this.address().address;
	const port = this.address().port;
	console.log(`kubedemo2 listening on ${address}:${port}`)
	console.log(`OpenAPI (Swagger) spec is available at ${address}:${port}/swagger/api`)
	console.log(`Swagger UI is available at ${address}:${port}/explorer`)
});
<commit_msg>removed stub code<commit_after>const cfenv = require('cfenv');
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
const Cloudant = require('cloudant');
const ObjectStorage = require('bluemix-objectstorage').ObjectStorage;

// Emulating VCAP_VARIABLES if running in local mode
try { require("./vcap-local"); } catch (e) {}
var appEnv = cfenv.getAppEnv();

// AppMetrics monitoring instrumentation
require('appmetrics-dash').attach();

// Swagger instrumentation
app.use("/swagger/api", express.static("./public/swagger.yaml"));
app.use("/explorer", express.static("./public/swagger-ui"));

// Business logic
app.get("/products", function(req, res, next){

	res.json([]);
});

app.post("/products", function(req, res, next){
	// Put your business logic here
	res.json();
});

app.get("/product/:id", function(req, res, next){
	// Put your business logic here
	res.json();
});

app.put("/product/:id", function(req, res, next){
	// Put your business logic here
	res.json();
});

app.delete("/product/:id", function(req, res, next){
	// Put your business logic here
	res.json();
});

// Starting the server
const port = 'PORT' in process.env ? process.env.PORT : 8080;
app.listen(port, function () {
	const address = (this.address().address === '::') ? 'http://localhost' : this.address().address;
	const port = this.address().port;
	console.log(`kubedemo2 listening on ${address}:${port}`)
	console.log(`OpenAPI (Swagger) spec is available at ${address}:${port}/swagger/api`)
	console.log(`Swagger UI is available at ${address}:${port}/explorer`)
});
<|endoftext|>


<commit_before>/**
 * build operation for Predator
 */

/**
 * module dependencies
 */
'use strict';
const kit = require('needle-kit');
const request = kit.request;
const fs = kit.fs;
const co = require('co');
const glob = require('glob');
const util = require('./util');
const Hash = util.Hash;
const fmt = require('util').format;
const path = require('path');
const UglifyJs = require('uglify-js');
const minify = require('html-minifier').minify;
const _ = require('lodash');
const CleanCss = require('clean-css');

/**
 * 只复制
 */
exports.buildCopy = function(globPatterns) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:copy');

  globPatterns.forEach(function(pattern) {
    const files = glob.sync(pattern, {
      cwd: cwd
    });

    files.forEach(function(f) {
      const src = self.home + '/app/' + f;
      const dest = self.buildDir + '/' + f;

      debug('copy %s -> %s', src, dest);
      fs.copySync(src, dest);
    });
  });
};

/**
 * 进行hash操作, 不引用其他的资源, 没有替换操作
 */
exports.buildStatic = function(globPatterns, rev) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:buildStatic');

  globPatterns.forEach(function(pattern) {

    const files = glob.sync(pattern, {
      cwd: cwd
    });

    files.forEach(function(f) {
      const original = f;
      const src = self.home + '/app/' + f;
      const hash = util.Hash.file(src);

      // setup rev map
      const parsed = path.parse(f);
      const hashed = fmt('%s/%s_%s%s', parsed.dir, parsed.name, hash, parsed.ext);
      debug('%s -> %s', original, hashed);
      rev[original] = hashed;

      // write file
      const dest = self.buildDir + '/' + hashed;
      fs.copySync(src, dest);
    });
  });
};

/**
 * less
 *
 * 处理less, 替换图片资源等
 */
exports.buildLessAsync = co.wrap(function*(globPatterns, rev, options) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:buildLessAsync');

  for (let i = 0; i < globPatterns.length; i++) {
    const pattern = globPatterns[i];
    const files = glob.sync(pattern, {
      cwd: cwd
    });

    for (let j = 0; j < files.length; j++) {
      const f = files[j];

      // build hash
      const src = self.home + '/app/' + f;
      let content = yield self.renderLessAsync(src, options);
      content = util.processRev(content, rev);

      // compute hash
      const hash = Hash.string(content);

      // f是文件, .less
      // original -> hashed, original 应为请求的css地址
      const parsed = path.parse(f);
      const original = fmt('%s/%s%s', parsed.dir, parsed.name, '.css');
      const hashed = fmt('%s/%s_%s%s', parsed.dir, parsed.name, hash, '.css');
      debug('%s -> %s', original, hashed);
      rev[original] = hashed;

      // write file
      const dest = self.buildDir + '/' + hashed;
      fs.outputFileSync(dest, content);
    }
  }
});

exports.buildJsAsync = co.wrap(function*(globPatterns, rev) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:buildJsAsync');

  for (let i = 0; i < globPatterns.length; i++) {
    const pattern = globPatterns[i];

    const files = glob.sync(pattern, {
      cwd: cwd
    });

    for (let j = 0; j < files.length; j++) {
      let f = files[j];
      if (f === 'global/js/main/index.json') { // hack on global js
        f = 'global/js/main/index.js';
      }
      const original = f;

      // build hash
      const src = self.home + '/app/' + f;

      // bundle
      const b = self.createBrowserify(src);
      let content = (yield b.bundleAsync()).toString('utf8');

      // process rev
      content = util.processRev(content, rev);

      // minify
      content = UglifyJs.minify(content, {
        fromString: true
      }).code;

      // do rev
      const hash = Hash.string(content);
      const parsed = path.parse(original);
      const hashed = fmt('%s/%s_%s%s', parsed.dir, parsed.name, hash, '.js');
      debug('%s -> %s', original, hashed);
      rev[original] = hashed;

      // write file
      const dest = self.buildDir + '/' + hashed;
      fs.outputFileSync(dest, content, 'utf8');
    }
  }
});

/**
 * 处理视图
 *
 * 只替换资源
 */
exports.buildView = function(globPatterns, rev) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:buildView');

  globPatterns.forEach(function(pattern) {
    const files = glob.sync(pattern, {
      cwd: cwd
    });

    files.forEach(function(f) {
      const file = self.home + '/app/' + f;
      let content = fs.readFileSync(file, 'utf8');
      content = util.processRev(content, rev);
      content = content.replace(/\/view(?=\/)/g, '/view_build');

      // write file
      const dest = file.replace(/\/view(?=\/)/, '/view_build');
      debug('%s -> %s', file, dest);
      fs.outputFileSync(dest, content, 'utf8');
    });
  });
};

/**
 * 不带 main 的 js/css
 *
 */
exports.buildOtherJsCss = function(globPatterns, rev) {
  const cwd = this.home + '/app';
  const self = this;
  const debug = require('debug')('predator:build:buildOtherJsCss');

  globPatterns.forEach(function(pattern) {
    const files = glob.sync(pattern, {
      cwd: cwd
    });

    files.forEach(function(f) {
      // do rev
      const original = f;
      const src = cwd + '/' + f;
      let content = fs.readFileSync(src, 'utf8');
      content = util.processRev(content, rev);
      const hash = Hash.string(content);
      const parsed = path.parse(original);
      const hashed = fmt('%s/%s_%s%s', parsed.dir, parsed.name, hash, parsed.ext);
      rev[original] = hashed;
      debug('%s -> %s', original, hashed);

      // write file
      const dest = self.buildDir + '/' + hashed;
      fs.outputFileSync(dest, content);
    });
  });
};

/**
 * build static html
 *
 * 规则是 `/` 结尾, + index.html
 * / -> /index.html
 * /foo/ -> /foo/index.html
 * /bar -> /bar
 */
exports.buildHtmlAsync = co.wrap(function*(paths, options) {
  const debug = require('debug')('predator:build:html');

  const server = this.app.listen(0);
  const address = server.address();
  const serverAddress = 'localhost:' + address.port;
  debug('server address : %s', serverAddress);

  try {
    // build all
    for (let i = 0; i < paths.length; i++) {
      const path = paths[i];

      let html = yield request
        .get(serverAddress + path)
        .endAsync()
        .then(function(res) {
          return res.text;
        });

      // options
      const defaults = {};
      options = _.merge(defaults, options);
      try {
        html = minify(html, options);
      } catch (e) {
        console.error('minify failed for : %s', path);
        console.error(e.stack || e);
      }

      // dest
      let dest = this.buildDir + path;
      if (dest.endsWith('/')) {
        dest += 'index.html';
      }

      // debug
      debug('%s -> %s', path, dest);

      // write
      fs.outputFileSync(dest, html);
    }
  } catch (e) {
    server.unref();
    throw e;
  }

  // unref
  server.unref();
});<commit_msg>fix: /global/index.js build on windows<commit_after>/**
 * build operation for Predator
 */

/**
 * module dependencies
 */
'use strict';
const kit = require('needle-kit');
const request = kit.request;
const fs = kit.fs;
const co = require('co');
const glob = require('glob');
const util = require('./util');
const Hash = util.Hash;
const fmt = require('util').format;
const path = require('path');
const UglifyJs = require('uglify-js');
const minify = require('html-minifier').minify;
const _ = require('lodash');
const CleanCss = require('clean-css');

/**
 * 只复制
 */
exports.buildCopy = function(globPatterns) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:copy');

  globPatterns.forEach(function(pattern) {
    const files = glob.sync(pattern, {
      cwd: cwd
    });

    files.forEach(function(f) {
      const src = self.home + '/app/' + f;
      const dest = self.buildDir + '/' + f;

      debug('copy %s -> %s', src, dest);
      fs.copySync(src, dest);
    });
  });
};

/**
 * 进行hash操作, 不引用其他的资源, 没有替换操作
 */
exports.buildStatic = function(globPatterns, rev) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:buildStatic');

  globPatterns.forEach(function(pattern) {

    const files = glob.sync(pattern, {
      cwd: cwd
    });

    files.forEach(function(f) {
      const original = f;
      const src = self.home + '/app/' + f;
      const hash = util.Hash.file(src);

      // setup rev map
      const parsed = path.parse(f);
      const hashed = fmt('%s/%s_%s%s', parsed.dir, parsed.name, hash, parsed.ext);
      debug('%s -> %s', original, hashed);
      rev[original] = hashed;

      // write file
      const dest = self.buildDir + '/' + hashed;
      fs.copySync(src, dest);
    });
  });
};

/**
 * less
 *
 * 处理less, 替换图片资源等
 */
exports.buildLessAsync = co.wrap(function*(globPatterns, rev, options) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:buildLessAsync');

  for (let i = 0; i < globPatterns.length; i++) {
    const pattern = globPatterns[i];
    const files = glob.sync(pattern, {
      cwd: cwd
    });

    for (let j = 0; j < files.length; j++) {
      const f = files[j];

      // build hash
      const src = self.home + '/app/' + f;
      let content = yield self.renderLessAsync(src, options);
      content = util.processRev(content, rev);

      // compute hash
      const hash = Hash.string(content);

      // f是文件, .less
      // original -> hashed, original 应为请求的css地址
      const parsed = path.parse(f);
      const original = fmt('%s/%s%s', parsed.dir, parsed.name, '.css');
      const hashed = fmt('%s/%s_%s%s', parsed.dir, parsed.name, hash, '.css');
      debug('%s -> %s', original, hashed);
      rev[original] = hashed;

      // write file
      const dest = self.buildDir + '/' + hashed;
      fs.outputFileSync(dest, content);
    }
  }
});

exports.buildJsAsync = co.wrap(function*(globPatterns, rev) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:buildJsAsync');

  for (let i = 0; i < globPatterns.length; i++) {
    const pattern = globPatterns[i];

    const files = glob.sync(pattern, {
      cwd: cwd
    });

    for (let j = 0; j < files.length; j++) {
      let f = files[j];
      if (f === path.normalize('global/js/main/index.json')) { // hack on global js
        f = 'global/js/main/index.js';
      }
      const original = f;

      // build hash
      const src = self.home + '/app/' + f;

      // bundle
      const b = self.createBrowserify(src);
      let content = (yield b.bundleAsync()).toString('utf8');

      // process rev
      content = util.processRev(content, rev);

      // minify
      content = UglifyJs.minify(content, {
        fromString: true
      }).code;

      // do rev
      const hash = Hash.string(content);
      const parsed = path.parse(original);
      const hashed = fmt('%s/%s_%s%s', parsed.dir, parsed.name, hash, '.js');
      debug('%s -> %s', original, hashed);
      rev[original] = hashed;

      // write file
      const dest = self.buildDir + '/' + hashed;
      fs.outputFileSync(dest, content, 'utf8');
    }
  }
});

/**
 * 处理视图
 *
 * 只替换资源
 */
exports.buildView = function(globPatterns, rev) {
  const self = this;
  const cwd = this.home + '/app';
  const debug = require('debug')('predator:build:buildView');

  globPatterns.forEach(function(pattern) {
    const files = glob.sync(pattern, {
      cwd: cwd
    });

    files.forEach(function(f) {
      const file = self.home + '/app/' + f;
      let content = fs.readFileSync(file, 'utf8');
      content = util.processRev(content, rev);
      content = content.replace(/\/view(?=\/)/g, '/view_build');

      // write file
      const dest = file.replace(/\/view(?=\/)/, '/view_build');
      debug('%s -> %s', file, dest);
      fs.outputFileSync(dest, content, 'utf8');
    });
  });
};

/**
 * 不带 main 的 js/css
 *
 */
exports.buildOtherJsCss = function(globPatterns, rev) {
  const cwd = this.home + '/app';
  const self = this;
  const debug = require('debug')('predator:build:buildOtherJsCss');

  globPatterns.forEach(function(pattern) {
    const files = glob.sync(pattern, {
      cwd: cwd
    });

    files.forEach(function(f) {
      // do rev
      const original = f;
      const src = cwd + '/' + f;
      let content = fs.readFileSync(src, 'utf8');
      content = util.processRev(content, rev);
      const hash = Hash.string(content);
      const parsed = path.parse(original);
      const hashed = fmt('%s/%s_%s%s', parsed.dir, parsed.name, hash, parsed.ext);
      rev[original] = hashed;
      debug('%s -> %s', original, hashed);

      // write file
      const dest = self.buildDir + '/' + hashed;
      fs.outputFileSync(dest, content);
    });
  });
};

/**
 * build static html
 *
 * 规则是 `/` 结尾, + index.html
 * / -> /index.html
 * /foo/ -> /foo/index.html
 * /bar -> /bar
 */
exports.buildHtmlAsync = co.wrap(function*(paths, options) {
  const debug = require('debug')('predator:build:html');

  const server = this.app.listen(0);
  const address = server.address();
  const serverAddress = 'localhost:' + address.port;
  debug('server address : %s', serverAddress);

  try {
    // build all
    for (let i = 0; i < paths.length; i++) {
      const path = paths[i];

      let html = yield request
        .get(serverAddress + path)
        .endAsync()
        .then(function(res) {
          return res.text;
        });

      // options
      const defaults = {};
      options = _.merge(defaults, options);
      try {
        html = minify(html, options);
      } catch (e) {
        console.error('minify failed for : %s', path);
        console.error(e.stack || e);
      }

      // dest
      let dest = this.buildDir + path;
      if (dest.endsWith('/')) {
        dest += 'index.html';
      }

      // debug
      debug('%s -> %s', path, dest);

      // write
      fs.outputFileSync(dest, html);
    }
  } catch (e) {
    server.unref();
    throw e;
  }

  // unref
  server.unref();
});
<|endoftext|>