text:
/**
 * Module dependencies
 */
var request = require('request'),
    config = require('./config'),
    events = require('events'),
    cheerio = require('cheerio'),
    qs = require('querystring'),
    crypto = require('crypto'),
    eventEmitter = new events.EventEmitter(),
    db = require('./db')(),
    express = require('express'),
    routes = require('./app/routes/router'),
    http = require('http'),
    path = require('path'),
    async = require('async'),
    AWS = require('aws-sdk'),
    ses = new AWS.SES(),
    passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy;
var userSettings;
var User;
var app = express();

var global_blacklist = require('./config/blacklist');
var global_whitelist = require('./config/whitelist');

// Grabs user settings explicitly in order to quickly update
var getUserSettings = function () {
    db.driver.execQuery('SELECT * FROM users_settings', function (err, data) {
        if (err) {
            console.error('ERROR GETTING USER SETTINGS: ' + err);
        }
        userSettings = data;
        console.log('Successfully loaded new user settings');
    });
};

// Initialization function definition.
var init = function () {
    // Load Models
    db.load('./app/models/user', function (err) {
        if (err) {
            console.error('Error loading User model' + err);
        }
        else {
            User = db.models.users;
        }
    });
    // Loads initial user stats after users have been loaded.
    getUserSettings();
};

// Grabs the body & selects only the 'latest pastes'. Parses the URLs
var parseLatestUrls =  function (body, cb) {
    var $ = cheerio.load(body);
    $('ul.right_menu > li > a').map(function (i, item) {
        var m = $(item).attr('href').replace('\/', ''),
            url = 'http://pastebin.com/raw.php?',
            params = { i: m };
        url += qs.stringify(params);
        cb(url);
    });
};

// Verify that the body of each post does not contain anything currently blacklisted
var checkBlacklist = function (body, url, cb) {
    var blacklist = global_blacklist,
    isntBlacklisted = true;

    for (var filter in blacklist) {
        if (!(blacklist[filter].reg.test(body))) {
            isntBlacklisted = true;
        }
        else {
            isntBlacklisted = false;
            break;
        }
    }
    if (isntBlacklisted) {
        cb(body, url);
    }
};

// If the body passed the blacklist filter, we then figure out what it contains and if it is of any interest
var masterFilter = function (body, url, cb) {
    var filters = global_whitelist;

    for (var filter in filters) {
        if (filters[filter].reg.test(body)) {
            filters[filter].count = body.match(filters[filter].reg).length;
        }
    }
    // After we have counted the occurrences, we pass it through to the callback with the counts
    var cbFilters = filters;
    cb(body, url, cbFilters);

    // And then we reset the counters
    for (var filter in filters) {
        if (filters.hasOwnProperty(filter)) {
            filters[filter].count = 0;
        }
    }
};

// Determines if a paste is indeed interesting to a user
var userFilter = function (body, url, cbFilters, cb) {
    // Loop through the userSettings array
    for (var i = 0; i < userSettings.length; i += 1) {
        // Get individual user's settings
        for (var filter in cbFilters) {
            if (cbFilters.hasOwnProperty(filter)) {
                var indivUserSettings = {};
                indivUserSettings = userSettings[i];
                // if individual user setting matches what's currently in the body, do something.
                if (indivUserSettings[filter] <= cbFilters[filter].count) {
                    cb(body, url, indivUserSettings, filter, cbFilters);
                }
            }
        }
    }
};

// PassportJS Serialize
passport.serializeUser(function (user, done) {
    done(null, user[0].id);
});

passport.deserializeUser(function (id, done) {
    User.get(id, function (err, user) {
        done(err, user);
    });
});

// Begin Execution
init();
// development only
if ('development' === app.get('env') || 'test' === app.get('env')) {
    app.use(express.errorHandler());
    app.set('views', __dirname + '/app/front/views');
    app.set('view engine', 'jade');
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(express.static(path.join(__dirname, 'app/front')));
}
else if ('production' === app.get('env')) {
    require('newrelic');
    app.set('views', __dirname + '/dist');
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    app.use(express.static(path.join(__dirname, 'dist')));
}

// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'my_precious' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(function (req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404', { url: req.url });
            return;
        }

      // respond with json
        if (req.accepts('json')) {
            res.send({ error: 'Not found' });
            return;
        }

      // default to plain-text. send()
        res.type('txt').send('Not found');
    });

// Grunt Stuff
module.exports = http.createServer(app).listen(app.get('port'), function () {
    console.log('Pasteye server listening on port ' + app.get('port') + ' in ' + app.get('env') + ' environment.');
});
module.exports.use = function () {
    app.use.apply(app, arguments);
};
module.exports.express = app;

module.exports.db = db;

// PassportJS strategies
passport.use(new LocalStrategy(
    function (username, password, done) {
        User.find({ username: username }, function (err, user) {
            if (err) {
                return done(err);
            }
            else if (!user[0]) {
                return done(null, false, { message: 'Incorrect username.' });
            }
            if (!user[0].authenticate(password)) {
                return done(null, false, { message: 'Incorrect password.' });
            }
            return done(null, user);
        });
    }
));

/*
 * Frontend Routing & Relative user actions
 */
app.get('/', function (req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    else {
        res.render('splash');
    }
},
    function (req, res) {
        res.redirect('/app');
    });
app.get('/beta', routes.beta);
app.get('/login', function (req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    else {
        res.render('login');
    }
},
    function (req, res) {
        res.redirect('/app');
    });
app.get('/signup', routes.signup);
app.get('/app', function (req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    else {
        res.redirect('/login');
    }
}, function (req, res) {
    res.render('app', {user: req.user});
});
app.get('/user/me', function (req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    else {
        res.redirect('/login');
    }
}, function (req, res) {
    res.send(req.user, 200);
});
app.get('/user/me/settings', function (req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    else {
        res.redirect('/login');
    }
}, function (req, res) {
    User.get(req.user.id, function (err, user) {
        if (err) {
            res.send('No such user', 500);
        }
        user.getSettings(function (err, settings) {
            res.send(settings, 200);
        });
    });
});
app.get('/user/me/stats', function (req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    else {
        res.redirect('/login');
    }
}, function (req, res) {
    User.get(req.user.id, function (err, user) {
        if (err) {
            res.send('No such user', 500);
        }
        user.getStats(function (err, stats) {
            res.send(stats, 200);
        });
    });
});
app.get('/logout', function (req, res)  {
    req.logout();
    res.redirect('/');
});
app.get('/resetpassword', routes.resetPassword);
app.get('/verifyuser', routes.verifyUser);
app.get('/verifyEmail', routes.verifyEmail);
app.get('/resendEmail', routes.resendEmail);
app.get('/forgotpassword', routes.forgotPassword);

app.post('/login',
    passport.authenticate('local'),
    function (req, res, next) {
        if (req.user[0].activated) {
            return next();
        }
        else {
            res.send('Your account has not been activated yet. Please check your e-mail for further instructions.', 406);
        }
    },
    function (req, res) {
    // If this function gets called, authentication & activation verification was successful.
        res.send('You have successfully logged in.', 200);
    });
app.post('/verifyUser', function (req, res) {
    var dateVerify = new Date();
    if (dateVerify.getDate().toString() === req.body.emailToken.toString().substr(0, dateVerify.getDate().toString().length)) {
        User.find({ userEmail: req.body.userEmail }, function (err, user) {
            if (err) {
                res.send(err, 500);
            }
            else {
                var digest = dateVerify.getDate() + crypto.createHmac('sha256', config.secretKey).update(dateVerify.getDate() + req.body.userEmail + user.id).digest('base64');
                if (digest === req.body.emailToken) {
                    var randPass = crypto.randomBytes(8).toString('base64');
                    user[0].password = randPass;
                    user[0].save(function (err) {
                        if (err) {
                            res.send(err, 500);
                        }
                        else {
                            res.send('Your password has been randomly regenerated. Please change it immediately in your user settings. Your password is: ' + randPass, 200);
                        }
                    });
                }
                else {
                    res.send('Invalid token. Please verify that the token you have entered is exactly the same as the one sent to you via e-mail.', 400);
                }
            }
        });
    }
    else {
        res.send('Your token has expired. Please generate a new one.', 400);
    }
});
app.post('/verifyEmail', function (req, res) {
    var dateVerify = new Date();
    if (dateVerify.getDate().toString() === req.body.emailToken.toString().substr(0, dateVerify.getDate().toString().length)) {
        User.find({ userEmail: req.body.userEmail }, function (err, user) {
            if (err) {
                res.send(err, 500);
            }
            else {
                var digest = dateVerify.getDate() + crypto.createHmac('sha256', config.secretKey).update(dateVerify.getDate() + user[0].userEmail).digest('base64');
                if (digest === req.body.emailToken) {
                    user[0].activated = true;
                    user[0].save(function (err) {
                        if (err) {
                            res.send(err, 500);
                        }
                        else {
                            res.send('You have been successfully activated.', 200);
                        }
                    });
                }
                else {
                    res.send('Invalid token. Please verify that the token you have entered is exactly the same as the one sent to you via e-mail.', 400);
                }
            }
        });
    }
    else {
        res.send('Your token has expired. Please generate a new one.', 400);
    }
});
app.post('/forgotPassword', function (req, res) {
    var date = new Date();
    User.find({ userEmail: req.body.userEmail }, function (err, user) {
            if (err || user.length  === 0) {
                res.send(err, 500);
            }
            else {
                var token = date.getDate() + crypto.createHmac('sha256', config.secretKey).update(date.getDate() + req.body.userEmail + user.id).digest('base64');
                ses.sendEmail({
                Source: 'noreply@' + config.host,
                Destination: {
                    ToAddresses: [req.body.userEmail]
                },
                Message: {
                    Subject: {
                        Data: 'Reset your password confirmation'
                    },
                    Body: {
                        Text: {
                            Data: 'Please visit http://'+ config.host + '/verifyuser and enter this token to begin the process of resetting your password: ' + token
                        }
                    }
                }
                }, function (err, data) {
                    if (err) {
                        res.send(err, 500);
                    }
                    else {
                        res.send('Success!', 200);
                    }
                });
            }
    });
});
app.post('/resendEmail', function (req, res) {
    var date = new Date();
    User.find({ userEmail: req.body.userEmail }, function (err, user) {
        if (err) {
            res.send(err, 500);
        }
        else {
            var emailToken = date.getDate() + crypto.createHmac('sha256', config.secretKey).update(date.getDate() + req.body.userEmail).digest('base64');
            ses.sendEmail({
                Source: 'noreply@' + config.host,
                Destination: {
                    ToAddresses: [req.body.userEmail]
                },
                Message: {
                    Subject: {
                        Data: 'Thanks for registering!'
                    },
                    Body: {
                        Text: {
                            Data: 'Please visit http://'+ config.host + '/verifyEmail and enter this token when prompted: ' + emailToken
                        }
                    }
                }
            }, function (err, data) {
                if (err) {
                    res.send(err, 500);
                }
                else {
                    res.send('Success!', 200);
                }
            });
        }
    });
});

/*
 * (Public?) API
 */
app.get('/api', function (req, res) {
    res.send('Pasteye API is running!');
});

// ##USERS##
// Get all users
app.get('/api/users', function (req, res) {
    if ('apikey' in req.body) {
        User.find({ apikey: req.body.apikey }, function (err, user) {
            if (err) {
                res.send(err, 500);
            }
            else if (user[0] === undefined || user.length > 1) {
                res.send('ERROR!', 500);
            }
            else if (user[0].isAdmin()) {
                db.driver.execQuery('SELECT users.username, "userEmail", users.id, users_settings.ip, users_settings.email, users_settings.hash FROM users, users_settings WHERE users.id = users_settings.users_id ORDER BY users.id', function (err, data) {
                    if (err) {
                        res.send(err, 500);
                    }
                    res.send(data, 200);
                });
            }
            else {
                res.send('You are unauthorized to perform this action.', 401);
            }
        });
    }
    else {
        res.send('Invalid query. Please include a valid API key', 400);
    }
});

// Get a user by ID
app.get('/api/users/:id', function (req, res) {
    if (req.params.id !== undefined) {
        if ('apikey' in req.body) {
            User.find({ apikey: req.body.apikey }, function (err, user) {
                if (err) {
                    res.send(err, 500);
                }
                else if (user[0] === undefined || user.length > 1) {
                    res.send('ERROR!', 500);
                }
                else if (user[0].isAdmin()) {
                    User.get(req.params.id, function (err, user) {
                        if (err) {
                            res.send('No such user', 500);
                        }
                        user.getSettings(function (err, settings) {
                            res.send(JSON.stringify({username: user.username, userEmail: user.userEmail, id: user.id}, null, '\t') + JSON.stringify({ip: settings.ip, email: settings.email, hash: settings.hash}, null, '\t'));
                        });
                    });
                }
                else {
                    res.send('You are unauthorized to perform this action.', 401);
                }
            });
        }
        else {
            res.send('Invalid query. Please include a valid API key', 400);
        }
    }
});

// Get a user's settings by ID
app.get('/api/users/:id/settings', function (req, res) {
    if (req.params.id !== undefined) {
        if ('apikey' in req.body) {
            User.find({ apikey: req.body.apikey }, function (err, user) {
                if (err) {
                    res.send(err, 500);
                }
                else if (user[0] === undefined || user.length > 1) {
                    res.send('ERROR!', 500);
                }
                else if (user[0].isAdmin()) {
                    User.get(req.params.id, function (err, user) {
                        if (err) {
                            res.send('No such user', 500);
                        }
                        user.getSettings(function (err, settings) {
                            res.send(JSON.stringify(settings, null, '\t'));
                        });
                    });
                }
                else {
                    res.send('You are unauthorized to perform this action.', 401);
                }
            });
        }
        else {
            res.send('Invalid query. Please include a valid API key', 400);
        }
    }
});

// Create a new user with or without settings
app.post('/api/users', function (req, res) {
    if ('apikey' in req.body) {
        User.find({ apikey: req.body.apikey }, function (err, user) {
            if (err) {
                res.send(err, 500);
            }
            else if (user[0] === undefined || user.length > 1) {
                res.send('ERROR!', 500);
            }
            else if (user[0].isAdmin()) {
                if ('users' in req.body && req.body.users instanceof Array) {
                    var tempUserCB = function (err) {
                        if (err) {
                            res.send(err, 500);
                        }
                        else {
                            tempUser.setStats({ip: 0, email: 0, hash: 0}, function (err) {
                                if (err) {
                                    res.send(err, 500);
                                }
                                else {
                                    tempUser.save(function (err) {
                                        if (err) {
                                            res.send(err, 500);
                                        }
                                        else {
                                            var date = new Date();
                                            var emailToken = date.getDate() + crypto.createHmac('sha256', config.secretKey).update(date.getDate() + req.body.userEmail).digest('base64');
                                            // Construct E-mail with Token + /verifyEmail && Send
                                            ses.sendEmail({
                                                Source: 'noreply@' + config.host,
                                                Destination: {
                                                    ToAddresses: [tempUser.userEmail]
                                                },
                                                Message: {
                                                    Subject: {
                                                        Data: 'Thanks for registering!'
                                                    },
                                                    Body: {
                                                        Text: {
                                                            Data: 'Please visit http://'+ config.host + '/verifyEmail and enter this token when prompted: ' + emailToken
                                                        }
                                                    }
                                                }
                                            }, function (err, data) {
                                                if (err) {
                                                    res.send(err, 500);
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    };
                    var tempUserErr = function (err) {
                        if (err) {
                            res.send(err, 500);
                        }
                    };
                    for (var i = 0; i < req.body.users.length; i += 1) {
                        var userFull = req.body.users[i];
                        if ('username' in userFull && 'password' in userFull && 'userEmail' in userFull && 'ip' in userFull && 'email' in userFull && 'hash' in userFull) {
                            var tempUser = new User({ username: userFull.username, password: userFull.password, userEmail: userFull.userEmail });
                            var tempUserSettings = { ip: userFull.ip, email: userFull.email, hash: userFull.hash };
                            tempUser.setSettings(tempUserSettings, tempUserCB);
                        }
                        else if ('username' in userFull && 'password' in userFull && 'userEmail' in userFull) {
                            var tempUser1 = new User({ username: userFull.username, password: userFull.password, userEmail: userFull.userEmail });
                            tempUser1.save(tempUserErr);
                        }
                    }
                    res.send('Batch operation completed.', 200);
                }
            }
            else {
                res.send('You are unauthorized to perform this action.', 401);
            }
        });
    }

    else if ('username' in req.body && 'password' in req.body && 'userEmail' in req.body && 'ip' in req.body && 'email' in req.body && 'hash' in req.body) {
        var reqUser = new User({ username: req.body.username, password: req.body.password, userEmail: req.body.userEmail });
        reqUser.setSettings({ip: req.body.ip, email: req.body.email, hash: req.body.hash }, function (err) {
            if (err) {
                res.send(err, 500);
            }
            else {
                reqUser.setStats({ip: 0, hash: 0, email: 0}, function (err) {
                    if (err) {
                        res.send(err, 500);
                    }
                    else {
                        reqUser.save(function (err) {
                            if (err) {
                                res.send(err, 500);
                            }
                            else {
                                reqUser.getSettings(function (err, settings) {
                                    if (err) {
                                        res.send(err, 500);
                                    }
                                    else {
                                        var date = new Date();
                                        var emailToken = date.getDate() + crypto.createHmac('sha256', config.secretKey).update(date.getDate() + req.body.userEmail).digest('base64');
                                        // Construct E-mail with Token + /verifyEmail && Send
                                        ses.sendEmail({
                                            Source: 'noreply@' + config.host,
                                            Destination: {
                                                ToAddresses: [reqUser.userEmail]
                                            },
                                            Message: {
                                                Subject: {
                                                    Data: 'Thanks for registering!'
                                                },
                                                Body: {
                                                    Text: {
                                                        Data: 'Please visit http://'+ config.host + '/verifyEmail and enter this token when prompted: ' + emailToken
                                                    }
                                                }
                                            }
                                        }, function (err, data) {
                                            if (err) {
                                                res.send(err, 500);
                                            }
                                            else {
                                                res.send('Successfully created user & dispatched e-mail to ' + reqUser.username + ' with settings: ' + JSON.stringify(settings, null, '\t'), 200);
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });

    }
    else if ('username' in req.body && 'password' in req.body && 'userEmail' in req.body) {
        var reqUser = new User({ username: req.body.username, password: req.body.password, userEmail: req.body.userEmail });
        reqUser.save(function (err) {
            if (err) {
                res.send(err, 500);
            }
            else {
                res.send('Successfully created user ' + reqUser.username + '.', 200);
            }
        });
    }
    else {
        res.send('Invalid query.', 400);
    }
});

app.put('/api/users/:id', function (req, res) {
    if (req.params.id !== undefined) {
        if ('apikey' in req.body) {
            User.find({ apikey: req.body.apikey }, function (err, user) {
                if (err) {
                    res.send(err, 500);
                }
                else if (user[0] === undefined || user.length > 1 || user.length === 0) {
                    res.send('ERROR!', 500);
                }
                else if (user[0].isAdmin() || user[0].getId() === parseInt(req.params.id, 10)) {
                    User.get(req.params.id, function (err, user) {
                        if (err) {
                            res.send('No such user', 500);
                        }
                        else {
                            user.getSettings(function (err, settings) {
                                if (err) {
                                    res.send(err, 500);
                                }
                                else {
                                    var fullObj = { username: user.username, password: user.password, userEmail: user.userEmail, ip: settings.ip, email: settings.email, hash: settings.hash };
                                    var userObj = { username: user.username, password: user.password, userEmail: user.userEmail };
                                    var settingsObj = { ip: settings.ip, email: settings.email, hash: settings.hash };
                                    var successArray = [];
                                    var userSettingsErr = function (err) {
                                        if (err) {
                                            res.send(err, 500);
                                        }
                                    };
                                    var emailErr = function (err, data) {
                                        if (err) {
                                            res.send(err, 500);
                                        }
                                    };

                                    for (var param in fullObj) {
                                        if (fullObj.hasOwnProperty(param)) {
                                            if (param in req.body && param in settingsObj) {
                                                settingsObj[param] = req.body[param];
                                                user.setSettings(settingsObj, userSettingsErr);
                                                successArray.push(param);
                                            }
                                            if (param in req.body && param in userObj) {
                                                if (param === 'userEmail') {
                                                    var date = new Date();
                                                    var emailToken = date.getDate() + crypto.createHmac('sha256', config.secretKey).update(date.getDate() + req.body.userEmail).digest('base64');
                                                    // Construct E-mail with Token + /verifyEmail && Send
                                                    ses.sendEmail({
                                                        Source: 'noreply@' + config.host,
                                                        Destination: {
                                                            ToAddresses: [user.userEmail]
                                                        },
                                                        Message: {
                                                            Subject: {
                                                                Data: 'You recently changed your profile E-mail address.'
                                                            },
                                                            Body: {
                                                                Text: {
                                                                    Data: 'Hi there. You recently changed your Pasteye profile e-mail address. If this is correct, please visit http://'+ config.host + '/verifyEmail and enter this token when prompted: ' + emailToken + '\nYou will not receive any further monitor notifications until you re-verify your account with us.'
                                                                }
                                                            }
                                                        }
                                                    }, emailErr());
                                                    user.activated = false;
                                                }
                                                user[param] = req.body[param];
                                                successArray.push(param);
                                            }
                                        }
                                    }
                                    if (successArray.length > 0) {
                                        user.save(function (err) {
                                            if (err) {
                                                res.send(err, 500);
                                            }
                                            else {
                                                res.send('Successfully updated user ' + user.id + ' with settings: ' + successArray.join(), 200);
                                                console.log('Successfully updated user ' + user.id + ' with settings: ' + successArray.join());
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    });
                }
                else {
                    res.send('You are unauthorized to perform this action.', 401);
                }
            });
        }
        else {
            res.send('Invalid query. Please include a valid API key', 400);
        }
    }
});

app.delete('/api/users', function (req, res) {
    if ('apikey' in req.body) {
        User.find({ apikey: req.body.apikey }, function (err, user) {
            if (err) {
                res.send(err, 500);
            }
            else if (user[0] === undefined || user.length > 1 || user.length === 0) {
                res.send('ERROR!', 500);
            }
            else {
                if ('users' in req.body && req.body.users instanceof Array) {
                    if (user[0].isAdmin()) {
                        var userFindCB = function (err, foundUsers) {
                            if (err) {
                                res.send(err, 500);
                            }
                            if (foundUsers[0] === undefined || foundUsers.length === 0) {
                                res.send(err, 500);
                            }
                            else {
                                foundUsers[0].removeSettings(usersSettingsErr);
                            }
                        };
                        var usersSettingsErr = function (err) {
                            if (err) {
                                res.send(err, 500);
                            }
                            else {
                                foundUsers[0].removeStats(function (err) {
                                    if (err) {
                                        res.send(err, 500);
                                    }
                                });
                            }
                        };
                        var userRemoveErr = function (err) {
                            if (err) {
                                res.send(err, 500);
                            }
                        };
                        var userGetCB =  function (err, foundUser) {
                            if (err) {
                                res.send(err, 500);
                            }
                            else {
                                foundUser.removeSettings(function (err) {
                                    if (err) {
                                        res.send(err, 500);
                                    }
                                    else {
                                        foundUser.removeStats(function (err) {
                                            if (err) {
                                                res.send(err, 500);
                                            }
                                        });
                                    }
                                });
                                foundUser.remove(function (err) {
                                    if (err) {
                                        res.send(err, 500);
                                    }
                                });
                            }
                        };
                        for (var i = 0; i < req.body.users.length; i += 1) {
                            if ('username' in req.body.users[i]) {
                                User.find({ username: req.body.users[i].username }, userFindCB);
                                User.find({ username: req.body.users[i].username }).remove(userRemoveErr);
                            }
                            else if ('id' in req.body.users[i]) {
                                User.get(req.body.users[i].id, userGetCB);
                            }
                        }
                        res.send('Batch operation completed successfully', 200);
                    }
                    else {
                        res.send('You are unauthorized to perform this action.', 401);
                    }
                }
                else if ('username' in req.body) {
                    if (user[0].getUsername() === req.body.username || user[0].isAdmin()) {
                        User.find({ username: req.body.username }, function (err, users) {
                            if (err) {
                                res.send(err, 500);
                            }
                            else if (users[0] === undefined || users.length > 1 || users.length === 0) {
                                res.send('ERROR!', 500);
                            }
                            else {
                                users[0].removeSettings(function (err) {
                                    if (err) {
                                        res.send(err, 500);
                                    }
                                    else {
                                        users[0].removeStats(function (err) {
                                            if (err) {
                                                res.send(err, 500);
                                            }
                                        });
                                    }
                                });
                            }
                        });
                        User.find({ username: req.body.username }).remove(function (err) {
                            if (err) {
                                res.send(err, 500);
                            }
                            else {
                                req.logout();
                                res.send('Successfully removed user ' + req.body.username, 200);
                            }
                        });
                    }
                    else {
                        res.send('Cannot delete another user.', 401);
                    }
                }
                else if ('id' in req.body) {
                    if (user[0].getId() === req.body.id || user[0].isAdmin()) {
                        User.get(req.body.id, function (err, user) {
                            if (err) {
                                res.send(err, 500);
                            }
                            else if (user === undefined) {
                                res.send('ERROR!', 500);
                            }
                            else {
                                user.removeSettings(function (err) {
                                    if (err) {
                                        res.send(err, 500);
                                    }
                                    else {
                                        user.removeStats(function (err) {
                                            if (err) {
                                                res.send(err, 500);
                                            }
                                        });
                                    }
                                });
                                user.remove(function (err) {
                                    if (err) {
                                        res.send(err, 500);
                                    }
                                    else {
                                        req.logout();
                                        res.send('Successfully removed user ' + req.body.id, 200);
                                    }
                                });
                            }
                        });
                    }
                    else {
                        res.send('Cannot delete another user.', 401);
                    }
                }
            }
        });
    }
    else {
        res.send('Invalid query. Please include a valid API key', 400);
    }
});

setInterval(function () {
    // GET the Pastebin front page
    request('http://pastebin.com/', function (error, response, body) {
        if (!error && response.statusCode === 200) {
            eventEmitter.emit('pageSuccess', body);
        }
    });
}, 25000);

db.on('userSave', function () {
    getUserSettings();
});

eventEmitter.on('pageSuccess', function (body) {
    parseLatestUrls(body, function (url) {
        request(url, function (error, response, body) {
            checkBlacklist(body, url, function (body, url) {
                masterFilter(body, url, function (body, url, cbFilters) {
                    userFilter(body, url, cbFilters, function (body, url, indivUserSettings, filter, cbFilters) {
                        var filterCount = cbFilters[filter].count;
                        User.get(indivUserSettings.users_id, function (err, user) {
                            if (err) {
                                console.error('ERROR @ getting user' + err);
                            }
                            else {
                                if (user.activated) {
                                    // Send an e-mail containing the paste data
                                    ses.sendEmail({
                                        Source: 'noreply@' + config.host,
                                        Destination: {
                                            ToAddresses: [user.userEmail]
                                        },
                                        Message: {
                                            Subject: {
                                                Data: '[NOTIFICATION][' + filter.toString().toUpperCase() + ']'
                                            },
                                            Body: {
                                                Text: {
                                                    Data: 'We think we found ' + filterCount + ' ' + filter + 's in the body of the paste located at URL: ' + url + '\n\n' + body
                                                }
                                            }
                                        }
                                    }, function (err, data) {
                                        if (err) {
                                            console.error('Error sending e-mail: ' + err);
                                        }
                                        else {
                                            console.log('E-mail Success!' + JSON.stringify(data));
                                            user.getStats(function (err, stats) {
                                                if (err) {
                                                    console.error('Error @ getting stats ' + err);
                                                }
                                                else {
                                                    var newStats = { ip: stats.ip, hash: stats.hash, email: stats.email };
                                                    var filterCount = stats[filter];
                                                    newStats[filter] = filterCount + 1;
                                                    user.setStats(newStats, function (err) {
                                                        if (err) {
                                                            console.error('Error setting stats: ' + err);
                                                        }
                                                        else {
                                                            user.save(function (err) {
                                                                if (err) {
                                                                    console.error('Error saving user: ' + err);
                                                                }
                                                            });
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    });
                                }
                            }
                        });
                        console.log('Found something interesting based on User ' + indivUserSettings.users_id + 's settings.');
                        console.log('We think we found ' + filterCount + ' ' + filter + 's in the body of the paste located at URL: ' + url);
                    });
                });
            });
        });
    });
});


text:
using Owin;
using System;
using System.Collections.Generic;

//The following libraries were added to this sample.
using System.Threading.Tasks;
using System.Web;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security;

//The following libraries were defined and added to this sample.
using DdacAssignment.Utils;
using System.Security.Claims;
using Newtonsoft.Json;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;

namespace DdacAssignment
{
    public partial class Startup
    {
        /// <summary>
        /// Configures OpenIDConnect Authentication & Adds Custom Application Authorization Logic on User Login.
        /// </summary>
        /// <param name="app">The application represented by a <see cref="IAppBuilder"/> object.</param>
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ConfigHelper.ClientId,
                    Authority = String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, ConfigHelper.Tenant), // For Single-Tenant
                    //Authority = ConfigHelper.CommonAuthority, // For Multi-Tenant
                    PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,

                    // Here, we've disabled issuer validation for the multi-tenant sample.  This enables users
                    // from ANY tenant to sign into the application (solely for the purposes of allowing the sample
                    // to be run out-of-the-box.  For a real multi-tenant app, reference the issuer validation in
                    // WebApp-MultiTenant-OpenIDConnect-DotNet.  If you're running this sample as a single-tenant
                    // app, you can delete the ValidateIssuer property below.
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        //ValidateIssuer = false, // For Multi-Tenant Only
                        RoleClaimType = "roles",
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    }
                });
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package gov.hhs.fha.nhinc.admingui.jee.jsf;

import gov.hhs.fha.nhinc.admingui.constant.NavigationConstant;
import gov.hhs.fha.nhinc.admingui.display.DisplayHolder;
import gov.hhs.fha.nhinc.admingui.services.RoleService;
import gov.hhs.fha.nhinc.admingui.services.RoleServiceImpl;
import gov.hhs.fha.nhinc.admingui.services.persistence.jpa.entity.UserLogin;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 * The listener interface for receiving userAuthorization events. The class that is interested in processing a
 * userAuthorization event implements this interface, and the object created with that class is registered with a
 * component using the component's <code>addUserAuthorizationListener<code> method. When
 * the userAuthorization event occurs, that object's appropriate
 * method is invoked.
 *
 * @author msw
 */
@Component
public class UserAuthorizationListener implements PhaseListener {

    private static final Logger LOG = Logger.getLogger(UserAuthorizationListener.class);

    /**
     * The Constant LOGIN_REQUIRED_DIR.
     */
    public static List<String> noLoginRequiredPages = null;

    /**
     * The Constant USER_INFO_SESSION_ATTRIBUTE.
     */
    public static final String USER_INFO_SESSION_ATTRIBUTE = "userInfo";

    private RoleService roleService = new RoleServiceImpl();

    /**
     * Serial version required for Serializable interface.
     *
     */
    private static final long serialVersionUID = 4891265644965340362L;

    /**
     *
     */
    public UserAuthorizationListener() {
        noLoginRequiredPages = new ArrayList<String>();
        noLoginRequiredPages.add("/login.xhtml");
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
     */
    @Override
    public void afterPhase(PhaseEvent event) {
        FacesContext facesContext = event.getFacesContext();
        String currentPage = facesContext.getViewRoot().getViewId();
        LOG.debug("current page: ".concat(currentPage));

        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        UserLogin currentUser = null;
        if (session != null) {
            currentUser = (UserLogin) session.getAttribute(USER_INFO_SESSION_ATTRIBUTE);
        }

        if (!noLoginRequiredPages.contains(currentPage) && currentUser == null) {
            LOG.debug("login required and current user is null, redirecting to login page.");
            NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
            nh.handleNavigation(facesContext, null, NavigationConstant.LOGIN_PAGE);
        } else {

            boolean hasRolePermission = roleService.checkRole(formatPageName(currentPage), currentUser);
            boolean isConfigured = checkConfiguredDisplay(formatPageName(currentPage));

            if (currentUser != null && (hasRolePermission == false || isConfigured == false)) {

                LOG.debug("User, " + currentUser.getUserName() + " can not access given page: " + currentPage);
                NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
                nh.handleNavigation(facesContext, null, NavigationConstant.STATUS_PAGE);
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
     */
    @Override
    public void beforePhase(PhaseEvent arg0) {
        // Do nothing.
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.faces.event.PhaseListener#getPhaseId()
     */
    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

    private String formatPageName(String pageName) {
        if (pageName.startsWith("/")) {
            return pageName.substring(1, pageName.length()).toLowerCase();
        } else {
            return pageName.toLowerCase();
        }
    }

    private boolean checkConfiguredDisplay(String currentPage) {
        if (currentPage.equals(NavigationConstant.DIRECT_XHTML)) {
            return DisplayHolder.getInstance().isDirectEnabled();
        } else if (currentPage.equals(NavigationConstant.FHIR_XHTML)) {
            return DisplayHolder.getInstance().isFhirEnabled();
        }
        return true;
    }

}


text:
import copy
from unittest import mock

from oslo_config import cfg
from oslo_limit import exception as limit_exceptions
from oslo_limit import fixture as limit_fixture
from oslo_utils.fixture import uuidsentinel as uuids

from nova import context
from nova import exception
from nova.limit import local as local_limit
from nova.limit import utils as limit_utils
from nova import objects
from nova import test

CONF = cfg.CONF

class TestLocalLimits(test.NoDBTestCase):
    def setUp(self):
        super(TestLocalLimits, self).setUp()
        self.flags(driver=limit_utils.UNIFIED_LIMITS_DRIVER, group="quota")
        self.context = context.RequestContext()

    def test_enforce_api_limit_metadata(self):
        # default max is 128
        self.useFixture(limit_fixture.LimitFixture(
            {local_limit.SERVER_METADATA_ITEMS: 128}, {}))
        local_limit.enforce_api_limit(local_limit.SERVER_METADATA_ITEMS, 128)

        e = self.assertRaises(exception.MetadataLimitExceeded,
                              local_limit.enforce_api_limit,
                              local_limit.SERVER_METADATA_ITEMS, 129)
        msg = ("Resource %s is over limit" % local_limit.SERVER_METADATA_ITEMS)
        self.assertIn(msg, str(e))

    def test_enforce_api_limit_skip(self):
        self.flags(driver="nova.quota.NoopQuotaDriver", group="quota")
        local_limit.enforce_api_limit(local_limit.SERVER_METADATA_ITEMS, 200)

    @mock.patch('oslo_limit.limit.Enforcer')
    def test_enforce_api_limit_session_init_error(self, mock_util):
        mock_util.side_effect = limit_exceptions.SessionInitError('error')

        e = self.assertRaises(exception.KeystoneConnectionFailed,
                              local_limit.enforce_api_limit,
                              local_limit.SERVER_METADATA_ITEMS, 42)
        expected = ('Failed to connect to keystone while enforcing '
                    'server_metadata_items quota limit.')
        self.assertIn(expected, str(e))

    def test_enforce_api_limit_raises_for_invalid_entity(self):
        e = self.assertRaises(ValueError,
                              local_limit.enforce_api_limit,
                              local_limit.KEY_PAIRS, 42)
        expected = '%s is not a valid API limit: %s' % (
            local_limit.KEY_PAIRS, local_limit.API_LIMITS)
        self.assertEqual(expected, str(e))

    def test_enforce_api_limit_no_registered_limit_found(self):
        self.useFixture(limit_fixture.LimitFixture({}, {}))
        e = self.assertRaises(exception.MetadataLimitExceeded,
                              local_limit.enforce_api_limit,
                              local_limit.SERVER_METADATA_ITEMS, 42)
        msg = ("Resource %s is over limit" % local_limit.SERVER_METADATA_ITEMS)
        self.assertIn(msg, str(e))

    def test_enforce_injected_files(self):
        reglimits = {local_limit.INJECTED_FILES: 5,
                     local_limit.INJECTED_FILES_CONTENT: 10 * 1024,
                     local_limit.INJECTED_FILES_PATH: 255}
        self.useFixture(limit_fixture.LimitFixture(reglimits, {}))

        local_limit.enforce_api_limit(local_limit.INJECTED_FILES, 5)
        local_limit.enforce_api_limit(local_limit.INJECTED_FILES_CONTENT,
                                      10 * 1024)
        local_limit.enforce_api_limit(local_limit.INJECTED_FILES_PATH, 255)

        e = self.assertRaises(exception.OnsetFileLimitExceeded,
                              local_limit.enforce_api_limit,
                              local_limit.INJECTED_FILES, 6)
        msg = ("Resource %s is over limit" % local_limit.INJECTED_FILES)
        self.assertIn(msg, str(e))
        e = self.assertRaises(exception.OnsetFileContentLimitExceeded,
                              local_limit.enforce_api_limit,
                              local_limit.INJECTED_FILES_CONTENT,
                              10 * 1024 + 1)
        msg = (
            "Resource %s is over limit" % local_limit.INJECTED_FILES_CONTENT)
        self.assertIn(msg, str(e))
        e = self.assertRaises(exception.OnsetFilePathLimitExceeded,
                              local_limit.enforce_api_limit,
                              local_limit.INJECTED_FILES_PATH, 256)
        msg = ("Resource %s is over limit" % local_limit.INJECTED_FILES_PATH)
        self.assertIn(msg, str(e))

    @mock.patch.object(objects.KeyPairList, "get_count_by_user")
    def test_enforce_db_limit_keypairs(self, mock_count):
        self.useFixture(limit_fixture.LimitFixture(
            {local_limit.KEY_PAIRS: 100}, {}))

        mock_count.return_value = 99
        local_limit.enforce_db_limit(self.context, local_limit.KEY_PAIRS,
                                     uuids.user_id, 1)
        mock_count.assert_called_once_with(self.context, uuids.user_id)

        self.assertRaises(exception.KeypairLimitExceeded,
                          local_limit.enforce_db_limit,
                          self.context, local_limit.KEY_PAIRS,
                          uuids.user_id, 2)

        mock_count.return_value = 100
        local_limit.enforce_db_limit(self.context, local_limit.KEY_PAIRS,
                                     uuids.user_id, 0)
        mock_count.return_value = 101
        self.assertRaises(exception.KeypairLimitExceeded,
                          local_limit.enforce_db_limit,
                          self.context, local_limit.KEY_PAIRS,
                          uuids.user_id, 0)

    def test_enforce_db_limit_skip(self):
        self.flags(driver="nova.quota.NoopQuotaDriver", group="quota")
        local_limit.enforce_db_limit(self.context, local_limit.KEY_PAIRS,
                                     uuids.user_id, 1)

    @mock.patch('oslo_limit.limit.Enforcer')
    def test_enforce_db_limit_session_init_error(self, mock_util):
        mock_util.side_effect = limit_exceptions.SessionInitError(
            test.TestingException())

        e = self.assertRaises(exception.KeystoneConnectionFailed,
                              local_limit.enforce_db_limit, self.context,
                              local_limit.KEY_PAIRS, uuids.user_id, 42)
        expected = ('Failed to connect to keystone while enforcing '
                    'server_key_pairs quota limit.')
        self.assertEqual(expected, str(e))

    def test_enforce_db_limit_raise_on_invalid(self):
        e = self.assertRaises(ValueError, local_limit.enforce_db_limit,
                              self.context, local_limit.INJECTED_FILES,
                              uuids.user_id, 1)
        fmt = '%s does not have a DB count function defined: %s'
        expected = fmt % (
            local_limit.INJECTED_FILES, local_limit.DB_COUNT_FUNCTION.keys())
        self.assertEqual(expected, str(e))

    @mock.patch.object(objects.KeyPairList, "get_count_by_user")
    def test_enforce_db_limit_no_registered_limit_found(self, mock_count):
        self.useFixture(limit_fixture.LimitFixture({}, {}))
        mock_count.return_value = 5
        e = self.assertRaises(exception.KeypairLimitExceeded,
                              local_limit.enforce_db_limit, self.context,
                              local_limit.KEY_PAIRS, uuids.user_id, 42)
        msg = ("Resource %s is over limit" % local_limit.KEY_PAIRS)
        self.assertIn(msg, str(e))

    def test_enforce_db_limit_raise_bad_delta(self):
        e = self.assertRaises(ValueError, local_limit.enforce_db_limit,
                              self.context, local_limit.KEY_PAIRS,
                              uuids.user_id, -1)
        self.assertEqual("delta must be a positive integer", str(e))

    @mock.patch.object(objects.InstanceGroupList, "get_counts")
    def test_enforce_db_limit_server_groups(self, mock_count):
        self.useFixture(limit_fixture.LimitFixture(
            {local_limit.SERVER_GROUPS: 10}, {}))

        mock_count.return_value = {'project': {'server_groups': 9}}
        local_limit.enforce_db_limit(self.context, local_limit.SERVER_GROUPS,
                                     uuids.project_id, 1)
        mock_count.assert_called_once_with(self.context, uuids.project_id)

        self.assertRaises(exception.ServerGroupLimitExceeded,
                          local_limit.enforce_db_limit,
                          self.context, local_limit.SERVER_GROUPS,
                          uuids.project_id, 2)

    @mock.patch.object(objects.InstanceGroup, "get_by_uuid")
    def test_enforce_db_limit_server_group_members(self, mock_get):
        self.useFixture(limit_fixture.LimitFixture(
            {local_limit.SERVER_GROUP_MEMBERS: 10}, {}))

        mock_get.return_value = objects.InstanceGroup(members=[])
        local_limit.enforce_db_limit(self.context,
                                     local_limit.SERVER_GROUP_MEMBERS,
                                     uuids.server_group, 10)
        mock_get.assert_called_once_with(self.context, uuids.server_group)

        self.assertRaises(exception.GroupMemberLimitExceeded,
                          local_limit.enforce_db_limit,
                          self.context, local_limit.SERVER_GROUP_MEMBERS,
                          uuids.server_group, 11)

    @mock.patch.object(objects.InstanceGroupList, "get_counts")
    def test_get_in_use(self, mock_count):
        mock_count.return_value = {'project': {'server_groups': 9}}
        usages = local_limit.get_in_use(self.context, uuids.project_id)
        expected_usages = {
            'injected_file_content_bytes': 0,
            'injected_file_path_bytes': 0,
            'injected_files': 0,
            'key_pairs': 0,
            'metadata_items': 0,
            'server_group_members': 0,
            'server_groups': 9
        }
        self.assertEqual(expected_usages, usages)

class GetLegacyLimitsTest(test.NoDBTestCase):
    def setUp(self):
        super(GetLegacyLimitsTest, self).setUp()
        self.new = {"server_metadata_items": 1,
                    "server_injected_files": 2,
                    "server_injected_file_content_bytes": 3,
                    "server_injected_file_path_bytes": 4,
                    "server_key_pairs": 5,
                    "server_groups": 6,
                    "server_group_members": 7}
        self.legacy = {"metadata_items": 1,
                       "injected_files": 2,
                       "injected_file_content_bytes": 3,
                       "injected_file_path_bytes": 4,
                       "key_pairs": 5,
                       "server_groups": 6,
                       "server_group_members": 7}
        self.resources = list(local_limit.API_LIMITS | local_limit.DB_LIMITS)
        self.resources.sort()
        self.flags(driver=limit_utils.UNIFIED_LIMITS_DRIVER, group="quota")

    def test_convert_keys_to_legacy_name(self):
        limits = local_limit._convert_keys_to_legacy_name(self.new)
        self.assertEqual(self.legacy, limits)

    def test_get_legacy_default_limits(self):
        reglimits = copy.deepcopy(self.new)
        reglimits.pop('server_key_pairs')
        self.useFixture(limit_fixture.LimitFixture(reglimits, {}))
        limits = local_limit.get_legacy_default_limits()
        expected = copy.deepcopy(self.legacy)
        expected['key_pairs'] = 0
        self.assertEqual(expected, limits)


text:
(function(){
	var Utils = FL.Utils;
	var DisplayObjectContainer = FL.DisplayObjectContainer;
	var Mouse = FL.Mouse;
	var Keyboard = FL.Keyboard;

	/**
	 * canvas, width, height, fps
	*/
	var Stage = FL.Stage = function(prop)
	{
		DisplayObjectContainer.call(this, prop);
		this.width = this.width||550;
		this.height = this.height||400;
		this.fps = this.fps||60;
		this.init();
	};
	Utils.extends(Stage, DisplayObjectContainer);

	Stage.prototype.init = function()
	{
		this.stage = this;
		this.timeStep = 1000/this.fps;
		this.canvas.width = this.width;
		this.canvas.height = this.height;
		this.ctx = this.canvas.getContext("2d");
	}

	Stage.prototype.addChildAt = function(obj, at)
	{
		this.superClass.addChildAt.call(this, obj, at);
	};

	Stage.prototype.render = function()
	{
		this.ctx.clearRect(0, 0, this.width, this.height);
		this.superClass.render.call(this, this.ctx)
	}

	Stage.prototype.start = function()
	{
		var that = this;
		this.stop();
		this._interval = setInterval(function(){
				that.render();
				that.callAll("update");
		}, 1000/this.fps);
	};

	Stage.prototype.update = function()
	{
	};

	Stage.prototype.initMouseEvent = function(mouseChildren){
		Mouse.init(this);
		if(mouseChildren)
		{
			this.addEventListener("mousedown", fireChildrenEvent);
			this.addEventListener("mousemove", fireChildrenEvent);
			this.addEventListener("mouseup", fireChildrenEvent);
		}
	};

	Stage.prototype.initKeyboardEvent = function(){
		Keyboard.init();
	};

	Stage.prototype.stop = function()
	{
		clearInterval(this._interval);
	};

	function fireChildrenEvent(e)
	{
		var children = this.children;
		for(var i = 0, l = this.children.length;i < l;i ++)
		{
			var child = children[i];

			if(child.mouseEnable && child.hitTestPoint(e.x, e.y))
			{
				child.dispatchEvent(e);
				return;
			}
		}
	}

})();


text:
package com.palmelf.eoffice.dao.system.impl;

import java.util.ArrayList;
import java.util.List;

import com.palmelf.core.dao.impl.BaseDaoImpl;
import com.palmelf.eoffice.dao.system.UserSubDao;
import com.palmelf.eoffice.model.system.UserSub;

public class UserSubDaoImpl extends BaseDaoImpl<UserSub> implements UserSubDao {
	public UserSubDaoImpl() {
		super(UserSub.class);
	}

	public List<Long> upUser(Long userId) {
		String hql = "from UserSub vo where vo.subAppUser.userId=?";
		Object[] objs = { userId };
		List<UserSub> list = this.findByHql(hql, objs);
		List idList = new ArrayList();
		for (UserSub sb : list) {
			idList.add(sb.getUserId());
		}
		return idList;
	}

	public List<Long> subUsers(Long userId) {
		String hql = "from UserSub vo where vo.userId=?";
		Object[] objs = { userId };
		List<UserSub> list = this.findByHql(hql, objs);
		List idList = new ArrayList();
		for (UserSub sb : list) {
			idList.add(sb.getSubAppUser().getUserId());
		}
		return idList;
	}

	public List<UserSub> findByUser(Long userId) {
		String hql = "from UserSub vo where vo.userId=? ";
		Object[] objs = { userId };
		return this.findByHql(hql, objs);
	}
}


text:
mod frame_stack;

pub unsafe fn frame_stack(multiboot: *const ::multiboot::Information) {
    frame_stack::init_frame_stack(multiboot)
}


text:
<?php

/**
 * Implementation of hook_info.
 */
function ft_db_info() {
  return array(
    'name' => 'Database: Enabled a database for other plugins to use.',
    'settings' => array(
      'path' => array(
        'default' => 'data/ft_db',
        'description' => t('The path to the database file.'),
      ),
      'flushtables' => array(
        'default' => FALSE,
        'description' => t('Can user delete database tables?'),
      ),
    ),
  );
}

/**
 * Implementation of hook_init.
 */
function ft_db_init() {
  global $ft;

  if (extension_loaded('pdo_sqlite')) {
    if ($ft['db']['link'] = new PDO('sqlite:'.$ft['plugins']['db']['settings']['path'])) {
      // Get a list of tables. That way other modules can determine if they need to install themselves or not.
      $result = $ft['db']['link']->query("SELECT name FROM SQLITE_MASTER WHERE type='table'");
      if ($result) {
        foreach ($result as $row) {
          $ft['db']['tables'][] = $row['name'];
        }
      }
    } else {
      ft_set_message(t('Database module could not be enabled. Database could not be created at !db.', array('!db' => $ft['plugins']['db']['settings']['path'])), 'error');
      ft_plugin_unload('db');
    }
  } else {
    ft_set_message(t('Database module could not be enabled. PHP PDO is not installed.'), 'error');
    ft_plugin_unload('db');
  }
}

/**
 * Implementation of hook_secondary_menu.
 */
function ft_db_secondary_menu() {
  global $ft;
  if (isset($ft['plugins']['db']['settings']['flushtables']) && $ft['plugins']['db']['settings']['flushtables'] === TRUE) {
    return ft_make_link(t('[db]'), "act=db", t("Manage database"));
  }
  return '';
}

/**
 * Implementation of hook_page.
 */
function ft_db_page($act) {
  global $ft;

  $str = '';
  if ($act == 'db' && isset($ft['plugins']['db']['settings']['flushtables']) && $ft['plugins']['db']['settings']['flushtables'] === TRUE) {
    // Show all DB tables.
    $str .= "
".t('Database tables')."
";
    // Other users.
    if (is_array($ft['db']) && is_array($ft['db']['tables']) && count($ft['db']['tables']) > 0) {
      $str .= '

'.t('Table name').'	'.t('Delete?').'
';
      foreach($ft['db']['tables'] as $name) {
        $str .= '
'.$name.'	'.ft_make_link(t('delete'), 'act=db_delete&value='.$name).'
';
      }
      $str .= '
';
    } else {
      $str .= '
'.t('No tables present in database.').'
';
    }
  } elseif ($act == 'db_delete') {
    $display_value = htmlentities($_GET['value']);
    $str = "
".t('Delete database table: !table', array('!table' => $display_value))."
";
    $str .= "
".t('Are you sure you want to continue? This will delete the table from the database.')."
";
    $str .= '<form action="'.ft_get_self().'" method="post">';
    $str .= '
';
    $str .= '<input type="hidden" name="value" value="'.$display_value.'">';
    $str .= '<input type="hidden" name="act" value="db_delete_submit">';
    $str .= '<input type="submit" name="ft_submit" value="'.t('Yes, delete this table').'">';
    $str .= '<input type="submit" name="ft_submit" value="'.t('Cancel').'">

    </form>';
  }
  return $str;
}

/**
 * Implementation of hook_action.
 */
function ft_db_action($act) {
  global $ft;
  // Delete a database table.
  if ($act == 'db_delete_submit' && isset($ft['plugins']['db']['settings']['flushtables']) && $ft['plugins']['db']['settings']['flushtables'] === TRUE) {
    // Check for cancel.
    if (strtolower($_REQUEST["ft_submit"]) == strtolower(t("Cancel"))) {
      ft_redirect("act=db");
    }
		// Check if table exists.
    $display_value = htmlentities($_POST['value']);
    if (is_array($ft['db']) && is_array($ft['db']['tables']) && count($ft['db']['tables']) > 0) {
      // Drop table.
      $result = $ft['db']['link']->query('DROP TABLE '.$ft['db']['link']->quote($_POST['value']));
      if ($result) {
        ft_set_message(t('Database table !table dropped.', array('!table' => $display_value)));
      } else {
        ft_set_message(t("Database table !table could not be dropped.", array('!table' => $display_value)), 'error');
      }
    } else {
      ft_set_message(t("Database table !table could not be removed because it doesn't exists.", array('!table' => $display_value)), 'error');
    }
		// Redirect.
    ft_redirect("act=db");
  }
}

/**
 * Create database table if it doesn't exists.
 *
 * @param $table
 *   Name of table name.
 * @param $sql
 *   SQL query to run to create table.
 * @return TRUE if table already exists or is created successfully.
 */
function ft_db_install_table($table, $sql) {
  global $ft;
  if (is_array($ft['db']['tables'])) {
    foreach ($ft['db']['tables'] as $c) {
      if ($c == $table) {
        return TRUE;
      }
    }
  }
  return $ft['db']['link']->query($sql);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PmSys.Components;
using PmSys.WebControls;

namespace PmSys.Web.Manager.Module.FrameWork.Projects
{
    public partial class ProjectManager : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                OnStart();
            }
        }

        private void OnStart()
        {
            InputData();
            switch (CMD)
            {
                case "New":
                    CMD_Txt = "增加";
                    HiddenDisp();
                    TopTr.Visible = false;
                    break;
                case "Edit":
                    CMD_Txt = "修改";
                    HiddenDisp();
                    HeadMenuButtonItem Bm0 = new HeadMenuButtonItem();
                    Bm0.ButtonPopedom = PopedomType.List;
                    Bm0.ButtonUrl = string.Format("?CMD=Look&S_ID={0}", S_ID);
                    Bm0.ButtonIcon = "back.gif";
                    Bm0.ButtonName = "返回";
                    HeadMenuWebControls1.ButtonList.Add(Bm0);
                    HeadMenuButtonItem Bm1 = new HeadMenuButtonItem();
                    Bm1.ButtonPopedom = PopedomType.Delete;
                    Bm1.ButtonUrlType = UrlType.JavaScript;
                    Bm1.ButtonUrl = string.Format("DelData('?CMD=Delete&S_ID={0}')", S_ID);
                    HeadMenuWebControls1.ButtonList.Add(Bm1);
                    break;
                case "Look":
                    HiddenInput();
                    HeadMenuButtonItem Bm2 = new HeadMenuButtonItem();
                    Bm2.ButtonPopedom = PopedomType.Edit;
                    Bm2.ButtonUrl = string.Format("?CMD=Edit&S_ID={0}", S_ID);
                    HeadMenuWebControls1.ButtonList.Add(Bm2);
                    break;
                case "Delete":
                    CMD_Txt = "删除";
                    PM_ProjectsTable sat = new PM_ProjectsTable();
                    sat.ProjectId = S_ID.ToString();
                    sat.DB_Option_Action_ = CMD;
                    BusinessFacade.PM_ProjectsTableInsertUpdate(sat);

                    EventMessage.MessageBox(1, "操作成功", "删除记录ID:(" + S_ID + ")成功!", Icon_Type.OK, Common.GetHomeBaseUrl("ProjectList.aspx"));
                    break;
            }
            All_Title_Txt = CMD_Txt + App_Txt;
            HeadMenuWebControls1.HeadOPTxt = TabOptionItem1.Tab_Name = All_Title_Txt;
        }

        private void InputData()
        {
            if (string.IsNullOrEmpty(S_ID))
                return;

            PM_ProjectsTable PJT = BusinessFacade.PM_ProjectsDisp(S_ID);
            if (PJT != null)
            {
                labelProjectNo.Text = PJT.ProjectNo;
                labelProjectName.Text = textBoxProjectName.Text = PJT.ProjectName;
                labelProjectStatus.Text = DropDownListProjectStatus.SelectedValue = PJT.ProjectStatus.ToString();
                labelProjectStartTime.Text = textBoxProjectStartTime.Text = PJT.ProjectStartTime.ToShortDateString();
                labelProjectDuration.Text = textBoxProjectDuration.Text = PJT.ProjectDuration.ToString();
                labelProjectBrief.Text = textProjectBrief.Text = PJT.ProjectBrief.ToString();
                labelProjectComments.Text = textProjectComments.Text = PJT.ProjectComments;
                labelProjectIcon.Text = textProjectIcon.Text = PJT.ProjectIcon;
            }
        }

        private void HiddenDisp()
        {
            this.labelProjectName.Visible = false;
            this.labelProjectStatus.Visible = false;
            this.labelProjectStartTime.Visible = false;
            this.labelProjectDuration.Visible = false;
            this.labelProjectBrief.Visible = false;
            this.labelProjectComments.Visible = false;
            this.labelProjectIcon.Visible = false;
        }
        private void HiddenInput()
        {
            this.textBoxProjectName.Visible = false;
            this.DropDownListProjectStatus.Visible = false;
            this.textBoxProjectStartTime.Visible = false;
            this.textBoxProjectDuration.Visible = false;
            this.textProjectBrief.Visible = false;
            this.textProjectComments.Visible = false;
            this.textProjectIcon.Visible = false;
        }

        protected void ButtonOK_Click(object sender, EventArgs e)
        {
            PM_ProjectsTable sat = new PM_ProjectsTable();
            sat.ProjectId = S_ID.ToString();
            sat.ProjectNo = string.Format("No{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
            sat.ProjectName = (string)Common.sink(textBoxProjectName.UniqueID, MethodType.Post, 50, 1, DataType.Str);
            sat.ProjectStatus =Convert.ToInt32(DropDownListProjectStatus.SelectedValue);
            sat.ProjectStartTime = (DateTime)Common.sink(textBoxProjectStartTime.UniqueID, MethodType.Post, 100, 1, DataType.Dat);
            sat.ProjectDuration =(int)Common.sink(textBoxProjectDuration.UniqueID, MethodType.Post, 50, 1, DataType.Int);
            sat.ProjectBrief = (string)Common.sink(textProjectBrief.UniqueID, MethodType.Post, 500, 0, DataType.Str);
            sat.ProjectComments = (string)Common.sink(textProjectComments.UniqueID, MethodType.Post, 500, 0, DataType.Str);
            sat.ProjectIcon = (string)Common.sink(textProjectIcon.UniqueID, MethodType.Post, 100, 0, DataType.Str);
            switch (CMD)
            {
                case "New":
                    CMD_Txt = "增加";
                    sat.DB_Option_Action_ = "Insert";
                    break;
                case "Edit":
                    CMD_Txt = "修改";
                    sat.DB_Option_Action_ = "Update";
                    break;
            }
            All_Title_Txt = CMD_Txt + App_Txt;
            BusinessFacade.PM_ProjectsTableInsertUpdate(sat);
            EventMessage.MessageBox(1, "操作成功", string.Format("{1}ID({0})成功!", S_ID, All_Title_Txt), Icon_Type.OK, Common.GetHomeBaseUrl("ProjectList.aspx"));

        }
    }
}


text:
package com.intellij.json.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface JsonLiteral extends JsonValue {

  boolean isQuotedString();

}


text:
package com.logginghub.analytics.charting;

import com.logginghub.analytics.AggregatedDataKey;
import com.logginghub.analytics.LineFormatController;
import com.logginghub.analytics.OHLCValue;
import com.logginghub.analytics.demo.DataFunction;
import com.logginghub.analytics.model.AggregatedData;
import com.logginghub.analytics.model.GeneralAggregatedData;
import com.logginghub.analytics.model.TimeSeriesData;
import com.logginghub.utils.FileUtils;
import com.logginghub.utils.IntegerFrequencyCount;
import com.logginghub.utils.MutableIntegerValue;
import com.logginghub.utils.NotImplementedException;
import com.logginghub.utils.Pair;
import com.logginghub.utils.StandardDateFormat;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.StackedBarRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.urls.StandardCategoryURLGenerator;
import org.jfree.data.general.Dataset;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Bar that takes care of itself. You just give it [series, value] values and it does the rest.
 *
 * @author James
 *
 */
public class StackedBarChartPanel extends JPanel implements ChartPanelInterface {

    private SortedCategoryDataset categoryDataset = new SortedCategoryDataset();
    private JFreeChart chart;
    private ChartPanel chartPanel;
    private int imageFileHeight = 768;

    private String imageFilename;
    private int imageFileWidth = 1024;
    private LineFormatController lineFormatController;

    private long mostRecentTimeValue;

    private CategoryPlot plot;
    private Map<String, XYSeries> seriesForSource = new HashMap<String, XYSeries>();
    private CategoryAxis xAxis;
    // private long timePeriod = 2 * 60 * 1000;
    // private int datapoints = 1000;
    // private long chunkPeriod = 1000;
    private NumberAxis yAxis;

    private float yMinimumFilter = Float.NaN;

    public static String newline = System.getProperty("line.separator");

    private static final long serialVersionUID = 1L;

    public StackedBarChartPanel() {

        xAxis = new CategoryAxis("domainAxisLabel");
        yAxis = new NumberAxis("rangeAxisLabel");

        boolean tooltips = true;
        boolean urls = false;

        StackedBarRenderer renderer = new StackedBarRenderer();
        if (tooltips) {
            renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
        }
        if (urls) {
            renderer.setBaseItemURLGenerator(new StandardCategoryURLGenerator());
        }

        plot = new CategoryPlot(categoryDataset, xAxis, yAxis, renderer);
        plot.setOrientation(PlotOrientation.VERTICAL);
        chart = new JFreeChart("title", JFreeChart.DEFAULT_TITLE_FONT, plot, true);

        renderer.setDrawBarOutline(false);
        renderer.setShadowVisible(false);
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());

        renderer.setBarPainter(new StandardBarPainter());

        // currentTheme.apply(chart);

        /*
         *
         * CategoryAxis numberaxis = new CategoryAxis("");
         *
         * yAxis = new NumberAxis("Count"); yAxis.setAutoRangeIncludesZero(true);
         *
         * // XYSplineRenderer xysplinerenderer = new XYSplineRenderer(); StackedBarRenderer
         * renderer = new StackedBarRenderer();
         *
         * plot = new CategoryPlot(categoryDataset, numberaxis, yAxis, renderer);
         * plot.setBackgroundPaint(Color.white); plot.setDomainGridlinePaint(Color.lightGray);
         * plot.setRangeGridlinePaint(Color.lightGray);
         *
         * // xyplot.setAxisOffset(new RectangleInsets(4D, 4D, 4D, 4D));
         *
         * // XYLineAndShapeRenderer xylineandshaperenderer = // (XYLineAndShapeRenderer)
         * xyplot.getRenderer(); // xylineandshaperenderer.setBaseShapesVisible(false); //
         * xylineandshaperenderer.setBaseShapesFilled(false);
         *
         * chart = new JFreeChart("Please set the title!", JFreeChart.DEFAULT_TITLE_FONT, plot,
         * true);
         *
         *
         * LegendTitle legend = chart.getLegend(); legend.setPosition(RectangleEdge.RIGHT);
         *
         * // ChartUtilities.applyCurrentTheme(chart);
         */
        setLayout(new BorderLayout());

        chartPanel = new ChartPanel(chart);
        chartPanel.setMaximumDrawHeight(Integer.MAX_VALUE);
        chartPanel.setMaximumDrawWidth(Integer.MAX_VALUE);
        chartPanel.setMinimumDrawHeight(0);
        chartPanel.setMinimumDrawWidth(0);

        add(chartPanel, BorderLayout.CENTER);
    }

    // public void setSplineRenderer(boolean splineRenderer) {
    // if (splineRenderer) {
    // xyplot.setRenderer(new XYSplineRenderer());
    // }
    // else {
    // xyplot.setRenderer(new XYLineAndShapeRenderer());
    // }
    // }

    public void addSeries(String category, IntegerFrequencyCount frequencyCount) {

        List<MutableIntegerValue> sortedValues = frequencyCount.getSortedValues();
        for (MutableIntegerValue value : sortedValues) {
            this.categoryDataset.addValue(value.value, category, value.key.toString());
        }

    }

    // public void updateValue(String series, long currentTimeMillis, double
    // value) {
    // XYSeries xySeries = getSeriesForSource(series);
    // synchronized (xySeries) {
    // xySeries.update(currentTimeMillis, value);
    // }
    // }

    // public void addValue(String series, long time, double value) {
    // XYSeries xySeries = getSeriesForSource(series);
    // // long chunk = chunk(time);
    // synchronized (xySeries) {
    // xySeries.add(time, value);
    // }
    //
    // mostRecentTimeValue = Math.max(time, mostRecentTimeValue);
    // }

    // private long chunk(long time) {
    // return time - (time % chunkPeriod);
    // }

    // protected XYSeries getSeriesForSource(String label) {
    // XYSeries xySeries;
    // synchronized (seriesForSource) {
    // xySeries = seriesForSource.get(label);
    // if (xySeries == null) {
    // xySeries = new XYSeries(label);
    // int seriesIndex = categoryDataset.getSeriesCount();
    // categoryDataset.addSeries(xySeries);
    //
    // // xySeries.setMaximumItemCount(datapoints);
    // seriesForSource.put(label, xySeries);
    //
    // if (lineFormatController != null) {
    // Paint paint = lineFormatController.allocateColour(label);
    //
    // XYPlot xyPlot = chart.getXYPlot();
    // XYItemRenderer xyir = xyPlot.getRenderer();
    // xyir.setSeriesPaint(seriesIndex, paint);
    //
    // Stroke stroke = lineFormatController.getStroke(label);
    // xyir.setSeriesStroke(seriesIndex, stroke);
    // }
    // }
    // }
    // return xySeries;
    // }

    // private void addUpperValueExceeded(double value, long
    // startOfCurrentChunk) {
    // // Hour hour = new Hour(2, new Day(22, 2, 2010));
    // // Minute minute = new Minute(15, hour);
    // // long d = minute.getFirstMillisecond();
    // //
    // ValueMarker valuemarker3 = new ValueMarker(startOfCurrentChunk);
    // valuemarker3.setPaint(Color.black);
    // valuemarker3.setLabel("Threshold exceeded (" + value + ")");
    // valuemarker3.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
    // valuemarker3.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // xyplot.addDomainMarker(valuemarker3);
    // }

    public void addYMarker(double xValue, String label, Color colour, double topOffset) {
        throw new UnsupportedOperationException();
    }

    public void clearChartData() {
        synchronized (seriesForSource) {
            Collection<XYSeries> values = seriesForSource.values();
            for (XYSeries xySeries : values) {
                xySeries.clear();
            }
        }
    }

    public void complete() {
        String filename = imageFilename;

        if (filename == null) {
            filename = chart.getTitle().getText() + ".png";
        }

        File file = new File(filename);
        try {
            ChartUtilities.saveChartAsPNG(file, chart, imageFileWidth, imageFileHeight);
            System.out.println("Chart written to " + file.getAbsolutePath());
        }
        catch (IOException e) {
            throw new RuntimeException(String.format("Failed to save png [%s]", file.getAbsolutePath()), e);
        }
    }

    public void createSeries(String seriesName, AggregatedData series, AggregatedDataKey key) {
        throw new UnsupportedOperationException();
    }

    public void createSeries(String seriesName, AggregatedData aggregatedData, DataFunction dataFunction) {
        throw new UnsupportedOperationException();
    }

    public void createSeries(String seriesName, GeneralAggregatedData aggregated, AggregatedDataKey key) {
        throw new UnsupportedOperationException();
    }

    // public void setDatapoints(int datapoints) {
    // this.datapoints = datapoints;
    // }

    @Override public void createSeries(String category, List<Pair<Comparable, Number>> data) {
        throw new UnsupportedOperationException();
    }

    public void createSeries(String seriesName, TimeSeriesData series) {
        createSeries(seriesName, series, 0);
    }

    public void createSeries(String seriesName, TimeSeriesData series, int valueIndex) {
        throw new UnsupportedOperationException();
    }

    public void enableLongCategoryNames() {
        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
        domainAxis.setMaximumCategoryLabelLines(2);
    }

    public JFreeChart getChart() {
        return chart;
    }

    public JComponent getComponent() {
        return chartPanel;
    }

    public Dataset getDataset() {
        return categoryDataset;
    }

    public Plot getPlot() {
        return this.plot;
    }

    public void saveChartData() {
        StringBuilder builder = new StringBuilder();
        synchronized (seriesForSource) {
            Set<Long> xValues = new HashSet<Long>();

            Collection<XYSeries> values = seriesForSource.values();
            for (XYSeries xySeries : values) {
                List<XYDataItem> items = xySeries.getItems();
                for (XYDataItem item : items) {
                    double xValue = item.getXValue();
                    long xTimeValue = (long) xValue;
                    xValues.add(xTimeValue);
                }
            }

            List<Long> xValuesList = new ArrayList<Long>(xValues);
            Collections.sort(xValuesList);
            Set<String> keys = seriesForSource.keySet();

            builder.append("Time,");
            for (String seriesKey : keys) {
                builder.append(seriesKey).append(",");
            }
            builder.append(newline);

            for (Long xValue : xValuesList) {
                Date date = new Date(xValue);
                builder.append(date.toString());
                builder.append(",");
                for (String seriesKeys : keys) {
                    XYSeries xySeries = seriesForSource.get(seriesKeys);
                    Double d = findValue(xySeries, xValue);
                    if (d != null) {
                        builder.append(d);
                    }
                    builder.append(",");
                }

                builder.append(newline);
            }
        }

        String filename = chart.getTitle().getText() + ".csv";
        File file = new File(filename);
        FileUtils.write(builder.toString(), file);
        System.out.println("Saved data to " + file.getAbsolutePath());
    }

    public void saveChartImage() {
        complete();
    }

    // public void createSeries(String seriesName, TimeSeriesData series, int
    // seriesDataIndex) {
    // XYSeries seriesForSource = new XYSeries(seriesName);
    //
    // for (TimeSeriesDataPoint dataPoint : series) {
    // seriesForSource.add(dataPoint.getTime(),
    // dataPoint.getValues()[seriesDataIndex]);
    // }
    //
    // categoryDataset.addSeries(seriesForSource);
    // }

    public void setImageFileHeight(int imageFileHeight) {
        this.imageFileHeight = imageFileHeight;
    }

    // public void createSeries(String seriesName, GeneralAggregatedData series,
    // AggregatedDataKey key) {
    //
    // XYSeries seriesForSource = new XYSeries(seriesName);
    //
    // for (GeneralAggregatedDataPoint aggregatedDataPoint : series) {
    // double startValue = aggregatedDataPoint.getStartValue();
    // double value = aggregatedDataPoint.getValue(key);
    // seriesForSource.add(startValue, value);
    // }
    //
    // categoryDataset.addSeries(seriesForSource);
    // }

    // public void createSeries(String seriesName, AggregatedData series,
    // DataFunction dataFunction) {
    //
    // XYSeries seriesForSource = new XYSeries(seriesName);
    //
    // for (AggregatedDataPoint aggregatedDataPoint : series) {
    // long startTime = aggregatedDataPoint.getStartTime();
    // double value =
    // dataFunction.function(aggregatedDataPoint.getValue(dataFunction.getKey()));
    // seriesForSource.add(startTime, value);
    // }
    //
    // categoryDataset.addSeries(seriesForSource);
    // }

    // public void createSeries(String seriesName, AggregatedData series,
    // AggregatedDataKey key) {
    //
    // XYSeries seriesForSource = new XYSeries(seriesName);
    //
    // for (AggregatedDataPoint aggregatedDataPoint : series) {
    // long startTime = aggregatedDataPoint.getStartTime();
    // double value = aggregatedDataPoint.getValue(key);
    // seriesForSource.add(startTime, value);
    // }
    //
    // categoryDataset.addSeries(seriesForSource);
    // }

    public void setImageFilename(String imageFilename) {
        this.imageFilename = imageFilename;
    }

    public void setImageFileWidth(int imageFileWidth) {
        this.imageFileWidth = imageFileWidth;
    }

    // public void setPlainXY() {
    // xyplot.setDomainAxis(new NumberAxis());
    // }

    // public void addYMarker(double xValue, String label, Color colour, double
    // topOffset) {
    //
    // ValueMarker valuemarker3 = new ValueMarker(xValue);
    // valuemarker3.setPaint(colour);
    // valuemarker3.setLabel(label);
    // valuemarker3.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
    // valuemarker3.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // valuemarker3.setLabelOffset(new RectangleInsets(topOffset, 0, 0, 0));
    //
    // double upperBound = xyplot.getDomainAxis().getUpperBound();
    // double newBound = Math.max(upperBound, xValue + 10);
    // xyplot.getDomainAxis().setUpperBound(newBound);
    //
    // xyplot.addDomainMarker(valuemarker3);
    // }

    public void setLegendVisible(boolean visible) {
        chart.getLegend().setVisible(visible);
    }

    public void setLineFormatController(LineFormatController lineFormatController) {
        this.lineFormatController = lineFormatController;
    }

    public void setNotify(boolean notifyOn) {
        chart.setNotify(notifyOn);
    }

    public void setOrientation(PlotOrientation orientation) {
        plot.setOrientation(orientation);
    }

    public void setPlainXY() {
        throw new UnsupportedOperationException();
    }

    public void setTitle(String title) {
        chart.setTitle(title);
    }

    public void setVerticalXAxisLabels(boolean b) {
        if (b) {
            xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        }
        else {
            xAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
        }
    }

    public void setXAxisLabel(String label) {
        plot.getDomainAxis().setLabel(label);
    }

    @Override public void setXAxisLogarithmicScale() {
        throw new UnsupportedOperationException();
    }

    public void setYAutoRangeMinimum(double value) {
        yAxis.setAutoRange(true);
        yAxis.setAutoRangeMinimumSize(value);
    }

    public void setYAxisLabel(String yAxisLabel) {
        yAxis.setLabel(yAxisLabel);
    }

    @Override public void setYAxisLogarithmicScale() {
        throw new UnsupportedOperationException();
    }

    public void setYMaximum(double value) {
        yAxis.setAutoRange(false);
        yAxis.setRange(0, value);
    }

    public void setYMinimumFilter(float yMinimumFilter) {
        this.yMinimumFilter = yMinimumFilter;
    }

    public void toCSV(File file) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(file));

            StandardDateFormat sdf = new StandardDateFormat();

            int columnCount = categoryDataset.getColumnCount();
            int rowCount = categoryDataset.getRowCount();

            for (int row = 0; row < rowCount; row++) {
                for (int column = 0; column < columnCount; column++) {

                    Comparable rowKey = categoryDataset.getRowKey(row);
                    Comparable columnKey = categoryDataset.getColumnKey(column);
                    Number value = categoryDataset.getValue(row, column);

                    writer.write(rowKey.toString());
                    writer.write(",");
                    writer.write(columnKey.toString());
                    writer.write(",");
                    writer.write(value.toString());
                    writer.newLine();
                }
            }
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            FileUtils.closeQuietly(writer);
        }
    }

    private Double findValue(XYSeries xySeries, long xValue) {
        Double value = null;

        List<XYDataItem> items = xySeries.getItems();
        for (XYDataItem item : items) {
            double itemXValue = item.getXValue();
            long xTimeValue = (long) itemXValue;

            if (xTimeValue == xValue) {
                value = item.getYValue();
                break;
            }
        }

        return value;
    }

    @Override public void yAxisLock(double value) {
        throw new NotImplementedException();
    }

    @Override public void addOHLCSeries(String category, List<Pair<Integer, OHLCValue>> values) {
        throw new NotImplementedException();
    }

    @Override public void addValue(String key, String string, double value) {}

    @Override public void setShowLegend(boolean showLegend) {
        chart.getLegend().setVisible(showLegend);
    }

    @Override public void createStatsSeries(String category, List<Pair<Long, Double>> data) {}
}


text:
package com.amazonaws.services.dynamodbv2.model.transform;

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

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.dynamodbv2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * DeleteGlobalSecondaryIndexActionMarshaller
 */
public class DeleteGlobalSecondaryIndexActionJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(
            DeleteGlobalSecondaryIndexAction deleteGlobalSecondaryIndexAction,
            StructuredJsonGenerator jsonGenerator) {

        if (deleteGlobalSecondaryIndexAction == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (deleteGlobalSecondaryIndexAction.getIndexName() != null) {
                jsonGenerator.writeFieldName("IndexName").writeValue(
                        deleteGlobalSecondaryIndexAction.getIndexName());
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static DeleteGlobalSecondaryIndexActionJsonMarshaller instance;

    public static DeleteGlobalSecondaryIndexActionJsonMarshaller getInstance() {
        if (instance == null)
            instance = new DeleteGlobalSecondaryIndexActionJsonMarshaller();
        return instance;
    }

}