try {
  module.exports = require('./build/Release/node_sleep.node');
} catch (e) {
  console.log('sleep: using busy loop fallback');

  module.exports = {
    sleep: function(s) {
      var e = new Date().getTime() + (s * 1000);

      while (new Date().getTime() <= e) {
        ;
      }
    },

    usleep: function(s) {
      var e = new Date().getTime() + (s / 1000);

      while (new Date().getTime() <= e) {
        ;
      }
    }
  };
}

try {
  module.exports = require('./build/Release/node_sleep.node');
} catch (e) {
  console.error('sleep: using busy loop fallback');

  module.exports = {
    sleep: function(s) {
      var e = new Date().getTime() + (s * 1000);

      while (new Date().getTime() <= e) {
        ;
      }
    },

    usleep: function(s) {
      var e = new Date().getTime() + (s / 1000);

      while (new Date().getTime() <= e) {
        ;
      }
    }
  };
}

Print fallback warning to stderr rather than stdout


'use strict';

/**
 * Export all prototypes.
 * (C) 2013 Alex Fernández.
 */

// requires
require('./lib/string.js');
require('./lib/array.js');
var mathLib = require('./lib/math.js');
var objectLib = require('./lib/object.js');

// exports
exports.overwriteWith(objectLib);
exports.overwriteWith(mathLib);

'use strict';

/**
 * Export all prototypes.
 * (C) 2013 Alex Fernández.
 */

// requires
require('./lib/string.js');
require('./lib/array.js');
var mathLib = require('./lib/math.js');
var objectLib = require('./lib/object.js');

// exports
exports={...objectLib, ...mathLib }

Fix jest error: undefined overwriteWith().


/* jshint node: true */
'use strict';

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

  included: function(app) {
    this._super.included(app);

    app.import({
      development: app.bowerDirectory + '/nouislider/distribute/nouislider.js',
      production:  app.bowerDirectory + '/nouislider/distribute/nouislider.min.js'
    });
    app.import(app.bowerDirectory + '/nouislider/distribute/nouislider.min.css');

    app.import('vendor/nouislider/shim.js', {
      exports: { 'noUiSlider': ['default'] }
    });
  }
};

/* jshint node: true */
'use strict';

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

  included: function(app) {
    this._super.included(app);
    if(!process.env.EMBER_CLI_FASTBOOT) {
      app.import({
        development: app.bowerDirectory + '/nouislider/distribute/nouislider.js',
        production:  app.bowerDirectory + '/nouislider/distribute/nouislider.min.js'
      });
      app.import(app.bowerDirectory + '/nouislider/distribute/nouislider.min.css');

      app.import('vendor/nouislider/shim.js', {
        exports: { 'noUiSlider': ['default'] }
      });
    }
  }
};

Put fastboot guard into correct file


// dependencies
var jipics  = "http://jipics.net/"
  , Request = require("request")
  , fs      = require("fs")
  ;

/**
 *  Upload method
 *
 *  Arguments
 *    @options: a string representing the image path or an
 *    object contanining the following fields:
 *      - path: the path to the image
 *      - deleteAfterUpload: if true, the image will be deleted after a sucessful upload
 *
 * */
exports.upload = function (options, callback) {

    // get the image from the request
    if (typeof options === "string") {
        options = {
            path: options
        }
    }

    // force options to be an object
    options = Object (options);

    // validate path
    if (!options.path) {
        return callback ("The path to the image must be provided.");
    }

    // upload the image to jipics.net
    Request.post(jipics, function (err, res) {

        // handle error
        if (err) { return callback (err); }

        // delete image
        if (options.deleteAfterUpload) {
            return fs.unlink(absoluteImagePath, callback);
        }

        callback (null, res);
    // create the read stream from image file
    }).form().append("image", fs.createReadStream(absoluteImagePath));
};

// dependencies
var jipics  = "http://jipics.net/"
  , Request = require("request")
  , fs      = require("fs")
  ;

/**
 *  Upload method
 *
 *  Arguments
 *    @options: a string representing the image path or an
 *    object contanining the following fields:
 *      - path: the path to the image
 *      - deleteAfterUpload: if true, the image will be deleted after a sucessful upload
 *
 * */
exports.upload = function (options, callback) {

    // get the image from the request
    if (typeof options === "string") {
        options = {
            path: options
        }
    }

    // force options to be an object
    options = Object (options);

    // validate path
    if (!options.path) {
        return callback ("The path to the image must be provided.");
    }

    // upload the image to jipics.net
    Request.post(jipics, function (err, res) {

        // handle error
        if (err) { return callback (err); }

        // delete image
        if (options.deleteAfterUpload) {
            return fs.unlink(absoluteImagePath, callback);
        }

        callback (null, res);
    // create the read stream from image file
    }).form().append("image", fs.createReadStream(options.path));
};

Use options.path instead of absoluteImagePath


/* jshint esnext: true, node: true */
'use strict';

var rollbar = require('rollbar');
var log = require('loglevel');

rollbar.init(process.env.ROLLBAR_TOKEN, {environment: process.env.ROLLBAR_ENVIRONMENT});

exports.rejectHandler = function (err) {
  rollbar.handleError(err);
  log.error(err);
  log.error(err.message);
  log.error(err.stack);
  log.error("Aborting run.");
  process.exit(1);
};

/* jshint esnext: true, node: true */
'use strict';

var rollbar = require('rollbar');
var log = require('loglevel');
var moment = require('moment');

rollbar.init(process.env.ROLLBAR_TOKEN, {environment: process.env.ROLLBAR_ENVIRONMENT});

exports.rejectHandler = function (err) {
  rollbar.handleError(err);
  log.error(err);
  log.error(err.message);
  log.error(err.stack);
  log.error("Aborting run.");
  process.exit(1);
};

exports.runCompleteHandler = function(startTime, exitCode) {
  let durationString = moment.utc(moment.utc() - startTime).format("HH:mm:ss.SSS");
  log.info(`Run complete. Took ${durationString}`);
  process.exit(exitCode || 0);
};

Add common handler for run completion messages


const Assert = require('assert')
const Child = require('child_process')
const Fs = require('fs')
const Path = require('path')

const packagePath = Path.join(process.cwd(), 'package.json')

let keys = []
let out = {}

module.exports = (options, done) => {
  if (typeof options === 'function') {
    done = options
    options = {}
  }

  Assert.equal(typeof options, 'object', 'Options must be an object')
  Assert.equal(typeof done, 'function', 'Must pass in a callback function')

  options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options)
  keys = Object.keys(options)

  Fs.readFile(packagePath, 'utf8', (err, packageJson) => {
    if (err) return done(err)

    packageJson = JSON.parse(packageJson)
    out = {
      name: packageJson.name,
      version: packageJson.version,
      env: process.env.NODE_ENV
    }

    return execute(options, done)
  })
}

const execute = (options, done) => {
  var key = keys.shift()

  if (!key) return done(null, out)

  Child.exec(options[key], function (err, stdout) {
    out[key] = err ? err.toString() : stdout.replace(/\n/g, '')
    return execute(options, done)
  })
}

const Assert = require('assert')
const Child = require('child_process')
const Fs = require('fs')
const Path = require('path')

let keys = []
let out = {}

module.exports = (options, done) => {
  if (typeof options === 'function') {
    done = options
    options = {}
  }

  Assert.equal(typeof options, 'object', 'Options must be an object')
  Assert.equal(typeof done, 'function', 'Must pass in a callback function')

  options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options)
  keys = Object.keys(options)

  out = { env: process.env.NODE_ENV }

  packageDetails((err, data) => {
    if (err) return done(err)

    Object.assign(out, data)

    return execute(options, done)
  })
}

const packageDetails = (done) => {
  const packagePath = Path.join(process.cwd(), 'package.json')

  Fs.readFile(packagePath, 'utf8', (err, data) => {
    if (err) return done(err)

    const { name, version } = JSON.parse(data)

    done(null, { name, version })
  })
}

const execute = (options, done) => {
  var key = keys.shift()

  if (!key) return done(null, out)

  Child.exec(options[key], function (err, stdout) {
    out[key] = err ? err.toString() : stdout.replace(/\n/g, '')
    return execute(options, done)
  })
}

Move package details to more function


/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-keyboard-shortcuts',

  included: function(app, parentAddon) {
    let target = (parentAddon || app);
    target.import(app.bowerDirectory + '/mousetrap/mousetrap.js');

    target.import(
      app.bowerDirectory +
      '/mousetrap/plugins/global-bind/mousetrap-global-bind.js'
    );
  }
};

/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-keyboard-shortcuts',

  included: function(app, parentAddon) {
    let target = (parentAddon || app);
    target.import(app.bowerDirectory + '/mousetrap/mousetrap.js');
  }
};

Remove import of mousetrap global plugin


const express = require('express');
const helmet = require('helmet');
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');

var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;

server.use(bodyParser.json());
server.use(helmet());
server.use('/', router);

function _get() {
  return server;
}

function run(fn) {

  fn = fn || function _defaultStart() {
    winston.info('Listening at ' + PORT);
  };

  return server.listen(PORT, fn);
}

if (require.main === module) {
  run();
}

module.exports = {
  _get: _get,
  run: run
};

const express = require('express');
const helmet = require('helmet');
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');
const q = require('q');
var mongoose = require('mongoose');

var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;

// Built-in Promise support is deprecated
mongoose.Promise = q.Promise;

server.use(bodyParser.json());
server.use(helmet());
server.use('/', router);

function _get() {
  return server;
}

function run(fn) {

  fn = fn || function _defaultStart() {
    winston.info('Listening at ' + PORT);
  };

  return server.listen(PORT, fn);
}

if (require.main === module) {
  run();
}

module.exports = {
  _get: _get,
  run: run
};

Replace Mongoose promise support with another Q's


var BufferList = require('bl');
var onFinished = require('on-finished');

module.exports = function bufferResponse(res, cb) {
	var write = res.write;
	var end = res.end;
	var buf = new BufferList();
	res.write = function(data, enc) {
		if (data != undefined) bufferAdd(buf, data, enc)
		write.bind(res)(data, enc);
	};
	res.end = function(data, enc) {
		if (data != undefined) bufferAdd(buf, data, enc)
		end.bind(res)(data, enc);
	};
	onFinished(res, function(err) {
		res.write = write;
		res.end = end;
		var len = parseInt(res.get('Content-Length'));
		if (!isNaN(len)) buf = buf.slice(0, len);
		cb(err, buf);
	});
};

function bufferAdd(buf, data, enc) {
	if (typeof data == "string") buf.append(new Buffer(data, enc));
	else if (data) buf.append(data);
}

var BufferList = require('bl');
var onFinished = require('on-finished');

module.exports = function bufferResponse(res, cb) {
	var write = res.write;
	var end = res.end;
	var buf = new BufferList();
	res.write = function(data, enc) {
		if (data != undefined) bufferAdd(buf, data, enc)
		write.bind(res)(data, enc);
	};
	res.end = function(data, enc) {
		if (data != undefined) bufferAdd(buf, data, enc)
		end.bind(res)(data, enc);
	};
	onFinished(res, function(err) {
		res.write = write;
		res.end = end;
		var len = parseInt(res.get('Content-Length'));
		if (!isNaN(len)) {
			buf = buf.slice(0, len);
		}
		if (!err && res.req.connection.destroyed) {
			res.statusCode = 0;
			buf = null;
		}
		cb(err, buf);
	});
};

function bufferAdd(buf, data, enc) {
	if (typeof data == "string") buf.append(new Buffer(data, enc));
	else if (data) buf.append(data);
}

Return statusCode 0 if request was aborted


(function (module) {
    module.controller("FileEditController", FileEditController);

    FileEditController.$inject = ['file', '$scope'];

    /* @ngInject */
    function FileEditController(file, $scope) {
        console.log('FileEditController');
        var ctrl = this;
        ctrl.file = file;

        $scope.$on('$viewContentLoaded', function(event) {
            console.log('$viewContentLoaded', event);
        });
    }
}(angular.module('materialscommons')));

(function (module) {
    module.controller("FileEditController", FileEditController);

    FileEditController.$inject = ['file'];

    /* @ngInject */
    function FileEditController(file) {
        var ctrl = this;
        ctrl.file = file;
    }
}(angular.module('materialscommons')));

Remove debug of ui router state changes.


import React, {Component} from 'react'

import AlloyEditor from 'alloyeditor/dist/alloy-editor/alloy-editor-no-react'
import 'alloyeditor/dist/alloy-editor/assets/alloy-editor-atlas.css'

AlloyEditor.Selections[3].buttons.splice(4, 2)

const ALLOY_CONFIG = {
	toolbars: {
		styles: { selections: AlloyEditor.Selections },
		add: { buttons: ['ul', 'ol', 'hline', 'table'] },
	}
}

export default class TextEditor extends Component {
	componentWillUnmount() {
		this.editor && this.editor.destroy()
	}

	componentWillReceiveProps(newProps) {
		if (newProps.value != this.container.innerHTML) {
			this.container.innerHTML = newProps.value
		}

		if (newProps.value && !this.editor) {
			this.editor = AlloyEditor.editable(this.container, ALLOY_CONFIG)
			this.editor.get('nativeEditor').on('change', () => {
				this.props.onChange(this.container.innerHTML)
			})
		}
	}

	render() {
		return <div className="text-editor" ref={(el) => { this.container = el }} />
	}
}

import React, {Component} from 'react'

import AlloyEditor from 'alloyeditor/dist/alloy-editor/alloy-editor-no-react'
import 'alloyeditor/dist/alloy-editor/assets/alloy-editor-atlas.css'

// this just removes a number of features we don't want from the Alloy toolbar
AlloyEditor.Selections[3].buttons.splice(4, 2)

const ALLOY_CONFIG = {
	toolbars: {
		styles: { selections: AlloyEditor.Selections },
		add: { buttons: ['ul', 'ol', 'hline', 'table'] },
	}
}

export default class TextEditor extends Component {
	componentDidMount() {
		if (!this.editor) {
			this.editor = AlloyEditor.editable(this.container, ALLOY_CONFIG)
			this.nativeEditor = this.editor.get('nativeEditor')

			this.nativeEditor.on('change', () => {
				this.props.onChange(this.nativeEditor.getData())
			})
		}

		this.componentWillReceiveProps(this.props)
	}

	componentWillUnmount() {
		this.editor && this.editor.destroy()
	}

	componentWillReceiveProps(newProps) {
		let html = newProps.value
		if (html !== this.nativeEditor.getData()) {
			this.nativeEditor.setData(html)
		}
	}

	render() {
		return <div className="text-editor" ref={(el) => { this.container = el }} />
	}
}

Make Alloy initialization work on blank and existing values


var app = angular.module("EAG_Home", ["Controllers"]);

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13 || event.which == 9) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });
                if(event.which != 9)
                  event.preventDefault();
            }
        });
    };
});

Support for enter/tab key to add new property line.


angular.module('proxtop').service('open', ['ipc', 'settings', '$state', function(ipc, settings, $state) {
    const self = this;
    ['Anime', 'Manga'].forEach(function(name) {
        const lower = name.toLowerCase();
        self['open' + name] = function(id, ep, sub) {
            const actualSettings = settings.get(lower);

            // TODO refactor this, this looks hacky
            if(actualSettings && (actualSettings.open_with === 'internal' || (lower === 'anime' && actualSettings.pass_raw_url))) {
                $state.go('watch', {
                    id: id,
                    ep: ep,
                    sub: sub
                });
            } else {
                ipc.send('open', lower, id, ep, sub);
            }
        };
    });

    this.openLink = function(link) {
        ipc.send('open-link', link);
    };
}]);

angular.module('proxtop').service('open', ['ipc', 'settings', '$state', function(ipc, settings, $state) {
    const self = this;
    ['Anime', 'Manga'].forEach(function(name) {
        const lower = name.toLowerCase();
        self['open' + name] = function(id, ep, sub) {
            const actualSettings = settings.get(lower);

            // TODO refactor this, this looks hacky
            if(actualSettings && (actualSettings.open_with === 'internal' || (lower === 'anime' && actualSettings.open_with === 'external' && actualSettings.pass_raw_url))) {
                $state.go('watch', {
                    id: id,
                    ep: ep,
                    sub: sub
                });
            } else {
                ipc.send('open', lower, id, ep, sub);
            }
        };
    });

    this.openLink = function(link) {
        ipc.send('open-link', link);
    };
}]);

Fix not opening watchlist entries in browser


/* global describe, it, before */

var requirejs = require("requirejs");
var assert = require("assert");
var should = require("should");
var jsdom = require('mocha-jsdom');
var skill = require('fs').readFileSync('./test/spec/links_test.json', 'utf8');

requirejs.config({
  baseUrl: 'app/',
  nodeRequire: require
});

describe('Utils', function () {
  var Utils;
  jsdom();
  before(function (done) {
    requirejs(['scripts/Utils'],
      function (Utils_Class) {
        Utils = Utils_Class;
        done();
      });
  });
  var all_skills = JSON.parse(skill);

  describe('D3 Links Test', function () {
    it('should return correct d3 links info', function () {
      Utils.parseDepends(all_skills.skills).toString().should.equal([{source: 1, target: 0}].toString())
    });
  });
});

/* global describe, it, before */

var requirejs = require("requirejs");
var assert = require("assert");
var should = require("should");
var jsdom = require('mocha-jsdom');
var skill = require('fs').readFileSync('./test/spec/links_test.json', 'utf8');

requirejs.config({
  baseUrl: 'app/',
  nodeRequire: require
});

describe('Utils', function () {
  var Utils;
  jsdom();
  before(function (done) {
    requirejs(['scripts/Utils'],
      function (Utils_Class) {
        Utils = Utils_Class;
        done();
      });
  });
  var all_skills = JSON.parse(skill);

  describe('D3 Links Test', function () {
    it('should return correct d3 links info', function () {
      Utils.parseDepends(all_skills.skills).toString().should.equal([{source: 1, target: 0}].toString())
    });
  });
  describe('Get Skill By id', function () {
    it('should return correct skill information by id', function () {
      Utils.getSkillById(all_skills.skills, 1).toString().should.equal({ id: 1, name: 'Web' }.toString())
    });
  });
});

Add test for get skill by id


  google.maps.event.addDomListener(window, 'load', initialize);

  function initialize() {
	  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
	  var mapOptions = {
	    zoom: 4,
	    center: myLatlng,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  }

	  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  }

google.maps.event.addDomListener(window, 'load', initialize);

function initialize() {

	var myLatlng = new google.maps.LatLng(43.663277,-79.396992);
	var bounds = new google.maps.LatLngBounds();
	var mapOptions = {
		zoom: 13,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}

	var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

	//TODO: replace mock data with API call
	var buildingList = [
	{
		"lat" 	: 43.667576,
		"lng" 	: -79.391868,
		"id"  	: "1",
		"title" : "building1"
	},
	{
		"lat" 	: 43.663991,
		"lng"	: -79.398580,
		"id"  	: "2",
		"title" : "building2"
	},
	{
		"lat"	: 43.651230,
		"lng" 	: -79.409866,
		"id"  	: "3",
		"title" : "building3"
	},
	{
		"lat" 	: 43.665326,
		"lng" 	: -79.411154,
		"id"  	: "4",
		"title" : "building4"
	},
	{
		"lat"	: 43.775326,
		"lng" 	: -79.411154,
		"id"  	: "5",
		"title" : "building5"
	}
	];

	$.each(buildingList, function(index, value) {
		var latLong = new google.maps.LatLng(value.lat, value.lng);
		bounds.extend(latLong);
		new google.maps.Marker({
			position: latLong,
			map: map,
			title: value.title
		});
	});
	map.fitBounds(bounds);
	map.panToBounds(bounds);
}

Add markers with mock data to the map on home page


"use strict";
const RequestResults = require("../constants/RequestResults");
const Utils = require("../utils/Utils");

let _token = null;
let _requester = null;

module.exports = {

    initialize: function(token, requester) {
        Utils.assertValidToken(token);
        Utils.assertValidRequester(requester);
        _token = token;
        _requester = requester;
    },

    query: function(projectId, callback, opts = {}) {
        Utils.assertValidToken(_token);
        let endpoint = "/namespaces/";
        const context = {
            projectId: projectId,
            options: opts
        };

        const req = _requester.getRequest(URL, _token);
        if (opts.name) {
            req.query({name: opts.name});
        } else if (opts.namespaceID) {
            endpoint = endpoint + opts.namespaceID;
        }
        const URL = _requester.getFullEndpoint(endpoint);

        const bodyHandler = function(resp, body, status) {
            if (status === RequestResults.SUCCESS) {
                resp.body = body;
            } else if (body && body.errors) {
                resp.error = body.errors[0].message;
            }
        };
        const innerCb = Utils.createInnerCb(callback, context, bodyHandler);
        _requester.execute(req, innerCb);
    }
};

"use strict";
const RequestResults = require("../constants/RequestResults");
const Utils = require("../utils/Utils");

let _token = null;
let _requester = null;

module.exports = {

    initialize: function(token, requester) {
        Utils.assertValidToken(token);
        Utils.assertValidRequester(requester);
        _token = token;
        _requester = requester;
    },

    query: function(projectId, callback, opts = {}) {
        Utils.assertValidToken(_token);
        let endpoint = "/namespaces/";
        const context = {
            projectId: projectId,
            options: opts
        };
        const URL = _requester.getFullEndpoint(endpoint);

        const req = _requester.getRequest(URL, _token);
        if (opts.name) {
            req.query({name: opts.name});
        } else if (opts.namespaceID) {
            endpoint = endpoint + opts.namespaceID;
        }

        const bodyHandler = function(resp, body, status) {
            if (status === RequestResults.SUCCESS) {
                resp.body = body;
            } else if (body && body.errors) {
                resp.error = body.errors[0].message;
            }
        };
        const innerCb = Utils.createInnerCb(callback, context, bodyHandler);
        _requester.execute(req, innerCb);
    }
};

Fix location of URL definition


// Rules from eslint-plugin-html
module.exports = {
    "plugins": ["html"],
    "settings": {
        "html": {
            // "html-extensions": [],
            // "xml-extensions": [],
            "indent": "+4",
            "report-bad-indent": 1
            // "javascript-mime-types": []
        }
    }
};

// Rules from eslint-plugin-html
module.exports = {
    "plugins": ["html"],
    "settings": {
        // Consider files ending with these extensions as HTML
        // "html/html-extensions": [],
        // Consider files ending with these extensions as XML
        // "html/xml-extensions": [],
        // Ensure that every script tags follow an uniform indentation
        "html/indent": "+4",
        // By default, this plugin won't warn if it encounters a problematic indentation, use in conjunction with the indent rule
        "html/report-bad-indent": 1
        // Customize the types that should be considered as JavaScript by providing one or multiple MIME types. If a MIME type starts with a /, it will be considered as RegExp
        // "html/javascript-mime-types": []
    }
};

Add doc comments for HTML rules


import extract from 'flarum/common/utils/extract';
import username from 'flarum/common/helpers/username';
import User from 'flarum/common/models/User';
import Group from 'flarum/common/models/Group';
import LinkButton from 'flarum/common/components/LinkButton';

export default function recipientLabel(recipient, attrs = {}) {
    attrs.style = attrs.style || {};
    attrs.className = 'RecipientLabel ' + (attrs.className || '');
    attrs.href = extract(attrs, 'link');

    let label;

    if (recipient instanceof User) {
        label = username(recipient);

        if (attrs.href) {
            attrs.title = recipient.username() || '';
            attrs.href = app.route.user(recipient);
        }
    } else if (recipient instanceof Group) {
        label = recipient.namePlural();
    } else {
        attrs.className += ' none';
        label = app.translator.trans('fof-byobu.forum.labels.user_deleted');
    }

    return LinkButton.component(attrs, label);
}

import extract from 'flarum/common/utils/extract';
import username from 'flarum/common/helpers/username';
import User from 'flarum/common/models/User';
import Group from 'flarum/common/models/Group';
import LinkButton from 'flarum/common/components/LinkButton';

export default function recipientLabel(recipient, attrs = {}) {
    attrs.style = attrs.style || {};
    attrs.className = 'RecipientLabel ' + (attrs.className || '');
    attrs.href = extract(attrs, 'link');

    let label;

    if (recipient instanceof User) {
        label = username(recipient);

        if (attrs.href) {
            attrs.title = recipient.username() || '';
            attrs.href = app.route.user(recipient);
        }
    } else if (recipient instanceof Group) {
        return {recipient.namePlural()}
    } else {
        attrs.className += ' none';
        label = app.translator.trans('fof-byobu.forum.labels.user_deleted');
    }

    return LinkButton.component(attrs, label);
}

Address group recipient link issue


Template.postsList.helpers({
  posts: function() {
    return Posts.find();
  }
});

Template.postsList.helpers({
  posts: function() {
    return Posts.find({}, {sort: {submitted: -1}});
  }
});

Sort posts by submitted timestamp.


/**
 * Load all external dependencies
 * We use var so it's global available : ) ( not let,const)
 */
var fs      = require('fs');
var _ = require('lodash');

/**
 * Load all internal dependencies
 */
const cfg     = require('../config.js');
var pkg     = require('../package.json');
var piJS     = require('./modules/pi-js-module');

let pi = new piJS(cfg);

var io = require('socket.io')(9090);

io.on('connection', function(socket) {
  console.info('socket connected. (' + socket.id + ')');

  socket.on('forward', function() {
    pi.handleAnswer('move forward');
    socket.emit('forward');
    console.info('forward');
  });

  socket.on('backward', function() {
    pi.handleAnswer('move backward');
    socket.emit('backward');
    console.info('backward');
  });

  socket.on('left', function() {
    pi.handleAnswer('move left');
    socket.emit('left');
    console.info('left');
  });

  socket.on('right', function() {
    pi.handleAnswer('move right');
    socket.emit('right');
    console.info('right');
  });

  socket.on('stop', function() {
    pi.handleAnswer('move stop');
    socket.emit('stop');
    console.info('stop');
  });
});

/**
 * Load all external dependencies
 * We use var so it's global available : ) ( not let,const)
 */
var fs      = require('fs');
var _ = require('lodash');

/**
 * Load all internal dependencies
 */
const cfg     = require('../config.js');
var pkg     = require('../package.json');
var piJS     = require('./modules/pi-js-module');

let pi = new piJS(cfg);

var io = require('socket.io')(9090);

io.on('connection', function(socket) {
  console.info('socket connected. (' + socket.id + ')');

  socket.on('forward', function() {
    pi.handleAnswer('move forward');
    socket.emit('forward');
    console.info('forward');
  });

  socket.on('backward', function() {
    pi.handleAnswer('move backward');
    socket.emit('backward');
    console.info('backward');
  });

  socket.on('left', function() {
    pi.handleAnswer('move left');
    socket.emit('left');
    console.info('left');
  });

  socket.on('right', function() {
    pi.handleAnswer('move right');
    socket.emit('right');
    console.info('right');
  });

  socket.on('stop', function() {
    pi.handleAnswer('stop');
    socket.emit('stop');
    console.info('stop');
  });
});

Stop is not called "move stop". Woops.


var fs = require('fs');
var path = require('path');
var xec = require('xbmc-event-client');

var keyboard = require('./lib/keyboard');

var kodikeys = function(opt) {

  var defaults = {
    port: 9777
  }
  opt = Object.assign({}, defaults, opt);

  var kodi = new xec.XBMCEventClient('kodikeys', opt)

  kodi.connect(function(errors, bytes) {
    if (errors.length) {
      console.error(`Connection failed to Kodi on $(opt.host), port ${opt.port}`)
      console.error(errors[0].toString());
      process.exit(1);
    }

    // init keyboard interactivity
    keyboard.init(kodi);

    console.log(`connected to ${opt.host} port ${opt.port}`);
  });
}

module.exports = kodikeys;

var fs = require('fs');
var path = require('path');
var xec = require('xbmc-event-client');

var keyboard = require('./lib/keyboard');

var kodikeys = function(opt) {

  var defaults = {
    port: 9777
  }
  opt = Object.assign({}, defaults, opt);

  var kodi = new xec.XBMCEventClient('kodikeys', opt)

  kodi.connect(function(errors, bytes) {
    if (errors.length) {
      console.error(`Connection failed to Kodi on $(opt.host), port ${opt.port}`)
      console.error(errors[0].toString());
      process.exit(1);
    }

    // init keyboard interactivity
    keyboard.init(kodi);

    // ping to keep connection  alive
    setInterval(kodi.ping.bind(kodi), 55 * 1000);

    console.log(`connected to ${opt.host} port ${opt.port}`);
  });
}

module.exports = kodikeys;

Add ping to keep connection alive


'use strict'

const ExtDate = require('./src/date')
const Bitmask = require('./src/bitmask')

const { parse } = require('./src/parser')

const types = [
  'Date', 'Year', 'Season', 'Interval', 'Set', 'List', 'Century', 'Decade'
]

function edtf(...args) {
  const res = parse(...args)
  return new ExtDate(res)
  //return new this[res.type](res)
}

module.exports = Object.assign(edtf, {
  Date: ExtDate,
  Bitmask,
  parse,
  types
})

'use strict'

const ExtDate = require('./src/date')
const Bitmask = require('./src/bitmask')

const { parse } = require('./src/parser')

const types = [
  'Date', 'Year', 'Season', 'Interval', 'Set', 'List', 'Century', 'Decade'
]

function edtf(...args) {
  if (!args.length) return new ExtDate()

  const res = parse(...args)
  return new ExtDate(res)
  //return new this[res.type](res)
}

module.exports = Object.assign(edtf, {
  Date: ExtDate,
  Bitmask,
  parse,
  types
})

Return new date by default


'use strict';

/**
 * Dependencies.
 */

var phonetics;

phonetics = require('double-metaphone');

/**
 * Define `doubleMetaphone`.
 */

function doubleMetaphone() {}

/**
 * Change handler.
 *
 * @this {WordNode}
 */

function onchange() {
    var data,
        value;

    data = this.data;
    value = this.toString();

    data.phonetics = value ? phonetics(value) : null;

    if ('stem' in data) {
        data.stemmedPhonetics = value ? phonetics(data.stem) : null;
    }
}

/**
 * Define `attach`.
 *
 * @param {Retext} retext
 */

function attach(retext) {
    var WordNode = retext.TextOM.WordNode;

    WordNode.on('changetextinside', onchange);
    WordNode.on('removeinside', onchange);
    WordNode.on('insertinside', onchange);
}

/**
 * Expose `attach`.
 */

doubleMetaphone.attach = attach;

/**
 * Expose `doubleMetaphone`.
 */

module.exports = doubleMetaphone;

'use strict';

/**
 * Dependencies.
 */

var phonetics;

phonetics = require('double-metaphone');

/**
 * Change handler.
 *
 * @this {WordNode}
 */

function onchange() {
    var data,
        value;

    data = this.data;
    value = this.toString();

    data.phonetics = value ? phonetics(value) : null;

    if ('stem' in data) {
        data.stemmedPhonetics = value ? phonetics(data.stem) : null;
    }
}

/**
 * Define `doubleMetaphone`.
 *
 * @param {Retext} retext
 */

function doubleMetaphone(retext) {
    var WordNode = retext.TextOM.WordNode;

    WordNode.on('changetextinside', onchange);
    WordNode.on('removeinside', onchange);
    WordNode.on('insertinside', onchange);
}

/**
 * Expose `doubleMetaphone`.
 */

module.exports = doubleMetaphone;

Refactor for changes in retext


var actionpack = {
  Action: require('./lib/action'),
  Route: require('./lib/route')
};

module.exports = actionpack;

var actionpack = {
  Action: require(__dirname + '/lib/action'),
  Route: require(__dirname + '/lib/route')
};

module.exports = actionpack;

Fix lib file reference in main actionpack file


'use strict'

var toArray = require('stream-to-array')
var Promise = require('bluebird')

module.exports = streamToPromise

function streamToPromise (stream) {
  if (stream.readable) return fromReadable(stream)
  if (stream.writable) return fromWritable(stream)
  return Promise.resolve()
}

function fromReadable (stream) {
  var promise = toArray(stream)

  // Ensure stream is in flowing mode
  stream.resume()

  return promise
    .then(function concat (parts) {
      return Buffer.concat(parts.map(bufferize))
    })
}

function fromWritable (stream) {
  return new Promise(function (resolve, reject) {
    stream.once('finish', resolve)
    stream.once('error', reject)
  })
}

function bufferize (chunk) {
  return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk)
}

'use strict'

var toArray = require('stream-to-array')
var Promise = require('bluebird')

module.exports = streamToPromise

function streamToPromise (stream) {
  if (stream.readable) return fromReadable(stream)
  if (stream.writable) return fromWritable(stream)
  return Promise.resolve()
}

function fromReadable (stream) {
  var promise = toArray(stream)

  // Ensure stream is in flowing mode
  if (stream.resume) stream.resume()

  return promise
    .then(function concat (parts) {
      return Buffer.concat(parts.map(bufferize))
    })
}

function fromWritable (stream) {
  return new Promise(function (resolve, reject) {
    stream.once('finish', resolve)
    stream.once('error', reject)
  })
}

function bufferize (chunk) {
  return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk)
}

Handle streams without a resume method


var path = require('path'),
    fs = require('fs');

function AssetManifestPlugin(output, keyRoot) {
  this.output = output;
  this.keyRoot = keyRoot;
}

AssetManifestPlugin.prototype.apply = function(compiler) {
  var assets = {},
      output  = this.output,
      keyRoot = this.keyRoot;

  var outputPath = compiler.options.output.path,
      publicPath = compiler.options.output.publicPath;

  function publicRelative(url) {
    return path.join(publicPath, url.replace(outputPath, ''));
  }

  function removeLeadSlash(path) {
    if(path[0] === '/') {
      return path.slice(1);
    }

    return path;
  }

  function formatKey(path) {
    var keyRootPath = path.replace(keyRoot, '');
    return removeLeadSlash(keyRootPath);
  }

  compiler.plugin('compilation', function(compilation) {
    compilation.plugin('module-asset', function(module, file) {
      assets[formatKey(module.userRequest)] = publicRelative(file);
    });
  });

  compiler.plugin('done', function() {
    fs.writeFileSync(output, JSON.stringify(assets, null, 2));
  });
};

module.exports = AssetManifestPlugin;

var path = require('path'),
    fs = require('fs');

function AssetManifestPlugin(output) {
  this.output = output;
}

AssetManifestPlugin.prototype.apply = function(compiler) {
  var assets = {},
      output  = this.output;

  var outputPath = compiler.options.output.path,
      publicPath = compiler.options.output.publicPath;

  function publicRelative(url) {
    return path.join(publicPath, url.replace(outputPath, ''));
  }

  function keyForModule(module) {
    return Object.keys(module.assets)[0];
  }

  compiler.plugin('compilation', function(compilation) {
    compilation.plugin('module-asset', function(module, file) {
      assets[keyForModule(module)] = publicRelative(file);
    });
  });

  compiler.plugin('done', function() {
    fs.writeFileSync(output, JSON.stringify(assets, null, 2));
  });
};

module.exports = AssetManifestPlugin;

Use Assets key as Manifest Key Instead


/*!
 * docdown v0.3.0
 * Copyright 2011-2016 John-David Dalton <http://allyoucanleet.com/>
 * Available under MIT license <http://mths.be/mit>
 */
'use strict';

var _ = require('lodash'),
    fs = require('fs'),
    path = require('path'),
    generator = require('./lib/generator.js');

/**
 * Generates Markdown documentation based on JSDoc comments.
 *
 * @name docdown
 * @param options The options to use to generate documentation.
 * @returns {string} The generated Markdown code.
 */
function docdown(options) {
  options = _.defaults(options, {
    'hash': 'default',
    'lang': 'js',
    'sort': true,
    'title': path.basename(options.path) + ' API documentation',
    'toc': 'properties'
  });

  if (!options.path || !options.url) {
    throw new Error('Path and URL must be specified');
  }
  return generator(fs.readFileSync(options.path, 'utf8'), options);
}

module.exports = docdown;

/*!
 * docdown v0.3.0
 * Copyright 2011-2016 John-David Dalton <http://allyoucanleet.com/>
 * Available under MIT license <https://mths.be/mit>
 */
'use strict';

var _ = require('lodash'),
    fs = require('fs'),
    path = require('path'),
    generator = require('./lib/generator.js');

/**
 * Generates Markdown documentation based on JSDoc comments.
 *
 * @name docdown
 * @param options The options to use to generate documentation.
 * @returns {string} The generated Markdown code.
 */
function docdown(options) {
  options = _.defaults(options, {
    'hash': 'default',
    'lang': 'js',
    'sort': true,
    'title': path.basename(options.path) + ' API documentation',
    'toc': 'properties'
  });

  if (!options.path || !options.url) {
    throw new Error('Path and URL must be specified');
  }
  return generator(fs.readFileSync(options.path, 'utf8'), options);
}

module.exports = docdown;

Use https for license link.


'use strict';

/**
 * @description
 * A tool that downloads a given number of pug images to the directory where it is run.
 *
 * @example
 * node pugbalm 5 // download 5 pugs
 */

var request = require('request'),
    _ = require('lodash'),
    apiKey = 'dc6zaTOxFJmzC',
    params;

/*
 * @jsdoc function
 * @name serializeParams
 * @param {object}
 * Object containing request parameters.
 * @returns {string}
 * Accepts a params object and returns a serialized string to be appended to a base URL.
 */

params = {
    q: 'pugs',
    api_key: apiKey,
};

function serializeParams(params) {

    return _.reduce(params, function(result, n, key) {

        return result + key + n;

    },'');

}

console.log(serializeParams(params));

'use strict';

/**
 * @description
 * A tool that downloads a given number of pug images to the directory where it is run.
 *
 * @example
 * node pugbalm 5 // download 5 pugs
 */

var request = require('request'),
    _ = require('lodash'),
    baseUrl = 'http://api.giphy.com/v1/gifs/search',
    apiKey = 'dc6zaTOxFJmzC',
    params;

/*
 * @jsdoc function
 * @name serializeParams
 * @param {object}
 * Object containing request parameters.
 * @returns {string}
 * Accepts a params object and returns a serialized string to be appended to a base URL.
 */

params = {
    q: 'pugs',
    api_key: apiKey,
};

function serializeParams(params) {

    var first = true;

    return _.reduce(params, function(result, n, key) {

        if (first) {
            first = false;
            return result + '?' + key + '=' + n;
        } else {
            return result + '&' + key + '=' + n;
        }

    },'');

}

request(baseUrl + serializeParams(params), function(error, response, body) {

    if (!error && response.statusCode === 200) {

        debugger;

    }
});

Use request library to hit the giphy api, passing serialized params object.


'use strict'

const markdownIt = require('markdown-it')

exports.name = 'markdown-it'
exports.outputFormat = 'html'
exports.inputFormats = ['markdown-it', 'markdown', 'md']

exports.render = function (str, options) {
  options = Object.assign({}, options || {})

  // Copy render rules from options, and remove them from options, since
  // they're invalid.
  var renderRules = Object.assign({}, options.renderRules || {})
  delete options.renderRules

  var md = markdownIt(options)

  // Enable render rules.
  Object.assign(md.renderer.rules, renderRules);

  // Parse the plugins.
  (options.plugins || []).forEach(plugin => {
    if (!Array.isArray(plugin)) {
      plugin = [plugin]
    }

    if (typeof plugin[0] === 'string') {
      // eslint-disable-next-line import/no-dynamic-require
      plugin[0] = require(plugin[0])
    }

    md.use.apply(md, plugin)
  });

  // Parse enable/disable rules.
  (options.enable || []).forEach(rule => {
    md.enable.apply(md, Array.isArray(rule) ? rule : [rule])
  });

  (options.disable || []).forEach(rule => {
    md.disable.apply(md, Array.isArray(rule) ? rule : [rule])
  })

  // Render the markdown.
  if (options.inline) {
    return md.renderInline(str)
  }
  return md.render(str)
}

'use strict'

const markdownIt = require('markdown-it')

exports.name = 'markdown-it'
exports.outputFormat = 'html'
exports.inputFormats = ['markdown-it', 'markdown', 'md']

exports.render = function (str, options) {
  options = Object.assign({}, options || {})

  // Copy render rules from options, and remove them from options, since
  // they're invalid.
  let renderRules = Object.assign({}, options.renderRules || {})
  delete options.renderRules

  const md = markdownIt(options)

  // Enable render rules.
  Object.assign(md.renderer.rules, renderRules);

  // Parse the plugins.
  (options.plugins || []).forEach(plugin => {
    if (!Array.isArray(plugin)) {
      plugin = [plugin]
    }

    if (typeof plugin[0] === 'string') {
      // eslint-disable-next-line import/no-dynamic-require
      plugin[0] = require(plugin[0])
    }

    md.use.apply(md, plugin)
  });

  // Parse enable/disable rules.
  (options.enable || []).forEach(rule => {
    md.enable.apply(md, Array.isArray(rule) ? rule : [rule])
  });

  (options.disable || []).forEach(rule => {
    md.disable.apply(md, Array.isArray(rule) ? rule : [rule])
  })

  // Render the markdown.
  if (options.inline) {
    return md.renderInline(str)
  }
  return md.render(str)
}

Fix unexpected var, use let or const instead


'use strict';

var path = require('path');

module.exports = class BowerResolvePlugin {
    constructor(options) {
        this.options = options;
    }

    apply(resolver) {
        resolver.plugin('existing-directory', function (request, callback) {
            if (request.path !== request.descriptionFileRoot) {
                return callback();
            }

            var mainModule = null;

            if (request.descriptionFilePath.endsWith('bower.json')) {
                var source = request.descriptionFileData;
                var modules = typeof source['main'] == 'string'
                    ? [source['main']]
                    : source['main'];

                mainModule = modules.find(module => { return module.endsWith('.js') });
            }

            if (! mainModule) {
                return callback();
            }

            var obj = Object.assign({}, request, {
                path: path.resolve(request.path, mainModule)
            });

            return resolver.doResolve('undescribed-raw-file', obj, 'using path: ' + mainModule, callback);
        });
    }
}

Make it work for node <= 5


var path = require('path')
var meta = require(path.join(__dirname, 'lib', 'meta.js'))

module.exports = Dat

// new Dat(cb)
// new Dat({foo: bar})
// new Dat({foo: bar}, cb)
// new Dat('./foo)
// new Dat('./foo', cb)
// new Dat('./foo', {foo: bar})
// new Dat('./foo', {foo: bar}, cb)

function Dat(dir, opts, onReady) {
  var self = this

  // if 'new' was not used
  if (!(this instanceof Dat)) return new Dat(dir, opts)

  if (typeof dir === 'function') {
    onReady = dir
    opts = {}
    dir = process.cwd()
  }

  if (typeof opts === 'function') {
    onReady = opts
    opts = {}
  }

  if (typeof dir === 'object') {
    onReady = opts
    opts = dir
    dir = process.cwd()
  }

  if (!onReady) onReady = function(){}

  this.dir = dir
  this.opts = opts

  this.meta = meta(this.dir, function(err) {
    if (err) return onReady()
    self._storage(opts, onReady)
  })
}

Dat.prototype = require(path.join(__dirname, 'lib', 'commands'))

var path = require('path')
var meta = require(path.join(__dirname, 'lib', 'meta.js'))
var commands = require(path.join(__dirname, 'lib', 'commands'))

module.exports = Dat

// new Dat(cb)
// new Dat({foo: bar})
// new Dat({foo: bar}, cb)
// new Dat('./foo)
// new Dat('./foo', cb)
// new Dat('./foo', {foo: bar})
// new Dat('./foo', {foo: bar}, cb)

function Dat(dir, opts, onReady) {
  var self = this

  // if 'new' was not used
  if (!(this instanceof Dat)) return new Dat(dir, opts)

  if (typeof dir === 'function') {
    onReady = dir
    opts = {}
    dir = process.cwd()
  }

  if (typeof opts === 'function') {
    onReady = opts
    opts = {}
  }

  if (typeof dir === 'object') {
    onReady = opts
    opts = dir
    dir = process.cwd()
  }

  if (!onReady) onReady = function(){}

  this.dir = dir
  this.opts = opts

  this.meta = meta(this.dir, function(err) {
    if (err) return onReady()
    commands._ensureExists(opts, function (err) {
      if (err) {
        console.error(err)
        process.exit(1)
      }

      self._storage(opts, onReady)
    })
  })
}

Dat.prototype = commands

Handle case where package.json exists but not .dat


var models = require('./lib/models');
var config = require('./config/gateway.config');
var dirty = require('dirty');
var db = dirty(config.datasource || './data/messages.db');

var storedMessages = new models.Messages();

db.on('load', function() {
	storedMessages = new models.Messages(db.get('messages') || []);
});

var Reader = module.exports.reader = {

	readMessages: function (callback) {
        if (storedMessages) {
            callback(storedMessages);
        } else {
            db.on('load', function() {
                storedMessages = new models.Messages(db.get('messages') || []);
                callback(storedMessages);
            });
        }
	},

	registerCommand: function (command, callback) {
		db.on('load', function() {
			var listener = db.get("listener");
			listener.push( command );
			db.set("listener", listener, function listenerSaved (){
				if (callback) {
					callback();
				}
			});
		});
	}

};

var models = require('./lib/models');
var config = require('./config/gateway.config');
var dirty = require('dirty');
var db = dirty(config.datasource || './data/messages.db');
var sms = require('./lib/sms');

var storedMessages = new models.Messages();

db.on('load', function() {
	storedMessages = new models.Messages(db.get('messages') || []);
});

var Reader = module.exports.reader = {

	readMessages: function (callback) {
        if (storedMessages) {
            callback(storedMessages);
        } else {
            db.on('load', function() {
                storedMessages = new models.Messages(db.get('messages') || []);
                callback(storedMessages);
            });
        }
	},

	registerCommand: function (command, callback) {
		db.on('load', function() {
			var listener = db.get("listener");
			listener.push( command );
			db.set("listener", listener, function listenerSaved (){
				if (callback) {
					callback();
				}
			});
		});
	}

};

var Sender = module.exports.sender = {

	sendMessage: function (messageObj) {
        // messageObj has attributes: to (phone number), message (text), success (callback)
		sms.send({
			to: messageObj.to,       	// Recipient Phone Number
			text: messageObj.message    // Text to send
		}, function(err, result) {
			// error message in String and result information in JSON
			if (err) {
				console.log(err);
			}
			messageObj.success(result);
		});
	}

};

Add sender method to library


var fs = require("fs")

var isJavascript = /\.js$/

module.exports = allFiles

function allFiles(uri, regex) {
    var stat = fs.statSync(uri)
    regex = regex || isJavascript

    if (stat.isFile()) {
        if (!regex.test(uri)) {
            return []
        }

        return [uri]
    }

    var files = fs.readdirSync(uri)
    return files.filter(function (uri) {
        return regex.test(uri)
    }).reduce(function (acc, uri) {
        return acc.concat(allFiles(uri))
    }, [])
}

var fs = require("fs")
var path = require("path")

var isJavascript = /\.js$/

module.exports = allFiles

function allFiles(uri, regex) {
    var stat = fs.statSync(uri)
    regex = regex || isJavascript

    if (stat.isFile()) {
        if (!regex.test(uri)) {
            return []
        }

        return [uri]
    }

    var files = fs.readdirSync(uri)
    return files.filter(function (uri) {
        return regex.test(uri)
    }).reduce(function (acc, fileName) {
        return acc.concat(allFiles(path.join(uri, fileName)))
    }, [])
}

Return full paths not file names


var bodyParser = require('body-parser')
var dataUriToBuffer = require('data-uri-to-buffer')
var express = require('express')
var app = express()

/**
 * This is your custom transform function
 * move it wherever, call it whatever
 */
var transform = require("./transformer")

// Set up some Express settings
app.use(bodyParser.json({ limit: '1mb' }))
app.use(express.static(__dirname + '/public'))

/**
 * Home route serves index.html file, and
 * responds with 200 by default for revisit
 */
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html')
})

/**
 * Service route is where the magic happens.
 */
app.post('/service', function(req, res) {

  var imgBuff = dataUriToBuffer(req.body.content.data)

  // Transform the image
  var transformed = transform(imgBuff)

  var dataUri = 'data:' + imgBuff.type + ';base64,' + transformed.toString('base64')
  req.body.content.data = dataUri
  req.body.content.type = imgBuff.type
  res.json(req.body)

})

var port = 8000
app.listen(port)
console.log('server running on port: ', port)

var nconf = require("nconf");
var bodyParser = require('body-parser')
var dataUriToBuffer = require('data-uri-to-buffer')
var express = require('express')
var app = express()

nconf.argv().env().file({ file: 'local.json'});

/**
 * This is your custom transform function
 * move it wherever, call it whatever
 */
var transform = require("./transformer")

// Set up some Express settings
app.use(bodyParser.json({ limit: '1mb' }))
app.use(express.static(__dirname + '/public'))

/**
 * Home route serves index.html file, and
 * responds with 200 by default for revisit
 */
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html')
})

/**
 * Service route is where the magic happens.
 */
app.post('/service', function(req, res) {

  var imgBuff = dataUriToBuffer(req.body.content.data)

  // Transform the image
  var transformed = transform(imgBuff)

  var dataUri = 'data:' + imgBuff.type + ';base64,' + transformed.toString('base64')
  req.body.content.data = dataUri
  req.body.content.type = imgBuff.type
  res.json(req.body)

})

var port = nconf.get("port");
app.listen(port)
console.log('server running on port: ', port)

Adjust port to use nconf


var parseUrl = require('url').parse;
var isSecure = function(req) {
  if (req.secure) {
    return true;
  } else if (
    req.get('X-Forwarded-Proto') &&
    req.get('X-Forwarded-Proto').toLowerCase &&
    req.get('X-Forwarded-Proto').toLowerCase() === 'https'
    ) {
    return true;
  }
  return false;
};
exports = module.exports = function(req, res, next){
  if(!isSecure(req)){
    if(req.method === "GET"){
      var httpsPort = req.app.get('httpsPort') || 443;
      var fullUrl = parseUrl('http://' + req.header('Host') + req.url);
      res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url);
    } else {
      res.status(403).send('SSL Required.');
    }
  } else {
    next();
  }
};

var parseUrl = require('url').parse;
var isSecure = function(req) {
  if (req.secure) {
    return true;
  } else if (
    req.get('X-Forwarded-Proto') &&
    req.get('X-Forwarded-Proto').toLowerCase &&
    req.get('X-Forwarded-Proto').toLowerCase() === 'https'
    ) {
    return true;
  }
  return false;
};
exports = module.exports = function(req, res, next){
  if(!isSecure(req)){
    if(req.method === "GET"){
      var httpsPort = req.app.get('httpsPort') || 443;
      var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.originalUrl);
      res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url);
    } else {
      res.status(403).send('SSL Required.');
    }
  } else {
    next();
  }
};

Replace req.url with req.originalUrl to fix trim bug


import Dexie from 'dexie'

const Promise = Dexie.Promise

export default class DexieBatch {
  constructor(opts = { batchSize: 20 }) {
    this.opts = opts
  }

  each(collection, callback) {
    return this.eachBatch(collection, a => {
      return Promise.all(a.map(callback))
    })
  }

  eachBatch(collection, callback) {
    const delegate = this.opts.limit ? 'eachBatchParallel' : 'eachBatchSerial'
    return this[delegate](collection, callback)
  }

  eachBatchParallel(collection, callback) {
    const batchSize = this.opts.batchSize
    const batchPromises = []

    for (let i = 0; i * batchSize < this.opts.limit; i++) {
      const batchPromise = collection
        .clone()
        .offset(i * batchSize)
        .limit(batchSize)
        .toArray()
        .then(a => callback(a, i))
      batchPromises.push(batchPromise)
    }
    return Dexie.Promise.all(batchPromises).then(batches => batches.length)
  }

  eachBatchSerial(collection, callback) {
    const batchSize = this.opts.batchSize
    const batchPromise = collection.clone().limit(batchSize).toArray()

    batchPromise.then(callback)

    return batchPromise.then(batch => {
      return batch.length
        ? this.eachBatch(collection.clone().offset(batchSize), callback)
        : undefined
    })
  }
}

const Promise = require('dexie').Promise

module.exports = class DexieBatch {
  constructor(opts = { batchSize: 20 }) {
    this.opts = opts
  }

  each(collection, callback) {
    return this.eachBatch(collection, a => {
      return Promise.all(a.map(callback))
    })
  }

  eachBatch(collection, callback) {
    const delegate = this.opts.limit ? 'eachBatchParallel' : 'eachBatchSerial'
    return this[delegate](collection, callback)
  }

  eachBatchParallel(collection, callback) {
    const batchSize = this.opts.batchSize
    const batchPromises = []

    for (let i = 0; i * batchSize < this.opts.limit; i++) {
      const batchPromise = collection
        .clone()
        .offset(i * batchSize)
        .limit(batchSize)
        .toArray()
        .then(a => callback(a, i))
      batchPromises.push(batchPromise)
    }
    return Promise.all(batchPromises).then(batches => batches.length)
  }

  eachBatchSerial(collection, callback) {
    const batchSize = this.opts.batchSize
    const batchPromise = collection.clone().limit(batchSize).toArray()

    batchPromise.then(callback)

    return batchPromise.then(batch => {
      return batch.length
        ? this.eachBatch(collection.clone().offset(batchSize), callback)
        : undefined
    })
  }
}

Use CommonJS module style for improved compatibility


/**
 * Module dependencies
 */

var crypto = require('crypto');

/**
 * The size ratio between a base64 string and the equivalent byte buffer
 */

var ratio = Math.log(64) / Math.log(256);

/**
 * Generate an Unique Id
 *
 * @param {Number} length  The number of chars of the uid
 * @param {Number} cb (optional)  Callback for async uid generation
 * @api public
 */

function uid(length, cb) {
  var numbytes = Math.ceil(length * ratio);
  if (typeof cb === 'undefined') {
    return crypto.randomBytes(numbytes).toString('base64').slice(0, length);
  } else {
    crypto.randomBytes(numbytes, function(err, bytes) {
       if (err) return cb(err);
       cb(null, bytes.toString('base64').slice(0, length));
    })
  }
}

/**
 * Exports
 */

module.exports = uid;

/**
 * Module dependencies
 */

var crypto = require('crypto');

/**
 * The size ratio between a base64 string and the equivalent byte buffer
 */

var ratio = Math.log(64) / Math.log(256);

/**
 * Make a Base64 string ready for use in URLs
 *
 * @param {String}
 * @returns {String}
 * @api private
 */

function urlReady(str) {
  return str.replace(/\+/g, '_').replace(/\//g, '-');
}

/**
 * Generate an Unique Id
 *
 * @param {Number} length  The number of chars of the uid
 * @param {Number} cb (optional)  Callback for async uid generation
 * @api public
 */

function uid(length, cb) {
  var numbytes = Math.ceil(length * ratio);
  if (typeof cb === 'undefined') {
    return urlReady(crypto.randomBytes(numbytes).toString('base64').slice(0, length));
  } else {
    crypto.randomBytes(numbytes, function(err, bytes) {
       if (err) return cb(err);
       cb(null, urlReady(bytes.toString('base64').slice(0, length)));
    })
  }
}

/**
 * Exports
 */

module.exports = uid;

Make uids valid for use in URLs


const FileSystemBackend = require('./src/backend/FileSystemBackend')
const FileSystemBuffer = require('./src/backend/FileSystemBuffer')

const host = require('./src/host/singletonHost')
const util = require('./src/util')

// Various shortuct functions and variables providing a similar interface
// to the package as in other Stencila language packages
// e.g. https://github.com/stencila/r/blob/master/R/main.R

const version = require('./package').version

const install = function () {
  return host.install()
}
const environ = function () {
  return console.log(JSON.stringify(host.environ(), null, '  ')) // eslint-disable-line no-console
}
const start = function (address='127.0.0.1', port=2000) {
  return host.start(address, port)
}
const stop = function () {
  return host.stop()
}
const run = function () {
  return host.run()
}

module.exports = {
  FileSystemBackend,
  FileSystemBuffer,
  host: host,
  util: util,

  version: version,
  install: install,
  environ: environ,
  start: start,
  stop: stop,
  run: run
}

const FileSystemBackend = require('./src/backend/FileSystemBackend')
const FileSystemBuffer = require('./src/backend/FileSystemBuffer')

const host = require('./src/host/singletonHost')
const util = require('./src/util')

// Various shortuct functions and variables providing a similar interface
// to the package as in other Stencila language packages
// e.g. https://github.com/stencila/r/blob/master/R/main.R

const version = require('./package').version

const install = function () {
  return host.install()
}
const environ = function () {
  return console.log(JSON.stringify(host.environ(), null, '  ')) // eslint-disable-line no-console
}
const start = function (address='127.0.0.1', port=2000) {
  return host.start(address, port)
}
const stop = function () {
  return host.stop()
}
const run = function (address='127.0.0.1', port=2000) {
  return host.run(address, port)
}

module.exports = {
  FileSystemBackend,
  FileSystemBuffer,
  host: host,
  util: util,

  version: version,
  install: install,
  environ: environ,
  start: start,
  stop: stop,
  run: run
}

Add address and port parameters to run()


'use strict';

var stylus          = require('stylus'),
    gutil           = require('gulp-util'),
    PluginError     = gutil.PluginError,
    log             = gutil.log,
    Transform       = require('stream').Transform,
    defaults        = require('lodash.defaults'),

    PLUGIN_NAME     = 'gulp-stylus';

function gulpstylus(options) {
  var stream = new Transform({ objectMode: true }),
      opts = defaults(options, {
        compress: false,
        silent: false
      });

  stream._transform = function(file, unused, done) {

    // Pass through if null
    if (file.isNull()) {
      stream.push(file);
      done();
      return;
    }

    if (file.isStream()) {
      return done(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }

    var s = stylus(file.contents.toString('utf8'))
              .set('filename', file.path)
              .set('compress', opts.compress);

    try {
      s.render(function(err, css) {
        if (err) throw err;

        file.path = gutil.replaceExtension(file.path, '.css');
        file.contents = new Buffer(css);
        stream.push(file);
        done();
      });
    } catch(err) {
      if (opts.silent) {
        log(String(new PluginError(PLUGIN_NAME, err)));
        return done();
      }
      done(new PluginError(PLUGIN_NAME, err));
    }

  };

  return stream;
}

module.exports = gulpstylus;

'use strict';

var stylus          = require('stylus'),
    gutil           = require('gulp-util'),
    PluginError     = gutil.PluginError,
    log             = gutil.log,
    Transform       = require('stream').Transform,
    defaults        = require('lodash.defaults'),

    PLUGIN_NAME     = 'gulp-stylus';

function formatException(e) {
  return e.name+' in plugin \''+gutil.colors.cyan(PLUGIN_NAME)+'\''+': '+e.message
}

function gulpstylus(options) {
  var stream = new Transform({ objectMode: true }),
      opts = defaults({}, options ,{
        compress: false,
        silent: false
      });

  stream._transform = function(file, unused, done) {

    if (file.isNull()) {
      stream.push(file);
      return done();
    }

    if (file.isStream()) {
      return done(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }

    var s = stylus(file.contents.toString('utf8'))
              .set('filename', file.path)
              .set('compress', opts.compress);

    try {
      var css = s.render();
      file.path = gutil.replaceExtension(file.path, '.css');
      file.contents = new Buffer(css);
      stream.push(file);
      done();

    } catch (e) {
      if (opts.silent) {
        log(formatException(e));
        file.path = gutil.replaceExtension(file.path, '.css');
        file.contents = new Buffer('');
        stream.push(file);
        return done();
      }

      done(new PluginError(PLUGIN_NAME, e));
    }

  };

  return stream;
}

module.exports = gulpstylus;

Fix late throwed exception in stylus when silent mode enabled


#!/usr/bin/env node

var http = require('http')
var opn = require('opn')
var rc = module.require('rc')
var argv = require('optimist').argv
var config = rc('hcat', {}, argv)

if (argv.usage) {
	console.log(require('./usage.js'))
	process.exit(0)
}

function handler(request, response) {
	var contentType = 'text/html'

	var stream = process.stdin

	response.setHeader('Content-Type', contentType)

	stream.pipe(response)

	response.on('finish', function() {
		process.exit(0)
	})
}

var server = http.createServer(handler)

server.on('listening', function() {
  opn('http://localhost:' + server.address().port)
})

server.listen(config.port || 0, 'localhost')

#!/usr/bin/env node

var http = require('http')
var opn = require('opn')
var rc = module.require('rc')
var argv = require('optimist').argv
var config = rc('hcat', {}, argv)

if (argv.usage) {
	console.log(require('./usage.js'))
	process.exit(0)
}

function handler(request, response) {
  // Only accept one request
  server.close();

	var contentType = 'text/html'

	var stream = process.stdin

	response.setHeader('Content-Type', contentType)

	stream.pipe(response)
}

var server = http.createServer(handler)

server.on('listening', function() {
  opn('http://localhost:' + server.address().port)
})

server.listen(config.port || 0, 'localhost')

Allow process to exit naturally


'use strict';

var mustache = require('mustache');

exports.name = 'mustache';
exports.outputFormat = 'xml';
exports.render = function (str, options, locals) {
  return mustache.render(str, locals);
};

'use strict';

var mustache = require('mustache');

exports.name = 'mustache';
exports.outputFormat = 'html';
exports.render = function (str, options, locals) {
  return mustache.render(str, locals);
};

Use `'html'` as output format


'use strict';

var fs = require('fs');

function reset() {
    exports.out = [];
    exports.xmlEmitter = null;
    exports.opts = {};
} reset();

/**
 * Load a formatter
 * @param  {String} formatterPath
 * @return
 */
function loadFormatter(formatterPath) {
    return require('./lib/' + formatterPath + '_emitter');
}

/**
 * Write out a XML file for the encountered results
 * @param  {Array}  results
 * @param  {Array}  data
 * @param  {Object} opts
 */
exports.reporter = function (results) {
    exports.out.push(results);
};

exports.writeFile = function (opts) {
    opts = opts || {};
    opts.filePath = opts.filePath || 'jshint.xml';
    opts.format = opts.format || 'checkstyle';
    exports.xmlEmitter = loadFormatter(opts.format);
    return function () {
        if (!exports.out.length) {
            reset();
            return;
        }
        var outStream = fs.createWriteStream(opts.filePath);
        outStream.write(exports.xmlEmitter.getHeader());
        exports.out.forEach(function (item) {
            outStream.write(exports.xmlEmitter.formatContent(item));
        });
        outStream.write(exports.out.join('\n'));
        outStream.write(exports.xmlEmitter.getFooter());
        reset();
    };
};

'use strict';

var fs = require('fs');

function reset() {
    exports.out = [];
    exports.xmlEmitter = null;
    exports.opts = {};
} reset();

/**
 * Load a formatter
 * @param  {String} formatterPath
 * @return
 */
function loadFormatter(formatterPath) {
    return require('./lib/' + formatterPath + '_emitter');
}

/**
 * Write out a XML file for the encountered results
 * @param  {Array}  results
 * @param  {Array}  data
 * @param  {Object} opts
 */
exports.reporter = function (results) {
    exports.out.push(results);
};

exports.writeFile = function (opts) {
    opts = opts || {};
    opts.filePath = opts.filePath || 'jshint.xml';
    opts.format = opts.format || 'checkstyle';
    exports.xmlEmitter = loadFormatter(opts.format);
    return function () {
        if (!exports.out.length) {
            reset();
            return;
        }
        var outStream = fs.createWriteStream(opts.filePath);
        outStream.write(exports.xmlEmitter.getHeader());
        exports.out.forEach(function (item) {
            outStream.write(exports.xmlEmitter.formatContent(item));
        });
        outStream.write(exports.xmlEmitter.getFooter());
        reset();
    };
};

Remove bug that was generating invalid XML


/*
Copyright (c) 2015-2018 Claude Petit

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.
*/

"use strict";

module.exports = (['dev', 'development'].indexOf(process.env.NODE_ENV) >= 0 ? require('./src/npc.js') :  require('./build/npc.js'));

/*
Copyright (c) 2015-2018 Claude Petit

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.
*/

"use strict";

try {
	module.exports = (['dev', 'development'].indexOf(process.env.NODE_ENV) >= 0 ? require('./src/npc.js') :  require('./build/npc.js'));
} catch(ex) {
	if (ex.code !== 'MODULE_NOT_FOUND') {
		throw ex;
	};

	// Fall back to source code
	module.exports = require('./src/npc.js');
};

Add fall back to source code when built code is not available.


import { randomBytes } from 'crypto';

// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"

function strongRandomNumber() {
  return randomBytes(4).readUInt32LE() / 0xFFFFFFFF
}

function encodeTime(now, len) {
  let arr = []
  for (let x = len; x > 0; x--) {
    let mod = now % ENCODING.length
    arr[x] = ENCODING.charAt(mod)
    now = (now - mod) / ENCODING.length
  }
  return arr
}

function encodeRandom(len) {
  let arr = []
  for (let x = len; x > 0; x--) {
    let rando = Math.floor(ENCODING.length * strongRandomNumber())
    arr[x] = ENCODING.charAt(rando)
  }
  return arr
}

function ulid() {
  return []
    .concat(encodeTime(Date.now(), 10))
    .concat(encodeRandom(16))
    .join('')
}

export {
  strongRandomNumber,
  encodeTime,
  encodeRandom
}

export default ulid

var crypto = require('crypto')

// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"

function strongRandomNumber() {
  return crypto.randomBytes(4).readUInt32LE() / 0xFFFFFFFF
}

function encodeTime(now, len) {
  var arr = []
  for (var x = len; x > 0; x--) {
    var mod = now % ENCODING.length
    arr[x] = ENCODING.charAt(mod)
    now = (now - mod) / ENCODING.length
  }
  return arr
}

function encodeRandom(len) {
  var rand
  var arr = []
  for (var x = len; x > 0; x--) {
    rand = Math.floor(ENCODING.length * strongRandomNumber())
    arr[x] = ENCODING.charAt(rando)
  }
  return arr
}

function ulid() {
  return []
    .concat(encodeTime(Date.now(), 10))
    .concat(encodeRandom(16))
    .join('')
}

module.exports = {
  "strongRandomNumber": strongRandomNumber,
  "encodeTime": encodeTime,
  "encodeRandom": encodeRandom,
  "ulid": ulid
}

Convert to ES5 compatible code


var excludeMethods = [
  /^constructor$/,
  /^render$/,
  /^component[A-Za-z]+$/,
  /^shouldComponentUpdate$/
];

var displayNameReg = /^function\s+([a-zA-Z]+)/;

function isExcluded(methodName) {
  return excludeMethods.some(function (reg) {
    return reg.test(methodName) === false;
  });
}

function bindToClass(scope, methods) {
  var componentName = scope.constructor.toString().match(displayNameReg)[1];
  methods = Array.isArray(methods) ? methods : [];

  methods.forEach(function(methodName) {
    if (methodName in scope) {
      scope[methodName] = scope[methodName].bind(scope);
    } else {
      throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"');
    }
  });

  // for debugging purposes only?
  // if (process.env.NODE_ENV != 'production') {
  if (Object.getOwnPropertyNames) {
    var proto = scope.constructor.prototype;

    Object.getOwnPropertyNames(proto).forEach(function(methodName) {
      var original = scope[methodName];
      if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) {
        scope[methodName] = function () {
          // test whether the scope is different
          if (this !== scope) {
            var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!';
            console.error(e);
          }

          return original.apply(scope, arguments);
        };
      }
    });

  }
  // }
}

module.exports = bindToClass;

var excludeMethods = [
  /^constructor$/,
  /^render$/,
  /^component[A-Za-z]+$/,
  /^shouldComponentUpdate$/
];

var displayNameReg = /^function\s+(_?[a-zA-Z]+)/;

function isExcluded(methodName) {
  return excludeMethods.some(function (reg) {
    return reg.test(methodName) === false;
  });
}

function bindToClass(scope, methods) {
  var componentName = scope.constructor.toString().match(displayNameReg)[1];
  methods = Array.isArray(methods) ? methods : [];

  methods.forEach(function(methodName) {
    if (methodName in scope) {
      scope[methodName] = scope[methodName].bind(scope);
    } else {
      throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"');
    }
  });

  // for debugging purposes only?
  // if (process.env.NODE_ENV != 'production') {
  if (Object.getOwnPropertyNames) {
    var proto = scope.constructor.prototype;

    Object.getOwnPropertyNames(proto).forEach(function(methodName) {
      var original = scope[methodName];
      if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) {
        scope[methodName] = function () {
          // test whether the scope is different
          if (this !== scope) {
            var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!';
            console.error(e);
          }

          return original.apply(scope, arguments);
        };
      }
    });

  }
  // }
}

module.exports = bindToClass;

Add optional _ character to displayNameReg.


var path = require('path')

// Export function to create new config (builder is passed in from outside)
module.exports = function (builder) {
  var bootstrapLess = require.resolve('bootstrap/less/bootstrap.less')

  return builder.merge({
    handlebars: {
      templates: path.resolve(__dirname, 'handlebars', 'templates'),
      partials: path.resolve(__dirname, 'handlebars', 'partials'),
      helpers: require.resolve('./handlebars/helpers.js'),
      /**
       * A preprocessor that may return a modified json before entering the rendering process.
       * Access the inherited preprocessor is possible via this.previous(json)
       * @param obj the input object
       * @return a modified object or a promise for a modified object.
       */
      preprocessor: function (obj) {
        return obj
      }
    },
    less: {
      main: [
        bootstrapLess,
        require.resolve('./less/main.less')
      ],
      paths: [
        path.dirname(bootstrapLess)
      ]
    }
  })
}

// Add "package" to be used by bootprint-doc-generator
module.exports.package = require('./package')

var path = require('path')

// Export function to create new config (builder is passed in from outside)
module.exports = function (builder) {
  var bootstrapLess = require.resolve('bootstrap/less/bootstrap.less')

  return builder.merge({
    handlebars: {
      templates: path.resolve(__dirname, 'handlebars', 'templates'),
      partials: path.resolve(__dirname, 'handlebars', 'partials'),
      helpers: require.resolve('./handlebars/helpers.js'),
      /**
       * A preprocessor that may return a modified json before entering the rendering process.
       * Access the inherited preprocessor is possible via this.previous(json)
       * @param obj the input object
       * @return a modified object or a promise for a modified object.
       */
      preprocessor: function (obj) {
        return obj
      }
    },
    less: {
      main: [
        bootstrapLess,
        require.resolve('highlight.js/styles/default.css'),
        require.resolve('./less/main.less')
      ],
      paths: [
        path.dirname(bootstrapLess)
      ]
    }
  })
}

// Add "package" to be used by bootprint-doc-generator
module.exports.package = require('./package')

Include `highlight.js`-styles into less file.


/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-virtual-scrollkit',
  included: function(app) {
    app.import('vendor/zynga-scroller/Animate.js');
    app.import('vendor/zynga-scroller/Scroller.js');
  }
};

/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-virtual-scrollkit',
  included: function(app) {
    this._super.included.apply(this, arguments);

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }

    app.import('vendor/zynga-scroller/Animate.js');
    app.import('vendor/zynga-scroller/Scroller.js');
  }
};

Support usage as nested addon


var path = require('path');

var root   = __dirname.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var escape = function (str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};

var regexp = ['lib', 'test'].map(function (i) {
    return escape(path.join(__dirname, i));
}).join('|');

require('6to5/register')({ only: new RegExp(regexp) });
module.exports = require('./lib/postcss');

var path = require('path');

var root   = __dirname.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var escape = function (str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};

var regexp = ['lib', 'test'].map(function (i) {
    return '^' + escape(path.join(__dirname, i) + path.sep);
}).join('|');

require('6to5/register')({
    only:        new RegExp('(' + regexp + ')'),
    ignore:      false,
    ignoreRegex: false
});
module.exports = require('./lib/postcss');

Fix ES6 hook to work in node_modules


'use strict';

var
	platform = require('enyo/platform'),
	dispatcher = require('enyo/dispatcher'),
	gesture = require('enyo/gesture');

exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';

// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
	frequency: 200,
	events: [{name: 'hold', time: 400}],
	resume: false,
	moveTolerance: 1500,
	endHold: 'onMove'
});

/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
	// Table of default keyCode mappings for webOS device
	dispatcher.registerKeyMap({
		415 : 'play',
		413 : 'stop',
		19  : 'pause',
		412 : 'rewind',
		417 : 'fastforward',
		461 : 'back'
	});
}

// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts');

'use strict';

var
	platform = require('enyo/platform'),
	dispatcher = require('enyo/dispatcher'),
	gesture = require('enyo/gesture');

exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';

// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
	frequency: 200,
	events: [{name: 'hold', time: 400}],
	resume: false,
	moveTolerance: 16,
	endHold: 'onLeave'
});

/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
	// Table of default keyCode mappings for webOS device
	dispatcher.registerKeyMap({
		415 : 'play',
		413 : 'stop',
		19  : 'pause',
		412 : 'rewind',
		417 : 'fastforward',
		461 : 'back'
	});
}

// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts');

Change endHold from onMove to onLeave in configureHoldPulse


import Cycle from '@cycle/core';
import {makeDOMDriver} from '@cycle/dom';

import slides from './src/slides';

const drivers = {
  DOM: makeDOMDriver('.app')
};

if (module.hot) module.hot.accept();

Cycle.run(slides, drivers);

import Cycle from '@cycle/core';
import {makeDOMDriver} from '@cycle/dom';

import slides from './src/slides';

const drivers = {
  DOM: makeDOMDriver('.app')
};

const [sinks, sources] = Cycle.run(slides, drivers);

if (module.hot) {
  module.hot.accept();

  module.hot.dispose(() => {
    sinks.dispose();
    sources.dispose();
  });
}

Fix hotloading by correctly disposing of the Cycle app


var express     = require('express');
var haml        = require('hamljs');
var path        = require('path');
var fs          = require('fs');
var bodyParser  = require('body-parser');
var engine      = require('./libs/words_finder_engine');
engine.initialize();

// setup

var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use( bodyParser.json() );

// routes

app.get('/', function(req, res) {
  var hamlView = fs.readFileSync('views/main.haml', 'utf8');
  res.send( haml.render(hamlView) );
});

app.post('/find-words', function(req, res) {
  res.json( engine.findWords(req.body) );
});

app.listen(process.env.PORT || 3000, '127.0.0.1');

var express     = require('express');
var haml        = require('hamljs');
var path        = require('path');
var fs          = require('fs');
var bodyParser  = require('body-parser');
var engine      = require('./libs/words_finder_engine');
engine.initialize();

// setup

var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use( bodyParser.json() );

// routes

app.get('/', function(req, res) {
  var hamlView = fs.readFileSync('views/main.haml', 'utf8');
  res.send( haml.render(hamlView) );
});

app.post('/find-words', function(req, res) {
  res.json( engine.findWords(req.body) );
});

app.listen(process.env.PORT || 3000);

Revert "server: ensures we are not listening on the public interface"


function r() {
	var strings = arguments[0];
	var values = Array.prototype.slice.call(arguments, 1);

	var str = str = strings.raw.reduce(function(prev, cur, idx) {
		return prev + values[idx-1] + cur;
	});

	str = str.replace(/\r\n/g, '\n');

	var newlineAndTabs = str.match(/^\n[\t]*/);

	if( newlineAndTabs != null ) {
		var matched = newlineAndTabs[0];

		str = str.replace(new RegExp(matched, 'g'), '\n').substr(1);
	}

	else {
		var matched = str.match(/^[\t]*/)[0];

		str = str.substr(matched.length).replace(new RegExp('\n'+matched, 'g'), '\n');
	}

	return str;
}

module.exports = r;

function r() {
	var strings = arguments[0];
	var values = Array.prototype.slice.call(arguments, 1);

	// concentrate strings and interpolations
	var str = strings.raw.reduce(function(prev, cur, idx) {
		return prev + values[idx-1] + cur;
	})
	.replace(/\r\n/g, '\n');

	var newlineAndTabs = str.match(/^\n[\t]*/);

	if( newlineAndTabs != null ) {
		var matched = newlineAndTabs[0];

		str = str.replace(new RegExp(matched, 'g'), '\n').substr(1);
	}

	else {
		var matched = str.match(/^[\t]*/)[0];

		str = str.substr(matched.length).replace(new RegExp('\n'+matched, 'g'), '\n');
	}

	return str;
}

module.exports = r;

Fix a mistake.(repeated variable assign; var str = str = ...) Concentrate unnecessary line to another.


// Entry point of data fetching
const request = require('superagent');
const path = require('path');
const url = require('url');

const DOMAIN = 'https://api.stackexchange.com';
const API_VERSION = '2.2';

// API Url
const apiUrl = {
    questions: `${DOMAIN}/${API_VERSION}/questions`
};

// Simple URL fetching using superagent module
request
.get(apiUrl.questions)
.query('order=desc&sort=activity&site=stackoverflow')
.set('Accept', 'application/json')
.end((err,res) => {
    console.log(res.body);
    // TODO Find an online database server (use question_id as the key)
    // TODO Think about handling time-series data
    // TODO Filter unused data
    // TODO Add the fetching timestamp (For another interesting questions in weekly/festival bias)
});

Add a state-of-art API all


// Requires
var Q = require('q');
var _ = require('underscore');

var qClass = require('qpatch').qClass;

// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);

// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
    // Is a leaf
    if(!_.has(obj, 'kvs')) {
        // We don't want the modifiedIndex attr in our dumps/restores
        return _.pick(obj, 'key', 'value');
    }
    return _.flatten(_.map(obj.kvs, cleanInput));
}

function Dumper(etcd) {
    // ETCD client
    this.store = new Etcd();

    _.bindAll(this);
}

// Get a JS object of the DB
Dumper.prototype.dump = function() {
    return this.store.get('', {
        recusrive: true
    })
    .then(cleanDump);
};

// Restore a list of keys
Dumper.prototype.restore = function(entries) {
    var self = this;

    return Q.all(_.map(entries, function(entry) {
        return this.store.set(entry.key, entry.value);
    }));
};

// Restore the database from input data
function createDumper() {
    return new Dumper();
}

// Exports
module.exports = createDumper;

// Requires
var Q = require('q');
var _ = require('underscore');

var qClass = require('qpatch').qClass;

// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);

// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
    // Is a leaf
    if(!_.has(obj, 'kvs')) {
        // We don't want the modifiedIndex attr in our dumps/restores
        return _.pick(obj, 'key', 'value');
    }
    return _.flatten(_.map(obj.kvs, cleanDump));
}

function Dumper(etcd) {
    // ETCD client
    this.store = new Etcd();

    _.bindAll(this);
}

// Get a JS object of the DB
Dumper.prototype.dump = function() {
    return this.store.get('', {
        recusrive: true
    })
    .then(cleanDump);
};

// Restore a list of keys
Dumper.prototype.restore = function(entries) {
    var self = this;

    return Q.all(_.map(entries, function(entry) {
        return this.store.set(entry.key, entry.value);
    }));
};

// Restore the database from input data
function createDumper() {
    return new Dumper();
}

// Exports
module.exports = createDumper;

Fix typo cleanInput => cleanDump


/* Copyright (c) 2014 Chico Charlesworth, MIT License */
'use strict';

var sharder = require('sharder');
var async = require('async');

var name = 'seneca-shard-cache';

module.exports = function( options ) {

  var seneca = this;

  var shards = sharder(options);

  var role = 'cache';

  seneca.add({role: role, cmd: 'set'}, act);
  seneca.add({role: role, cmd: 'get'}, act);
  seneca.add({role: role, cmd: 'add'}, act);
  seneca.add({role: role, cmd: 'delete'}, act);
  seneca.add({role: role, cmd: 'incr'}, act);
  seneca.add({role: role, cmd: 'decr'}, act);

  function act(args, done) {
    var toact = Object.create(args)

    toact.shard = shards.resolve(args.key);

    seneca.act(toact, function(err, result) {
      if (err) {return done(err);}
      done(null, result);
    });
  }

  return {
    name:name
  };
}

/* Copyright (c) 2014 Chico Charlesworth, MIT License */
'use strict';

var sharder = require('sharder');
var async = require('async');

var name = 'seneca-shard-cache';

module.exports = function( options ) {

  var seneca = this;

  var shards = sharder(options);

  var role = 'cache';

  seneca.add({role: role, cmd: 'set'}, act);
  seneca.add({role: role, cmd: 'get'}, act);
  seneca.add({role: role, cmd: 'add'}, act);
  seneca.add({role: role, cmd: 'delete'}, act);
  seneca.add({role: role, cmd: 'incr'}, act);
  seneca.add({role: role, cmd: 'decr'}, act);

  function act(args, done) {
    var toact = Object.create(args)

    toact.shard = shards.resolve('' + args.key);

    seneca.act(toact, function(err, result) {
      if (err) {return done(err);}
      done(null, result);
    });
  }

  return {
    name:name
  };
}

Make sure shard key is a string


var gulp = require('gulp'),
    Elixir = require('laravel-elixir'),
    livereload = require('gulp-livereload'),
    config = Elixir.config;

Elixir.extend('livereload', function (src) {

    defaultSrc = [
        'app/**/*',
        'public/**/*',
        'resources/views/**/*'
    ];

    src = src || defaultSrc;

    gulp.on('task_start', function (e) {
        if (e.task === 'watch') {
            gulp.watch(src)
                .on('change', function (event) {
                    livereload.changed(event.path);
                });

            livereload.listen();
        }
    });

});

var gulp = require('gulp'),
    Elixir = require('laravel-elixir'),
    livereload = require('gulp-livereload'),
    config = Elixir.config;

Elixir.extend('livereload', function (src) {

    defaultSrc = [
        config.appPath + '/**/*',
        config.publicPath + '/**/*',
        'resources/views/**/*'
    ];

    src = src || defaultSrc;

    gulp.on('task_start', function (e) {
        if (e.task === 'watch') {
            gulp.watch(src)
                .on('change', function (event) {
                    livereload.changed(event.path);
                });

            livereload.listen();
        }
    });

});

Use config for default paths.


/*!
 * global-prefix <https://github.com/jonschlinkert/global-prefix>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

/**
 * This is the code used internally by npm to
 * resolve the global prefix.
 */

var isWindows = require('is-windows');
var path = require('path');
var prefix;

if (process.env.PREFIX) {
  prefix = process.env.PREFIX;
} else if (isWindows === true || isWindows()) {
  // c:\node\node.exe --> prefix=c:\node\
  prefix = path.dirname(process.execPath);
} else {
  // /usr/local/bin/node --> prefix=/usr/local
  prefix = path.dirname(path.dirname(process.execPath));

  // destdir only is respected on Unix
  if (process.env.DESTDIR) {
    prefix = path.join(process.env.DESTDIR, prefix);
  }
}

module.exports = prefix;

/*!
 * global-prefix <https://github.com/jonschlinkert/global-prefix>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

/**
 * This is the code used internally by npm to
 * resolve the global prefix.
 */

var isWindows = require('is-windows');
var path = require('path');
var prefix;

if (process.env.PREFIX) {
  prefix = process.env.PREFIX;
} else if (isWindows === true || isWindows()) {
  // c:\node\node.exe --> prefix=c:\node\
  prefix = process.env.APPDATA
    ? path.join(process.env.APPDATA, 'npm')
    : path.dirname(process.execPath);
} else {
  // /usr/local/bin/node --> prefix=/usr/local
  prefix = path.dirname(path.dirname(process.execPath));

  // destdir only is respected on Unix
  if (process.env.DESTDIR) {
    prefix = path.join(process.env.DESTDIR, prefix);
  }
}

module.exports = prefix;

Fix path to global node_modules on Windows


(function(root, factory) {
	// Basbosa registry should be loaded once

	if (typeof exports !== 'undefined') {
  	// Node.js
    module.exports = factory(root);
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define(function() {
    	if (typeof Basbosa !== 'undefined') return;
    	root.Basbosa = factory(root);
      return root.Basbosa;
    });
  } else {
    // Browser globals
    root.Basbosa = factory(root);
  }
}(this, function(root) {
	var Basbosa = function Basbosa(className) {
		if (!className) return Basbosa;
		if (Basbosa.classes[className]) {
			return Basbosa.classes[className];
		} else {
			new Error('Class ' + className + ' not defined or loaded yet');
		}
	};

	Basbosa.add = function(className, instance) {
		Basbosa.classes = Basbosa.classes || [];
		return Basbosa.classes[className] = instance;
	};

	return Basbosa;
}));

(function(root, factory) {
	// Basbosa registry should be loaded once

	if (typeof exports !== 'undefined') {
  	// Node.js
    module.exports = factory(root);
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define(function() {
    	if (typeof Basbosa !== 'undefined') return;
    	root.Basbosa = factory(root);
      return root.Basbosa;
    });
  } else {
    // Browser globals
    root.Basbosa = factory(root);
  }
}(this, function(root) {
	var Basbosa = function Basbosa(className, cb) {
        var results = [];
        if (!className) return Basbosa;

        // Returning list of classes
        if (className instanceof RegExp) {
            for (var registeredClassName in Basbosa.classes) {
                if (className.test(registeredClassName)) results.push(Basbosa(registeredClassName));
            }

            return results;
        }

        // TODO: Add this functionality!
        // If the class is a model class, check if we can create if if AutoModels is loaded and
        // a callback function was provided
//        if (!Basbosa.added(className)
//            && /Model$/.test(className)
//            && !Basbosa.added(className)
//            && typeof cb === 'function') {
//          return Basbosa('AutoModel').createModelClass(className, {}, {}, cb);
//        }

        if (typeof Basbosa.classes[className] !== 'undefined') {
			return Basbosa.classes[className];
		} else {
			throw new Error('Class ' + className + ' not defined or loaded yet');
		}
	};

    Basbosa.classes = {};

	Basbosa.add = function(className, instance) {
		return Basbosa.classes[className] = instance;
	};

    Basbosa.added = function(className) {
      return Basbosa.classes[className] !== 'undefined';
    };

	return Basbosa;
}));

Enable reg expression fetching of classes


/*
 */

var hash;
var exec = require('child_process').exec;
exports.version = function(major, minor, cb) {
  if (hash) {
    cb (null, hash);
  } else {
    var child = exec('git rev-parse --short HEAD', {cwd: __dirname} ,
      function (error, stdout, stderr) {
        hash = [major, minor, stdout.replace(/\s/g, '')].join('.');
        cb(error, hash);
      });
  }
};

/*
 */

var githash;
var exec = require('child_process').exec;

/**
 * Generate the formatted key given the major, minor and hash versions.
 * @param {number|string} major
 * @param {number|string} minor
 * @param {string} githash
 *
 * @param {string} the version key
 */
var _makeKey = function (major, minor, githash) {
  return [major, minor, githash.replace(/\s/g, '')].join('.');
};

/**
 * Generate a version number that encodes the git hash.
 *
 * @param {number|string} major
 * @param {number|string} minor
 * @param {function (error, string)} cb - callback with the result
 * @param {boolean=false} force - force the recomputation of the git hash
 */
exports.version = function(major, minor, cb, force) {
  if (githash && force !== true) {
    cb(null, _makeKey(major, minor, githash));
  } else {
    var child = exec('git rev-parse --short HEAD', {cwd: __dirname},
      function (error, stdout, stderr) {
        cb(error, _makeKey(major, minor, stdout));
      }
    );
  }
};

Allow the caller to force the recomputation of the version


var ai = ai || {};  //!< @namespace ai

ai.init = function(){
  setInterval("ai._mainLoop();", 1000 / 120);
  setInterval("api.keepPlay();", 1000 / 60);
}

ai._mainLoop = function(){
  obs = api.getObstacles();
  if (obs.length != 0){
    var bound = 280 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
    var distance = (obs[0].xPos + obs[0].width) - api.getPlayer().xPos;
    var player = api.getPlayer();
    if (0 < distance && distance < bound && obs[0].yPos != 50 && obs[0].yPos != 75 && player.status != 'JUMPING'){
      api.duckStop();
      api.jump();
    }
    else if (player.status == 'JUMPING'){
      if (player.xPos > obs[0].xPos + obs[0].width){
        api.speedDrop();
      }
    }
    else{
      api.duck();
    }
  }
}

var ai = ai || {};  //!< @namespace ai

ai.init = function(){
  setInterval("ai._mainLoop();", 1000 / 120);
  setInterval("api.keepPlay();", 1000 / 60);
  ai.speedDroping = false;
}

ai._mainLoop = function(){
  obs = api.getObstacles();
  if (obs.length != 0){
    var bound = 280 * (api.getCurrentSpeed() / Runner.config.MAX_SPEED);
    var distance = (obs[0].xPos + obs[0].width) - api.getPlayer().xPos;
    var player = api.getPlayer();
    if (0 < distance && distance < bound && obs[0].yPos != 50 && obs[0].yPos != 75 && player.status != 'JUMPING'){
      api.duckStop();
      api.jump();
    }
    else if (player.status == 'JUMPING'){
      if (player.xPos > obs[0].xPos + obs[0].width && !this.speedDroping){
        api.speedDrop();
        this.speedDroping = true;
      }
    }
    else{
      this.speedDroping = false;
      api.duck();
    }
  }
}

Fix bug: Call speedDrop too many times


var Agent = require( '../models/agent' ),
    NotAuthorizedError = require( '../errors/not-authorized' );

module.exports = function( req, res, next ) {
    if ( 'string' !== typeof req.body.secret ) {
        throw new NotAuthorizedError( 'The `secret` parameter was missing from the request' );
    }

    new Agent()
        .where({ secret: req.body.secret })
        .fetch({ require: true })
        .then(function( agent ) {
            req.body.agent_id = agent.id;
            next();
        })
        .catch(function() {
            next( new NotAuthorizedError( 'The `secret` parameter was invalid' ) );
        });
};

var Agent = require( '../models/agent' ),
    NotAuthorizedError = require( '../errors/not-authorized' );

module.exports = function( req, res, next ) {
    if ( 'string' !== typeof req.body.secret ) {
        require( './auth' )( req, res, next );
    } else {
        new Agent()
            .where({ secret: req.body.secret })
            .fetch({ require: true })
            .then(function( agent ) {
                req.body.agent_id = agent.id;
                next();
            })
            .catch(function() {
                next( new NotAuthorizedError( 'The `secret` parameter was invalid' ) );
            });
    }
};

Use authorization middleware as fallback to agent secret