<commit_before>//Import electron
var electron = require('electron');
var app = electron.app;

//Import dependencies
var fs = require('fs');
var path = require('path');
var pathurl = require('url');
var ejs = require('ejs');
var mime = require('mime');

//Main function
function ElectronEjs(options)
{
  //Check options
  if(typeof options === 'undefined') { var options = {}; }

  //App ready event
  app.on('ready', function(){

    //Import protocol
    var protocol = require('protocol');

    //Intercept the file protocol
    protocol.interceptBufferProtocol('file', function(request, callback){

      //Get the file
      var file = ParsePath(request.url);

      //Get the file extension
      var extension = path.extname(file);

      //Get the file content
      fs.readFile(file, 'utf8', (err, content) => {
        if(err)
        {
          return callback(-6);
        }
        try
        {
          //Check the extension
          if(extension === '.ejs')
          {
            //Add the path to options
            options.filename = file;

            //Get the full file
            var full = ejs.render(content, options)

            //Return the callback
            return callback({data: new Buffer(full), mimeType:'text/html'});
          }
          else
          {
            //Get the mime type
            var mimet = mime.lookup(extension);

            //Return the callback
            return callback({data: new Buffer(content), mimeType: mimet});
          }
        }
        catch(ex)
        {
          return callback(-2);
        }
      });
    });
  });
}

//Function for parse the path
function ParsePath(url)
{
  //Parse the url
  var p = pathurl.parse(url);

  //Return the path name
  return p.pathname;
}

//Exports to node
module.exports = ElectronEjs;
<commit_msg>Fixing content handling<commit_after>//Import electron
var electron = require('electron');
var app = electron.app;

//Import dependencies
var fs = require('fs');
var path = require('path');
var pathurl = require('url');
var ejs = require('ejs');
var mime = require('mime');

//Main function
function ElectronEjs(options)
{
  //Check options
  if(typeof options === 'undefined') { var options = {}; }

  //App ready event
  app.on('ready', function(){

    //Import protocol
    var protocol = require('protocol');

    //Intercept the file protocol
    protocol.interceptBufferProtocol('file', function(request, callback){

      //Get the file
      var file = ParsePath(request.url);

      //Get the file extension
      var extension = path.extname(file);

      //Get the file content
      fs.readFile(file, 'utf8', (err, content) => {
        if(err)
        {
          return callback(-6);
        }
        try
        {
          //Check the extension
          if(extension === '.ejs')
          {
            //Add the path to options
            options.filename = file;

            //Get the full file
            var full = ejs.render(content.toString("utf8"), options)

            //Return the callback
            return callback({data: new Buffer(full), mimeType:'text/html'});
          }
          else
          {
            //Get the mime type
            var mimet = mime.lookup(extension);

            //Return the callback
            return callback({data: content, mimeType: mimet});
          }
        }
        catch(ex)
        {
          return callback(-2);
        }
      });
    });
  });
}

//Function for parse the path
function ParsePath(url)
{
  //Parse the url
  var p = pathurl.parse(url);

  //Return the path name
  return p.pathname;
}

//Exports to node
module.exports = ElectronEjs;
<|endoftext|>


<commit_before>'use strict';
var present = require('present');

function Benchmark(fn, options = {}) {
	if (!fn) {
		throw new Error('No function specified');
	}

	this.maxTime = options.maxTime || this.maxTime;
	this.repetitions = options.repetitions || this.repetitions;
	return this.run(fn);
}

// default options
Benchmark.prototype.maxTime = 2000; // 2s
Benchmark.prototype.repetitions = 100;

Benchmark.prototype.run = function (fn) {
	// Try initial one, to be safe it works
	return new Promise(function (resolve, reject) {
		fn({resolve, reject});
		setTimeout(() => reject(), this.maxTime);
	}).then(() => {
		// Run actual performance tests
		return this.measure(fn, this.repetitions).then(accumulatedResults => accumulatedResults / this.repetitions);
	}, () => {
		console.log('You initial run took more than ', this.maxTime);
	});
};

Benchmark.prototype.measure = function (fn, repetitions) {
	return new Promise((resolve, reject) => {
		if (repetitions <= 0) {
			resolve(0);
			return;
		}

		this.singleTest(fn).then(initialResult => {
			this.measure(fn, repetitions - 1).then(accumulatedResults => {
				resolve(accumulatedResults + initialResult);
			});
		}, () => {
			console.log('Failed');
			reject();
		});
	});
};

Benchmark.prototype.singleTest = function (fn) {
	var initTime;
	return new Promise(function (resolve, reject) {
		initTime = present();
		fn({resolve, reject});
	}).then(function () {
		return present() - initTime;
	}).then(function (result) {
		return result;
	});
};

module.exports = Benchmark;
<commit_msg>moved to es6<commit_after>'use strict';
const present = require('present');

function Benchmark(fn, options = {}) {
	if (!fn) {
		throw new Error('No function specified');
	}

	this.maxTime = options.maxTime || this.maxTime;
	this.repetitions = options.repetitions || this.repetitions;
	return this.run(fn);
}

// default options
Benchmark.prototype.maxTime = 2000; // 2s
Benchmark.prototype.repetitions = 100;

Benchmark.prototype.run = function (fn) {
	// Try initial one, to be safe it works
	return new Promise(function (resolve, reject) {
		fn({resolve, reject});
		setTimeout(() => reject(), this.maxTime);
	}).then(() => {
		// Run actual performance tests
		return this.measure(fn, this.repetitions).then(accumulatedResults => accumulatedResults / this.repetitions);
	}, () => {
		console.log('You initial run took more than ', this.maxTime);
	});
};

Benchmark.prototype.measure = function (fn, repetitions) {
	return new Promise((resolve, reject) => {
		if (repetitions <= 0) {
			resolve(0);
			return;
		}

		this.singleTest(fn).then(initialResult => {
			this.measure(fn, repetitions - 1).then(accumulatedResults => {
				resolve(accumulatedResults + initialResult);
			});
		}, () => {
			console.log('Failed');
			reject();
		});
	});
};

Benchmark.prototype.singleTest = function (fn) {
	var initTime;
	return new Promise(function (resolve, reject) {
		initTime = present();
		fn({resolve, reject});
	}).then(function () {
		return present() - initTime;
	}).then(function (result) {
		return result;
	});
};

module.exports = Benchmark;
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var through = require('through2');
var fs = require('fs');
var path = require('path');
var cssTransform = require('./css-transform');
var CleanCSS = require('clean-css');

var defaults = {
    'autoInject': true,
    'autoInjectOptions': {
        'verbose': true
    },
    'rootDir': process.cwd(),
    'minify': false,
    'minifyOptions': {
        // Check out a list of CSS minify options at [CleanCSS](https://github.com/jakubpawlowicz/clean-css#how-to-use-clean-css-programmatically).
    }
};

try {
    var pkg = JSON.parse(fs.readFileSync(process.cwd() + '/package.json') || '{}');
    var options = pkg['browserify-css'] || defaults;
    if (typeof options === 'string') {
        var base = path.relative(__dirname, process.cwd());
        options = require(path.join(base, options)) || defaults;
    }
} catch (err) {
    options = defaults;
}
options = _.defaults(options, defaults);

module.exports = function(filename, opts) {
    if ( ! /\.css$/i.test(filename)) {
        return through();
    }

    var cssBuffer = {};
    var buffer = '';
    var externalURLs = [];

    options = _.extend({}, options, opts);

    return through(
        function transform(chunk, enc, next) {
            buffer += chunk;
            next();
        },
        function flush(done) {
            var that = this;

            cssTransform({ rootDir: options['rootDir'] }, filename, function(data) {
                var moduleBody = '';
                var rootDir = path.resolve(process.cwd(), options.rootDir);
                var relativePath = path.relative(rootDir, path.dirname(filename));
                var href = path.join(relativePath, path.basename(filename));

                if (options['minify']) {
                    data = new CleanCSS(options['minifyOptions']).minify(data);
                }

                if ( ! options['autoInject']) {
                    moduleBody = 'module.exports = ' + JSON.stringify(data) + ';';
                } else {
                    if (options.autoInjectOptions['verbose']) {
                        moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify(__dirname) + ').createStyle(css, { "href": ' + JSON.stringify(href) + '})); module.exports = css;';
                    } else {
                        moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify(__dirname) + ').createStyle(css)); module.exports = css;';
                    }
                }

                that.push(moduleBody);
                that.push(null);
                done();
            });
        }
    );
};
<commit_msg>Remove unused variables<commit_after>'use strict';

var _ = require('lodash');
var through = require('through2');
var fs = require('fs');
var path = require('path');
var cssTransform = require('./css-transform');
var CleanCSS = require('clean-css');

var defaults = {
    'autoInject': true,
    'autoInjectOptions': {
        'verbose': true
    },
    'rootDir': process.cwd(),
    'minify': false,
    'minifyOptions': {
        // Check out a list of CSS minify options at [CleanCSS](https://github.com/jakubpawlowicz/clean-css#how-to-use-clean-css-programmatically).
    }
};

try {
    var pkg = JSON.parse(fs.readFileSync(process.cwd() + '/package.json') || '{}');
    var options = pkg['browserify-css'] || defaults;
    if (typeof options === 'string') {
        var base = path.relative(__dirname, process.cwd());
        options = require(path.join(base, options)) || defaults;
    }
} catch (err) {
    options = defaults;
}
options = _.defaults(options, defaults);

module.exports = function(filename, opts) {
    if ( ! /\.css$/i.test(filename)) {
        return through();
    }

    var buffer = '';

    options = _.extend({}, options, opts);

    return through(
        function transform(chunk, enc, next) {
            buffer += chunk;
            next();
        },
        function flush(done) {
            var that = this;

            cssTransform({ rootDir: options['rootDir'] }, filename, function(data) {
                var moduleBody = '';
                var rootDir = path.resolve(process.cwd(), options.rootDir);
                var relativePath = path.relative(rootDir, path.dirname(filename));
                var href = path.join(relativePath, path.basename(filename));

                if (options['minify']) {
                    data = new CleanCSS(options['minifyOptions']).minify(data);
                }

                if ( ! options['autoInject']) {
                    moduleBody = 'module.exports = ' + JSON.stringify(data) + ';';
                } else {
                    if (options.autoInjectOptions['verbose']) {
                        moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify(__dirname) + ').createStyle(css, { "href": ' + JSON.stringify(href) + '})); module.exports = css;';
                    } else {
                        moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify(__dirname) + ').createStyle(css)); module.exports = css;';
                    }
                }

                that.push(moduleBody);
                that.push(null);
                done();
            });
        }
    );
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

var multipart = require('connect-multiparty');
var express = require('express');
var nodemailer = require('nodemailer');

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

var app = express();
var transport = nodemailer.createTransport(config.mailer);

app.set('port', 8088);

app.use(multipart({ uploadDir: path.join(__dirname, 'upload') }));

app.get('/', function(req, res) {
    res.sendFile('/uploader.html', {
        root: __dirname
    });
});

app.post('/upload', function(req, res) {
    if (! /^([a-zA-Z0-9_.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(req.body.to)) {
        return;
    }

    if (!req.files.book || req.files.book.name.search('.txt') == -1) {
        return;
    }

    var bookname = req.files.book.name;
    var bookpath = __dirname + '/books/' + req.files.book.name;

    fs.renameSync(req.files.book.path, bookpath);

    transport.sendMail({
        from: '<' + config.mailer.auth.user + '>',
        to: '<' + req.body.to + '>',
        subject: 'Convert',
        attachments: [
            {
                path: bookpath
            }
        ]
    }, function(error, response) {
        if (error) {
            console.log('发送失败: ' + error);
        }
        else {
            console.log('发送成功！');
        }

        transport.close();
    });

    res.redirect('/');
});

var server = app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + server.address().port);
});<commit_msg>Initial commit<commit_after>var fs = require('fs');
var path = require('path');

var multipart = require('connect-multiparty');
var express = require('express');
var nodemailer = require('nodemailer');

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

var app = express();
var transport = nodemailer.createTransport(config.mailer);

app.set('port', 8088);

app.use(multipart({ uploadDir: path.join(__dirname, 'upload') }));

app.get('/', function(req, res) {
    res.sendFile('/uploader.html', {
        root: __dirname
    });
});

app.post('/upload', function(req, res) {
    if (! /^([a-zA-Z0-9_.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(req.body.to)) {
        return;
    }

    if (!req.files.book || req.files.book.name.search('.txt') == -1) {
        return;
    }

    var bookname = req.files.book.name;
    var bookpath = __dirname + '/books/' + req.files.book.name;

    fs.renameSync(req.files.book.path, bookpath);

    transport.sendMail({
        from: config.mailer.auth.user,
        to: req.body.to,
        subject: 'Convert',
        attachments: [
            {
                path: bookpath
            }
        ]
    }, function(error, info) {
        if (error) {
            console.log('发送失败: ' + error);
        }
        else {
            console.log('发送成功: ' + info.response);
        }

        transport.close();
    });

    res.redirect('/');
});

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


<commit_before>var https = require('https');
var crypto = require('crypto');
var url = require('url');
var fs = require('fs');
var basic = require('basic-auth');

/**
 * Two parameters mode
 *  If a is undefined, return b else a
 * Three parameters mode
 *  If a is undefined, return c else b
 * @param {*} a
 * @param {*} b
 * @param {*=} c
 * @returns {*}
 */
function ifnotundef(a, b, c) {
    return (typeof c == 'undefined') ? ((typeof a != 'undefined' && a != null) ? a : b) : ((typeof a != 'undefined' && a != null) ? b : c);
}

/**
 * Generates a random Xrf key of a given size within a set of given chars
 * @param {integer=} [size=16]
 * @param {string=} [chars=abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789]
 * @returns {string}
 */
function generateXrfkey(size, chars) {
    size = size || 16;
    chars = chars || 'abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789';

    var rnd = crypto.randomBytes(size), value = new Array(size), len = chars.length;

    for (var i = 0; i < size; i++) {
        value[i] = chars[rnd[i] % len]
    }

    return value.join('');
}

/**
 * Makes a request on a Qlik Sense API endpoint defined in the options object, posting the params object
 * @param {Object} params the parameters to post to the API endpoint
 * @param {Object} options the options to connect to the API endpoint
 * @returns {Promise}
 */
function request(params, options) {

    var xrfkey = generateXrfkey();
    var restUri = url.parse(options.restUri);

    var headers = {
        'X-Qlik-Xrfkey': xrfkey,
        'Content-Type': 'application/json'
    };

    if(typeof options.UserDirectory != 'undefined' || typeof options.UserId != 'undefined')
        headers['X-Qlik-User'] = 'UserDirectory= ' + ifnotundef(options.UserDirectory, '.') + '; UserId= ' + ifnotundef(options.UserId, 'qlikservice');

    if(typeof options.session != 'undefined')
        headers['Cookie'] = options.session;

    var settings = {
        protocol: restUri.protocol,
        host: restUri.hostname,
        port: restUri.port,
        path: restUri.pathname + '?' + ifnotundef(restUri.query, restUri.query + '&', '') + 'xrfkey=' + xrfkey,
        method: ifnotundef(options.method, 'POST'),
        headers: headers,
        pfx: ifnotundef(options.pfx, null),
        passphrase: ifnotundef(options.passPhrase, null),
        rejectUnauthorized: false,
        agent: false
    };

    return new Promise(function(resolve, reject) {

        if(settings.protocol != 'https:') reject('https is needed to make API call');
        else {

            var apireq = https.request(settings, function (apires) {

                var body = "";
                apires.on('data', function (d) {
                    body += d.toString()
                });

                apires.on('end', function (d) {
                    resolve(JSON.parse(body));
                });

            });

            if(params) {
                apireq.write(JSON.stringify(params));
            }

            apireq.end();

            apireq.on('error', function (e) {
                reject(e);
            });

        }

    });

};

/**
 * Generates a ticket on Qlik Sense QRS Api
 * @param {Object} params the ticket parameters
 * @param {Object} options the options to connect to the ticket API endpoint
 * @returns {Promise}
 */
function getTicket(params, options) {

    var restUri = url.parse(options.restUri);

    var ticketOptions = {
        restUri: restUri.protocol + '//' + restUri.host + '/qps/ticket',
        method: 'POST',
        pfx: options.pfx,
        passPhrase: options.passPhrase
    };

    return request(params, ticketOptions);

}

/**
 * Opens a session on the Qlik Sense Hub with the given ticket and returns the session cookie
 * @param {Object} ticket the generated ticket
 * @param {Object} options parsed url of the Qlik Sense Hub
 * @returns {Promise}
 */
function openSession(ticket, options) {

    var p = new Promise(function(resolve, reject) {

        var settings = {
            host: options.hostname,
            port: options.port,
            path: options.pathname + '?' + ifnotundef(options.query, options.query + '&', '') + 'qlikTicket=' + ticket.Ticket,
            method: 'GET',
            rejectUnauthorized: false,
            agent: false
        };

        var prot = (options.protocol == 'https:') ? https : http;

        var req = prot.request(settings, function (response) {
            response.on('data', function (d) {
                var cookies = response.headers['set-cookie'];
                resolve(cookies[0]);
            });
        });
        req.on('error', function(e) {
            reject(e);
        });
        req.end();
    });

    return p;
}

/**
 * Adds the given ip address to the websocket whitelist of the given virtual proxy
 * @param  {string} ip the ip to add
 * @param  {Object} options the endpoint to add the ip to
 * @returns {Promise}
 */
function addToWhiteList(ip, options) {

    var restUri = url.parse(options.restUri);

    return utils.request(null, {
        restUri: restUri.protocol + '//' + restUri.host + '/qrs/proxyservice/local',
        method: 'GET',
        pfx: options.pfx,
        passPhrase: options.passPhrase,
        UserId: options.UserId,
        UserDirectory: options.UserDirectory
    }).then(function(settings) {

        var vpsettings = settings.settings.virtualProxies[0];

        return utils.request(null, {
            restUri: restUri.protocol + '//' + restUri.host + '/qrs/virtualproxyconfig/' + vpsettings.id,
            method: 'GET',
            pfx: options.pfx,
            passPhrase: options.passPhrase,
            UserId: options.UserId,
            UserDirectory: options.UserDirectory
        })

    }).then(function(settings) {

        settings.websocketCrossOriginWhiteList.push(ip);

        var currDate = new Date();
        var oldDate = new Date(settings.modifiedDate);
        var newDate;

        if(currDate > oldDate) {
            newDate = currDate;
        } else {
            newDate = oldDate;
            newDate.setSeconds(newDate.getSeconds() + 1);
        }

        settings.modifiedDate = newDate.toISOString();

        return utils.request(settings, {
            restUri: restUri.protocol + '//' + restUri.host + '/qrs/virtualproxyconfig/' + settings.id,
            method: 'PUT',
            pfx: options.pfx,
            passPhrase: options.passPhrase,
            UserId: options.UserId,
            UserDirectory: options.UserDirectory
        });

    })

}

/**
 * Simple basic auth middleware for use with Express 4.x.
 *
 * @example
 * app.use('/api-requiring-auth', utils.basicAuth([{user: 'username', pass: 'password'}]));
 *
 * @param   {Object}   username list of usernames & passwords
 * @returns {function} Express 4 middleware requiring the given credentials
 */
function basicAuth(users) {
    return function(req, res, next) {
        var user = basic(req);

        if(
            !user || users.filter(function(item) {
                return item.user == user.name && item.pass == user.pass;
            }).length == 0
        ) {
            res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
            return res.send(401);
        }

        req.authUser = user.name;
        next();
    };
};

module.exports = {
    request: request,
    getTicket: getTicket,
    openSession: openSession,
    addToWhiteList: addToWhiteList,
    basicAuth: basicAuth
}
<commit_msg>bug correction<commit_after>var https = require('https');
var crypto = require('crypto');
var url = require('url');
var fs = require('fs');
var basic = require('basic-auth');

/**
 * Two parameters mode
 *  If a is undefined, return b else a
 * Three parameters mode
 *  If a is undefined, return c else b
 * @param {*} a
 * @param {*} b
 * @param {*=} c
 * @returns {*}
 */
function ifnotundef(a, b, c) {
    return (typeof c == 'undefined') ? ((typeof a != 'undefined' && a != null) ? a : b) : ((typeof a != 'undefined' && a != null) ? b : c);
}

/**
 * Generates a random Xrf key of a given size within a set of given chars
 * @param {integer=} [size=16]
 * @param {string=} [chars=abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789]
 * @returns {string}
 */
function generateXrfkey(size, chars) {
    size = size || 16;
    chars = chars || 'abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789';

    var rnd = crypto.randomBytes(size), value = new Array(size), len = chars.length;

    for (var i = 0; i < size; i++) {
        value[i] = chars[rnd[i] % len]
    }

    return value.join('');
}

/**
 * Makes a request on a Qlik Sense API endpoint defined in the options object, posting the params object
 * @param {Object} params the parameters to post to the API endpoint
 * @param {Object} options the options to connect to the API endpoint
 * @returns {Promise}
 */
function request(params, options) {

    var xrfkey = generateXrfkey();
    var restUri = url.parse(options.restUri);

    var headers = {
        'X-Qlik-Xrfkey': xrfkey,
        'Content-Type': 'application/json'
    };

    if(typeof options.UserDirectory != 'undefined' || typeof options.UserId != 'undefined')
        headers['X-Qlik-User'] = 'UserDirectory= ' + ifnotundef(options.UserDirectory, '.') + '; UserId= ' + ifnotundef(options.UserId, 'qlikservice');

    if(typeof options.session != 'undefined')
        headers['Cookie'] = options.session;

    var settings = {
        protocol: restUri.protocol,
        host: restUri.hostname,
        port: restUri.port,
        path: restUri.pathname + '?' + ifnotundef(restUri.query, restUri.query + '&', '') + 'xrfkey=' + xrfkey,
        method: ifnotundef(options.method, 'POST'),
        headers: headers,
        pfx: ifnotundef(options.pfx, null),
        passphrase: ifnotundef(options.passPhrase, null),
        rejectUnauthorized: false,
        agent: false
    };

    return new Promise(function(resolve, reject) {

        if(settings.protocol != 'https:') reject('https is needed to make API call');
        else {

            var apireq = https.request(settings, function (apires) {

                var body = "";
                apires.on('data', function (d) {
                    body += d.toString()
                });

                apires.on('end', function (d) {
                    resolve(JSON.parse(body));
                });

            });

            if(params) {
                apireq.write(JSON.stringify(params));
            }

            apireq.end();

            apireq.on('error', function (e) {
                reject(e);
            });

        }

    });

};

/**
 * Generates a ticket on Qlik Sense QRS Api
 * @param {Object} params the ticket parameters
 * @param {Object} options the options to connect to the ticket API endpoint
 * @returns {Promise}
 */
function getTicket(params, options) {

    var restUri = url.parse(options.restUri);

    var ticketOptions = {
        restUri: restUri.protocol + '//' + restUri.host + '/qps/ticket',
        method: 'POST',
        pfx: options.pfx,
        passPhrase: options.passPhrase
    };

    return request(params, ticketOptions);

}

/**
 * Opens a session on the Qlik Sense Hub with the given ticket and returns the session cookie
 * @param {Object} ticket the generated ticket
 * @param {Object} options parsed url of the Qlik Sense Hub
 * @returns {Promise}
 */
function openSession(ticket, options) {

    var p = new Promise(function(resolve, reject) {

        var settings = {
            host: options.hostname,
            port: options.port,
            path: options.pathname + '?' + ifnotundef(options.query, options.query + '&', '') + 'qlikTicket=' + ticket.Ticket,
            method: 'GET',
            rejectUnauthorized: false,
            agent: false
        };

        var prot = (options.protocol == 'https:') ? https : http;

        var req = prot.request(settings, function (response) {
            response.on('data', function (d) {
                var cookies = response.headers['set-cookie'];
                resolve(cookies[0]);
            });
        });
        req.on('error', function(e) {
            reject(e);
        });
        req.end();
    });

    return p;
}

/**
 * Adds the given ip address to the websocket whitelist of the given virtual proxy
 * @param  {string} ip the ip to add
 * @param  {Object} options the endpoint to add the ip to
 * @returns {Promise}
 */
function addToWhiteList(ip, options) {

    var restUri = url.parse(options.restUri);

    return request(null, {
        restUri: restUri.protocol + '//' + restUri.host + '/qrs/proxyservice/local',
        method: 'GET',
        pfx: options.pfx,
        passPhrase: options.passPhrase,
        UserId: options.UserId,
        UserDirectory: options.UserDirectory
    }).then(function(settings) {

        var vpsettings = settings.settings.virtualProxies[0];

        return request(null, {
            restUri: restUri.protocol + '//' + restUri.host + '/qrs/virtualproxyconfig/' + vpsettings.id,
            method: 'GET',
            pfx: options.pfx,
            passPhrase: options.passPhrase,
            UserId: options.UserId,
            UserDirectory: options.UserDirectory
        })

    }).then(function(settings) {

        settings.websocketCrossOriginWhiteList.push(ip);

        var currDate = new Date();
        var oldDate = new Date(settings.modifiedDate);
        var newDate;

        if(currDate > oldDate) {
            newDate = currDate;
        } else {
            newDate = oldDate;
            newDate.setSeconds(newDate.getSeconds() + 1);
        }

        settings.modifiedDate = newDate.toISOString();

        return request(settings, {
            restUri: restUri.protocol + '//' + restUri.host + '/qrs/virtualproxyconfig/' + settings.id,
            method: 'PUT',
            pfx: options.pfx,
            passPhrase: options.passPhrase,
            UserId: options.UserId,
            UserDirectory: options.UserDirectory
        });

    })

}

/**
 * Simple basic auth middleware for use with Express 4.x.
 *
 * @example
 * app.use('/api-requiring-auth', utils.basicAuth([{user: 'username', pass: 'password'}]));
 *
 * @param   {Object}   username list of usernames & passwords
 * @returns {function} Express 4 middleware requiring the given credentials
 */
function basicAuth(users) {
    return function(req, res, next) {
        var user = basic(req);

        if(
            !user || users.filter(function(item) {
                return item.user == user.name && item.pass == user.pass;
            }).length == 0
        ) {
            res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
            return res.send(401);
        }

        req.authUser = user.name;
        next();
    };
};

module.exports = {
    request: request,
    getTicket: getTicket,
    openSession: openSession,
    addToWhiteList: addToWhiteList,
    basicAuth: basicAuth
}
<|endoftext|>


<commit_before>/**
 * index.js
 * This file was created on 10/02/17 by kkprince, and is
 * a part of gunpowder. This file may be proprietary,
 * however please se the LICENSE file in the root of this
 * project for specific handling instructions
 */

/**
 * This file handles the creation of the child threads for:
 * - Webui
 */

const PROJECT_ROOT = __dirname
global.THREAD_NAME = process.env.GP_THREAD_NAME || 'main'

const d = require('./src/util/d')

const child_process = require('child_process')

let procs = {
    webui: './src/webui'
    // test: './test.js'
}

for (let proc in procs) {
    procs[proc] = child_process.fork(procs[proc], [], {
        cwd: process.cwd(),
        env: Object.assign({
            GP_PROJECT_ROOT: PROJECT_ROOT,
            GP_THREAD_NAME: proc
        }, process.env),
        silent: false
    })
    procs[proc].name = proc
    procs[proc].on('exit', (code) => {
        procs[proc].exit = code
        clearTimeout(procs[proc].killing)
        if (typeof procs[proc].killer.func === "function") {
            procs[proc].killer.func()
        }
        d(`${proc.name} is dead.`)
    })

    procs[proc].on('message', (msg, sendHandle) => {
        if (
            typeof msg !== "object" || Array.isArray(msg) || typeof msg.dest !== "string"
            || typeof msg.msg !== "object"
        ) {
            d('Error: Invalid IPC message received: ', msg)
        } else if (typeof procs[msg.dest] === "undefined") {
            d('Error: Invalid IPC Destination received: ' + msg.dest)
        } else {
            procs[msg.dest].send(msg.msg, sendHandle)
        }
    })
}

function killer(proc, cb, tryn = 0, dead = false) {
    if (typeof proc.exit !== 'undefined') {
        if(typeof cb === 'function') cb()
        return
    }
    if (tryn >= 10) {
        d(`trying to SIGKILL ${proc.name}...`)
        proc.kill('SIGKILL')
    } else {
        d(`trying to kill ${proc.name}...`)
        proc.kill()
    }
    proc.killer = {
        func: killer.bind(this, proc, cb, ++tryn)
    }

    proc.killer.id = setTimeout(proc.killer.func, 500)
}

function killAll(obj, cb) {
    let n=Object.keys(obj).length
    for (let proc in obj)
        if (obj.hasOwnProperty(proc)) {
            proc = procs[proc]
            killer(proc, ()=>{
                if(--n === 0){
                    d('Killing done')
                    if(typeof cb === 'function') cb()
                } else d(`Killing has ${n} left`)
            })
        }
}

['exit', 'SIGINT', 'SIGHUP', 'SIGTERM', 'uncaughtException'].forEach(signal=>process.on(signal, ()=>{
    d(`Caught ${signal}`)
    killAll(procs, process.exit)
    process.removeAllListeners()
}))

setInterval(() => {
    procs.webui.emit('message', {
        dest: 'webui',
        msg: {
            act: 'console',
            text: 'Testing: ' + (new Date())
        }
    })
}, 5000)<commit_msg>fix when cwd != PROJECT_ROOT<commit_after>/**
 * index.js
 * This file was created on 10/02/17 by kkprince, and is
 * a part of gunpowder. This file may be proprietary,
 * however please se the LICENSE file in the root of this
 * project for specific handling instructions
 */

/**
 * This file handles the creation of the child threads for:
 * - Webui
 */

const PROJECT_ROOT = __dirname
global.THREAD_NAME = process.env.GP_THREAD_NAME || 'main'

const d = require('./src/util/d')

const child_process = require('child_process')

let procs = {
    webui: '/src/webui'
    // test: './test.js'
}

for (let proc in procs) {
    procs[proc] = child_process.fork(PROJECT_ROOT + procs[proc], [], {
        cwd: process.cwd(),
        env: Object.assign({
            GP_PROJECT_ROOT: PROJECT_ROOT,
            GP_THREAD_NAME: proc
        }, process.env),
        silent: false
    })
    procs[proc].name = proc
    procs[proc].on('exit', (code) => {
        procs[proc].exit = code
        clearTimeout(procs[proc].killing)
        if (typeof procs[proc].killer.func === "function") {
            procs[proc].killer.func()
        }
        d(`${proc.name} is dead.`)
    })

    procs[proc].on('message', (msg, sendHandle) => {
        if (
            typeof msg !== "object" || Array.isArray(msg) || typeof msg.dest !== "string"
            || typeof msg.msg !== "object"
        ) {
            d('Error: Invalid IPC message received: ', msg)
        } else if (typeof procs[msg.dest] === "undefined") {
            d('Error: Invalid IPC Destination received: ' + msg.dest)
        } else {
            procs[msg.dest].send(msg.msg, sendHandle)
        }
    })
}

function killer(proc, cb, tryn = 0, dead = false) {
    if (typeof proc.exit !== 'undefined') {
        if(typeof cb === 'function') cb()
        return
    }
    if (tryn >= 10) {
        d(`trying to SIGKILL ${proc.name}...`)
        proc.kill('SIGKILL')
    } else {
        d(`trying to kill ${proc.name}...`)
        proc.kill()
    }
    proc.killer = {
        func: killer.bind(this, proc, cb, ++tryn)
    }

    proc.killer.id = setTimeout(proc.killer.func, 500)
}

function killAll(obj, cb) {
    let n=Object.keys(obj).length
    for (let proc in obj)
        if (obj.hasOwnProperty(proc)) {
            proc = procs[proc]
            killer(proc, ()=>{
                if(--n === 0){
                    d('Killing done')
                    if(typeof cb === 'function') cb()
                } else d(`Killing has ${n} left`)
            })
        }
}

['exit', 'SIGINT', 'SIGHUP', 'SIGTERM', 'uncaughtException'].forEach(signal=>process.on(signal, ()=>{
    d(`Caught ${signal}`)
    killAll(procs, process.exit)
    process.removeAllListeners()
}))

setInterval(() => {
    procs.webui.emit('message', {
        dest: 'webui',
        msg: {
            act: 'console',
            text: 'Testing: ' + (new Date())
        }
    })
}, 5000)<|endoftext|>


<commit_before>const Koa = require('koa');
const fetch = require('node-fetch');
const app = new Koa();
const port = process.env.PORT || 3000;

app.use(async(ctx, next) => {
  if (/ping/.test(ctx.path)) {
    ctx.body = 'pong';
  } else {
    const response = await fetch('http://inspirobot.me/api?generate=true');
    const url = await response.text();
    const result = {
      parse: "full",
      response_type: "in_channel",
      text: url,
      attachments: [{
        image_url: url
      }],
      unfurl_media: false,
      unfurl_links: false
    };
    ctx.set('Content-Type', 'application/json');
    ctx.body = result;
  }
});

// Keep heroku instance alive
setInterval(() => {
  fetch('https://inspirobotnrk.herokuapp.com/ping');
}, 299000);

if (!module.parent) app.listen(port);
<commit_msg>fix url<commit_after>const Koa = require('koa');
const fetch = require('node-fetch');
const app = new Koa();
const port = process.env.PORT || 3000;

app.use(async(ctx, next) => {
  if (/ping/.test(ctx.path)) {
    ctx.body = 'pong';
  } else {
    const response = await fetch('http://inspirobot.me/api?generate=true');
    const url = await response.text();
    const result = {
      parse: "full",
      response_type: "in_channel",
      text: url,
      attachments: [{
        image_url: url
      }],
      unfurl_media: false,
      unfurl_links: false
    };
    ctx.set('Content-Type', 'application/json');
    ctx.body = result;
  }
});

// Keep heroku instance alive
setInterval(() => {
  fetch('https://inspirobotnetlight.herokuapp.com/ping');
}, 299000);

if (!module.parent) app.listen(port);
<|endoftext|>


<commit_before>/**
 * The main module to run the linters.
 */
var async = require("async");
var less = require("less");
var postcss = require("postcss");
var sourceMap = require("source-map");

var abcLint = require("./lib/abc-lint");
var overqualifiedLint = require("./lib/overqualified-lint");
var nestingLint = require("./lib/nesting-lint");

const CSS_LINTERS = [overqualifiedLint];
const LESS_LINTERS = [abcLint, nestingLint];

module.exports = function(filename, code) {
    var errors = [];
    function reportError(error) {
        errors.push(error);
    }

    function runLessLinters(done) {
        less.parse(code, function(err, ast) {
            if (err) {
                return done(err);
            }

            LESS_LINTERS.forEach(function(linter) {
                linter(code, ast, reportError);
            });

            done();
        });
    }

    function runCSSLinters(done) {
        var options = {
            sourceMap: {
                outputSourceFiles: true,
            },
        };

        less.render(code, options, function(err, result) {
            if (err) {
                return done(err);
            }

            // Establish a SourceMapConsumer to point to the original less
            var smc = new sourceMap.SourceMapConsumer(result.map);
            var ast = postcss.parse(result.css);
            CSS_LINTERS.forEach(function(linter) {
                linter(ast, smc, reportError);
            });

            done();
        });
    }

    // Run the linter groups in parallel
    async.parallel([runLessLinters, runCSSLinters], function(err) {
        if (err) {
            // Parsing error
            var location = "(" + err.line + ":" + err.column + ")";
            console.log("Error parsing: unrecognized input " + location);
            process.exit(1);
        }

        // Report any errors
        if (errors.length) {
            errors.forEach(function(error) {
                console.log(error.reason +
                    " (line " + error.line +
                    ", col: " + error.character + ")");
            });

            process.exit(1);
        }
    });
};
<commit_msg>moved error location to beginning of line<commit_after>/**
 * The main module to run the linters.
 */
var async = require("async");
var less = require("less");
var postcss = require("postcss");
var sourceMap = require("source-map");

var abcLint = require("./lib/abc-lint");
var overqualifiedLint = require("./lib/overqualified-lint");
var nestingLint = require("./lib/nesting-lint");

const CSS_LINTERS = [overqualifiedLint];
const LESS_LINTERS = [abcLint, nestingLint];

module.exports = function(filename, code) {
    var errors = [];
    function reportError(error) {
        errors.push(error);
    }

    function runLessLinters(done) {
        less.parse(code, function(err, ast) {
            if (err) {
                return done(err);
            }

            LESS_LINTERS.forEach(function(linter) {
                linter(code, ast, reportError);
            });

            done();
        });
    }

    function runCSSLinters(done) {
        var options = {
            sourceMap: {
                outputSourceFiles: true,
            },
        };

        less.render(code, options, function(err, result) {
            if (err) {
                return done(err);
            }

            // Establish a SourceMapConsumer to point to the original less
            var smc = new sourceMap.SourceMapConsumer(result.map);
            var ast = postcss.parse(result.css);
            CSS_LINTERS.forEach(function(linter) {
                linter(ast, smc, reportError);
            });

            done();
        });
    }

    // Run the linter groups in parallel
    async.parallel([runLessLinters, runCSSLinters], function(err) {
        if (err) {
            // Parsing error
            var location = "(" + err.line + ":" + err.column + ")";
            console.log(location + " Error parsing: unrecognized input");
            process.exit(1);
        }

        // Report any errors
        if (errors.length) {
            errors.forEach(function(error) {
                var location = "(" + error.line + ":" + error.character + ")";
                console.log(location + " " + error.reason);
            });

            process.exit(1);
        }
    });
};
<|endoftext|>


<commit_before>'use strict';

var fs = require("fs")
var path = require('path')
var loaderUtils = require('loader-utils');
var elmCompiler = require('node-elm-compiler');
var yargs = require('yargs');

var runningInstances = 0;
var alreadyCompiledFiles = [];

var defaultOptions = {
  cache: false,
  forceWatch: false,
  optimize: false
};

var getFiles = function(options) {
  var files = options && options.files;

  if (files === undefined) return [this.resourcePath];

  if (!Array.isArray(files)) {
    throw new Error('files option must be an array');
  }

  if (files.length === 0) {
    throw new Error("You specified the 'files' option but didn't list any files");
  }

  delete options.files;
  return files;
};

var getOptions = function() {
  var globalOptions = this.options
    ? this.options.elm || {}
    : this.query.elm || {};
  var loaderOptions = loaderUtils.getOptions(this) || {};
  return Object.assign({}, defaultOptions, globalOptions, loaderOptions);
};

var _addDependencies = function(dependency) {
  this.addDependency(dependency);
};

var _addDirDependency = function(dirs){
  dirs.forEach(this.addContextDependency.bind(this));
};

var isFlagSet = function(args, flag) {
  return typeof args[flag] !== "undefined" && args[flag];
};

/* Figures out if webpack has been run in watch mode
    This currently means either that the `watch` command was used
    Or it was run via `webpack-dev-server`
*/
var isInWatchMode = function(){
  // parse the argv given to run this webpack instance
  var argv = yargs(process.argv)
      .alias('w', 'watch')
      .alias('stdin', 'watch-stdin')
      .argv;

  var hasWatchArg = isFlagSet(argv, 'watch');
  var hasStdinArg = isFlagSet(argv, 'watch-stdin');

  var hasWebpackServe = Array.prototype.filter.call(process.argv, function (arg) {
    return arg.indexOf('webpack-serve') !== -1;
  }).length > 0;

  var hasWebpackDevServer = Array.prototype.filter.call(process.argv, function (arg) {
    return arg.indexOf('webpack-dev-server') !== -1;
  }).length > 0;

  return hasWebpackServe || hasWebpackDevServer || hasWatchArg || hasStdinArg;
};

/* Takes a working dir, tries to read elm.json, then grabs all the modules from in there
*/
var filesToWatch = function(cwd){
  var readFile = fs.readFileSync(path.join(cwd, "elm.json"), 'utf8');
  var elmPackage = JSON.parse(readFile);

  var paths = elmPackage["source-directories"].map(function(dir){
    return path.join(cwd, dir);
  });

  return paths;
};

var dependenciesFor = function(resourcePath, files) {
  return findAllDependencies(files)
    .then(function (dependencies) {
      return unique(dependencies.concat(remove(resourcePath, files)));
    });
}

var findAllDependencies = function(files) {
  return Promise.all(files.map(
    function(f) { return elmCompiler.findAllDependencies(f) }
  ))
  .then(flatten);
}

module.exports = function() {
  this.cacheable && this.cacheable();

  var callback = this.async();
  if (!callback) {
    throw 'elm-webpack-loader currently only supports async mode.';
  }

  // bind helper functions to `this`
  var addDependencies = _addDependencies.bind(this);
  var addDirDependency = _addDirDependency.bind(this);
  var emitError = this.emitError.bind(this);

  var options = getOptions.call(this);
  var files = getFiles.call(this, options);
  var resourcePath = this.resourcePath;

  var promises = [];

  // we only need to track deps if we are in watch mode
  // otherwise, we trust elm to do it's job
  if (options.forceWatch || isInWatchMode()){
    // we can do a glob to track deps we care about if cwd is set
    if (typeof options.cwd !== "undefined" && options.cwd !== null){
      // watch elm.json
      var elmPackage = path.join(options.cwd, "elm.json");
      addDependencies(elmPackage);
      var dirs = filesToWatch(options.cwd);
      // watch all the dirs in elm.json
      addDirDependency.bind(this)(dirs);
    }

    // find all the deps, adding them to the watch list if we successfully parsed everything
    // otherwise return an error which is currently ignored
    var dependencies = dependenciesFor(resourcePath, files).then(function(dependencies){
      // add each dependency to the tree
      dependencies.map(addDependencies);
      return { kind: 'success', result: true };
    }).catch(function(v){
      emitError(v);
      return { kind: 'error', error: v };
    })

    promises.push(dependencies);
  }

  delete options.forceWatch

  var maxInstances = options.maxInstances;

  if (typeof maxInstances === "undefined"){
    maxInstances = 1;
  } else {
    delete options.maxInstances;
  }

  var intervalId = setInterval(function(){
    if (runningInstances >= maxInstances) return;
    runningInstances += 1;
    clearInterval(intervalId);

    // If we are running in watch mode, and we have previously compiled
    // the current file, then let the user know that `elm make` is running
    // and can be slow
    if (alreadyCompiledFiles.indexOf(resourcePath) > -1){
      console.log('Started compiling Elm..');
    }

    var compilation = elmCompiler.compileToString(files, options)
      .then(function(v) { runningInstances -= 1; return { kind: 'success', result: v }; })
      .catch(function(v) { runningInstances -= 1; return { kind: 'error', error: v }; });

    promises.push(compilation);

    Promise.all(promises)
      .then(function(results) {
        var output = results[results.length - 1]; // compilation output is always last

        if (output.kind === 'success') {
          alreadyCompiledFiles.push(resourcePath);
          callback(null, output.result);
        } else {
          if (typeof output.error === 'string') {
            output.error = new Error(output.error);
          }

          output.error.message = 'Compiler process exited with error ' + output.error.message;
          callback(output.error);
        }
      }).catch(function(err){
        callback(err);
      });

  }, 200);
}

// HELPERS

function flatten(arrayOfArrays) {
  return arrayOfArrays.reduce(function(flattened, array) {
    return flattened.concat(array)
  }, []);
}

function unique(items) {
  return items.filter(function(item, index, array) {
    return array.indexOf(item) === index;
  });
}

function remove(condemned, items) {
  return items.filter(function(item) {
    return item !== condemned;
  });
}
<commit_msg>Use customised version of compileToString function taken from node-elm-compiler<commit_after>'use strict';

var fs = require("fs");
var path = require('path');
var temp = require("temp").track();
var loaderUtils = require('loader-utils');
var elmCompiler = require('node-elm-compiler');
var yargs = require('yargs');

var runningInstances = 0;
var alreadyCompiledFiles = [];

var defaultOptions = {
  cache: false,
  forceWatch: false,
  optimize: false
};

var getFiles = function(options) {
  var files = options && options.files;

  if (files === undefined) return [this.resourcePath];

  if (!Array.isArray(files)) {
    throw new Error('files option must be an array');
  }

  if (files.length === 0) {
    throw new Error("You specified the 'files' option but didn't list any files");
  }

  delete options.files;
  return files;
};

var getOptions = function() {
  var globalOptions = this.options
    ? this.options.elm || {}
    : this.query.elm || {};
  var loaderOptions = loaderUtils.getOptions(this) || {};
  return Object.assign({}, defaultOptions, globalOptions, loaderOptions);
};

var _addDependencies = function(dependency) {
  this.addDependency(dependency);
};

var _addDirDependency = function(dirs){
  dirs.forEach(this.addContextDependency.bind(this));
};

var isFlagSet = function(args, flag) {
  return typeof args[flag] !== "undefined" && args[flag];
};

/* Figures out if webpack has been run in watch mode
    This currently means either that the `watch` command was used
    Or it was run via `webpack-dev-server`
*/
var isInWatchMode = function(){
  // parse the argv given to run this webpack instance
  var argv = yargs(process.argv)
      .alias('w', 'watch')
      .alias('stdin', 'watch-stdin')
      .argv;

  var hasWatchArg = isFlagSet(argv, 'watch');
  var hasStdinArg = isFlagSet(argv, 'watch-stdin');

  var hasWebpackServe = Array.prototype.filter.call(process.argv, function (arg) {
    return arg.indexOf('webpack-serve') !== -1;
  }).length > 0;

  var hasWebpackDevServer = Array.prototype.filter.call(process.argv, function (arg) {
    return arg.indexOf('webpack-dev-server') !== -1;
  }).length > 0;

  return hasWebpackServe || hasWebpackDevServer || hasWatchArg || hasStdinArg;
};

/* Takes a working dir, tries to read elm.json, then grabs all the modules from in there
*/
var filesToWatch = function(cwd){
  var readFile = fs.readFileSync(path.join(cwd, "elm.json"), 'utf8');
  var elmPackage = JSON.parse(readFile);

  var paths = elmPackage["source-directories"].map(function(dir){
    return path.join(cwd, dir);
  });

  return paths;
};

var dependenciesFor = function(resourcePath, files) {
  return findAllDependencies(files)
    .then(function (dependencies) {
      return unique(dependencies.concat(remove(resourcePath, files)));
    });
}

var findAllDependencies = function(files) {
  return Promise.all(files.map(
    function(f) { return elmCompiler.findAllDependencies(f) }
  ))
  .then(flatten);
}

module.exports = function() {
  this.cacheable && this.cacheable();

  var callback = this.async();
  if (!callback) {
    throw 'elm-webpack-loader currently only supports async mode.';
  }

  // bind helper functions to `this`
  var addDependencies = _addDependencies.bind(this);
  var addDirDependency = _addDirDependency.bind(this);
  var emitError = this.emitError.bind(this);

  var options = getOptions.call(this);
  var files = getFiles.call(this, options);
  var resourcePath = this.resourcePath;

  var promises = [];

  // we only need to track deps if we are in watch mode
  // otherwise, we trust elm to do it's job
  if (options.forceWatch || isInWatchMode()){
    // we can do a glob to track deps we care about if cwd is set
    if (typeof options.cwd !== "undefined" && options.cwd !== null){
      // watch elm.json
      var elmPackage = path.join(options.cwd, "elm.json");
      addDependencies(elmPackage);
      var dirs = filesToWatch(options.cwd);
      // watch all the dirs in elm.json
      addDirDependency.bind(this)(dirs);
    }

    // find all the deps, adding them to the watch list if we successfully parsed everything
    // otherwise return an error which is currently ignored
    var dependencies = dependenciesFor(resourcePath, files).then(function(dependencies){
      // add each dependency to the tree
      dependencies.map(addDependencies);
      return { kind: 'success', result: true };
    }).catch(function(v){
      emitError(v);
      return { kind: 'error', error: v };
    })

    promises.push(dependencies);
  }

  delete options.forceWatch

  var maxInstances = options.maxInstances;

  if (typeof maxInstances === "undefined"){
    maxInstances = 1;
  } else {
    delete options.maxInstances;
  }

  var intervalId = setInterval(function(){
    if (runningInstances >= maxInstances) return;
    runningInstances += 1;
    clearInterval(intervalId);

    // If we are running in watch mode, and we have previously compiled
    // the current file, then let the user know that `elm make` is running
    // and can be slow
    if (alreadyCompiledFiles.indexOf(resourcePath) > -1){
      console.log('Started compiling Elm..');
    }

    var compilation = compile(files, options)
      .then(function(v) { runningInstances -= 1; return { kind: 'success', result: v }; })
      .catch(function(v) { runningInstances -= 1; return { kind: 'error', error: v }; });

    promises.push(compilation);

    Promise.all(promises)
      .then(function(results) {
        var output = results[results.length - 1]; // compilation output is always last

        if (output.kind === 'success') {
          alreadyCompiledFiles.push(resourcePath);
          callback(null, output.result);
        } else {
          if (typeof output.error === 'string') {
            output.error = new Error(output.error);
          }

          output.error.message = 'Compiler process exited with error ' + output.error.message;
          callback(output.error);
        }
      }).catch(function(err){
        callback(err);
      });

  }, 200);
}

// Functions pulled and modified from node-elm-compiler:

// this was called compileToString
// - altered to log output to console instead to retain formatting
function compile(sources, options) {
  var suffix = getSuffix(options.output, '.js');
  return new Promise(function (resolve, reject) {
    temp.open({ suffix: suffix }, function (err, info) {
      if (err) {
        return reject(err);
      }
      options.output = info.path;
      options.processOpts = { stdio: 'inherit' };

      var compiler;

      try {
        compiler = elmCompiler.compile(sources, options);
      }
      catch (compileError) {
        return reject(compileError);
      }

      compiler.on("close", function (exitCode) {
        if (exitCode !== 0) {
          return reject('Compilation failed');
        }
        else if (options.verbose) {
          console.log(output);
        }
        fs.readFile(info.path, { encoding: "utf8" }, function (err, data) {
          return err ? reject(err) : resolve(data);
        });
      });
    });
  });
}

function getSuffix(outputPath, defaultSuffix) {
  if (outputPath) {
    return path.extname(outputPath) || defaultSuffix;
  }
  else {
    return defaultSuffix;
  }
}

// HELPERS

function flatten(arrayOfArrays) {
  return arrayOfArrays.reduce(function(flattened, array) {
    return flattened.concat(array)
  }, []);
}

function unique(items) {
  return items.filter(function(item, index, array) {
    return array.indexOf(item) === index;
  });
}

function remove(condemned, items) {
  return items.filter(function(item) {
    return item !== condemned;
  });
}
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var fs   = require('fs');
var path = require('path');
var Funnel = require('broccoli-funnel');

module.exports = {
  name: 'ember-cli-photoswipe',

  included: function(app) {
    this.app  = app;
    var psDir = app.bowerDirectory + '/photoswipe';

    app.import(psDir + '/dist/photoswipe.css');
    app.import(psDir + '/dist/default-skin/default-skin.css');
    app.import(psDir + '/dist/photoswipe.js');
    app.import(psDir + '/dist/photoswipe-ui-default.min.js');
    app.import(psDir + '/dist/default-skin/default-skin.svg');
  },

  treeForPublic: function() {
    var svgPath = path.join(this.app.bowerDirectory, 'photoswipe', 'dist', 'default-skin');
    var publicTree = new Funnel(this.treeGenerator(svgPath), {
      srcDir: '/',
      destDir: '/assets'
    });
    return publicTree;
  }
};
<commit_msg>don't add unnecessary files to assets<commit_after>/* jshint node: true */
'use strict';

var fs   = require('fs');
var path = require('path');
var Funnel = require('broccoli-funnel');

module.exports = {
  name: 'ember-cli-photoswipe',

  included: function(app) {
    this.app  = app;
    var psDir = app.bowerDirectory + '/photoswipe';

    app.import(psDir + '/dist/photoswipe.css');
    app.import(psDir + '/dist/default-skin/default-skin.css');
    app.import(psDir + '/dist/photoswipe.js');
    app.import(psDir + '/dist/photoswipe-ui-default.min.js');
  },

  treeForPublic: function() {
    var svgPath = path.join(this.app.bowerDirectory, 'photoswipe', 'dist', 'default-skin');
    var publicTree = new Funnel(this.treeGenerator(svgPath), {
      srcDir: '/',
      destDir: '/assets',
      exclude: ['default-skin.css']
    });
    return publicTree;
  }
};
<|endoftext|>


<commit_before>'use strict'

const cheerio = require('cheerio')
const request = require('request')

const base_url = 'https://github.com'

const parse = function (el) {
  return el.text().split('\n').join('').replace(/ +/g, ' ').trim()
}

const api = function (url, fn, cb) {
  request.get(url, function (err, res, body) {
    let $ = cheerio.load(body)
    let $body = $('body')

    if (err) {
      throw err
    }

    fn($, $body, cb)
  })
}

const find = function($body, el) {
  let $items = $body.find(el)

  return { items: $items, li: [] }
}

const parseRepos = function ($, $body, cb) {
  let { li, items } = find($body, 'li.repo-list-item')

  $(items).each(function (i, elem) {
    let el = $(elem)
    let name = el.find('h3.repo-list-name')
    let link = el.find('h3.repo-list-name a').attr('href')
    let description = el.find('p.repo-list-description')
    let meta = el.find('p.repo-list-meta')
    let item = {
      name: parse(name),
      link: `${base_url}${link}`,
      description: parse(description),
      meta: parse(meta)
    }

    li.push(item)
  })

  cb(li)
}

const parseDevs = function ($, $body, cb) {
  let { items, li } = find($body, 'li.user-leaderboard-list-item')

  $(items).each(function (i, elem) {
    let el = $(elem)
    let name = el.find('h2.user-leaderboard-list-name')
    let href = el.find('.user-leaderboard-list-name a').attr('href')
    let item = {
      name: parse(name),
      href: base_url + href
    }

    li.push(item)
  })

  cb(li)
}

const matchTime = function (time) {
  switch (time.toLowerCase()) {
    case 'weekly':
    case 'monthly':
    case 'daily':
      return true
    default:
      return false
  }
}

const constructUrl = function (lang, time, cb) {
  let options = {}

  if (typeof (lang) === 'boolean' && typeof (time) === 'string' && typeof (cb) === 'function') {
    options.url = `${base_url}/trending/developers?since=${time}`
    options.callback = cb
  } else if (typeof (lang) === 'boolean' && typeof (time) === 'function') {
    options.url = `${base_url}/trending/developers`
    options.callback = time
  } else if (typeof (lang) === 'string' && typeof (time) === 'string' && typeof (cb) === 'function') {
    options.url = `${base_url}/trending/${lang}?since=${time}`
    options.callback = cb
  } else if (typeof (lang) === 'string' && matchTime(lang) && typeof (time) === 'function') {
    options.url = `${base_url}/trending?since=${lang}`
    options.callback = time
  } else if (typeof (lang) === 'string' && !matchTime(lang) && typeof (time) === 'function') {
    options.url = `${base_url}/trending/${lang}`
    options.callback = time
  } else {
    options.url = `${base_url}/trending`
    options.callback = lang
  }

  return options
}

const findRepos = function (lang, time, cb) {
  util(lang, time, cb, parseRepos)
}

const findDevs = function (time, cb) {
  util(true, time, cb, parseDevs)
}

const util = function (bool, time, cb, fn) {
  let { url, callback } = constructUrl(bool, time, cb)

  api(url, fn, callback)
}

module.exports = {
  findDevs: findDevs,
  findRepos: findRepos,
  constructUrl: constructUrl,
  matchTime: matchTime
}
<commit_msg>Remove switch<commit_after>'use strict'

const cheerio = require('cheerio')
const request = require('request')

const base_url = 'https://github.com'

const parse = el => el.text().split('\n').join('').replace(/ +/g, ' ').trim()

const api = function (url, fn, cb) {
  request.get(url, function (err, res, body) {
    let $ = cheerio.load(body)
    let $body = $('body')

    if (err) {
      throw err
    }

    fn($, $body, cb)
  })
}

const find = function($body, el) {
  let $items = $body.find(el)

  return { items: $items, li: [] }
}

const parseRepos = function ($, $body, cb) {
  let { li, items } = find($body, 'li.repo-list-item')

  $(items).each(function (i, elem) {
    let el = $(elem)
    let name = el.find('h3.repo-list-name')
    let link = el.find('h3.repo-list-name a').attr('href')
    let description = el.find('p.repo-list-description')
    let meta = el.find('p.repo-list-meta')
    let item = {
      name: parse(name),
      link: `${base_url}${link}`,
      description: parse(description),
      meta: parse(meta)
    }

    li.push(item)
  })

  cb(li)
}

const parseDevs = function ($, $body, cb) {
  let { items, li } = find($body, 'li.user-leaderboard-list-item')

  $(items).each(function (i, elem) {
    let el = $(elem)
    let name = el.find('h2.user-leaderboard-list-name')
    let href = el.find('.user-leaderboard-list-name a').attr('href')
    let item = {
      name: parse(name),
      href: base_url + href
    }

    li.push(item)
  })

  cb(li)
}

const matchTime = function (time) {
  return time.toLowerCase().match(/weekly|monthly|daily/) ? true : false
}

const constructUrl = function (lang, time, cb) {
  let options = {}

  if (typeof (lang) === 'boolean' && typeof (time) === 'string' && typeof (cb) === 'function') {
    options.url = `${base_url}/trending/developers?since=${time}`
    options.callback = cb
  } else if (typeof (lang) === 'boolean' && typeof (time) === 'function') {
    options.url = `${base_url}/trending/developers`
    options.callback = time
  } else if (typeof (lang) === 'string' && typeof (time) === 'string' && typeof (cb) === 'function') {
    options.url = `${base_url}/trending/${lang}?since=${time}`
    options.callback = cb
  } else if (typeof (lang) === 'string' && matchTime(lang) && typeof (time) === 'function') {
    options.url = `${base_url}/trending?since=${lang}`
    options.callback = time
  } else if (typeof (lang) === 'string' && !matchTime(lang) && typeof (time) === 'function') {
    options.url = `${base_url}/trending/${lang}`
    options.callback = time
  } else {
    options.url = `${base_url}/trending`
    options.callback = lang
  }

  return options
}

const findRepos = (lang, time, cb) => util(lang, time, cb, parseRepos)

const findDevs = (time, cb) => util(true, time, cb, parseDevs)

const util = function (bool, time, cb, fn) {
  let { url, callback } = constructUrl(bool, time, cb)

  api(url, fn, callback)
}

module.exports = {
  findDevs: findDevs,
  findRepos: findRepos,
  constructUrl: constructUrl,
  matchTime: matchTime
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Plays Crazy Music
 * @return {object}
 */
module.exports = function() {

    var SPM = function(toneClass){
      this.tone = toneClass;
      this.connection = undefined;
    };

    SPM.prototype.start = function() {
      window.WebSocket = window.WebSocket || window.MozWebSocket;

      this.connect(window.WebSocket);
    }

    SPM.prototype.setupConnection = function() {
      this.connection.onopen = function () {
        console.log('[WS conn OK]');
      };

      this.connection.onclose = (function (_this) {
        return function() {
          console.log('[WS closed]');
          window.setTimeout(function(){
            _this.connect(window.WebSocket);
          }, 1000);
        }
      })(this);

      this.connection.onerror = function (error) {
        console.log('Some error with WebSocket');
      };

      this.connection.onmessage = this.onWsMessage.bind(this);
    }

    SPM.prototype.onWsMessage = function(message) {
      try {
        var json = JSON.parse(message.data);
      } catch (e) {
        console.log('This doesn\'t look like a valid JSON: ', message.data);
        return;
      }

      this.play(json.text, json.channel, json.user);
    }

    SPM.prototype.connect = function(WebSocketClass) {
      this.connection = new WebSocketClass('ws://' + window.location.hostname + ':1337');
      this.setupConnection();
    }

    SPM.prototype.play = function(text, channel, user) {

      var channelDiv = $('

');
      channelDiv.append(' @' + user + ' in ' + channel + '.');
      $('#panel').append(channelDiv);
      channelDiv.animate({flexGrow: 1}); // all for the beauty of the world

      var synth = this.getInstrumentForChannel(channel);

      var accTime = 0;

      for (var word of text.split(' ')) {
        if (word.length == 0){
          accTime += 0.5;
          continue;
        }

        var note = this.getNoteFromWord(word);
        var time = this.getSustainFromWord(word);

        synth.triggerAttackRelease(note, time, '+' + accTime);

        (function(_this, _word){
          window.setTimeout(function(){
            channelDiv.css({background: _this.getColorFromWord(_word)});
          }, accTime * 1000);
        }(this, word));

        accTime += time;
      }

      window.setTimeout(function(){
        channelDiv.css({transition: 'initial'});
        channelDiv.animate({flexGrow: 0, height: 0}, 500, 'swing', function(){
          channelDiv.remove();
        });
      }, accTime * 1000); // 0.5s transition
    }

    SPM.prototype.getInstrumentForChannel = function(channel) {
      // return new this.tone.Synth({
      //   "oscillator" : {
      //     "type" : "pwm",
      //     "modulationFrequency" : 0.2
      //   },
      //   "envelope" : {
      //     "attack" : 0.02,
      //     "decay" : 0.1,
      //     "sustain" : 0.2,
      //     "release" : 0.9,
      //   }
      // }).toMaster();
      return new this.tone.Synth().toMaster();
    }

    SPM.prototype.getColorFromWord = function(word) {
      var maxLength = 256 * 256 * 256;

      var charCode = -1; // chr('!') == 33

      for (var l of word.split('')) {
        charCode += (l.charCodeAt(0) - 32) * Math.floor(maxLength / 60); // must sync with notes C1 = black B5 = white
      }

      charCode = (charCode % maxLength);

      var color = '#' + ('000000' + (charCode).toString(16)).slice(-6);

      return color;
    }

    SPM.prototype.getNoteFromWord = function(word) {
      var notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
      var note = 'C';
      var octave = 1;
      var maxLength = notes.length * 5;

      if (word.length == 0) {
        return notes[0] + octave;
      }

      var charCode = -1; // chr('!') == 33

      for (var l of word.split('')) {
        charCode += l.charCodeAt(0) - 32;
      }

      charCode = (charCode % maxLength);
      octave = Math.floor(charCode / notes.length) + 1;
      note = notes[charCode % notes.length];

      return note + octave;
    }

    SPM.prototype.getSustainFromWord = function(word) {
      return word.length * 0.1;
    }

    return SPM;
}(this);
<commit_msg>Improve MagicNumber logic<commit_after>'use strict';

/**
 * Plays Crazy Music
 * @return {object}
 */
module.exports = function() {

    var SPM = function(toneClass){
      this.tone = toneClass;
      this.connection = undefined;
    };

    SPM.NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];

    SPM.MIN_OCTAVE = 1;

    SPM.MAX_OCTAVE = 6;

    SPM.prototype.start = function() {
      window.WebSocket = window.WebSocket || window.MozWebSocket;

      this.connect(window.WebSocket);
    }

    SPM.prototype.setupConnection = function() {
      this.connection.onopen = function () {
        console.log('[WS conn OK]');
      };

      this.connection.onclose = (function (_this) {
        return function() {
          console.log('[WS closed]');
          window.setTimeout(function(){
            _this.connect(window.WebSocket);
          }, 1000);
        }
      })(this);

      this.connection.onerror = function (error) {
        console.log('Some error with WebSocket');
      };

      this.connection.onmessage = this.onWsMessage.bind(this);
    }

    SPM.prototype.onWsMessage = function(message) {
      try {
        var json = JSON.parse(message.data);
      } catch (e) {
        console.log('This doesn\'t look like a valid JSON: ', message.data);
        return;
      }

      this.play(json.text, json.channel, json.user);
    }

    SPM.prototype.connect = function(WebSocketClass) {
      this.connection = new WebSocketClass('ws://' + window.location.hostname + ':1337');
      this.setupConnection();
    }

    SPM.prototype.play = function(text, channel, user) {

      var channelDiv = $('

');
      channelDiv.append(' @' + user + ' in ' + channel + '.');
      $('#panel').append(channelDiv);
      channelDiv.animate({flexGrow: 1}); // all for the beauty of the world

      var synth = this.getInstrumentForChannel(channel);

      var accTime = 0;

      for (var word of text.split(' ')) {
        if (word.length == 0){
          accTime += 0.5;
          continue;
        }

        var note = this.getNoteFromWord(word);
        var time = this.getSustainFromWord(word);

        synth.triggerAttackRelease(note, time, '+' + accTime);

        (function(_this, _word){
          window.setTimeout(function(){
            channelDiv.css({background: _this.getColorFromWord(_word)});
          }, accTime * 1000);
        }(this, word));

        accTime += time;
      }

      window.setTimeout(function(){
        channelDiv.css({transition: 'initial'});
        channelDiv.animate({flexGrow: 0, height: 0}, 500, 'swing', function(){
          channelDiv.remove();
        });
      }, accTime * 1000); // 0.5s transition
    }

    SPM.prototype.getInstrumentForChannel = function(channel) {
      // return new this.tone.Synth({
      //   "oscillator" : {
      //     "type" : "pwm",
      //     "modulationFrequency" : 0.2
      //   },
      //   "envelope" : {
      //     "attack" : 0.02,
      //     "decay" : 0.1,
      //     "sustain" : 0.2,
      //     "release" : 0.9,
      //   }
      // }).toMaster();
      return new this.tone.Synth().toMaster();
    }

    // I really don't know how can i name this number
    SPM.prototype.getMagicNumberFromWord = function(word) {
      var maxLength = SPM.NOTES.length * (SPM.MAX_OCTAVE - SPM.MIN_OCTAVE + 1);
      var charCode = -1;
      for (var l of word.split('')) {
        charCode += l.charCodeAt(0) - '!'.charCodeAt(0) + 1; // ! is the first valid char
      }
      return charCode % maxLength;
    }

    SPM.prototype.getColorFromWord = function(word) {
      var maxLength = 256 * 256 * 256; // #FFFFFF
      var maxMagicNumberLength = SPM.NOTES.length * (SPM.MAX_OCTAVE - SPM.MIN_OCTAVE + 1);
      var magicNumber = this.getMagicNumberFromWord(word);

      magicNumber = Math.floor((magicNumber * maxLength) / maxMagicNumberLength);

      var color = '#' + ('000000' + (magicNumber).toString(16)).slice(-6);

      console.log(color);
      return color;
    }

    SPM.prototype.getNoteFromWord = function(word) {
      var notes = SPM.NOTES;
      var octave = SPM.MIN_OCTAVE;
      var note = notes[0];

      if (word.length == 0) {
        return notes[0] + octave; // just a fallback
      }

      var magicNumber = this.getMagicNumberFromWord(word);

      octave = Math.floor(magicNumber / notes.length) + 1;
      note = notes[magicNumber % notes.length];
      return note + octave;
    }

    SPM.prototype.getSustainFromWord = function(word) {
      return word.length * 0.1;
    }

    return SPM;
}(this);
<|endoftext|>


<commit_before>var Prism = require('prismjs');
var languages = require('prismjs').languages;
var path = require('path');
var fs = require('fs');
var cheerio = require('cheerio');
var mkdirp = require('mkdirp');

var DEFAULT_LANGUAGE = 'markup';
var MAP_LANGUAGES = {
  'py': 'python',
  'js': 'javascript',
  'rb': 'ruby',
  'cs': 'csharp',
  'html': 'markup'
};

function getAssets() {

  var cssFiles = this.config.get('pluginsConfig.prism.css', []);
  var cssFolder = null;
  var cssNames = [];
  var cssName = null;

  if (cssFiles.length === 0) {
    cssFiles.push('prismjs/themes/prism.css');
  }

  cssFiles.forEach(function(cssFile) {
    var cssPath = require.resolve(cssFile);
    cssFolder = path.dirname(cssPath);
    cssName = path.basename(cssPath);
    cssNames.push(cssName);
  });

  return {
    assets: cssFolder,
    css: cssNames
  };
}

module.exports = {
  book: getAssets,
  ebook: function() {

    // Adding prism-ebook.css to the CSS collection forces Gitbook
    // reference to it in the html markup that is converted into a PDF.
    var assets = getAssets.call(this);
    assets.css.push('prism-ebook.css');
    return assets;

  },
  blocks: {
    code: function(block) {

      var highlighted = '';

      // Normalize language id
      var lang = block.kwargs.language || DEFAULT_LANGUAGE;
      lang = MAP_LANGUAGES[lang] || lang;

      // Try and find the language definition in components folder
      if (!languages[lang]) {
        try {
          require('prismjs/components/prism-' + lang + '.js');
        } catch (e) {
          console.warn('Failed to load prism syntax: ' + lang);
          console.warn(e);
        }
      }

      if (!languages[lang]) lang = DEFAULT_LANGUAGE;

      // Check against html, prism "markup" works for this
      if (lang === 'html') {
        lang = 'markup';
      }

      try {
        // The process can fail (failed to parse)
        highlighted = Prism.highlight(block.body, languages[lang]);
      } catch (e) {
        console.warn('Failed to highlight:');
        console.warn(e);
        highlighted = block.body;
      }

      return highlighted;

    }
  },
  hooks: {

    // Manually copy prism-ebook.css into the temporary directory that Gitbook uses for inlining
    // styles from this plugin. The getAssets() (above) function can't be leveraged because
    // ebook-prism.css lives outside the folder referenced by this plugin's config.
    //
    // @Inspiration https://github.com/GitbookIO/plugin-styles-less/blob/master/index.js#L8
    init: function() {

      var book = this;

      if (book.output.name !== 'ebook') {
        // Logic below does not apply to non-ebook formats
        return;
      }

      var outputDirectory = path.join(book.output.root(), '/gitbook/gitbook-plugin-prism');
      var outputFile = path.resolve(outputDirectory, 'prism-ebook.css');
      var inputFile = path.resolve(__dirname, './prism-ebook.css');
      mkdirp.sync(outputDirectory);

      try {
        fs.writeFileSync(outputFile, fs.readFileSync(inputFile));
      } catch (e) {
        console.warn('Failed to write prism-ebook.css. See https://git.io/v1LHY for side effects.');
        console.warn(e);
      }

    },
    page: function(page) {

      var highlighted = false;

      var $ = cheerio.load(page.content);

      // Prism css styles target the <code> and <pre> blocks using
      // a substring CSS selector:
      //
      //    code[class*="language-"], pre[class*="language-"]
      //
      // Adding "language-" to <pre> element should be sufficient to trigger
      // correct color theme.
      $('pre').each(function() {
        highlighted = true;
        const $this = $(this);
        $this.addClass('language-');
      });

      if (highlighted) {
        page.content = $.html();
      }

      return page;
    }
  }
};
<commit_msg>Fix importing language definition with dependencies<commit_after>var Prism = require('prismjs');
var languages = require('prismjs').languages;
var path = require('path');
var fs = require('fs');
var cheerio = require('cheerio');
var mkdirp = require('mkdirp');

var DEFAULT_LANGUAGE = 'markup';
var MAP_LANGUAGES = {
  'py': 'python',
  'js': 'javascript',
  'rb': 'ruby',
  'cs': 'csharp',
  'html': 'markup'
};

// Base languages syntaxes, extended by other syntaxes, need to be
// required before all.
var PRELUDE = ['clike', 'javascript', 'markup', 'c', 'ruby', 'css'];
PRELUDE.map(requireSyntax);

/**
 * Load the syntax definition for a language id
 */
function requireSyntax(lang) {
    require('prismjs/components/prism-' + lang + '.js');
}

function getAssets() {

  var cssFiles = this.config.get('pluginsConfig.prism.css', []);
  var cssFolder = null;
  var cssNames = [];
  var cssName = null;

  if (cssFiles.length === 0) {
    cssFiles.push('prismjs/themes/prism.css');
  }

  cssFiles.forEach(function(cssFile) {
    var cssPath = require.resolve(cssFile);
    cssFolder = path.dirname(cssPath);
    cssName = path.basename(cssPath);
    cssNames.push(cssName);
  });

  return {
    assets: cssFolder,
    css: cssNames
  };
}

module.exports = {
  book: getAssets,
  ebook: function() {

    // Adding prism-ebook.css to the CSS collection forces Gitbook
    // reference to it in the html markup that is converted into a PDF.
    var assets = getAssets.call(this);
    assets.css.push('prism-ebook.css');
    return assets;

  },
  blocks: {
    code: function(block) {

      var highlighted = '';

      // Normalize language id
      var lang = block.kwargs.language || DEFAULT_LANGUAGE;
      lang = MAP_LANGUAGES[lang] || lang;

      // Try and find the language definition in components folder
      if (!languages[lang]) {
        try {
            requireSyntax(lang);
        } catch (e) {
          console.warn('Failed to load prism syntax: ' + lang);
          console.warn(e);
        }
      }

      if (!languages[lang]) lang = DEFAULT_LANGUAGE;

      // Check against html, prism "markup" works for this
      if (lang === 'html') {
        lang = 'markup';
      }

      try {
        // The process can fail (failed to parse)
        highlighted = Prism.highlight(block.body, languages[lang]);
      } catch (e) {
        console.warn('Failed to highlight:');
        console.warn(e);
        highlighted = block.body;
      }

      return highlighted;

    }
  },
  hooks: {

    // Manually copy prism-ebook.css into the temporary directory that Gitbook uses for inlining
    // styles from this plugin. The getAssets() (above) function can't be leveraged because
    // ebook-prism.css lives outside the folder referenced by this plugin's config.
    //
    // @Inspiration https://github.com/GitbookIO/plugin-styles-less/blob/master/index.js#L8
    init: function() {

      var book = this;

      if (book.output.name !== 'ebook') {
        // Logic below does not apply to non-ebook formats
        return;
      }

      var outputDirectory = path.join(book.output.root(), '/gitbook/gitbook-plugin-prism');
      var outputFile = path.resolve(outputDirectory, 'prism-ebook.css');
      var inputFile = path.resolve(__dirname, './prism-ebook.css');
      mkdirp.sync(outputDirectory);

      try {
        fs.writeFileSync(outputFile, fs.readFileSync(inputFile));
      } catch (e) {
        console.warn('Failed to write prism-ebook.css. See https://git.io/v1LHY for side effects.');
        console.warn(e);
      }

    },
    page: function(page) {

      var highlighted = false;

      var $ = cheerio.load(page.content);

      // Prism css styles target the <code> and <pre> blocks using
      // a substring CSS selector:
      //
      //    code[class*="language-"], pre[class*="language-"]
      //
      // Adding "language-" to <pre> element should be sufficient to trigger
      // correct color theme.
      $('pre').each(function() {
        highlighted = true;
        const $this = $(this);
        $this.addClass('language-');
      });

      if (highlighted) {
        page.content = $.html();
      }

      return page;
    }
  }
};
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2015 Nils Knappmeier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
 * Create a new LineCounter instance counting lines in a given string.
 * The class provides a method `countUpTo` that pushes an internal counter
 * to the line of a specified char-index in the string.
 *
 * Example:
 *
 * ```js
 * var LineCounter = require('line-counter');
 * var lc = new LineCounter('abc\ncde\nefg');
 * lc.countUpTo(0); // == 1
 * lc.countUpTo(8); // == 3
 * ```
 *
 * @param {string} `contents` the string that is parsed (i.e. file contents)
 * @constructor
 * @api public
 */
function LineCounter(contents) {

    // Regex to determine line endings [see XML-1.0 Spec Chapter 2.11 End-of-Line Handling](http://www.w3.org/TR/REC-xml/#sec-line-ends)
    var lineRegex = /\r\n?|\n/mg;

    // The number of the current line (the value is one-based,
    // but in the beginning, we are not on the first line yet).
    var currentLine = 0;

    // The end of the current line (in the beginning, we assume,
    // that the line before the first line ends just before the string).
    var eolIndex = -1;

    // The start of the current line
    var startOfLineIndex = -1;

    /**
     * Returns the line-number of a given char-index within the string.
     *
     *
     * @param {number} `upTo` a char-index within the `contents`-string. This char-index must
     *    be greater or equal to the line-start of the last char-index passed to the previous
     *    call to `countUpTo`
     * @returns {number} the line-number of this char-index.
     * @api public
     */
    this.countUpTo = function (upTo) {
        if (upTo >= contents.length) {
            throw new Error(
                "Index out of bounds! " +
                "Index " + upTo + " is not beyound the end of the string."
            )
        }
        if (upTo < startOfLineIndex) {
            throw new Error(
                "Cannot go back to index " + upTo + ". " +
                "Current line ("+currentLine+") starts at index " + startOfLineIndex +"."
            );
        }
        // Go to the next line until the line
        // we hit the line following the 'upTo' index
        while (eolIndex < upTo) {
            // Next line
            currentLine++;
            // Move startOfLineIndex to the start of the next line
            startOfLineIndex = eolIndex + 1;
            // Find next line-end
            var match = lineRegex.exec(contents);
            if (match !== null) {
                // The end-of-line is the matched new-line character,
                // In case of a CRLF, it is the LF
                eolIndex = match.index + match[0].length - 1;
            } else {
                // If there is no match, then we are in the last line
                // so the eolIndex is the last character in the string.
                eolIndex = contents.length - 1;
            }
        }

        return currentLine;
    }
}

module.exports = LineCounter;
<commit_msg>Typo in Error-Message<commit_after>/*
The MIT License (MIT)

Copyright (c) 2015 Nils Knappmeier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
 * Create a new LineCounter instance counting lines in a given string.
 * The class provides a method `countUpTo` that pushes an internal counter
 * to the line of a specified char-index in the string.
 *
 * Example:
 *
 * ```js
 * var LineCounter = require('line-counter');
 * var lc = new LineCounter('abc\ncde\nefg');
 * lc.countUpTo(0); // == 1
 * lc.countUpTo(8); // == 3
 * ```
 *
 * @param {string} `contents` the string that is parsed (i.e. file contents)
 * @constructor
 * @api public
 */
function LineCounter(contents) {

    // Regex to determine line endings [see XML-1.0 Spec Chapter 2.11 End-of-Line Handling](http://www.w3.org/TR/REC-xml/#sec-line-ends)
    var lineRegex = /\r\n?|\n/mg;

    // The number of the current line (the value is one-based,
    // but in the beginning, we are not on the first line yet).
    var currentLine = 0;

    // The end of the current line (in the beginning, we assume,
    // that the line before the first line ends just before the string).
    var eolIndex = -1;

    // The start of the current line
    var startOfLineIndex = -1;

    /**
     * Returns the line-number of a given char-index within the string.
     *
     *
     * @param {number} `upTo` a char-index within the `contents`-string. This char-index must
     *    be greater or equal to the line-start of the last char-index passed to the previous
     *    call to `countUpTo`
     * @returns {number} the line-number of this char-index.
     * @api public
     */
    this.countUpTo = function (upTo) {
        if (upTo >= contents.length) {
            throw new Error(
                "Index out of bounds! " +
                "Index " + upTo + " is beyond the end of the string."
            )
        }
        if (upTo < startOfLineIndex) {
            throw new Error(
                "Cannot go back to index " + upTo + ". " +
                "Current line ("+currentLine+") starts at index " + startOfLineIndex +"."
            );
        }
        // Go to the next line until the line
        // we hit the line following the 'upTo' index
        while (eolIndex < upTo) {
            // Next line
            currentLine++;
            // Move startOfLineIndex to the start of the next line
            startOfLineIndex = eolIndex + 1;
            // Find next line-end
            var match = lineRegex.exec(contents);
            if (match !== null) {
                // The end-of-line is the matched new-line character,
                // In case of a CRLF, it is the LF
                eolIndex = match.index + match[0].length - 1;
            } else {
                // If there is no match, then we are in the last line
                // so the eolIndex is the last character in the string.
                eolIndex = contents.length - 1;
            }
        }

        return currentLine;
    }
}

module.exports = LineCounter;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var request = require('request');

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

app.get('/', function(req, res) {
  res.send('You got it.');
});

app.post('/', function(req, res) {
  var payload = {
    channel: "#hackers",
    username: "Doom Guy",
    text: "Test Post",
    icon_emoji: ":godmode:"
  };

  var type = req.query.type;

  switch(type) {
    case 'boxerror':
      payload.text = 'Alert from Loggly: Box Error';
      break;
    case 'elevatedclientalerts':
      payload.text = 'Alert from Loggly: Elevated Client Alerts';
      break;
    case 'elevatedserveralerts':
      payload.text = 'Alert from Loggly: Elevated Server Alerts';
      break;
    case 'jobfailed':
      payload.text = 'Alert from Loggly: Job Failed';
      break;
    case 'memoryquotaexceeded':
      payload.text = 'Alert from Loggly: Memory Quota Exceeded';
      break;
    case 'requesttimeouts':
      payload.text = 'Alert from Loggly: Request Timeouts';
      break;
    case 'slowrequests':
      payload.text = 'Alert from Loggly: Slow Requests';
      break;
    default:
      break;
  }

  request({
    url: process.env.WEBSITE,
    method: 'POST',
    body: JSON.stringify(payload)
  }, function() {
    res.sendStatus(201);
  });
});

var server = app.listen(app.get('port'));
<commit_msg>Log stuffs.<commit_after>var express = require('express');
var app = express();
var request = require('request');

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

app.get('/', function(req, res) {
  res.send('You got it.');
});

app.post('/', function(req, res) {
  var payload = {
    channel: "#hackers",
    username: "Doom Guy",
    text: "Test Post",
    icon_emoji: ":godmode:"
  };

  var type = req.query.type;

  switch(type) {
    case 'boxerror':
      payload.text = 'Alert from Loggly: Box Error';
      break;
    case 'elevatedclientalerts':
      payload.text = 'Alert from Loggly: Elevated Client Alerts';
      break;
    case 'elevatedserveralerts':
      payload.text = 'Alert from Loggly: Elevated Server Alerts';
      break;
    case 'jobfailed':
      payload.text = 'Alert from Loggly: Job Failed';
      break;
    case 'memoryquotaexceeded':
      payload.text = 'Alert from Loggly: Memory Quota Exceeded';
      break;
    case 'requesttimeouts':
      payload.text = 'Alert from Loggly: Request Timeouts';
      break;
    case 'slowrequests':
      payload.text = 'Alert from Loggly: Slow Requests';
      break;
    default:
      break;
  }
  console.log('website', process.env.WEBSITE)
  console.log('payload', payload)
  request({
    url: process.env.WEBSITE,
    method: 'POST',
    body: JSON.stringify(payload)
  }, function() {
    res.sendStatus(201);
  });
});

var server = app.listen(app.get('port'));
<|endoftext|>