/**
 * @class CM_Page_Abstract
 * @extends CM_Component_Abstract
 */
var CM_Page_Abstract = CM_Component_Abstract.extend({

  /** @type String */
  _class: 'CM_Page_Abstract',

  /** @type String[] */
  _stateParams: [],

  /** @type String|Null */
  _fragment: null,

  _ready: function() {
    this._fragment = window.location.pathname + window.location.search;
    // @todo routeToState

    CM_Component_Abstract.prototype._ready.call(this);
  },

  /**
   * @returns {String|Null}
   */
  getFragment: function() {
    return this._fragment;
  },

  /**
   * @returns {String[]}
   */
  getStateParams: function() {
    return this._stateParams;
  },

  /**
   * @param {Object} state
   * @param {String} fragment
   */
  routeToState: function(state, fragment) {
    this._fragment = fragment;
    this._changeState(state);
  },

  /**
   * @param {Object} state
   */
  _changeState: function(state) {
  }

});

/**
 * @class CM_Page_Abstract
 * @extends CM_Component_Abstract
 */
var CM_Page_Abstract = CM_Component_Abstract.extend({

  /** @type String */
  _class: 'CM_Page_Abstract',

  /** @type String[] */
  _stateParams: [],

  /** @type String|Null */
  _fragment: null,

  _ready: function() {
    var location = window.location;
    var params = queryString.parse(location.search);
    var state = _.pick(params, _.intersection(_.keys(params), this.getStateParams()));
    this.routeToState(state, location.pathname + location.search);

    CM_Component_Abstract.prototype._ready.call(this);
  },

  /**
   * @returns {String|Null}
   */
  getFragment: function() {
    return this._fragment;
  },

  /**
   * @returns {String[]}
   */
  getStateParams: function() {
    return this._stateParams;
  },

  /**
   * @param {Object} state
   * @param {String} fragment
   */
  routeToState: function(state, fragment) {
    this._fragment = fragment;
    this._changeState(state);
  },

  /**
   * @param {Object} state
   */
  _changeState: function(state) {
  }

});

Call "routeToState" on page's ready()


'use strict'

const { addGenErrorHandler } = require('../errors')

const { getParams } = require('./params')
const { stringifyConfigFunc } = require('./tokenize')

// Process config function, i.e. fires it and returns its value
const runConfigFunc = function ({
  configFunc,
  mInput,
  mInput: { serverParams },
  params,
}) {
  // If this is not config function, returns as is
  if (typeof configFunc !== 'function') { return configFunc }

  const paramsA = getParams(mInput, { params, serverParams, mutable: false })

  return configFunc(paramsA)
}

const eRunConfigFunc = addGenErrorHandler(runConfigFunc, {
  message: ({ configFunc }) =>
    `Function failed: '${stringifyConfigFunc({ configFunc })}'`,
  reason: 'CONFIG_RUNTIME',
})

module.exports = {
  runConfigFunc: eRunConfigFunc,
}

'use strict'

const { addGenPbHandler } = require('../errors')

const { getParams } = require('./params')
const { stringifyConfigFunc } = require('./tokenize')

// Process config function, i.e. fires it and returns its value
const runConfigFunc = function ({
  configFunc,
  mInput,
  mInput: { serverParams },
  params,
}) {
  // If this is not config function, returns as is
  if (typeof configFunc !== 'function') { return configFunc }

  const paramsA = getParams(mInput, { params, serverParams, mutable: false })

  return configFunc(paramsA)
}

const eRunConfigFunc = addGenPbHandler(runConfigFunc, {
  message: ({ configFunc }) =>
    `Function failed: '${stringifyConfigFunc({ configFunc })}'`,
  reason: 'CONFIG_RUNTIME',
  extra: ({ configFunc }) => ({ value: stringifyConfigFunc({ configFunc }) }),
})

module.exports = {
  runConfigFunc: eRunConfigFunc,
}

Improve error handling of config functions


// ==UserScript==
// @name           Lighthouse Inline Image Attachments
// @namespace      headinsky.dk
// @description    Show image attachments for Lighthouse tickets inline
// @include        https://*.lighthouseapp.com/*
// @require		     http://code.jquery.com/jquery-latest.js
// ==/UserScript==

var width = $("div#main div.attachments").width();

$("ul.attachment-list li.aimg a").each(function()
{
    img = document.createElement('img');
    img.setAttribute('src', this.getAttribute('href'));
    img.setAttribute('style','max-width: ' + (width-45) + 'px;');
    this.replaceChild(img, this.firstChild);
});

// ==UserScript==
// @name           Lighthouse Inline Image Attachments
// @namespace      headinsky.dk
// @description    Show image attachments for Lighthouse tickets inline
// @include        https://*.lighthouseapp.com/*
// @require		     http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

var width = $("div#main div.attachments").width();

$("ul.attachment-list li.aimg a").each(function()
{
    img = document.createElement('img');
    img.setAttribute('src', this.getAttribute('href'));
    img.setAttribute('style','max-width: ' + (width-45) + 'px;');
    this.replaceChild(img, this.firstChild);
});

Use optimized jQuery from Google APIs


const ex = require('../util/express');
const pdfCore = require('../core/pdf-core');

const getRender = ex.createRoute((req, res) => {
  const opts = {
    // TODO: add all params here
  };

  return pdfCore.render(req.query)
    .then((data) => {
      res.set('content-type', 'application/pdf');
      res.send(data);
    });
});

const postRender = ex.createRoute((req, res) => {
  return pdfCore.render(req.body)
    .then((data) => {
      res.set('content-type', 'application/pdf');
      res.send(data);
    });
});

module.exports = {
  getRender,
  postRender
};

const ex = require('../util/express');
const pdfCore = require('../core/pdf-core');

const getRender = ex.createRoute((req, res) => {
  const opts = {
    url: req.query.url,
    scrollPage: req.query.scrollPage,
    emulateScreenMedia: req.query.emulateScreenMedia,
    waitFor: req.query.waitFor,
    viewport: {
      width: req.query['viewport.width'],
      height: req.query['viewport.height'],
      deviceScaleFactor: req.query['viewport.deviceScaleFactor'],
      isMobile: req.query['viewport.isMobile'],
      hasTouch: req.query['viewport.hasTouch'],
      isLandscape: req.query['viewport.isLandscape'],
    },
    goto: {
      timeout: req.query['goto.timeout'],
      waitUntil: req.query['goto.waitUntil'],
      networkIdleInflight: req.query['goto.networkIdleInflight'],
      networkIdleTimeout: req.query['goto.networkIdleTimeout'],
    },
    pdf: {
      scale: req.query['pdf.scale'],
      displayHeaderFooter: req.query['pdf.displayHeaderFooter'],
      landscape: req.query['pdf.landscape'],
      pageRanges: req.query['pdf.pageRanges'],
      format: req.query['pdf.format'],
      width: req.query['pdf.width'],
      height: req.query['pdf.height'],
      margin: {
        top: req.query['pdf.margin.top'],
        right: req.query['pdf.margin.right'],
        bottom: req.query['pdf.margin.bottom'],
        left: req.query['pdf.margin.left'],
      },
      printBackground: req.query['pdf.printBackground'],
    },
  };

  return pdfCore.render(opts)
    .then((data) => {
      res.set('content-type', 'application/pdf');
      res.send(data);
    });
});

const postRender = ex.createRoute((req, res) => {
  return pdfCore.render(req.body)
    .then((data) => {
      res.set('content-type', 'application/pdf');
      res.send(data);
    });
});

module.exports = {
  getRender,
  postRender
};

Implement parameters for GET request


import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
import {Wrapper} from "./Wrapper";

/**
 * Container Component for BuildSnapshots.
 *
 * @param {*} props input property containing an array of build data to be
 * rendered through BuildSnapshot.
 */
export const BuildSnapshotContainer = React.memo((props) => {
    const SOURCE = '/data';
    const [data, setData] = React.useState([]);

    /**
    * Fetch data when component is mounted.
    * Pass in empty array as second paramater to prevent
    * infinite callbacks as component refreshes.
    * @see Fetching
    */
    React.useEffect(() => {
      fetch(SOURCE).then(res => setData(res.json()));
    }, []);

    return (
      <Wrapper>
        {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)}
      </Wrapper>
    );
  }
);

import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
import {Wrapper} from "./Wrapper";

/**
 * Container Component for BuildSnapshots.
 *
 * @param {*} props input property containing an array of build data to be
 * rendered through BuildSnapshot.
 */
export const BuildSnapshotContainer = React.memo((props) => {
    const SOURCE = '/data';
    const [data, setData] = React.useState([]);

    /**
    * Fetch data when component is mounted.
    * Pass in empty array as second paramater to prevent
    * infinite callbacks as component refreshes.
    *
    * @see Fetching
    */
    React.useEffect(() => {
      fetch(SOURCE).then(res => setData(res.json()));
    }, []);

    return (
      <Wrapper>
        {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)}
      </Wrapper>
    );
  }
);

Add space between comment summary and @see


(function(app) {
  'use strict';

  var jCore = require('jcore');
  var helper = app.helper || require('../helper.js');
  var Module = app.Module || require('./module.js');

  var ModuleContainer = helper.inherits(function(props) {
    ModuleContainer.super_.call(this);

    this.modules = this.prop([]);
    this.element = this.prop(props.element);

    this.deleter = ModuleContainer.prototype.deleter.bind(this);
  }, jCore.Component);

  ModuleContainer.prototype.loadModule = function(props) {
    props.deleter = this.deleter;
    var module = new Module(props);
    this.modules().push(module);
    module.parentElement(this.element());
    module.redraw();
    return module.loadComponent().then(function() {
      return module;
    });
  };

  ModuleContainer.prototype.deleter = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
  };

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleContainer;
  else
    app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));

(function(app) {
  'use strict';

  var jCore = require('jcore');
  var helper = app.helper || require('../helper.js');
  var Module = app.Module || require('./module.js');

  var ModuleContainer = helper.inherits(function(props) {
    ModuleContainer.super_.call(this);

    this.modules = this.prop([]);
    this.element = this.prop(props.element);

    this.deleter = ModuleContainer.prototype.deleter.bind(this);
  }, jCore.Component);

  ModuleContainer.prototype.loadModule = function(props) {
    props.deleter = this.deleter;
    var module = new Module(props);
    this.modules().push(module);
    module.parentElement(this.element());
    module.redraw();
    return module.loadComponent().then(function() {
      return module;
    });
  };

  ModuleContainer.prototype.toFront = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
    modules.push(module);
  };

  ModuleContainer.prototype.deleter = function(module) {
    var modules = this.modules();
    var index = modules.indexOf(module);

    if (index === -1)
      return;

    modules.splice(index, 1);
  };

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleContainer;
  else
    app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));

Add method to move a module on top of others


(function($) {
    function init_editor(e) {
        var editor = $(e);
        var selector = editor.data('selector');
        editor.cropit({
            imageState: {
                src: editor.data('original-image')
            }
        });

        $("body").on('click', '#' + selector + '_btn', function(e) {
            e.preventDefault();
            e.stopPropagation();
          // Move cropped image data to hidden input
          var imageData = editor.cropit('export');
          $('#' + selector).val(imageData);
          return false;
        });
    }

    $(document).ready(function() {
        var editors = $('.image-editor');
        $.each(editors, function(index, value) {
            init_editor(value);
        });
    });

})(django.jQuery);

(function($) {
    function init_editor(e) {
        var editor = $(e);
        var selector = editor.data('selector');
        editor.cropit({
            imageState: {
                src: editor.data('original-image')
            }
        });

        $("form[class*='form'").submit(function( event ) {
            // Move cropped image data to hidden input
            var imageData = editor.cropit('export');
            $('#' + selector).val(imageData);
        });
    }

    $(document).ready(function() {
        var editors = $('.image-editor');
        $.each(editors, function(index, value) {
            init_editor(value);
        });
    });

})(django.jQuery);

Save cropped image on submit and not by clicking on the button.


import { LOAD_PAGE, LOAD_PAGE_REQUEST } from '../actions/constants'

const initialState = {
  page: 1,
  photos: [],
  loading: true
}

export default function (state = initialState, action) {
  switch (action.type) {
    case LOAD_PAGE_REQUEST:
      return Object.assign({}, state, {
        loading: true
      })

    case LOAD_PAGE:
      return Object.assign({}, state, {
        page: action.payload.page,
        photos: action.payload.photos,
        loading: false
      })

    default:
      return state
  }
}

import { LOAD_PAGE, LOAD_PAGE_REQUEST } from '../actions/constants'

const initialState = {
  page: 1,
  photos: [],
  loading: true
}

export default function (state = initialState, action) {
  switch (action.type) {
    case LOAD_PAGE_REQUEST:
      return {
        ...state,
        loading: true
      }

    case LOAD_PAGE:
      return {
        ...state,
        page: action.payload.page,
        photos: action.payload.photos,
        loading: false
      }

    default:
      return state
  }
}

Use object spread operator instead of Object.assign


import { InjectionToken } from 'yabf'

import { LOG_LEVEL } from '../services'

export const OPTION_PATH_FILE_TOKEN = new InjectionToken()

export const APP_LOG_LEVEL_TOKEN = new InjectionToken()
export const APP_LOG_LEVEL = LOG_LEVEL.ALL

import { InjectionToken } from 'yabf'

import { LOG_LEVEL } from '../services'

export const OPTION_PATH_FILE_TOKEN = new InjectionToken()

export const APP_LOG_LEVEL_TOKEN = new InjectionToken()
export const APP_LOG_LEVEL = LOG_LEVEL.ERROR

Set log level to ERROR


var _        = require('lodash');
var os       = require('os');
var path     = require('path');
var crypto   = require('crypto');
var commands = require('./commands.json');

/**
 * Look up the command for executing a file in any language.
 *
 * @param  {String} language
 * @param  {String} file
 * @param  {String} args
 * @return {String}
 */
module.exports = function (language, file, args) {
  // Unsupported language.
  if (!commands[language]) {
    return;
  }

  // Render the language using EJS to enable support for inline JavaScript.
  return _.template(commands[language], {
    file:      file,
    tmpdir:    os.tmpdir(),
    tmpfile:   path.join(os.tmpdir(), crypto.randomBytes(32).toString('hex')),
    dirname:   path.dirname,
    extname:   path.extname,
    basename:  path.basename,
    type:      os.type(),
    arch:      os.arch(),
    platform:  os.platform(),
    sep:       path.sep,
    join:      path.join,
    delimiter: path.delimiter,
    args:      args
  });
};

var _        = require('lodash');
var os       = require('os');
var path     = require('path');
var crypto   = require('crypto');
var commands = require('./commands.json');

/**
 * Look up the command for executing a file in any language.
 *
 * @param  {String} language
 * @param  {String} file
 * @param  {Array}  args
 * @return {String}
 */
module.exports = function (language, file, args) {
  // Unsupported language.
  if (!commands[language]) {
    return;
  }

  // Render the language using EJS to enable support for inline JavaScript.
  return _.template(commands[language], {
    file:      file,
    tmpdir:    os.tmpdir(),
    tmpfile:   path.join(os.tmpdir(), crypto.randomBytes(32).toString('hex')),
    dirname:   path.dirname,
    extname:   path.extname,
    basename:  path.basename,
    type:      os.type(),
    arch:      os.arch(),
    platform:  os.platform(),
    sep:       path.sep,
    join:      path.join,
    delimiter: path.delimiter,
    args:      Array.isArray(args) ? args.map(JSON.stringify).join(' ') : args
  });
};

Support an array of arguments.


(function($) {

  if (!$.cookie('first_time_visitor')) {
    $.cookie('first_time_visitor', true, { expires: 1000, path: '/' });

    var $overlayWrapper = $('.overlay-wrapper');

    $overlayWrapper.show();

    setTimeout(function() {
      $overlayWrapper.addClass('in');
    }, 0);

    $overlayWrapper.find('.close-btn, .go').click(function () {
      if ($.support.transition.end) {
        $overlayWrapper.one($.support.transition.end, function() {
          $overlayWrapper.hide();
        });
      }
      $overlayWrapper.removeClass('in');
    });
  }

})(jQuery);

(function($) {

  if (!$.cookie('first_time_visitor')) {
    $.cookie('first_time_visitor', true, { expires: 1000, path: '/' });

    var $overlayWrapper = $('.overlay-wrapper');

    $overlayWrapper.show();

    setTimeout(function() {
      $overlayWrapper.addClass('in');
    }, 0);

    $overlayWrapper.find('.close-btn, .go').click(function () {
      if ($.support.transition && $.support.transition.end) {
        $overlayWrapper.one($.support.transition.end, function() {
          $overlayWrapper.hide();
        });
      }
      $overlayWrapper.removeClass('in');
    });
  }

})(jQuery);

Fix missing transition variable in map overlay.


"use strict";

var BlogController = require('./controllers/blog');
var BloggerController = require('./controllers/blogger');
var RSS = require('rss');

exports.serveRoutes = function(router) {
	router.get('/main', function(req, res) {
		var mainFeed = new RSS({
			title: "CS Blogs Main Feed",
			description: "All of the blog posts from bloggers on CSBlogs.com",
			feed_url: "http://feeds.csblogs.com/main",
			site_url: "http://csblogs.com",
		});

		BlogController.getAllBlogs({}, function(blogs, error) {
			blogs.forEach(function(blog) {
				mainFeed.item({
					title: 			blog.title,
					description: 	blog.summary,
					url: 			blog.link,
					guid: 			blog.link,
					author: 		"CS Blogs User",
					date: 			blog.pubDate
				});
			});
		});

		res.header('Content-Type','application/rss+xml');
		res.send(mainFeed.xml({indent: true}));
	});
};

"use strict";

var BlogController = require('./controllers/blog');
var BloggerController = require('./controllers/blogger');
var RSS = require('rss');

exports.serveRoutes = function(router) {
	router.get('/main', function(req, res) {
		var mainFeed = new RSS({
			title: "CS Blogs Main Feed",
			description: "All of the blog posts from bloggers on CSBlogs.com",
			feed_url: "http://feeds.csblogs.com/main",
			site_url: "http://csblogs.com",
		});

		BlogController.getAllBlogs({}, function(blogs, error) {
			blogs.forEach(function(blog) {
				mainFeed.item({
					title: 			blog.title,
					description: 	blog.summary,
					url: 			blog.link,
					guid: 			blog.link,
					author: 		"CS Blogs User",
					date: 			blog.pubDate
				});
			});

			res.header('Content-Type','application/rss+xml');
			res.send(mainFeed.xml({indent: true}));
		});
	});
};

Fix for sending XML before async call returns


import Oasis from "oasis";
import { services } from "conductor/services";
import { copy } from "conductor/lang";
import { a_indexOf } from "oasis/shims";

function ConductorCapabilities() {
  this.capabilities = [
    'xhr', 'metadata', 'render', 'data', 'lifecycle', 'height',
    'nestedWiretapping' ];
  this.services = copy(services);
}

ConductorCapabilities.prototype = {
  defaultCapabilities: function () {
    return this.capabilities;
  },

  defaultServices: function () {
    return this.services;
  },

  addDefaultCapability: function (capability, service) {
    if (!service) { service = Oasis.Service; }
    this.capabilities.push(capability);
    this.services[capability] = service;
  },

  removeDefaultCapability: function (capability) {
    var index = a_indexOf.call(this.capabilities, capability);
    if (index) {
      return this.capabilities.splice(index, 1);
    }
  }
};

export default ConductorCapabilities;

import Oasis from "oasis";
import { services } from "conductor/services";
import { copy } from "conductor/lang";
import { a_indexOf } from "oasis/shims";

function ConductorCapabilities() {
  this.capabilities = [
    'xhr', 'metadata', 'render', 'data', 'lifecycle', 'height',
    'nestedWiretapping' ];
  this.services = copy(services);
}

ConductorCapabilities.prototype = {
  defaultCapabilities: function () {
    return this.capabilities;
  },

  defaultServices: function () {
    return this.services;
  },

  addDefaultCapability: function (capability, service) {
    if (!service) { service = Oasis.Service; }
    this.capabilities.push(capability);
    this.services[capability] = service;
  },

  removeDefaultCapability: function (capability) {
    var index = a_indexOf.call(this.capabilities, capability);
    if (index !== -1) {
      return this.capabilities.splice(index, 1);
    }
  }
};

export default ConductorCapabilities;

Fix index check in `removeDefaultCapability`.


/**
 * Defines a dummy module
 *
 * @module Modules/Module
 */

var App;

/**
 * App
 * @param el
 * @constructor
 */
App = function(el) {
	'use strict';

	this.el = el;
};

/**
 * Function used to to render the App
 *
 * @memberof module:Modules/Module
 * @returns {Object} the App itself.
 */
App.prototype.render = function() {
	'use strict';

	// Return false if not 'el' was set in the app.
	if(!this.el) {
		return false;
	}

	this.el.innerHTML = 'App is rendered properly!';
};

module.exports = App;

/**
 * Defines a dummy module
 *
 * @module Modules/Module
 */

var App;

/**
 * App
 * @param el
 * @constructor
 */
App = function(el) {
	'use strict';

	this.el = el;
};

/**
 * Function used to to render the App
 *
 * @memberof module:Modules/Module
 * @returns {Object} The App itself.
 */
App.prototype.render = function() {
	'use strict';

	// Return false if not 'el' was set in the app.
	if(!this.el) {
		return false;
	}

	this.el.innerHTML = 'App is rendered properly!';

	return this;
};

module.exports = App;

Make sure the example App modules render method returns the module


'use strict';
var path = require('path');
var program = require('commander');

var jsdoctest = require('../..');
var packageJson = require('../../package.json');

/**
 * The main command-line utility's entry point.
 *
 * @param {Array.<String>} The `process.argv` array.
 */

exports.run = function(argv) {
  program
    .usage('[FILES...]')
    .version(packageJson.version);

  program.parse(argv);

  if(program.args.length === 0) {
    program.displayUsage();
    process.exit(1);
  }

  // Base test running case
  for(var i = 0, len = program.args.length; i < len; i++) {
    var fileName = program.args[i];
    var failed = jsdoctest.run(path.join(process.cwd(), fileName));

    if(failed) {
      exports._fail(new Error('Tests failed'));
    } else {
      console.log('Tests passed');
    }
  }
};

/**
 * Prints an error to stderr and exits.
 */

exports._fail = function fail(err) {
  console.error(err.message);
  process.exit(err.code || 1);
};

'use strict';
var path = require('path');
var program = require('commander');

var jsdoctest = require('../..');
var packageJson = require('../../package.json');

/**
 * The main command-line utility's entry point.
 *
 * @param {Array.<String>} The `process.argv` array.
 */

exports.run = function(argv) {
  program
    .usage('[FILES...]')
    .version(packageJson.version);

  program.parse(argv);

  if(program.args.length === 0) {
    program.help();
  }

  // Base test running case
  for(var i = 0, len = program.args.length; i < len; i++) {
    var fileName = program.args[i];
    var failed = jsdoctest.run(path.join(process.cwd(), fileName));

    if(failed) {
      exports._fail(new Error('Tests failed'));
    } else {
      console.log('Tests passed');
    }
  }
};

/**
 * Prints an error to stderr and exits.
 */

exports._fail = function fail(err) {
  console.error(err.message);
  process.exit(err.code || 1);
};

Fix help message on wrong calls


function displayKeys() {

    // Retrieve all keyPairs
    var sql = "select K.name from key K";

    dbRetrieve(sql, [], function(res) {

        // Populate key list
        var html = '
';
        for (var i = 0; i < res.rows.length; ++i) {
            var keyName  = res.rows.item(i).name;
            html += '' + keyName + '

';
        }

        // Update GUI
        document.getElementById("key_list").innerHTML = html;
    });
}

function showPubKey(keyName) {

    // Retrieve all keyPairs
    var sql = "select K.keyPair from key K where K.name = ?";

    dbRetrieve(sql, [keyName.toString()], function(res) {

        if (res.rows.length === 1) {

            // Extract public key and create qr-code
            var key = buf2hex(cryptoJS.publicKey(hex2buf(res.rows.item(0).keyPair)));

            alert(key);

            cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, key,
                function (success) {
                    alert('succes');
                    alert("Encode succes: " + success);
                },
                function (fail) {
                    alert('fail');
                    alert("Encoding failed: " + fail);
                }
            );
        }
    });
}

function displayKeys() {

    // Retrieve all keyPairs
    var sql = "select K.name from key K";

    dbRetrieve(sql, [], function(res) {

        // Populate key list
        var html = '<hr>';
        for (var i = 0; i < 1; ++i) {
            var keyName  = res.rows.item(i).name;
            html += '<button onclick="showPubKey(this.innerHTML);">' + keyName + '</button>';
        }

        // Update GUI
        document.getElementById("key_list").innerHTML = html;
    });
}

function showPubKey(keyName) {

    // Retrieve all keyPairs
    var sql = "select K.keyPair from key K where K.name = ?";

    dbRetrieve(sql, [keyName.toString()], function(res) {

        if (res.rows.length === 1) {

            // Extract public key and create qr-code
            var key = buf2hex(cryptoJS.publicKey(hex2buf(res.rows.item(0).keyPair)));

            alert(key);

            cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, key,
                function (success) {
                    alert('succes');
                    alert("Encode succes: " + success);
                },
                function (fail) {
                    alert('fail');
                    alert("Encoding failed: " + fail);
                }
            );
        }
    });
}

Print key on click (try 5 - button)


"use strict";

// modified from https://github.com/es-shims/es6-shim
var keys = Object.keys || require('object-keys');

var assignShim = function assign(target, source) {
	return keys(source).reduce(function (target, key) {
		target[key] = source[key];
		return target;
	}, target);
};

assignShim.shim = function shimObjectAssign() {
    if (!Object.assign) {
        Object.assign = assignShim;
    }
    return Object.assign || assignShim;
};

module.exports = assignShim;

"use strict";

// modified from https://github.com/es-shims/es6-shim
var keys = Object.keys || require('object-keys');

var assignShim = function assign(target, source) {
	var props = keys(source);
	for (var i = 0; i < props.length; ++i) {
		target[props[i]] = source[props[i]];
	}
	return target;
};

assignShim.shim = function shimObjectAssign() {
    if (!Object.assign) {
        Object.assign = assignShim;
    }
    return Object.assign || assignShim;
};

module.exports = assignShim;

Use a for loop, because ES3 browsers don't have "reduce"


'use strict';

var mote = require('mote');

exports.name = 'mote';
exports.outputFormat = 'html';

exports.compile = function (str, options) {
  return mote.compile(str);
};

'use strict';

var mote = require('mote');

exports.name = 'mote';
exports.outputFormat = 'html';

exports.compile = mote.compile;

Make compile use mote's compile


/**
 * Copyright (c) 2016, Christopher Ramírez
 * All rights reserved.
 *
 * This source code is licensed under the MIT license.
 */

'use strict'

const validIdNumberRegExp = /^(\d{3})[ -]?(\d{6})[ -]?(\d{4}\S{1})$/

class NicaraguanId {
    constructor(number) {
        this.fullName = undefined
        this.birthPlace = undefined
        this.birthDate = undefined
        this.validSince = undefined
        this.validThrough = undefined
        this.setNewNumber(number)
    }

    checkNumber(number) {
        if (!validIdNumberRegExp.test(number)) {
            throw `${number} is an invalid nicaraguan ID number.`
        }
    }

    setNewNumber(number) {
        this.checkNumber(number)

        let [_, cityId, birthDigits, consecutive] = validIdNumberRegExp.exec(number)
        this.number = number
        this.cityId = cityId
        this.birthDigits = birthDigits
        this.consecutive = consecutive
        this.birthDate = dateFromSixIntDigits(this.birthDigits)
    }
}

function dateFromSixIntDigits(sixIntDigits) {
    const dateFormat = /^(\d{2})(\d{2})(\d{2})$/
    let [_, day, month, year] = dateFormat.exec(this.birthDigits)
    return new Date(parseInt(year), parseInt(month) -1, parseInt(day))
}

module.exports.NicaraguanId = NicaraguanId

/**
 * Copyright (c) 2016, Christopher Ramírez
 * All rights reserved.
 *
 * This source code is licensed under the MIT license.
 */

'use strict'

const validIdNumberRegExp = /^(\d{3})[ -]?(\d{6})[ -]?(\d{4}\S{1})$/

class NicaraguanId {
    constructor(number) {
        this.fullName = undefined
        this.birthPlace = undefined
        this.birthDate = undefined
        this.validSince = undefined
        this.validThrough = undefined
        this.setNewNumber(number)
    }

    setNewNumber(number) {
        this.checkNumber(number)

        let [_, cityId, birthDigits, consecutive] = validIdNumberRegExp.exec(number)
        this.number = number
        this.cityId = cityId
        this.birthDigits = birthDigits
        this.consecutive = consecutive
        this.birthDate = dateFromSixIntDigits(this.birthDigits)
    }

    checkNumber(number) {
        if (!validIdNumberRegExp.test(number)) {
            throw `${number} is an invalid nicaraguan ID number.`
        }
    }
}

function dateFromSixIntDigits(sixIntDigits) {
    const dateFormat = /^(\d{2})(\d{2})(\d{2})$/
    let [_, day, month, year] = dateFormat.exec(this.birthDigits)
    return new Date(parseInt(year), parseInt(month) -1, parseInt(day))
}

module.exports.NicaraguanId = NicaraguanId

Move checkNumber function to the buttom of class implementation.


Emoji = {};

Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/';

Emoji.convert = function (str) {
    if (typeof str !== 'string') {
        return '';
    }

    return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) {
        var imgName = match.slice(1, -1),
            path = Emoji.baseImagePath + imgName + '.png';
        return '<img class="emoji" alt="' + match + '" src="' + path + '"/>';
    });
};

// borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js
if (Package.templating) {
  var Template = Package.templating.Template;
  var Blaze = Package.blaze.Blaze; // implied by `templating`
  var HTML = Package.htmljs.HTML; // implied by `blaze`

  Blaze.Template.registerHelper('emoji', new Template('emoji', function () {
    var view = this,
        content = '';

    if (view.templateContentBlock) {
      // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}}
      content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING);
    }
    else {
      // this is for the direct usage eg: {{> emoji ':blush:'}}
      content = view.parentView.dataVar.get();
    }
    return HTML.Raw(Emoji.convert(content));
  }));
}

Emoji = {};

Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/';

Emoji.convert = function (str) {
    if (typeof str !== 'string') {
        return '';
    }

    return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) {
        var imgName = match.slice(1, -1),
            path = Emoji.baseImagePath + imgName + '.png';
        return '<img class="emoji" alt="' + match + '" src="' + path + '" draggable="false" />';
    });
};

// borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js
if (Package.templating) {
  var Template = Package.templating.Template;
  var Blaze = Package.blaze.Blaze; // implied by `templating`
  var HTML = Package.htmljs.HTML; // implied by `blaze`

  Blaze.Template.registerHelper('emoji', new Template('emoji', function () {
    var view = this,
        content = '';

    if (view.templateContentBlock) {
      // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}}
      content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING);
    }
    else {
      // this is for the direct usage eg: {{> emoji ':blush:'}}
      content = view.parentView.dataVar.get();
    }
    return HTML.Raw(Emoji.convert(content));
  }));
}

Add draggable attr to <img>s and set it to false


#!/usr/bin/env node
'use strict'; /*jslint node: true, es5: true, indent: 2 */

var Parser = exports.Parser = require('./parser');
var Stringifier = exports.Stringifier = require('./stringifier');

// function logEvents(emitter, prefix, names) {
//   names.forEach(function(name) {
//     emitter.on(name, function(/*...*/) {
//       console.error(prefix + ':' + name, arguments);
//     });
//   });
// }

if (require.main === module) {
  var argv = require('optimist')
    .usage([
      'Consolidate any tabular format.',
      '',
      '  argv will be passed directly to the Stringifier constructor.',
      '  process.stdin will be set to utf8',
    ].join('\n'))
    .argv;

  var parser = new Parser();
  var stringifier = new Stringifier(argv);

  process.stdin.setEncoding('utf8');
  process.stdin.pipe(parser).pipe(stringifier).pipe(process.stdout);
}

#!/usr/bin/env node
'use strict'; /*jslint node: true, es5: true, indent: 2 */

var Parser = exports.Parser = require('./parser');
var Stringifier = exports.Stringifier = require('./stringifier');

// function logEvents(emitter, prefix, names) {
//   names.forEach(function(name) {
//     emitter.on(name, function(/*...*/) {
//       console.error(prefix + ':' + name, arguments);
//     });
//   });
// }

if (require.main === module) {
  var optimist = require('optimist')
    .usage([
      'Consolidate any tabular format.',
      '',
      '  argv will be passed directly to the Stringifier constructor.',
      '  process.stdin will be set to utf8',
      '',
      '  cat data.tsv | sv > data.csv'
    ].join('\n'));

  var parser = new Parser();
  var stringifier = new Stringifier(optimist.argv);

  if (process.stdin.isTTY) {
    optimist.showHelp();
    console.error("You must supply data via STDIN");
  }
  else {
    process.stdin.setEncoding('utf8');
    process.stdin.pipe(parser).pipe(stringifier).pipe(process.stdout);
  }
}

Check for process.stdin.isTTY when run directly


"use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")

module.exports = function (spec, where, cb) {
  if (where instanceof Function) cb = where, where = null
  if (where == null) where = "."
  cb = dz(cb)
  try {
    var dep = npa(spec)
  }
  catch (e) {
    return cb(e)
  }
  var specpath = path.resolve(where, dep.type == "local" ? dep.spec : spec)
  fs.stat(specpath, function (er, s) {
    if (er) return finalize()
    if (!s.isDirectory()) return finalize("local")
    fs.stat(path.join(specpath, "package.json"), function (er) {
      finalize(er ? null : "directory")
    })
  })
  function finalize(type) {
    if (type != null) dep.type = type
    if (dep.type == "local" || dep.type == "directory") dep.spec = specpath
    cb(null, dep)
  }
}

"use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")

module.exports = function (spec, where, cb) {
  if (where instanceof Function) cb = where, where = null
  if (where == null) where = "."
  cb = dz(cb)
  try {
    var dep = npa(spec)
  }
  catch (e) {
    return cb(e)
  }
  var specpath = dep.type == "local"
               ? path.resolve(where, dep.spec)
               : path.resolve(spec)
  fs.stat(specpath, function (er, s) {
    if (er) return finalize()
    if (!s.isDirectory()) return finalize("local")
    fs.stat(path.join(specpath, "package.json"), function (er) {
      finalize(er ? null : "directory")
    })
  })
  function finalize(type) {
    if (type != null) dep.type = type
    if (dep.type == "local" || dep.type == "directory") dep.spec = specpath
    cb(null, dep)
  }
}

Resolve ONLY file:// deps relative to package root, everything else CWD


'use strict'

var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')

module.exports = function CircleBounce (data) {
  return function render (time) {
    var mask = Mask(renderInner(data.radius,  time))
    var outer = renderOuter(data.radius, time, data.fill, mask.id)

    var options = Size({x: data.radius * 2, y: data.radius * 2})

    return svg('svg', options, [
      mask.vtree,
      outer
    ])
  }
}

function renderInner (radius, time) {
  var coefficient = curve(time < 0.5 ? time : 1 - time)

  return Circle({
    radius: radius * coefficient,
    center: radius
  })
}

function renderOuter (radius, time, fill, mask) {
  var coefficent = curve(time < 0.5 ? 1 - time : time)

  return Circle({
    id: 'circle-bounce-circle',
    radius: radius * coefficent,
    center: radius,
    fill: fill,
    mask: mask
  })
}

function curve (value) {
  return bezier(.10, 0.45, .9, .45).get(value)
}

'use strict'

var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')

module.exports = function CircleBounce (data) {
  return function render (time) {
    var mask = Mask(renderInner(data.radius,  time))
    var outer = renderOuter(data.radius, time, data.fill, mask.id)

    var options = Size({x: data.radius * 2, y: data.radius * 2})

    return svg('svg', options, [
      mask.vtree,
      outer
    ])
  }
}

function renderInner (radius, time) {
  var coefficient = 0.95 * curve(time < 0.5 ? time : 1 - time)

  return Circle({
    radius: radius * coefficient,
    center: radius
  })
}

function renderOuter (radius, time, fill, mask) {
  var coefficent = curve(time < 0.5 ? 1 - time : time)

  return Circle({
    id: 'circle-bounce-circle',
    radius: radius * coefficent,
    center: radius,
    fill: fill,
    mask: mask
  })
}

function curve (value) {
  return bezier(.10, 0.45, .9, .45).get(value)
}

Multiply inner circle coefficient by .95 to ensure a stroke remains


const onepass = require("onepass")({
  bundleId: "com.sudolikeaboss.sudolikeaboss"
});

exports.decorateTerm = (Term, { React }) => {
  return class extends React.Component {

    _onTerminal (term) {
      if (this.props && this.props.onTerminal) this.props.onTerminal(term);

      term.uninstallKeyboard();

      term.keyboard.handlers_ = term.keyboard.handlers_.map(handler => {
        if (handler[0] !== "keydown") {
          return handler;
        }

        return [
          "keydown",
          function(e) {
            if (e.metaKey && e.keyCode === 220) {
              onepass.password("sudolikeaboss://local")
                     .then(pass => this.terminal.io.sendString(pass))
                     .catch(() => {});
            }
            return this.onKeyDown_(e);
          }.bind(term.keyboard)
        ];
      });

      term.installKeyboard();
    }

    render () {
      return React.createElement(Term, Object.assign({}, this.props, {
        onTerminal: this._onTerminal
      }));
    }

  };
};

const onepass = require("onepass")({
  bundleId: "com.sudolikeaboss.sudolikeaboss"
});

exports.decorateTerm = (Term, { React }) => {
  return class extends React.Component {

    _onTerminal (term) {
      if (this.props && this.props.onTerminal) this.props.onTerminal(term);

      term.uninstallKeyboard();

      term.keyboard.handlers_ = term.keyboard.handlers_.map(handler => {
        if (handler[0] !== "keydown") {
          return handler;
        }

        const fn = handler[1];

        return [
          "keydown",
          function(e) {
            if (e.metaKey && e.keyCode === 220) {
              onepass.password("sudolikeaboss://local")
                     .then(pass => this.terminal.io.sendString(pass))
                     .catch(() => {});
            }
            return fn(e);
          }.bind(term.keyboard)
        ];
      });

      term.installKeyboard();
    }

    render () {
      return React.createElement(Term, Object.assign({}, this.props, {
        onTerminal: this._onTerminal
      }));
    }

  };
};

Extend existing keydown handler, instead of overriding it


(function(root, factory) {

    if (typeof define === 'function' && define.amd) {

        define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) {

            return (root.Hal = factory(root, Backbone, _, PageableCollection));

        });

    }

    else if (typeof exports !== 'undefined') {

        var Backbone = require('backbone');
        var _ = require('underscore');
        var PageableCollection = require('backbone.paginator');

        module.exports = factory(root, Backbone, _, PageableCollection);

    }

    else {

        root.Hal = factory(root, root.Backbone, root._, root.PageableCollection);

    }

}(this, function(root) {

    'use strict';

    /**
     * @namespace Hal
     */
    var Hal = {};

    // @include link.js
    // @include model.js
    // @include collection.js

    return Hal;

}));

(function(root, factory) {

    if (typeof define === 'function' && define.amd) {

        define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) {

            Backbone.PageableCollection = PageableCollection;

            return (root.Hal = factory(root, Backbone, _));

        });

    }

    else if (typeof exports !== 'undefined') {

        var Backbone = require('backbone');
        var _ = require('underscore');
        Backbone.PageableCollection = require('backbone.paginator');

        module.exports = factory(root, Backbone, _);

    }

    else {

        root.Hal = factory(root, root.Backbone, root._);

    }

}(this, function(root, Backbone, _) {

    'use strict';

    /**
     * @namespace Hal
     */
    var Hal = {};

    // @include link.js
    // @include model.js
    // @include collection.js

    return Hal;

}));

Fix AMD / UMD problems.


#! /usr/bin/env node

var opts = require('optimist').argv
var through = require('through2');

function indexhtmlify(opts) {
    var s = through(function onwrite(chunk, enc, cb) {
        s.push(chunk)
        cb()
    }, function onend(cb) {
        s.push('</script>\n')
        s.push('\n')
        cb()
    })

    s.push('<!DOCTYPE html>\n')
    s.push('\n')
    s.push('\n')
    s.push('<title>---</title>\n')
    s.push('<meta content="width=device-width, initial-scale=1.0, ' +
        'maximum-scale=1.0, user-scalable=0" name="viewport" />\n')
    s.push('<meta charset=utf-8>\n')

    if (opts.style) {
        s.push('\n')
    }

    s.push('\n')
    s.push('

#! /usr/bin/env node

var opts = require('optimist').argv
var through = require('through2');

function indexhtmlify(opts) {
    opts = opts || {}

    var s = through(function onwrite(chunk, enc, cb) {
        s.push(chunk)
        cb()
    }, function onend(cb) {
        s.push('</script>\n')
        s.push('\n')
        cb()
    })

    s.push('<!DOCTYPE html>\n')
    s.push('\n')
    s.push('\n')
    s.push('<title>' + (opts.title || '---') + '</title>\n')
    s.push('<meta content="width=device-width, initial-scale=1.0, ' +
        'maximum-scale=1.0, user-scalable=0" name="viewport" />\n')
    s.push('<meta charset=utf-8>\n')

    if (opts.style) {
        s.push('\n')
    }

    s.push('\n')
    s.push('

Allow passing in a title


const Automerge = require('automerge')

function applyCodeMirrorChangeToAutomerge(state, findList, change, cm) {
  const startPos = cm.indexFromPos(change.from)

  if (change.to.line === change.from.line && change.to.ch === change.from.ch) {
    // nothing was removed.
  } else {
    // delete.removed contains an array of removed lines as strings, so this adds
    // all the lengths. Later change.removed.length - 1 is added for the \n-chars
    // (-1 because the linebreak on the last line won't get deleted)
    let delLen = 0
    for (let rm = 0; rm < change.removed.length; rm++) {
      delLen += change.removed[rm].length
    }
    delLen += change.removed.length - 1
    state = Automerge.changeset(state, 'Delete', doc => {
      findList(doc).splice(startPos, delLen)
    })
  }
  if (change.text) {
    state = Automerge.changeset(state, 'Insert', doc => {
      findList(doc).splice(startPos, 0, ...change.text.join('\n').split(''))
    })
  }
  if (change.next) {
    state = applyCodeMirrorChangeToAutomerge(state, change.next, cm)
  }
  return state
}

module.exports = {
  applyCodeMirrorChangeToAutomerge,
}

const Automerge = require('automerge')

function applyCodeMirrorChangeToAutomerge(state, findList, change, cm) {
  const startPos = cm.indexFromPos(change.from)

  if (change.to.line === change.from.line && change.to.ch === change.from.ch) {
    // nothing was removed.
  } else {
    // delete.removed contains an array of removed lines as strings.
    // each removed line does not include the \n, so we add +1
    // Finally remove 1 because the last \n won't be deleted
    let delLen =
      change.removed.reduce((sum, remove) => sum + remove.length + 1, 0) - 1

    state = Automerge.changeset(state, 'Delete', doc => {
      findList(doc).splice(startPos, delLen)
    })
  }
  if (change.text) {
    state = Automerge.changeset(state, 'Insert', doc => {
      findList(doc).splice(startPos, 0, ...change.text.join('\n').split(''))
    })
  }
  if (change.next) {
    state = applyCodeMirrorChangeToAutomerge(state, change.next, cm)
  }
  return state
}

module.exports = {
  applyCodeMirrorChangeToAutomerge,
}

Use Array.reduce to compute how much to delete


import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'

class App extends Component {
  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

    )
  }
}

export default App

import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'

class App extends Component {
  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

          This project will be the form to submit projects to the Icelandic Web
          Awards.

    )
  }
}

export default App

Add some text to try out ci setup


// DecentCMS (c) 2015 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';

function UrlHelper(scope) {
  this.scope = scope;
}
UrlHelper.prototype.feature = 'content';
UrlHelper.prototype.service = 'url-helper';
UrlHelper.prototype.scope = 'shell';
UrlHelper.prototype.getUrl = function getUrl(id) {
  var middlewares = this.scope.getServices('middleware')
    .sort(function(m1, m2) {
      return m1.routePriority - m2.routePriority;});
  for (var i = 0; i < middlewares.length; i++) {
    var middleware = middlewares[i];
    if (middleware.getUrl) {
      var url = middleware.getUrl(id);
      if (url) return url;
    }
  }
  return '/';
};
module.exports = UrlHelper;

// DecentCMS (c) 2015 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';

function UrlHelper(scope) {
  this.scope = scope;
}
UrlHelper.feature = 'content';
UrlHelper.service = 'url-helper';
UrlHelper.scope = 'shell';
UrlHelper.prototype.getUrl = function getUrl(id) {
  var middlewares = this.scope.getServices('middleware')
    .sort(function(m1, m2) {
      return m1.routePriority - m2.routePriority;});
  for (var i = 0; i < middlewares.length; i++) {
    var middleware = middlewares[i];
    if (middleware.getUrl) {
      var url = middleware.getUrl(id);
      if (url) return url;
    }
  }
  return '/';
};
module.exports = UrlHelper;

Define UrlHelper meta-data on the class instead of the prototype.


describe('traffic', function() {
  beforeEach(function() {
    window.matrix.settings = {
      profileId: ''
    };
    subject =  window.matrix.traffic;
  });
  it('has initial points', function() {
    expect(subject.points).to.eq(720);
  });
  it('has empty counts', function() {
    expect(subject.counts).to.eql([]);
  });
  it('has interval of 2 minutes', function() {
    expect(subject.interval).to.eq(120000);
  });
});

describe('traffic', function() {
  beforeEach(function() {
    window.matrix.settings = {
      profileId: ''
    };
    subject =  window.matrix.traffic;
  });
  it('has initial points', function() {
    expect(subject.points).to.eq(720);
  });
  it('has empty counts', function() {
    expect(subject.counts).to.eql([]);
  });
  it('has interval of 2 minutes', function() {
    expect(subject.interval).to.eq(120000);
  });
  describe('#endpoint', function() {
    it('returns the path to the servers realtime endpoint', function() {
      expect(subject.endpoint()).to.eql('/realtime?ids=ga:&metrics=rt:activeUsers&max-results=10');
    });
    context('with profileId', function() {
      beforeEach(function() {
        window.matrix.settings = {
          profileId: 'Test'
        };
      });
      it('returns correct profile Id in the endpoint path', function() {
        expect(subject.endpoint()).to.eql('/realtime?ids=ga:Test&metrics=rt:activeUsers&max-results=10');
      });
    });
  });
});

Add test for the endpoint method


"use strict";

describe('keyCapture', function() {
  beforeEach(module('arethusa.core'));

  describe('onKeyPressed', function() {
    it('calls the given callback', inject(function(keyCapture) {
      var event = {
        keyCode: 27,
        target: { tagname: '' }
      };
      var callbackCalled = false;
      var callback = function() { callbackCalled = true; };
      keyCapture.onKeyPressed('esc', callback);

      keyCapture.keyup(event);

      expect(callbackCalled).toBe(true);
    }));
  });
});

"use strict";

describe('keyCapture', function() {
  beforeEach(module('arethusa.core'));

  var keyCapture;
  beforeEach(inject(function(_keyCapture_) {
    keyCapture = _keyCapture_;
  }));

  var Event = function(key, shift) {
    this.keyCode = key;
    this.shiftKey = shift;
    this.target = { tagname: '' };
  };

  describe('onKeyPressed', function() {
    it('calls the given callback', function() {
      // 27 is esc
      var event = new Event(27);

      var callbackCalled = false;
      var callback = function() { callbackCalled = true; };
      keyCapture.onKeyPressed('esc', callback);

      keyCapture.keyup(event);

      expect(callbackCalled).toBe(true);
    });

    it('handles shifted keys', function() {
      // 74 is j
      var eventWithShift    = new Event(74, true);
      var eventWithoutShift = new Event(74);
      var e1callbackCalled = 0;
      var e2callbackCalled = 0;
      var e1callback = function() { e1callbackCalled++; };
      var e2callback = function() { e2callbackCalled++; };

      keyCapture.onKeyPressed('J', e1callback);
      keyCapture.onKeyPressed('j', e2callback);

      keyCapture.keyup(eventWithShift);
      expect(e1callbackCalled).toEqual(1);
      expect(e2callbackCalled).toEqual(0);

      keyCapture.keyup(eventWithoutShift);
      expect(e1callbackCalled).toEqual(1);
      expect(e2callbackCalled).toEqual(1);
    });
  });
});

Add spec for new keyCapture modifier handling


require.config({
  paths:{
    jquery: "vendor/assets/javascripts/jquery/jquery-1.7.2.min",
    jsmin: "vendor/assets/javascripts/jsmin",
    polyfills: "vendor/assets/javascripts/polyfills",
    lib: 'public/assets/javascripts/lib',
    handlebars: 'vendor/assets/javascripts/handlebars',
    underscore: 'vendor/assets/javascripts/underscore',
    jplugs: "vendor/assets/javascripts/jquery/plugins",
    pointer: "vendor/assets/javascripts/pointer",
    touchwipe: "vendor/assets/javascripts/jquery.touchwipe.1.1.1",
    s_code: "vendor/assets/javascripts/omniture/s_code"
  }
});

require.config({
  paths:{
    jquery: "vendor/assets/javascripts/jquery/jquery-1.7.2.min",
    jsmin: "vendor/assets/javascripts/jsmin",
    lib: 'public/assets/javascripts/lib',
    handlebars: 'vendor/assets/javascripts/handlebars',
    underscore: 'vendor/assets/javascripts/underscore',
    jplugs: "vendor/assets/javascripts/jquery/plugins",
    pointer: "vendor/assets/javascripts/pointer",
    touchwipe: "vendor/assets/javascripts/jquery.touchwipe.1.1.1",
    s_code: "vendor/assets/javascripts/omniture/s_code"
  }
});

Remove polyfills from the specHelper temporarily (as it fixes a weird bug)


import { useEffect, useState } from 'react';
import { isBlackFridayPeriod } from 'proton-shared/lib/helpers/blackfriday';

const EVERY_TEN_MINUTES = 10 * 60 * 1000;

const useBlackFriday = () => {
    const [blackFriday, setBlackFriday] = useState(isBlackFridayPeriod());

    useEffect(() => {
        const intervalID = setInterval(() => {
            setBlackFriday(isBlackFridayPeriod());
        }, EVERY_TEN_MINUTES);

        return () => {
            clearInterval(intervalID);
        };
    }, []);

    return blackFriday;
};

export default useBlackFriday;

import { useEffect, useState } from 'react';
import { isBlackFridayPeriod } from 'proton-shared/lib/helpers/blackfriday';

const EVERY_MINUTE = 60 * 1000;

const useBlackFriday = () => {
    const [blackFriday, setBlackFriday] = useState(isBlackFridayPeriod());

    useEffect(() => {
        const intervalID = setInterval(() => {
            setBlackFriday(isBlackFridayPeriod());
        }, EVERY_MINUTE);

        return () => {
            clearInterval(intervalID);
        };
    }, []);

    return blackFriday;
};

export default useBlackFriday;

Check BF condition every minute


var isPatched = false;

if (isPatched) return console.log('already patched');

function addColor(string, name) {
  var colors = {
    green: ['\x1B[32m', '\x1B[39m'],
    red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'],
    yellow: ['\x1B[33m', '\x1B[39m']
  }

  return colors[name][0] + string + colors[name][1];
}

function getColorName(methodName) {
  switch (methodName) {
    case 'error': return 'red';
    case 'warn': return 'yellow';
    default: return 'green';
  }
}

['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
  var baseConsoleMethod = console[method];
  var slice = Array.prototype.slice;
  var color = getColorName(method);
  var messageType = method.toUpperCase();
  var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout';

  console[method] = function() {
    var date = (new Date()).toISOString();
    var args = slice.call(arguments);

    if (process[output].isTTY)
      messageType = addColor(messageType, color);

    process[output].write('[' + date + '] ' + messageType + ' ');

    return baseConsoleMethod.apply(console, args);
  }
});

isPatched = true;

var isPatched = false;
var slice = Array.prototype.slice;

if (isPatched) return console.log('already patched');

function addColor(string, name) {
  var colors = {
    green: ['\x1B[32m', '\x1B[39m'],
    red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'],
    yellow: ['\x1B[33m', '\x1B[39m']
  }

  return colors[name][0] + string + colors[name][1];
}

function getColorName(methodName) {
  switch (methodName) {
    case 'error': return 'red';
    case 'warn': return 'yellow';
    default: return 'green';
  }
}

['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
  var baseConsoleMethod = console[method];
  var color = getColorName(method);
  var messageType = method.toUpperCase();
  var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout';

  console[method] = function() {
    var date = (new Date()).toISOString();
    var args = slice.call(arguments);

    if (process[output].isTTY)
      messageType = addColor(messageType, color);

    process[output].write('[' + date + '] ' + messageType + ' ');

    return baseConsoleMethod.apply(console, args);
  }
});

isPatched = true;

Move slice variable assignment out of loop


var fs      = require('fs');
var path    = require('path');
var sass    = require('node-sass');

module.exports = function dmpSass ($, document, done) {
  sass.render({
    file: 'assets/css/style.scss',
    outputStyle: 'compressed',
    sourceMap: false,
    success: function (result) {
      var cache = require('documark-cache')(document);
      var file = cache.fileWriteStream('sass-cache.css');

      file.end(result.css);
      $.root().append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
    },
    error: function (error) {
      console.log(error.message);
    }
  });

  done();
};

var fs          = require('fs');
var path        = require('path');
var sass        = require('node-sass');
var cacheHelper = require('documark-cache');

module.exports = function dmpSass ($, document, done) {
  sass.render({
    file: 'assets/css/style.scss',
    outputStyle: 'compressed',
    sourceMap: false,
    success: function (result) {
      var cache = cacheHelper(document);
      var file = cache.fileWriteStream('sass-cache.css');
      var container = $.('head');

      if ( !container.length ) {
        container = $.root();
      }

      file.end(result.css);
      container.append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');

      done();
    },
    error: function (error) {
      done(error.message);
    }
  });
};

Move documark-cache dependency to top of the document. Check for head container


var postcss = require('postcss'),
    colors = require('color');

module.exports = postcss.plugin('postcss-lowvision', function () {
    return function (css) {
        css.walkDecls('color', function (decl) {
            var color = decl.value
            var rgb = colors.rgb(color);
            decl.value = rgb;
            decl.cloneAfter({ prop: 'text-shadow',
                              value: '0 0 5px rgba(0,0,0,0.5)' });
        });
    };
});

var postcss = require('postcss'),
    color = require('color');

module.exports = postcss.plugin('postcss-lowvision', function () {
    return function (css) {
        css.walkDecls('color', function (decl) {
            var val = decl.value
            var rgb = color(val);
            rgb.rgb();
            decl.value = rgb;
            decl.cloneAfter({ prop: 'text-shadow',
                              value: '0 0 5px rgba(0,0,0,0.5)' });
        });
    };
});

Test to see if colors package works


'use strict'

const driver = require('node-phantom-simple')

function genPromiseFunc(originalFunc) {
  return function () {
    const _args = Array.prototype.slice.call(arguments)
    const _this = this

    return new Promise(function (resolve, reject) {
      _args.push(function () {
        const _args2 = Array.prototype.slice.call(arguments)

        const err = _args2.shift()

        if (err) {
          reject(err)
        } else {
          const _arg3 = _args2.map(function (arg) {
            return promisifyAll(arg)
          })

          resolve.apply(null, _arg3)
        }
      })

      originalFunc.apply(_this, _args)
    })
  }
}

function promisifyAll(target) {
  if (typeof target !== 'object' || Array.isArray(target)) {
    return target
  }

  const promisifiedTarget = {}

  for (let targetPropName of Object.keys(target)) {
    if (typeof target[targetPropName] !== 'function') {
      promisifiedTarget[targetPropName] = target[targetPropName]
      continue
    }

    promisifiedTarget[targetPropName] = genPromiseFunc(target[targetPropName])
  }

  return promisifiedTarget
}

return promisifyAll(driver)

'use strict'

const driver = require('node-phantom-simple')

function genPromiseFunc(originalFunc) {
  return function () {
    const _args = Array.prototype.slice.call(arguments)
    const _this = this

    return new Promise(function (resolve, reject) {
      _args.push(function () {
        const _args2 = Array.prototype.slice.call(arguments)

        const err = _args2.shift()

        if (err) {
          reject(err)
        } else {
          const _arg3 = _args2.map(function (arg) {
            return promisifyAll(arg)
          })

          resolve.apply(null, _arg3)
        }
      })

      originalFunc.apply(_this, _args)
    })
  }
}

function promisifyAll(target) {
  if (typeof target !== 'object' || Array.isArray(target)) {
    return target
  }

  const promisifiedTarget = {}

  for (let targetPropName of Object.keys(target)) {
    if (typeof target[targetPropName] !== 'function') {
      promisifiedTarget[targetPropName] = target[targetPropName]
      continue
    }

    promisifiedTarget[targetPropName] = genPromiseFunc(target[targetPropName])
  }

  return promisifiedTarget
}

module.exports = promisifyAll(driver)

Use module.exports instead of return


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

// Load all stated versions into the module exports
module.exports.version = {};

['2.0.0', '2.0.1', '2.0.2', '2.1.0', '2.1.1', 'latest'].map(function(version) {
    module.exports.version[version] = JSON.parse(
        fs.readFileSync(
            path.join(__dirname, version, 'reference.json'), 'utf8'));
});

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

// Load all stated versions into the module exports
module.exports.version = {};

['2.0.0', '2.0.1', '2.0.2', '2.1.0', '2.1.1', 'latest'].map(function(version) {
    module.exports.version[version] = JSON.parse(
        fs.readFileSync(
            path.join(__dirname, version, 'reference.json'), 'utf8'));
    if (version === 'latest') {
        module.exports.version[version].datasources = JSON.parse(
            fs.readFileSync(
                path.join(__dirname, version, 'datasources.json'), 'utf8')).datasources;
    }
});

Include datasources key in latest reference.


"use strict";

// Return the panorama ID
var getPanoID = function(string) {
	let value = decodeURIComponent(string).match("^https:\/\/.*\!1s(.*)\!2e.*$");

	if (value === null) {
		throw "URL incorrect";
	}

	value = "F:" + value[1];

	return value;
};

// Return Embed URL to use on iframe
var getEmbed = function(string) {
	let id = getPanoID(string);
	let embedURL = "https://www.google.com/maps/embed/v1/streetview?pano=" + id + "&key=YOUR_APIKEY";

	return embedURL;
};

// Method main
var main = function(url, options) {
	try {
		options = options || {};

		if (typeof options !== "object") {
			throw "Expected an object";
		}

		return options.embed === true ? getEmbed(url) : getPanoID(url);
	} catch (error) {
		return error;
	}
};

module.exports = main;

"use strict";

// Return the panorama ID
var getPanoID = function(string) {
	let value = decodeURIComponent(string).match("^https:\/\/.*\!1s(.*)\!2e.*$");

	if (value === null) {
		throw "Incorrect URL";
	}

	return "F:" + value[1];
};

// Return Embed URL to use on iframe
var getEmbed = function(string) {
	let id = getPanoID(string);
	let embedURL = "https://www.google.com/maps/embed/v1/streetview?pano=" + id + "&key=YOUR_APIKEY";

	return embedURL;
};

// Method main
var main = function(url, options) {
	try {
		options = options || {};

		if (typeof options !== "object") {
			throw "Expected an object";
		}

		return options.embed ? getEmbed(url) : getPanoID(url);
	} catch (error) {
		return error;
	}
};

module.exports = main;

Fix typo and remove some illogical code


/*
 * This is a very basic webserver and HTTP Client.
 * In production, you may want to use something like Express.js
 * or Botkit to host a webserver and manage API calls
 */
const {TOKEN, PORT} = process.env,
      triage = require('./triage'),
      qs = require('querystring'),
      axios = require('axios'),
      http = require('http');

// Handle any request to this server and parse the POST
function handleRequest(req, res){
  let body = "";
  req.on('data', data => body += data);
  req.on('end', () => handleCommand(qs.parse(body)));
  res.end('');
}

// Get channel history, build triage report, and respond with results
function handleCommand(payload) {
  let {channel_id, response_url} = payload;

  // load channel history
  let params = qs.stringify({ count: 1000, token: TOKEN, channel: channel_id });
  let getHistory = axios.post('https://slack.com/api/channels.history', params);

  // build the triage report
  let buildReport = result => Promise.resolve( triage(payload, result.data.messages) );

  // post back to channel
  let postResults = results => axios.post(response_url, results);

  // execute
  getHistory.then(buildReport).then(postResults);
}

// start server
http.createServer(handleRequest).listen(PORT, () => console.log(`server started on ${PORT}`));

/*
 * This is a very basic webserver and HTTP Client.
 * In production, you may want to use something like Express.js
 * or Botkit to host a webserver and manage API calls
 */
const {TOKEN, PORT} = process.env,
      triage = require('./triage'),
      qs = require('querystring'),
      axios = require('axios'),
      http = require('http');

// Handle any request to this server and parse the POST
function handleRequest(req, res){
  let body = "";
  req.on('data', data => body += data);
  req.on('end', () => handleCommand(qs.parse(body)));
  res.end('');
}

// Get channel history, build triage report, and respond with results
function handleCommand(payload) {
  let {channel_id, response_url} = payload;

  // load channel history
  let params = qs.stringify({ count: 1000, token: TOKEN, channel: channel_id });
  let getHistory = axios.post('https://slack.com/api/channels.history', params);

  // build the triage report
  let buildReport = result => Promise.resolve( triage(payload, result.data.messages || []) );

  // post back to channel
  let postResults = results => axios.post(response_url, results);

  // execute
  getHistory.then(buildReport).then(postResults).catch(console.error);
}

// start server
http.createServer(handleRequest).listen(PORT, () => console.log(`server started on ${PORT}`));

Handle rejected promise, handle zero message case.


/* eslint-env node */
'use strict';

module.exports = {
  name: 'ember-cli-chart',
  included: function included(app) {
   this._super.included(app);
   app.import(app.bowerDirectory + '/chartjs/dist/Chart.js');
  }
};

/* eslint-env node */
'use strict';

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

    var target = (parentAddon || app);
    if (target.app) {
      target = target.app;
    }

    var bowerDir = target.bowerDirectory;
    app.import(bowerDir + '/chartjs/dist/Chart.js');
  }
};

Allow usage in nested addons


"use strict";

angular.module('arethusa.confEditor').directive('pluginConf', function() {
  return {
    restrict: 'AE',
    scope: true,
    link: function(scope, element, attrs) {
      var name = scope.$eval(attrs.name);
      scope.template = 'templates/configs/' + name + '.html';
    },
    templateUrl: 'templates/plugin_conf.html'
  };
});

"use strict";

angular.module('arethusa.confEditor').directive('pluginConf', function() {
  return {
    restrict: 'AE',
    scope: true,
    link: function(scope, element, attrs) {
      var name = scope.$eval(attrs.name);

      // Right now paths to such configuration are hardcoded to a specific
      // folder. This will be much more dynamic in the future.
      scope.template = 'templates/configs/' + name + '.html';
    },
    templateUrl: 'templates/plugin_conf.html'
  };
});

Add comment to plugin conf


'use strict';

module.exports = function(){

};

'use strict';

var fs = require('fs');
var stream = require('stream');
var readline = require('readline');
var moment = require('moment');

function readFileContent(filename, callback){
  var lines = [];

  var instream = fs.createReadStream(filename);
  var outstream = new stream;
  outstream.readable = true;
  outstream.writable = true;

  var rl = readline.createInterface({
    input: instream,
    output: outstream,
    terminal: false
  });

  rl.on('line', function(line){
    lines.push(formatLine(line));
  });

  rl.on('close', function(){
    callback(null, lines);
  });
}

function formatLine(line) {
  // Remove empty lines
  if(!line || !line.length) {
    return;
  }

  var lineParts = line.split(': ');
  return messageDetails(lineParts);
}
function messageDetails(parts){
  var date = formatDate(parts[0]);

  var details = {
    date: date
  };

  if(parts[2]){
    details.sender = parts[1];

    // remove timestamp and sender info
    parts.splice(0, 2);

    details.message = parts.join(': ');

    return details;
  }

  details.message = parts[1];
  details.announcement = true;

  return details;
}
function formatDate(timestamp){
  if(timestamp.length !== 17){
    throw new Error('Timestamp is of the wrong length:', timestamp);
  }

  return moment(timestamp, 'DD/MM/YY HH:mm:ss').format();
}

module.exports = function(filename){
  return readFileContent.apply(this, arguments);
};

Add initial file-reading and line formatting


var forIn = require('for-in'),
    xobj = require('xhr'),
    XhrError = require('xhrerror');

function noop() { }

function xhr(options, callback, errback) {
  var req = xobj();

  if(Object.prototype.toString.call(options) == '[object String]') {
    options = { url: options };
  }

  req.open(options.method || 'GET', options.url, true);

  if(options.credentials) {
    req.withCredentials = true;
  }

  forIn(options.headers || {}, function (value, key) {
    req.setRequestHeader(key, value);
  });

  req.onreadystatechange = function() {
    if(req.readyState != 4) return;

    if([
      200,
      304,
      0
    ].indexOf(req.status) === -1) {
      (errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status));
    } else {
      (callback || noop)(req.responseText);
    }
  };

  req.send(options.data || void 0);
}

module.exports = xhr;

var forIn = require('for-in'),
    xobj = require('xhr'),
    XhrError = require('xhrerror');

function noop() { }

function xhr(options, callback, errback) {
  var req = xobj();

  if(Object.prototype.toString.call(options) == '[object String]') {
    options = { url: options };
  }

  req.open(options.method || 'GET', options.url, true);

  if(options.credentials) {
    req.withCredentials = true;
  }

  forIn(options.headers || {}, function (value, key) {
    req.setRequestHeader(key, value);
  });

  req.onreadystatechange = function() {
    if(req.readyState != 4) return;

    if([
      200,
      304,
      0
    ].indexOf(req.status) === -1) {
      (errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status));
    } else {
      (callback || noop)(req);
    }
  };

  req.send(options.data || void 0);
}

module.exports = xhr;

Send the req to the callback.


import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";

const googleStorageEndpoint = `http://storage.googleapis.com/akkad-assets-1/`;

const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights;
const {Mesh, Position, Rotate} = systems;

class MeshPage extends Component {
    render() {
        return (

                    Mesh Example

                <Akkad>
                    <Scene>
                        <ArcRotateCamera
                            initialPosition={[0, 0, 100]}
                            target={[0, 0, 0]}
                        />
                        <HemisphericLight />
                        <Mesh
                            path={googleStorageEndpoint}
                            fileName={'skull.babylon'}
                        >
                            <Position vector={[0, 0, 0]}/>
                            <Rotate
                                axis={[0, 1.2, 0]}
                                amount={60}
                                space="LOCAL"
                            />
                        </Mesh>
                    </Scene>
                </Akkad>

        );
    }
}

export default MeshPage;

import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";

const googleStorageEndpoint = `https://storage.googleapis.com/akkad-assets-1/`;

const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights;
const {Mesh, Position, Rotate} = systems;

class MeshPage extends Component {
    render() {
        return (

                    Mesh Example

                <Akkad>
                    <Scene>
                        <ArcRotateCamera
                            initialPosition={[0, 0, 100]}
                            target={[0, 0, 0]}
                        />
                        <HemisphericLight />
                        <Mesh
                            path={googleStorageEndpoint}
                            fileName={'skull.babylon'}
                        >
                            <Position vector={[0, 0, 0]}/>
                            <Rotate
                                axis={[0, 1.2, 0]}
                                amount={60}
                                space="LOCAL"
                            />
                        </Mesh>
                    </Scene>
                </Akkad>

        );
    }
}

export default MeshPage;

Change google storage endpoint to us https


var mozjpeg = require('mozjpeg')
var dcp = require('duplex-child-process')

/**
  * @param {Object} options
  * @param {Number} opts.quality the 1 to 100. Docs suggest 5 to 95 is actual useable range.
  * @param {String} opts.args raw `mozjpeg` args for the connoisseur. See: https://github.com/mozilla/mozjpeg/blob/master/usage.txt#L70
  */
module.exports = function (opts) {
  opts = opts || {}
  // Force the quality flag to be specified, because: https://github.com/mozilla/mozjpeg/issues/181
  opts.quality = opts.quality || 75
  var args = []
  if (opts.quality) args.push('-quality', opts.quality)
  if (opts.args) args.push(opts.args.split[' '])

  var foo = dcp.spawn(mozjpeg, args)
  return foo
}

var mozjpeg = require('mozjpeg')
var dcp = require('duplex-child-process')

/**
  * @param {Object} options
  * @param {Number} opts.quality the 1 to 100. Docs suggest 5 to 95 is actual useable range.
  * @param {String} opts.args raw `mozjpeg` args for the connoisseur. See: https://github.com/mozilla/mozjpeg/blob/master/usage.txt#L70
  */
module.exports = function (opts) {
  opts = opts || {}
  // Force the quality flag to be specified, because: https://github.com/mozilla/mozjpeg/issues/181
  opts.quality = opts.quality || 75
  var args = []
  if (opts.quality) args.push('-quality', opts.quality)
  if (opts.args) {
    args = args.concat(opts.args.split(' '))
  }
  return dcp.spawn(mozjpeg, args)
}

Fix args option not functioning


var Promise = require('bluebird')
var request = require('got')
var extend = require('xtend')

var BASE_URL = 'http://www.broadbandmap.gov/broadbandmap/broadband/jun2014/'

module.exports = function broadbandMap (lat, long, options) {
  options = extend({
    types: ['wireline', 'wireless']
  }, options || {})

  var promises = []

  options.types.forEach(function (type) {
    promises.push(buildRequest(lat, long, type))
  })

  return Promise.all(promises)
  .spread(function (res1, res2) {
    var results = []

    if (res1 && res1.body) results.push(JSON.parse(res1.body).Results)
    if (res2 && res2.body) results.push(JSON.parse(res2.body).Results)

    return results
  })
  .catch(function (err) {
    throw err
  })
}

function buildRequest (lat, long, type) {
  return request.get(BASE_URL + type + '?latitude=' +
    lat + '&longitude=' + long + '&format=json')
}

var Promise = require('bluebird')
var request = require('got')
var extend = require('xtend')

var BASE_URL = 'http://www.broadbandmap.gov/broadbandmap/broadband/jun2014/'

module.exports = function broadbandMap (lat, long, options) {
  options = extend({
    types: ['wireline', 'wireless']
  }, options || {})

  return Promise.map(options.type, buildRequest)
  .spread(function (res1, res2) {
    var results = []

    if (res1 && res1.body) results.push(JSON.parse(res1.body).Results)
    if (res2 && res2.body) results.push(JSON.parse(res2.body).Results)

    return results
  })
  .catch(function (err) {
    throw err
  })

  function buildRequest (type) {
    return request.get(BASE_URL + type + '?latitude=' +
      lat + '&longitude=' + long + '&format=json')
  }
}

Use promise.map to build requests


/*!
 * data-driven
 * Copyright(c) 2013 Fluent Software Solutions Ltd <info@fluentsoftware.co.uk>
 * MIT Licensed
 */

 module.exports = function(data, fn) {
    var mochaIt = it

    data.forEach(function(testData) {
        try {
            it = function(title, f) {

                for (var key in testData) {
                    title = title.replace('{'+key+'}',testData[key])
                }

                var testFn = f.length < 2 ?
                    function() {
                        f(testData)
                    } :
                    function(done) {
                        f(testData,done)
                    }

                mochaIt(title, testFn)
            }

            fn()
        } finally {
            it = mochaIt
        }
    })
}

/*!
 * data-driven
 * Copyright(c) 2013 Fluent Software Solutions Ltd <info@fluentsoftware.co.uk>
 * MIT Licensed
 */

 module.exports = function(data, fn) {
    var mochaIt = it
    var mochaBefore = before

    data.forEach(function(testData) {
        try {
            it = function(title, f) {
                for (var key in testData) {
                    title = title.replace('{'+key+'}',testData[key])
                }

                if (f !== undefined) {
                    var testFn = f.length < 2 ?
                        function() {
                            f(testData)
                        } :
                        function(done) {
                            f(testData,done)
                        }
		}

                mochaIt(title, testFn)
            }

            before = function(f) {
                var testFn = f.length < 2 ?
                    function() {
                        f(testData)
                    } :
                    function(done) {
                        f(testData,done)
                    }

                mochaBefore(testFn)
            }

            fn()
        } finally {
            it = mochaIt
	    before = mochaBefore
        }
    })
}

Add support for pending, undefined it() tests and for data-driving Mocha's before()


'use strict';

function DefaultRegistry(){
  this._tasks = {};
}

DefaultRegistry.prototype.get = function get(name){
  return this._tasks[name];
};

DefaultRegistry.prototype.set = function set(name, fn){
  this._tasks[name] = fn;
};

DefaultRegistry.prototype.tasks = function tasks(){
  return Object.keys(this._tasks).map(this.get, this);
};

module.exports = DefaultRegistry;

'use strict';

function DefaultRegistry(){
  this._tasks = {};
}

DefaultRegistry.prototype.get = function get(name){
  return this._tasks[name];
};

DefaultRegistry.prototype.set = function set(name, fn){
  this._tasks[name] = fn;
};

DefaultRegistry.prototype.tasks = function tasks(){
  var self = this;

  return Object.keys(this._tasks).reduce(function(tasks, name){
    tasks[name] = self.get(name);
    return tasks;
  }, {});
};

module.exports = DefaultRegistry;

Make `.tasks` return an object instead of array


/**
 * Turnpike.JS
 *
 * A lightweight and politely opinionated MVC framework for Node.js. Turnpike can be used as a traditional
 * framework, with code generation and rapid deployment, or invoked as a library for more obscure use cases.
 *
 * Within the framework, some elements will be documented as "plumbing". If you are using Turnpike as a rapid
 * deployment framework, then these should be treated as the internal workings of the Turnpike "black box".
 * You shouldn't need or want to use or call any of the plumbing yourself.
 * If you are using Turnpike as a library, you will probably need use use a good deal of the plumbing directly.
 * If you do this, that's fine, but be aware that continuing development of the Turnpike framework may radically
 * alter the plumbing interfaces at any time, even between minor versions and revisions.
 *
 * Other elements of the framework are documented as "porcelain". These are the entry points to the framework we
 * expect any app relying on Turnpike to use. In general, after the 0.1.0 release, we will aim to maintain the
 * existing plumbing interfaces with few to no changes without a bump in the major version number.
 */

var turnpike = {};

//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");

//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");

module.exports.turnpike = turnpike;

/**
 * Turnpike.JS
 *
 * A lightweight and politely opinionated MVC framework for Node.js. Turnpike can be used as a traditional
 * framework, with code generation and rapid deployment, or invoked as a library for more obscure use cases.
 *
 * Within the framework, some elements will be documented as "plumbing". If you are using Turnpike as a rapid
 * deployment framework, then these should be treated as the internal workings of the Turnpike "black box".
 * You shouldn't need or want to use or call any of the plumbing yourself.
 * If you are using Turnpike as a library, you will probably need use use a good deal of the plumbing directly.
 * If you do this, that's fine, but be aware that continuing development of the Turnpike framework may radically
 * alter the plumbing interfaces at any time, even between minor versions and revisions.
 *
 * Other elements of the framework are documented as "porcelain". These are the entry points to the framework we
 * expect any app relying on Turnpike to use. In general, after the 0.1.0 release, we will aim to maintain the
 * existing plumbing interfaces with few to no changes without a bump in the major version number.
 */

var turnpike = {};

//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");
turnpike.drive = require("./lib/Drive");

//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");
turnpike.Connection = require("./lib/Connection");

module.exports = turnpike;

Declare a few more entry points


var es = require('event-stream');
var coffee = require('coffee-script');
var gutil = require('gulp-util');
var formatError = require('./lib/formatError');
var Buffer = require('buffer').Buffer;

module.exports = function(opt){
  function modifyFile(file, cb){
    if (file.isNull()) return cb(null, file); // pass along
    if (file.isStream()) return cb(new Error("gulp-coffee: Streaming not supported"));

    var str = file.contents.toString('utf8');

    try {
      file.contents = new Buffer(coffee.compile(str, opt));
    } catch (err) {
      var newError = formatError(file, err);
      return cb(newError);
    }
    file.path = gutil.replaceExtension(file.path, ".js");
    cb(null, file);
  }

  return es.map(modifyFile);
};

var es = require('event-stream');
var coffee = require('coffee-script');
var gutil = require('gulp-util');
var formatError = require('./lib/formatError');
var Buffer = require('buffer').Buffer;

module.exports = function(opt){
  function modifyFile(file){
    if (file.isNull()) return this.emit('data', file); // pass along
    if (file.isStream()) return this.emit('error', new Error("gulp-coffee: Streaming not supported"));

    var str = file.contents.toString('utf8');

    try {
      file.contents = new Buffer(coffee.compile(str, opt));
    } catch (err) {
      var newError = formatError(file, err);
      return this.emit('error', newError);
    }
    file.path = gutil.replaceExtension(file.path, ".js");
    this.emit('data', file);
  }

  return es.through(modifyFile);
};

Use es.through instead of es.map


export default function materialConfig($mdThemingProvider) {
  'ngInject';
  $mdThemingProvider.theme('default')
    .primaryPalette('pink')
    .accentPalette('orange');
}

export default function materialConfig($mdThemingProvider) {
  'ngInject';
  $mdThemingProvider.theme('default')
    .primaryPalette('brown')
    .accentPalette('orange');
}

Change primary palette to brown


'use strict';

/**
 * Global config settings.
 * (C) 2015 Diego Lafuente.
 */

 // requires
var Log = require('log');

// globals
exports.logLevel = 'info';
var log = new Log(exports.logLevel);

exports.limit = 100;
exports.expressPort = 8080;
exports.packagesCollection = 'packages';
exports.mongoConnection = 'mongodb://localhost/quality?autoReconnect=true&connectTimeoutMS=5000';
exports.testMongoConnection = 'mongodb://localhost/qualitytest?autoReconnect=true&connectTimeoutMS=5000';

try {
    var localConfig = require("./local-config.js");
    for (var key in localConfig) {
        exports[key] = localConfig[key];
    }
} catch(exception) {
    log.notice("local-config.js not found");
}

'use strict';

/**
 * Global config settings.
 * (C) 2015 Diego Lafuente.
 */

 // requires
var Log = require('log');

// globals
exports.logLevel = 'info';
var log = new Log(exports.logLevel);

exports.limit = 100;
exports.expressPort = 8080;
exports.packagesCollection = 'packages';
exports.mongoConnection = 'mongodb://localhost/quality?autoReconnect=true&connectTimeoutMS=5000';
exports.testMongoConnection = 'mongodb://localhost/qualitytest?autoReconnect=true&connectTimeoutMS=5000';
exports.githubToken = '';

try {
    var localConfig = require("./local-config.js");
    for (var key in localConfig) {
        exports[key] = localConfig[key];
    }
} catch(exception) {
    log.notice("local-config.js not found");
}

Add an empty githubToken to avoid request auth crash


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

module.exports = {
  name: 'emberfire-utils'
};

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

var Funnel = require('broccoli-funnel');
var featuresToExclude = [];

function filterFeatures(addonConfig) {
  addonConfig.exclude.forEach((exclude) => {
    if (exclude === 'firebase-util') {
      featuresToExclude.push('**/firebase-util.js');
      featuresToExclude.push('**/has-limited.js');
    }
  });
}

module.exports = {
  name: 'emberfire-utils',

  included: function(app) {
    this._super.included.apply(this, arguments);

    var addonConfig = this.app.options[this.name];

    if (addonConfig) {
      filterFeatures(addonConfig);
    }
  },

  treeForApp: function() {
    var tree = this._super.treeForApp.apply(this, arguments);

    return new Funnel(tree, { exclude: featuresToExclude });
  },

  treeForAddon: function() {
    var tree = this._super.treeForAddon.apply(this, arguments);

    return new Funnel(tree, { exclude: featuresToExclude });
  },
};

Add base code for tree-shaking


var fs = require( "fs" );
var path = require( "path" );
var slash = require( "slash" );
var through = require( "through2" );

module.exports = function( jadeFile, options ) {
	var scriptTags = "";
	options.root = options.root || process.cwd();

	var write = function( file, encoding, callback ) {
		if( file.path != "undefined" ) {
			scriptTags = scriptTags + "\n" + "script(src=\"" + slash( path.relative( options.root, file.path ) ) + "\")";
		}
		this.push( file );
		callback();
	};

	var flush = function( callback ) {
		fs.writeFile( jadeFile, scriptTags, callback );
	};

	return through.obj( write, flush );
};

var fs = require( "fs" );
var path = require( "path" );
var slash = require( "slash" );
var through = require( "through2" );

module.exports = function( jadeFile, options ) {
	var scriptTags = "";
	options.root = options.root || process.cwd();

	var write = function( file, encoding, callback ) {
		if( file.path != "undefined" ) {
			scriptTags = scriptTags + "script(src=\"" + slash( path.relative( options.root, file.path ) ) + "\")" + "\n";
		}
		this.push( file );
		callback();
	};

	var flush = function( callback ) {
		fs.writeFile( jadeFile, scriptTags, callback );
	};

	return through.obj( write, flush );
};

Put newline at end of output


'use strict';

var buttons = require('sdk/ui/button/action');

buttons.ActionButton({
    id: 'elasticmarks-sidebar-button',
    label: 'Open Elastic Bookmarks Sidebar',
    icon: {
        '16': './bookmark-16.png',
        '32': './bookmark-32.png',
        '64': './bookmark-64.png'
    },
    onClick: handleClick
});

function handleClick() {
    sidebar.show();
}

var sidebar = require('sdk/ui/sidebar').Sidebar({
    id: 'elasticmarks-sidebar',
    title: 'Elastic Bookmarks Sidebar',
    url: './sidebar.html',
    onAttach: function (worker) {
        worker.port.on('bmquery', function(query, queryId) {
            let { search } = require('sdk/places/bookmarks');

            search(
                { query: query }
            ).on('end', function (results) {
                worker.port.emit('queryResults', results, queryId);
            });
        });
    }
});

'use strict';

var buttons = require('sdk/ui/button/action');

buttons.ActionButton({
    id: 'elasticmarks-sidebar-button',
    label: 'Open Elastic Bookmarks Sidebar',
    icon: {
        '16': './bookmark-16.png',
        '32': './bookmark-32.png',
        '64': './bookmark-64.png'
    },
    onClick: handleClick
});

function handleClick() {
    sidebar.show();
}

var sidebar = require('sdk/ui/sidebar').Sidebar({
    id: 'elasticmarks-sidebar',
    title: 'Elastic Bookmarks Sidebar',
    url: './sidebar.html',
    onAttach: function (worker) {
        worker.port.on('bmquery', function(query, queryId) {
            let { search } = require('sdk/places/bookmarks');

            search(
                { query: query }
            ).on('end', function (bookmarks) {
                const fixedBookmarks = bookmarks.map(bookmark => {bookmark.tags = [...bookmark.tags]; return bookmark;});
                worker.port.emit('queryResults', fixedBookmarks, queryId);
            });
        });
    }
});

Make tags accessible in sidebar


var path = require('path');
var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');

module.exports = function(source, map) {
  this.cacheable && this.cacheable();
  this.addDependency(this.resourcePath);
  var callback = this.async();

  // Pass on query parameters as an options object to the DtsCreator. This lets
  // you change the default options of the DtsCreator and e.g. use a different
  // output folder.
  var options = loaderUtils.getOptions(this) || {};
  var context = options.context || this.context || this.rootContext;
  var emitFile = !options.noEmit;

  // Make sure to not modify options object directly
  var creatorOptions = JSON.parse(JSON.stringify(options));
  delete creatorOptions.noEmit;

  var creator = new DtsCreator(creatorOptions);

  // creator.create(..., source) tells the module to operate on the
  // source variable. Check API for more details.
  creator.create(this.resourcePath, source).then(content => {
    if (emitFile) {
        // Emit the created content as well
        this.emitFile(path.relative(context, content.outputFilePath), content.contents || [''], map);
    }
    content.writeFile().then(_ => {
      callback(null, source, map);
    });
  });
};

var path = require('path');
var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');

module.exports = function(source, map) {
  this.cacheable && this.cacheable();
  this.addDependency(this.resourcePath);
  var callback = this.async();

  // Pass on query parameters as an options object to the DtsCreator. This lets
  // you change the default options of the DtsCreator and e.g. use a different
  // output folder.
  var options = loaderUtils.getOptions(this) || {};
  var context = options.context || this.context || this.rootContext;
  var emitFile = !options.noEmit;

  // Make sure to not modify options object directly
  var creatorOptions = Object.assign({}, options);
  delete creatorOptions.noEmit;

  var creator = new DtsCreator(creatorOptions);

  // creator.create(..., source) tells the module to operate on the
  // source variable. Check API for more details.
  creator.create(this.resourcePath, source).then(content => {
    if (emitFile) {
        // Emit the created content as well
        this.emitFile(path.relative(context, content.outputFilePath), content.contents || [''], map);
    }
    content.writeFile().then(_ => {
      callback(null, source, map);
    });
  });
};

Use Object.assign for better performance


var build = require('./build');
var clean = require('./clean');
var copy = require('./copy');
var karma = require('./default-karma.conf');
var lint = require('./lint');
var requirejs = require('./requirejs');
var resolve = require('./resolve');
var test = require('./test');
var teamCity = require('./teamCity');
var typescript = require('./typescript');

module.exports = {
	build: build,
	clean: clean,
	copy: copy,
	karma: karma,
	lint: lint,
	requirejs: requirejs,
	resolve: resolve,
	test: test,
	teamCity: teamCity,
	typescript: typescript,
};

var build = require('./build');
var clean = require('./clean');
var compile = require('./compile');
var copy = require('./copy');
var karma = require('./default-karma.conf');
var lint = require('./lint');
var requirejs = require('./requirejs');
var resolve = require('./resolve');
var teamCity = require('./teamCity');
var test = require('./test');
var typescript = require('./typescript');

module.exports = {
	build: build,
	clean: clean,
	compile: compile,
	copy: copy,
	karma: karma,
	lint: lint,
	requirejs: requirejs,
	resolve: resolve,
	teamCity: teamCity,
	test: test,
	typescript: typescript,
};

Add compile and rearrange (alphabetical)


const Assert = require('assert');
const FS = require('fs');

const Winston = require('winston');

const Factory = require('./lib/factory');

var exceptionLogger;

function isString(str) {
  return typeof str === 'string';
}

module.exports = function (namespace) {
  var level;

  Assert(namespace && isString(namespace), 'must provide namespace');
  level = process.env.LOG_LEVEL || 'info'; // eslint-disable-line no-process-env

  return Factory(namespace, level, !exceptionLogger);
};

module.exports.writeExceptions = function (path) {
  Assert(path && isString(path), 'must provide a file path');

  // TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0
  FS.appendFileSync(path, ''); // eslint-disable-line no-sync

  exceptionLogger = new Winston.Logger({
    transports: [
      new Winston.transports.File({
        exitOnError: true,
        filename: path,
        handleExceptions: true,
        humanReadableUnhandledException: true
      })
    ]
  });
};

const Assert = require('assert');
const FS = require('fs');

const Winston = require('winston');

const Factory = require('./lib/factory');

var exceptionLogger;

function isString(str) {
  return typeof str === 'string';
}

module.exports = function (namespace) {
  var level;

  Assert(namespace && isString(namespace), 'must provide namespace');
  level = process.env.LOG_LEVEL || 'info'; // eslint-disable-line no-process-env

  return Factory(namespace, level, !exceptionLogger);
};

module.exports.writeExceptions = function (path, exitOnError) {
  Assert(path && isString(path), 'must provide a file path');

  // TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0
  FS.appendFileSync(path, ''); // eslint-disable-line no-sync

  exceptionLogger = new Winston.Logger({
    transports: [
      new Winston.transports.File({
        exitOnError: exitOnError,
        filename: path,
        handleExceptions: true,
        humanReadableUnhandledException: true
      })
    ]
  });
};

Add exitOnError as optional parameter


$(document).ready(function() {
  $("#date_range").daterangepicker({ format: 'YYYY-MM-DD' });

  $("#date_range").on('apply.daterangepicker', function(ev, picker){
    Chartkick.eachChart( function(chart) {
      var path, search;
      [path, search] = chart.dataSource.split('?')
      var params = new URLSearchParams(search);
      params.set('date_start', picker.startDate.format('YYYY-MM-DD'));
      params.set('date_end', picker.endDate.format('YYYY-MM-DD'));
      chart.dataSource = path + '?' + params.toString();
      chart.refreshData();
    });
  });
});

$(document).ready(function() {
  $("#date_range").daterangepicker({
    locale: { format: 'YYYY-MM-DD' }
  });

  $("#date_range").on('apply.daterangepicker', function(ev, picker){
    Chartkick.eachChart( function(chart) {
      var path, search;
      [path, search] = chart.dataSource.split('?')
      var params = new URLSearchParams(search);
      params.set('date_start', picker.startDate.format('YYYY-MM-DD'));
      params.set('date_end', picker.endDate.format('YYYY-MM-DD'));
      chart.dataSource = path + '?' + params.toString();
      chart.refreshData();
    });
  });
});

Fix date ranrge picker format


'use strict'

const port = 5000

var server = require('./server')

server.listen(port, () => console.log('Server is up on port %d.', port))

'use strict'

let ENV
try { // look for local environment variable file first
  ENV = require('./env')
} catch (LocalEnvFileNotFound) {
  ENV = process.env
}

const PORT = ENV.PORT || 5000

let server = require('./server')

server.listen(PORT, () => console.log('Server is up on port %d.', PORT))

Use port specified in environment for server