import dotenv from 'dotenv';
import authControllers from '../controllers';
import authenticate from '../middleware/authenticate';

const usersController = authControllers.users;
const loginController = authControllers.login;
const groupsController = authControllers.group;
const messagesController = authControllers.messages;

dotenv.config();

module.exports = (app) => {
  app.get('/api', (req, res) => res.status(200).send({
    message: 'Welcome to the Postit API!',
  }));

  app.post('/api/user/signin', loginController.login);

  app.post('/api/user/signup', usersController.create);

  // An API route that allow users create broadcast groups:
  // POST: /api/group
  app.post('/api/group', authenticate, groupsController.create);

  // An API route that allow users add other users to groups:
  app.post('/api/group/:groupid/user', authenticate, groupsController.addNewUser);

  // An API route that allows a logged in user post messages to created groups:
  app.post('/api/group/:groupid/message', authenticate, messagesController.create);

  // An API route that allows a logged in user retrieve messages that have been
  // posted to groups he/she belongs to:
  app.get('/api/group/:groupid/messages', authenticate, groupsController.list);

  // Root route
  app.get('*', (req, res) => res.send('Sorry, the page u requested does not exist'));
};

import dotenv from 'dotenv';
import authControllers from '../controllers';
import authenticate from '../middleware/authenticate';
import validateGroup from '../middleware/validateGroup';

const usersController = authControllers.users;
const loginController = authControllers.login;
const groupsController = authControllers.group;
const messagesController = authControllers.messages;

dotenv.config();

module.exports = (app) => {
  app.get('/api', (req, res) => res.status(200).send({
    message: 'Welcome to the Postit API!',
  }));

  app.post('/api/user/signin', loginController.login);

  app.post('/api/user/signup', usersController.create);

  // An API route that allow users create broadcast groups:
  // POST: /api/group
  app.post('/api/group', authenticate, validateGroup.name, groupsController.create);

  // An API route that allow users add other users to groups:
  app.post('/api/group/:groupid/user', authenticate, groupsController.addNewUser);

  // An API route that allows a logged in user post messages to created groups:
  app.post('/api/group/:groupid/message', authenticate, messagesController.create);

  // An API route that allows a logged in user retrieve messages that have been
  // posted to groups he/she belongs to:
  app.get('/api/group/:groupid/messages', authenticate, groupsController.list);

  // Root route
  app.get('*', (req, res) => res.send('Sorry, the page u requested does not exist'));
};

Add group validation middleware to routes


var settings = require('../../settings.json');

/**
 * Returns true if the build is running in production mode
 *
 * @returns {Boolean} True if production mode is enabled
 */
var isProductionBuild = function() {
  if(process.env.NODE_ENV && process.env.NODE_ENV === 'prod') {
    return true;
  }

  return false;
};

/**
 * Get the root build folder by checking the NODE_ENV variable
 *
 * @returns {String} The root folder for the build
 */
var getBuildRootFolder = function() {
  if(isProductionBuild()) {
    return settings.build.prodDir;
  }

  return settings.build.devDir;
};

module.exports = {
  isProductionBuild: isProductionBuild,
  getBuildRootFolder: getBuildRootFolder
}

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

/**
 * Returns true if the build is running in production mode
 *
 * @returns {Boolean} True if production mode is enabled
 */
var isProductionBuild = function() {
  if(process.env.NODE_ENV && process.env.NODE_ENV === 'prod') {
    return true;
  }

  return false;
};

/**
 * Get the root build folder by checking the NODE_ENV variable
 *
 * @returns {String} The root folder for the build
 */
var getBuildRootFolder = function() {
  if(isProductionBuild()) {
    return config.build.prodDir;
  }

  return config.build.devDir;
};

/**
 * Create the build folder if it doesn't exist
 */
var createBuildRootFolderIfNotAvailable = function() {
  var buildFolder = getBuildRootFolder();

  if (!fs.existsSync(buildFolder)) {
    fs.mkdirSync(buildFolder);
  }
};

module.exports = {
  isProductionBuild: isProductionBuild,
  getBuildRootFolder: getBuildRootFolder,
  createBuildRootFolderIfNotAvailable: createBuildRootFolderIfNotAvailable
}

Add helper to create build folder


/* eslint-env node */
module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_args: {
    Chrome: [
      '--disable-gpu',
      '--headless',
      '--remote-debugging-port=9222',
      '--window-size=1440,900'
    ]
  }
};

/* eslint-env node */
module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_args: {
    Chrome: [
      '--disable-gpu',
      '--headless',
      '--no-sandbox',
      '--remote-debugging-port=9222',
      '--window-size=1440,900'
    ]
  }
};

Fix issues with sudo: false infra on Travis CI.


(function (module) {
    module.controller('ProjectHomeController', ProjectHomeController);
    ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state"];

    function ProjectHomeController(project, mcmodal, templates, $state) {
        var ctrl = this;

        ctrl.project = project;
        ctrl.chooseTemplate = chooseTemplate;
        ctrl.chooseExistingProcess = chooseExistingProcess;
        ctrl.createSample = createSample;
        ctrl.useTemplate = useTemplate;
        ctrl.templates = templates;

        /////////////////////////

        function chooseTemplate() {
            mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
                $state.go('projects.project.processes.create', {process: processTemplateName});
            });
        }

        function useTemplate(templateName) {
            $state.go('projects.project.processes.create', {process: templateName});
        }

        function createSample() {
            $state.go('projects.project.processes.create', {process: 'As Received'});
        }

        function chooseExistingProcess() {
            mcmodal.chooseExistingProcess(ctrl.project).then(function (existingProcess) {
                $state.go('projects.project.processes.create', {process:  existingProcess.process_name, process_id: existingProcess.id});
            });
        }
    }
}(angular.module('materialscommons')));

(function (module) {
    module.controller('ProjectHomeController', ProjectHomeController);
    ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];

    function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
        var ctrl = this;

        ctrl.project = project;
        ctrl.chooseTemplate = chooseTemplate;
        ctrl.chooseExistingProcess = chooseExistingProcess;
        ctrl.createSample = createSample;
        ctrl.useTemplate = useTemplate;
        ctrl.templates = templates;

        /////////////////////////

        function chooseTemplate() {
            mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
                $state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
            });
        }

        function useTemplate(templateName) {
            $state.go('projects.project.processes.create', {process: templateName, process_id: ''});
        }

        function createSample() {
            $state.go('projects.project.processes.create', {process: 'As Received', process_id: ''});
        }

        function chooseExistingProcess() {
            Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
                mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
                    var processName = existingProcess.process_name ? existingProcess.process_name : 'TEM';
                    $state.go('projects.project.processes.create', {process: processName, process_id: existingProcess.id});
                });
            });
        }
    }
}(angular.module('materialscommons')));

Add process_id into the $state.go statements. Have chooseExistingProcess make a REST call to get the list of processes.


'use strict';

angular.module('admin').controller('ReloadController', ['$scope', 'Admin',
	function($scope, Admin) {
		 $scope.reload = function () {
             Admin.reload(function(res) {
                 $scope.reloadedDevices = res.reloadedDevices;
             });
         };
	}
]);

'use strict';

angular.module('admin').controller('ReloadController', ['$scope', '$location', 'Authentication', 'Admin',
	function($scope, $location, Authentication, Admin) {
        // If user is not signed in then redirect back home
        if (!Authentication.user) $location.path('/');

		 $scope.reload = function () {
             Admin.reload(function(res) {
                 $scope.reloadedDevices = res.reloadedDevices;
             });
         };
	}
]);

Fix not logged-in users being able to access the reload page.


const express = require('express'),
      app = express(),
      bodyParser = require('body-parser'),
      methodOverride = require('method-override'),
      mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mojibox');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));

const userRoutes = require('./routes/users');
const emoticonRoutes = require('./routes/emoticons');

app.use('/user', userRoutes);
app.use('/user/:username/collection', emoticonRoutes);

app.get('/', function(req, res, next) {
  res.redirect('/user');
});

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.listen(3000, function() {
  console.log('Server is listening on port 3000');
});

const express = require('express'),
      app = express(),
      bodyParser = require('body-parser'),
      methodOverride = require('method-override'),
      mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mojibox');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));

const userRoutes = require('./routes/users');
const emoticonRoutes = require('./routes/emoticons');

app.use('/user', userRoutes);
app.use('/user/:username/collection', emoticonRoutes);

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

app.get('/', function(req, res, next) {
  res.redirect('/user');
});

app.listen(3000, function() {
  console.log('Server is listening on port 3000');
});

Reorder error handler and '/' route


console.warn();
console.warn('This package (facebook) has been deprecated.');
console.warn("You should not use this anymore.");
console.warn(
    "If you need the export Facebook, you can now simply use facebook-oauth" +
    "and import from it. If you need the Blaze OAuth configuration UI, add the " +
    "facebook-config-ui along with accounts-ui."
);
console.warn();

console.warn();
console.warn('This package (facebook) has been deprecated.');
console.warn(
  "To use the `Facebook` symbol, use the `facebook-oauth` package " +
  "and import from it."
);
console.warn(
    "If you need the Blaze OAuth configuration UI, add " +
    "`facebook-config-ui` alongside `accounts-ui`."
);
console.warn();

Change the wording a little


var Cart = function(baseUrl) {
  var self = this
  this.baseUrl = baseUrl
  this.userID = '';
  this.online = []
  ko.track(this)
}

Cart.prototype = Object.create(Array.prototype)

Cart.prototype.doesntContain = function(doc) {
  var found = false
  for (var i=0; i<this.length; ++i) {
    found = (this[i].id === doc.id ? true : found)
  }
  return !found
}

Cart.prototype.add = function(doc) {
  if (this.doesntContain(doc)) {
    this.push(doc)
  }
}

Cart.prototype.drop = function(doc) {
  var index = this.indexOf(doc)
  if (index < 0) {
    return
  }
  this.splice(index, 1)
}

Cart.prototype.save = function() {
  var self = this
  if (this.userID === '') {
    alert('Please enter a user name first.')
    return
  }
  var docIDs = []
  for (var i=0; i<self.length; i++) {
    docIDs.push(self[i].id)
  }
  $.ajax({
    url: this.baseUrl + '/data/carts/' + this.userID,
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(docIDs),
    success: function() {
      for (var i=0; i<self.length; i++) {
        self.online.push(self[i])
      }
      self.splice(0, self.length)
    }
  })
}

var Cart = function(baseUrl) {
  var self = this
  this.baseUrl = baseUrl
  this.userID = '';
  this.online = []
  ko.track(this)
}

Cart.prototype = Object.create(Array.prototype)

Cart.prototype.doesntContain = function(doc) {
  var found = false
  for (var i=0; i<this.length; ++i) {
    found = (this[i].id === doc.id ? true : found)
  }
  return !found
}

Cart.prototype.add = function(doc) {
  if (this.doesntContain(doc)) {
    this.push(doc)
  }
}

Cart.prototype.drop = function(doc) {
  var index = this.indexOf(doc)
  if (index < 0) {
    return
  }
  this.splice(index, 1)
}

Cart.prototype.save = function() {
  var self = this
  if (this.userID === '') {
    alert('Please enter a user name first.')
    return
  }
  var docIDs = []
  for (var i=0; i<self.length; i++) {
    docIDs.push(self[i].id)
  }
  $.ajax({
    url: this.baseUrl + '/data/carts/' + this.userID,
    type: 'POST',
    contentType: 'application/json; charset=UTF-8',
    data: JSON.stringify(docIDs),
    success: function() {
      for (var i=0; i<self.length; i++) {
        self.online.push(self[i])
      }
      self.splice(0, self.length)
    }
  })
}

Add charset specification to ajax request.


require('dotenv/config');
const request = require('then-request');

let server = null;

let url = null;
switch (process.argv[2]) {
  case 'local':
    url = 'http://localhost:3000';
    server = require('../server');
    process.env.PIPERMAIL_SOURCE = 'https://mail.mozilla.org/pipermail/es-discuss/';
    break;
  case 'staging':
    url = 'https://esdiscuss-bot-staging.herokuapp.com';
    break;
  case 'prod':
    url = 'https://bot.esdiscuss.org';
    break;
  default:
    console.error('Unrecognised environment ' + process.argv[2]);
    process.exit(1);
    break;
}

const timeout = Date.now() + 10 * 60 * 1000;
function poll() {
  request('GET', url).done(res => {
    if (res.statusCode === 503 && Date.now() < timeout) {
      return poll();
    }
    if (res.statusCode !== 200) {
      console.log(res.body.toString('utf8'));
      process.exit(1);
    } else if (server) {
      process.exit(0);
    }
  });
}
poll();

require('dotenv/config');
const request = require('then-request');

let server = null;

let url = null;
switch (process.argv[2]) {
  case 'local':
    url = 'http://localhost:3000';
    server = require('../server');
    process.env.PIPERMAIL_SOURCE = 'https://mail.mozilla.org/pipermail/es-discuss/';
    break;
  case 'staging':
    url = 'https://esdiscuss-bot-staging.herokuapp.com';
    break;
  case 'prod':
    url = 'https://bot.esdiscuss.org';
    break;
  default:
    console.error('Unrecognised environment ' + process.argv[2]);
    process.exit(1);
    break;
}

const slow = Date.now() + 60 * 1000;
const timeout = Date.now() + 5 * 60 * 1000;
function poll() {
  request('GET', url).done(res => {
    if (res.statusCode === 503 && Date.now() < timeout) {
      if (Date.now() > slow) {
        console.log(res.body.toString('utf8'));
      }
      return poll();
    }
    if (res.statusCode !== 200) {
      console.log(res.body.toString('utf8'));
      process.exit(1);
    } else if (server) {
      process.exit(0);
    }
  });
}
poll();

Reduce test timeout to 5 minutes


'use strict';

const http = require('http');
const path = require('path');
const url  = require('url');
const auth = require('http-auth');
const HttpStatusCodes = require('http-status-codes');
const stream_file_to_bd = require('./lib/stream_file_to_bd');

const basic_auth = auth.basic({
  realm: 'Vidya',
  file:  path.join(__dirname, 'test', 'test_files', 'htpasswd')
});

const app = (request, response) => {
  const target_url = new url.URL(request.url, 'http://localhost');

  if (target_url.pathname !== '/') {
    return reject_connection(response, HttpStatusCodes.NOT_FOUND);
  }

  if (request.method !== 'PUT') {
    return reject_connection(response, HttpStatusCodes.METHOD_NOT_ALLOWED);
  }

  stream_file_to_bd(request)
    .then(_ => {
      response.writeHead(HttpStatusCodes.OK, { 'Content-Type': 'text/plain' });
      response.end();
    })
    .catch(_ => {
      reject_connection(response, HttpStatusCodes.INTERNAL_SERVER_ERROR);
    });
};

function reject_connection (response, status) {
  response.writeHead(status, { 'Content-Type': 'text/plain' });
  return response.end();
}

module.exports = http.createServer(basic_auth.check(app));

'use strict';

const http = require('http');
const path = require('path');
const url  = require('url');
const auth = require('http-auth');
const HttpStatusCodes = require('http-status-codes');
const stream_file_to_bd = require('./lib/stream_file_to_bd');

const basic_auth = auth.basic({
  realm: 'Vidya',
  file:  path.join(__dirname, 'test', 'test_files', 'htpasswd')
});

const app = (request, response) => {
  const target_url = new url.URL(request.url, 'http://localhost');

  if (target_url.pathname !== '/') {
    return reject_connection(response, HttpStatusCodes.NOT_FOUND);
  }

  if (request.method !== 'PUT') {
    return reject_connection(response, HttpStatusCodes.METHOD_NOT_ALLOWED);
  }

  stream_file_to_bd(request)
    .then(() => {
      response.writeHead(HttpStatusCodes.OK, { 'Content-Type': 'text/plain' });
      response.end();
    })
    .catch(() => {
      reject_connection(response, HttpStatusCodes.INTERNAL_SERVER_ERROR);
    });
};

function reject_connection (response, status) {
  response.writeHead(status, { 'Content-Type': 'text/plain' });
  return response.end();
}

module.exports = http.createServer(basic_auth.check(app));

Replace _ with () on callbacks that don't use any argument


(function (window, document, $, undefined) {

})(window, document, jQuery);

(function (window, document, $, undefined) {

  var rockhopper = function () {

    return {

    };
  }();

})(window, document, jQuery);

Set up revealing module patter


var quilt = require("@quilt/quilt");

exports.New = function(count) {
    var inf = quilt.createDeployment({});

    var machine = new quilt.Machine({
        provider: "Amazon",
        size: "m4.xlarge",
        sshKeys: quilt.githubKeys("ejj"),
    });

    inf.deploy(machine.asMaster());
    inf.deploy(machine.asWorker().replicate(count));
    return inf
}

var quilt = require("@quilt/quilt");

exports.New = function(count) {
    var inf = quilt.createDeployment({});

    var machine = new quilt.Machine({
        provider: "Amazon",
        cpus: new quilt.Range(4, 8),
        ram: new quilt.Range(16, 64),
        sshKeys: quilt.githubKeys("ejj"),
    });

    inf.deploy(machine.asMaster());
    inf.deploy(machine.asWorker().replicate(count));
    return inf
}

Switch to generic instance specification


if (typeof(window.less) === 'undefined') { window.less = {}; }
less = window.less;
tree = window.less.tree = {};
less.mode = 'browser';

if (typeof(window.less) === 'undefined' || typeof(window.less.nodeType) !== 'undefined') { window.less = {}; }
less = window.less;
tree = window.less.tree = {};
less.mode = 'browser';

Fix IE8 issue if 'less' is a dom element


'use strict';

const
    Command = require('../Command'),
    MentionsMiddleware = require('../../middleware/MentionsMiddleware'),
    RestrictChannelsMiddleware = require('../../middleware/RestrictChannelsMiddleware');

class CommandWelcome extends Command {
    constructor(module, commandConfig) {
        super(module, commandConfig);

        this.id = 'welcome';
        this.helpText = 'Welcomes people to the server and directs them to the read-first channel.';
        this.shortHelpText = 'Welcomes people to the server';

        this.middleware = [
            new RestrictChannelsMiddleware({ types: 'text' }),
            new MentionsMiddleware({ types: 'mention' })
        ];
    }

    onCommand(response) {
        const welcomeChannel = response.message.guild.channels.get(this.config.get.target_channel);
        return (
            `Hey there {mentions}, welcome to The Raiders Inn! ` +
            `Be sure to head over to ${welcomeChannel} to get started. ` +
            'You will find our rules and general information there. ' +
            `Don't forget to assign yourself to a server!\n\n` +
            'Enjoy your stay! :beers:'
        );
    }
}

module.exports = CommandWelcome;

'use strict';

const
    Command = require('../Command'),
    MentionsMiddleware = require('../../middleware/MentionsMiddleware'),
    RestrictChannelsMiddleware = require('../../middleware/RestrictChannelsMiddleware');

class CommandWelcome extends Command {
    constructor(module, commandConfig) {
        super(module, commandConfig);

        this.id = 'welcome';
        this.helpText = 'Welcomes people to the server and directs them to the read-first channel.';
        this.shortHelpText = 'Welcomes people to the server';

        this.middleware = [
            new RestrictChannelsMiddleware({ types: 'text' }),
            new MentionsMiddleware({ types: 'mention' })
        ];
    }

    onCommand(response) {
        const welcomeChannel = response.message.guild.channels.get(this.config.target_channel);
        return (
            `Hey there {mentions}, welcome to The Raiders Inn! ` +
            `Be sure to head over to ${welcomeChannel} to get started. ` +
            'You will find our rules and general information there. ' +
            `Don't forget to assign yourself to a server!\n\n` +
            'Enjoy your stay! :beers:'
        );
    }
}

module.exports = CommandWelcome;

Fix target channel of !welcome


var $ = require('jquery');
var m = require('mithril');
var Meetings = require('../meetings.js');
var Submissions = require('../submissions.js');

new Meetings(window.contextVars.meetings);

var request = $.getJSON('/api/v1/meetings/submissions/');
var DonateBanner = require('js/home-page/donateBannerPlugin');
var columnSizeClass = '.col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2';

request.always(function() {
    $('#allMeetingsLoader').hide();
});
request.done(function(data) {
    new Submissions(data.submissions);
});

$(document).ready(function(){
    var osfDonateBanner = {
        view : function(ctrl, args) {
            return [
                m(DonateBanner.background, m('.container',
                    [
                        m('.row', [
                            m(columnSizeClass,  m.component(DonateBanner.Banner, {}))
                        ])
                    ]
                )),
            ];
        }
    };
    m.mount(document.getElementById('osfDonateBanner'), m.component(osfDonateBanner, {}));
});

var $ = require('jquery');
var m = require('mithril');
var Meetings = require('../meetings.js');
var Submissions = require('../submissions.js');

new Meetings(window.contextVars.meetings);

var request = $.getJSON('/api/v1/meetings/submissions/');
var DonateBanner = require('js/home-page/donateBannerPlugin');
var columnSizeClass = '.col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2';

request.always(function() {
    $('#allMeetingsLoader').hide();
});
request.done(function(data) {
    new Submissions(data.submissions);
});

$(document).ready(function(){
    var osfDonateBanner = {
        view : function(ctrl, args) {
            return [
                m('.donate-banner-background', m('.container',
                    [
                        m(columnSizeClass, m.component(DonateBanner, {}))
                    ]
                )),
            ];
        }
    };
    m.mount(document.getElementById('osfDonateBanner'), m.component(osfDonateBanner, {}));
});

Fix to work on meetings landing page


(function (App) {
  'use strict';

  App.View.ColorSelectorView = Backbone.View.extend({
    events: {
      'change input[type="color"]': '_updateColor'
    },

    /**
     * Update the color corresponding to the modified input
     * @param {Event} e - DOM input node
     */
    _updateColor: function (e) {
      var color = e.currentTarget.value;
      var textInput = this.el.querySelector('input[type="text"]');

      textInput.value = color;
    }
  });
})(this.App);

(function (App) {
  'use strict';

  App.View.ColorSelectorView = Backbone.View.extend({
    events: {
      'change input[type="text"]': '_updateColor',
      'change input[type="color"]': '_updateColor'
    },

    /**
     * Update the color corresponding to the modified input
     * @param {Event} e - DOM input node
     */
    _updateColor: function (e) {
      var color = e.currentTarget.value;
      var textInput = this.el.querySelector('input[type="text"]');
      var colorInput = this.el.querySelector('input[type="color"]');

      textInput.value = color;
      colorInput.value = color;
    }
  });
})(this.App);

Fix bug where color selector's inputs'd be out of sync


/**
 * Created by ivan on 10/5/14.
 */
angular.module('Frosch')
    .factory('ConfiguracionService', function ($http, $translate) {

        var clase = function () {
            var me = this;
            this.equipos = true;
            this.maxPorEquipo = 1;
            this.puntos = 800;
            this.numJugadores = 3;
            this.blanqueada = -10;

            var httpPromise = $http.get('config/config.json');
            return httpPromise.then(function (httpResponse) {
                me.configuracion = httpResponse.data;
                return $translate.use(me.configuracion.idioma).then(function(){
                    return me;
                }); //el cambio de idioma es promise

            });
        };

        clase.prototype.setMaxPorEquipo = function (cantidad) {
            this.maxPorEquipo = cantidad * 1;
            this.equipos = this.maxPorEquipo > 1;
        };

        clase.prototype.creditosPorJugador = function () {
            return this.configuracion.creditosPorPuntaje[this.puntos] * this.maxPorEquipo;
        };

        clase.prototype.setNumJugadores = function (numJugadores) {
            if (numJugadores !== Math.round(numJugadores))
                throw new Error("El número de jugadores debe ser exacto");

            this.numJugadores = numJugadores;
        };

        return new clase();
    });

/**
 * Created by ivan on 10/5/14.
 */
angular.module('Frosch')
    .factory('ConfiguracionService', function ($http, $translate) {

        var clase = function () {
            var me = this;
            this.equipos = true;
            this.maxPorEquipo = 1;
            this.puntos = 800;
            this.numJugadores = 6;
            this.blanqueada = -10;

            var httpPromise = $http.get('config/config.json');
            return httpPromise.then(function (httpResponse) {
                me.configuracion = httpResponse.data;
                return $translate.use(me.configuracion.idioma).then(function(){
                    return me;
                }); //el cambio de idioma es promise

            });
        };

        clase.prototype.setMaxPorEquipo = function (cantidad) {
            this.maxPorEquipo = cantidad * 1;
            this.equipos = this.maxPorEquipo > 1;
        };

        clase.prototype.creditosPorJugador = function () {
            return this.configuracion.creditosPorPuntaje[this.puntos] * this.maxPorEquipo;
        };

        clase.prototype.setNumJugadores = function (numJugadores) {
            if (numJugadores !== Math.round(numJugadores))
                throw new Error("El número de jugadores debe ser exacto");

            this.numJugadores = numJugadores;
        };

        return new clase();
    });

Fix para que los jugadores mantengan su posición


(function (context) {
  var noflo = context.require('noflo');
  var Base = context.require('noflo-noflo-runtime-base');

  var Iframe = function () {
    this.prototype.constructor.apply(this, arguments);
    this.receive = this.prototype.receive;
  };
  Iframe.prototype = Base;
  Iframe.prototype.send = function (protocol, topic, payload, ctx) {
    if (payload instanceof Error) {
      payload = {
        message: payload.toString()
      };
    }
    context.parent.postMessage({
      protocol: protocol,
      command: topic,
      payload: payload
    }, ctx.href);
  };
  var runtime = new Iframe();

  context.addEventListener('message', function (message) {
    if (message.origin !== context.parent.location.origin) {
      return;
    }
    if (!message.data.protocol) {
      return;
    }
    if (!message.data.command) {
      return;
    }
    runtime.receive(message.data.protocol, message.data.command, message.data.payload, {
      href: context.parent.location.href
    });
  });

})(window);

(function (context) {
  var noflo = context.require('noflo');
  var Base = context.require('noflo-noflo-runtime-base');

  var Iframe = function (options) {
    if (!options) {
      options = {};
    }

    if (options.catchExceptions) {
      context.onerror = function (err) {
        this.send('network', 'error', {
          message: err.toString()
        }, {
          href: context.parent.location.href
        });
        return true;
      }.bind(this);
    }

    this.prototype.constructor.apply(this, arguments);
    this.receive = this.prototype.receive;
  };
  Iframe.prototype = Base;
  Iframe.prototype.send = function (protocol, topic, payload, ctx) {
    if (payload instanceof Error) {
      payload = {
        message: payload.toString()
      };
    }
    context.parent.postMessage({
      protocol: protocol,
      command: topic,
      payload: payload
    }, ctx.href);
  };
  var runtime = new Iframe({
    catchExceptions: true
  });

  context.addEventListener('message', function (message) {
    if (message.origin !== context.parent.location.origin) {
      return;
    }
    if (!message.data.protocol) {
      return;
    }
    if (!message.data.command) {
      return;
    }
    runtime.receive(message.data.protocol, message.data.command, message.data.payload, {
      href: context.parent.location.href
    });
  });

})(window);

Allow catching uncaught exceptions and transmitting them via the error protocol


"use strict";

var restify = require('restify');
var async = require('async');
var Anyfetch = require('anyfetch');

module.exports.get = function get(req, res, next) {
  if(!req.query.query) {
    return next(new restify.ConflictError());
  }
  async.waterfall([
    function getDocuments(cb) {
      var anyfetchClient = new Anyfetch(req.accessToken.token);
      anyfetchClient.getDocuments({ search: req.query.query, render_templates: true }, cb);
    },
    function remapDocuments(documentsRes, cb) {
      res.send(200, documentsRes.body.data.map(function mapDocuments(document) {
        return {
          type: document.document_type.name,
          id: document.id,
          date: document.modification_date,
          snippet: document.rendered_snippet,
          title: document.rendered_title
        };
      }));
      cb();
    }
  ], next);
};

"use strict";

var restify = require('restify');
var async = require('async');
var Anyfetch = require('anyfetch');

module.exports.get = function get(req, res, next) {
  if(!req.query.query) {
    return next(new restify.ConflictError("Missing query parameter"));
  }
  async.waterfall([
    function getDocuments(cb) {
      var anyfetchClient = new Anyfetch(req.accessToken.token);
      anyfetchClient.getDocuments({ search: req.query.query, render_templates: true }, cb);
    },
    function remapDocuments(documentsRes, cb) {
      res.send(200, documentsRes.body.data.map(function mapDocuments(document) {
        return {
          type: document.document_type.name,
          id: document.id,
          date: document.modification_date,
          snippet: document.rendered_snippet,
          title: document.rendered_title
        };
      }));
      cb();
    }
  ], next);
};

Add a message when refusing due to a lack of query parameter


Quotes = new Meteor.Collection("quotes");
Quotes.attachSchema(new SimpleSchema({
  body: {
    type: String,
    label: "Body"
  },
  description: {
    type: String,
    label: "Description",
    optional: true
  }
}));

if (Meteor.isClient) {
  Template.quotes.quotes = function () {
    return Quotes.find({});
  };
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

Quotes = new Meteor.Collection("quotes");
Quotes.attachSchema(new SimpleSchema({
  body: {
    type: String,
    label: "Body",
    autoform: {
      rows: 6
    }
  },
  description: {
    type: String,
    label: "Description",
    optional: true,
    autoform: {
      rows: 2
    }
  }
}));

if (Meteor.isClient) {
  Template.quotes.quotes = function () {
    return Quotes.find({});
  };
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

Use textareas in the form


var xhr = require('xmlhttprequest');
var mongoose = require('mongoose');
var moment = require('moment');
var tz = require('moment-timezone');
var range = require('moment-range');

setInterval(function(){

  var currentTime = moment().tz('America/New_York');
  var openTime = moment().tz('America/New_York').hours(9).minutes(30).seconds(0);
  var closeTime = moment().tz('America/New_York').hours(16).minutes(0).seconds(0);
  var tradingHours = moment.range(openTime, closeTime)

  if (currentTime.within(tradingHours)){
    console.log("Sending request at", new Date())
    var XMLHttpRequest = xhr.XMLHttpRequest;
    var request = new XMLHttpRequest();
    request.open('GET', "http://localhost:3000/quotes/save", true);
    request.send();
    request.onload = function(reponse){
      if (request.status >= 200 && request.status < 400) {
        console.log(request.responseText)
      } else {
        console.log("Server error", request.status);
      }
    }
  } else {
    console.log(currentTime.format('lll'), 'is outside current trade hours')
  }
}, 30000);

var xhr = require('xmlhttprequest');
var moment = require('moment');
var tz = require('moment-timezone');
var range = require('moment-range');

setInterval(function(){

  var currentTime = moment().tz('America/New_York');
  var openTime = moment().tz('America/New_York').hours(9).minutes(30).seconds(0);
  var closeTime = moment().tz('America/New_York').hours(16).minutes(0).seconds(0);
  var tradingHours = moment.range(openTime, closeTime)

  if (currentTime.within(tradingHours)){
    console.log("Sending request at", new Date())
    var XMLHttpRequest = xhr.XMLHttpRequest;
    var request = new XMLHttpRequest();
    request.open('GET', "http://localhost:3000/quotes/save", true);
    request.send();
    request.onload = function(reponse){
      if (request.status >= 200 && request.status < 400) {
        console.log(request.responseText)
      } else {
        console.log("Server error", request.status);
      }
    }
  } else {
    console.log(currentTime.format('lll'), 'is outside current trade hours')
  }
}, 30000);

Remove unnecessary dependency from interval script


var express = require('express');
var router = express.Router();
var moment = require('moment');
var languageColors = require('../language_colors');

// GET home page
languageColors.get(function (languages, updated) {
  // HTML
  router.get('/', function(req, res) {
    res.render('index', {
      languages: languages,
      updated: moment(updated).fromNow()
    });
  });

  // JSON
  router.get('/index.json', function(req, res) {
    res.json(languages);
  });
});

module.exports = router;

var express = require('express');
var router = express.Router();
var moment = require('moment');
var languageColors = require('../language_colors');

// GET home page
languageColors.get().then(function (result) {
  // HTML
  router.get('/', function(req, res) {
    result.updated = moment(result.updated).fromNow();
    res.render('index', result);
  });

  // JSON
  router.get('/index.json', function(req, res) {
    res.json(result.languages);
  });
}, function () {
  throw('color loading failed');
});

module.exports = router;

Fix the routes so they handle the promise properly


/**
 * ErrorNotice stories.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */

import ErrorNotice from './ErrorNotice';

const Template = ( args ) => <ErrorNotice { ...args } />;

export const Default = Template.bind( {} );
Default.args = {
	error: new Error( 'This is error text' ),
};

export default {
	title: 'Components/ErrorNotice',
	component: ErrorNotice,
};

/**
 * ErrorNotice stories.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import { provideModules } from '../../../tests/js/utils';
import WithRegistrySetup from '../../../tests/js/WithRegistrySetup';
import { MODULES_ANALYTICS } from '../modules/analytics/datastore/constants';
import ErrorNotice from './ErrorNotice';

const notFoundError = {
	code: 404,
	message: 'Not found',
	data: {
		status: 404,
	},
};

const Template = ( { setupRegistry = () => {}, ...args } ) => (
	<WithRegistrySetup func={ setupRegistry }>
		<ErrorNotice { ...args } />
	</WithRegistrySetup>
);

export const Default = Template.bind( {} );
Default.args = {
	error: new Error( 'This is error text' ),
};

export const WithRetryLink = Template.bind( {} );
WithRetryLink.args = {
	error: notFoundError,
	storeName: MODULES_ANALYTICS,
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'analytics',
			},
		] );
		registry
			.dispatch( MODULES_ANALYTICS )
			.receiveError( notFoundError, 'getReport', [] );
	},
};

export default {
	title: 'Components/ErrorNotice',
	component: ErrorNotice,
};

Add retryable error to story.


"use strict";

const HookTask = require('./HookTask');

class RebundleTask extends HookTask {

    constructor(buildManager, taskRunner) {
        super(buildManager, taskRunner);
        this.command = "rebundle-hook";
    }

    action() {
        console.log('rebundleeeee');
        var Promise= require('bluebird');
        return Promise.resolve();
    }

    _getTasks() {
        return this._buildManager.options.onRebundle;
    }
}

module.exports = RebundleTask;

"use strict";

const HookTask = require('./HookTask');

class RebundleTask extends HookTask {

    constructor(buildManager, taskRunner) {
        super(buildManager, taskRunner);
        this.command = "rebundle-hook";
    }

    _getTasks() {
        return this._buildManager.options.onRebundle;
    }
}

module.exports = RebundleTask;

Remove typo from rebundle task


 var app = angular.module('at', ['pascalprecht.translate']);

      app.config(function ($translateProvider) {
        $translateProvider.useStaticFilesLoader({
          prefix: '/json/',
          suffix: '.json'
        });
        $translateProvider.translations('en', {
          TITLE: 'Hello',
          FOO: 'This is a paragraph.',
          BUTTON_LANG_EN: 'english',
          BUTTON_LANG_DE: 'german'
        });
        $translateProvider.translations('de', {
          TITLE: 'Hallo',
          FOO: 'Dies ist ein Paragraph.',
          BUTTON_LANG_EN: 'englisch',
          BUTTON_LANG_DE: 'deutsch'
        });
        $translateProvider.preferredLanguage('po');
      });

 var app = angular.module('at', ['pascalprecht.translate']);

      app.config(function ($translateProvider) {
        $translateProvider.useStaticFilesLoader({
          prefix: '/json/',
          suffix: '.json'
        });
        /*$translateProvider.translations('en', {
          TITLE: 'Hello',
          FOO: 'This is a paragraph.',
          BUTTON_LANG_EN: 'english',
          BUTTON_LANG_DE: 'german'
        });
        $translateProvider.translations('de', {
          TITLE: 'Hallo',
          FOO: 'Dies ist ein Paragraph.',
          BUTTON_LANG_EN: 'englisch',
          BUTTON_LANG_DE: 'deutsch'
        });*/
        $translateProvider.preferredLanguage('po');
      });

Test commit for conflict resolution


import path from 'path';
import express from 'express';

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 8080 : process.env.PORT;
const address = process.env.DOCKER_HOST || process.env.APP_IP || 'localhost';
const app = express();

app.use(express.static(__dirname + '/build/client'));

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'client', 'index.html'));
});

app.listen(port, address, function (err) {
  if (err) {
    // TODO : Add logging.
    return console.error(err);
  } else {
    console.info('Listening on http://%s:%s in %s', address, port, isDeveloping ? 'developer mode' : 'production mode');
  }
});

import path from 'path';
import express from 'express';

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 8000 : process.env.PORT;
const address = process.env.DOCKER_HOST || process.env.APP_IP || 'localhost';
const app = express();

app.use(express.static(__dirname + '/build/client'));

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'client', 'index.html'));
});

app.listen(port, address, function (err) {
  if (err) {
    // TODO : Add logging.
    return console.error(err);
  } else {
    console.info('Listening on http://%s:%s in %s', address, port, isDeveloping ? 'developer mode' : 'production mode');
  }
});

Fix port on main server


class C {
  static foo() { return 23; }
}

module.exports = C;

// semmle-extractor-options: --abort-on-parse-errors

Remove a redundant extractor option.


import React, { Component } from 'react';
import './Tile.css';

class Tile extends Component {

  showTile(tileId) {
    this.props.showTile(tileId);
  }

  render() {
    let {tile} = this.props;
    let selected = tile.selected || tile.match ? " flipped" : "";
    let imgUrl = tile.selected ? tile.src : tile.src;
    let match = tile.match ? " match" : "";
    const componentClasses = ['container'];
    componentClasses.push(match);
    const backTileImageSrc = `images/back/${this.props.backTileId}.jpg`;

    return (

 this.showTile(tile.id)}>

    );
  }
}

export default Tile;

import React, { Component } from 'react';
import './Tile.css';

class Tile extends Component {

  showTile(e,tileId) {
    e.preventDefault();
    this.props.showTile(tileId);
  }

  render() {
    let {tile} = this.props;
    let selected = tile.selected || tile.match ? " flipped" : "";
    let imgUrl = tile.selected ? tile.src : tile.src;
    let match = tile.match ? " match" : "";
    const componentClasses = ['container'];
    componentClasses.push(match);
    const backTileImageSrc = `images/back/${this.props.backTileId}.jpg`;

    return (

 this.showTile(e,tile.id)} onClick={(e) => this.showTile(e,tile.id)}>

    );
  }
}

export default Tile;

Make it respond to touch events - much more responsive now


import {Origin} from 'aurelia-metadata';
import {JadeView} from './jade';

/**
Retrieves a `.jade`-type view via usual convention used by `ConventionView`.

@class JadeConventionView
@extends JadeView
@param viewModel {Object} ViewModel to determine viewUrl by convention from
@param [isCompiled] {Boolean} If true, will not attempt to use SystemJS plugin loader (i.e. no '!' suffix)
@param [extension] {String} Custom extension used for your views (defaults to `.jade.js` for compiled, `jade` for non-compiled)
**/
export default class JadeConventionView extends JadeView {
	constructor(viewModel, isCompiled) {
		this.moduleId = Origin.get(viewModel.constructor).moduleId;

		return super(
			JadeConventionView.convertModuleIdToViewUrl(this.moduleId),
			isCompiled
		);
	}

	/**
	Converts a given module ID into the conventional view URL

	@static
	@method convertModuleIdToViewUrl
	@param moduleId {String} Module ID to convert
	**/
	static convertModuleIdToViewUrl(moduleId, isCompiled) {
		return moduleId + '.jade';
	}
}

import {Origin} from 'aurelia-metadata';
import JadeView from './jade';

/**
Retrieves a `.jade`-type view via usual convention used by `ConventionView`.

@class JadeConventionView
@extends JadeView
@param viewModel {Object} ViewModel to determine viewUrl by convention from
@param [isCompiled] {Boolean} If true, will not attempt to use SystemJS plugin loader (i.e. no '!' suffix)
@param [extension] {String} Custom extension used for your views (defaults to `.jade.js` for compiled, `jade` for non-compiled)
**/
export default class JadeConventionView extends JadeView {
	constructor(viewModel, isCompiled) {
		this.moduleId = Origin.get(viewModel.constructor).moduleId;

		return super(
			JadeConventionView.convertModuleIdToViewUrl(this.moduleId),
			isCompiled
		);
	}

	/**
	Converts a given module ID into the conventional view URL

	@static
	@method convertModuleIdToViewUrl
	@param moduleId {String} Module ID to convert
	**/
	static convertModuleIdToViewUrl(moduleId, isCompiled) {
		return moduleId + '.jade';
	}
}

Fix problem with convention import


import Vue from 'vue'
import VueFire from 'vuefire'
import App from './App'

import 'jquery-ui/jquery-ui.min.js'

// import imagesLoaded from 'imagesloaded'
// imagesLoaded.makeJQueryPlugin($)

import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'

// import marked from 'marked'

Vue.use(VueFire)

// Register a global custom directive called v-dropdown
Vue.directive('dropdown', {
  bind (el) {
    $(el).dropdown()
  },
  unbind (el) {
    $(el).dropdown('destroy')
  }
})

Vue.filter('capitalise', (text) => {
  return text[0].toUpperCase() + text.slice(1)
})

Vue.filter('formatDate', (value) => {
  var date = new Date(value)
  return date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear()
})

console.log('NEWT!')

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

import Vue from 'vue'
import VueFire from 'vuefire'

import 'jquery-ui/jquery-ui.min.js'

// import imagesLoaded from 'imagesloaded'
// imagesLoaded.makeJQueryPlugin($)

import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'

// import marked from 'marked'

import AutoSize from 'autosize'

Vue.use(VueFire)

// Register a global custom directive called v-dropdown
Vue.directive('dropdown', {
  bind (el) {
    $(el).dropdown()
  },
  unbind (el) {
    $(el).dropdown('destroy')
  }
})

// Register a global custom directive called v-autosize
Vue.directive('autosize', {
  bind (el) {
    AutoSize($(el))
  },
  unbind (el) {
    AutoSize.destroy($(el))
  }
})

// Register a global custom directive called v-modal
Vue.directive('modal', {
  bind (el) {
    $(el).modal()
  },
  unbind (el) {
    $(el).modal('destroy')
  }
})

Vue.filter('capitalise', (text) => {
  return text[0].toUpperCase() + text.slice(1)
})

Vue.filter('formatDate', (value) => {
  var date = new Date(value)
  return date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear()
})

console.log('NEWT!')

import App from './App'
/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

Add autosize and modal directives


import handleFrontMatter from './transforms/handle-front-matter';
import handleMarkdown from './transforms/handle-markdown';
import wrapReact from './transforms/wrap-react';
import readContent from './read-content';
import writeContent from './write-content';

readContent('./content').catch((err) =>  console.log(err))
    .then(handleFrontMatter)
    .then(handleMarkdown)
    .then(wrapReact)
    .then(writeContent('./output'))
    .then((result) => {
        console.log(result.items);
    }).catch((err) => {
        console.log(err);
    });

import handleFrontMatter from './transforms/handle-front-matter';
import handleMarkdown from './transforms/handle-markdown';
import wrapReact from './transforms/wrap-react';
import readContent from './read-content';
import writeContent from './write-content';

readContent('./content').catch((err) =>  console.error(err))
    .then(handleFrontMatter)
    .then(handleMarkdown)
    .then(wrapReact)
    .then(writeContent('./output'))
    .then((result) => {
        console.log(result.items);
    }).catch((err) => {
        console.error(err);
    });

Change console.log to console.error where appropriate


#!/usr/bin/env node

"use strict";

let fs = require("fs");
let peg = require("../lib/peg");
let options = require("./options");

// Helpers

function readStream(inputStream, callback) {
  let input = "";
  inputStream.on("data", data => { input += data; });
  inputStream.on("end", () => { callback(input); });
}

function abort(message) {
  console.error(message);
  process.exit(1);
}

// Main

let inputStream, outputStream;

if (options.inputFile === "-") {
  process.stdin.resume();
  inputStream = process.stdin;
  inputStream.on("error", () => {
    abort(`Can't read from file "${options.inputFile}".`);
  });
} else {
  inputStream = fs.createReadStream(options.inputFile);
}

if (options.outputFile === "-") {
  outputStream = process.stdout;
} else {
  outputStream = fs.createWriteStream(options.outputFile);
  outputStream.on("error", () => {
    abort(`Can't write to file "${options.outputFile}".`);
  });
}

readStream(inputStream, input => {
  let location, source;

  try {
    source = peg.generate(input, options);
  } catch (e) {
    if (e.location !== undefined) {
      location = e.location.start;
      abort(location.line + ":" + location.column + ": " + e.message);
    } else {
      abort(e);
    }
  }

  outputStream.write(source);
  if (outputStream !== process.stdout) {
    outputStream.end();
  }
});

#!/usr/bin/env node

"use strict";

let fs = require("fs");
let peg = require("../lib/peg");
let options = require("./options");

// Helpers

function readStream(inputStream, callback) {
  let input = "";
  inputStream.on("data", data => { input += data; });
  inputStream.on("end", () => { callback(input); });
}

function abort(message) {
  console.error(message);
  process.exit(1);
}

// Main

let inputStream, outputStream;

if (options.inputFile === "-") {
  process.stdin.resume();
  inputStream = process.stdin;
} else {
  inputStream = fs.createReadStream(options.inputFile);
  inputStream.on("error", () => {
    abort(`Can't read from file "${options.inputFile}".`);
  });
}

if (options.outputFile === "-") {
  outputStream = process.stdout;
} else {
  outputStream = fs.createWriteStream(options.outputFile);
  outputStream.on("error", () => {
    abort(`Can't write to file "${options.outputFile}".`);
  });
}

readStream(inputStream, input => {
  let location, source;

  try {
    source = peg.generate(input, options);
  } catch (e) {
    if (e.location !== undefined) {
      location = e.location.start;
      abort(location.line + ":" + location.column + ": " + e.message);
    } else {
      abort(e);
    }
  }

  outputStream.write(source);
  if (outputStream !== process.stdout) {
    outputStream.end();
  }
});

Fix incorrect error subscription on input stream


'use strict';

var CONFIG = require('config');

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

var ALL_PLUGINS = util.loadPluginsSync(__dirname, CONFIG);

exports.handleRequest = function(request, response, options, callback) {
  var plugins = util.filterPlugins(ALL_PLUGINS.request, options);

  // Handles request with given plugin (per id) and recursively calls the next
  // plugin handler if unsuccessful.
  function handleRequest(pluginIndex) {
    if (pluginIndex >= plugins.length) {
      // No plugin could successfully handle the request.
      callback(null, false);
      return;
    }

    var plugin = plugins[pluginIndex];

    plugin.handleRequest(request, response, options, function(err, handled) {
      if (!err && handled) {
        // The plugin successfully handled the request, abort the series.
        callback(null, true);
      } else {
        // The plugin failed handling the request, try the next plugin.
        handleRequest(pluginIndex + 1);
      }
    });
  }

  // Initiate the request handling series with the first plugin.
  handleRequest(0);
};

exports.handleResponse = function(request, source, dest, options) {
  var currentSource = source;
  var currentDest = null;
  var plugins = util.filterPlugins(ALL_PLUGINS.response, options);
  plugins.forEach(function(plugin, i) {
    currentDest = i === plugins.length - 1 ?
                  dest :
                  new util.PipedResponse(currentSource);
    plugin.handleResponse(request, currentSource, currentDest, options);
    currentSource = currentDest;
  });
};

'use strict';

var CONFIG = require('config');

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

var ALL_PLUGINS = util.loadPluginsSync(__dirname, CONFIG);

exports.handleRequest = function(request, response, options, callback) {
  var plugins = util.filterPlugins(ALL_PLUGINS.request, options);

  function tryNextPlugin() {
    if (plugins.length === 0) {
      callback(null, false);
      return;
    }

    var plugin = plugins.shift();

    plugin.handleRequest(request, response, options, function(err, handled) {
      if (!err && handled) {
        // The plugin successfully handled the request, abort the series.
        callback(null, true);
      } else {
        tryNextPlugin();
      }
    });
  }

  tryNextPlugin();
};

exports.handleResponse = function(request, source, dest, options) {
  var currentSource = source;
  var currentDest = null;
  var plugins = util.filterPlugins(ALL_PLUGINS.response, options);
  plugins.forEach(function(plugin, i) {
    currentDest = i === plugins.length - 1 ?
                  dest :
                  new util.PipedResponse(currentSource);
    plugin.handleResponse(request, currentSource, currentDest, options);
    currentSource = currentDest;
  });
};

Clean up request plugin handling a bit


import isEqual from 'lodash/isEqual'

import { collectionAttachedSchema } from '../schemaHelper'

const collectionLabel = collection =>
  collection._name ? `collection named "${collection._name}"` : '#{this}'

export const plugin = (chai) => {
  const Assertion = chai.Assertion

  Assertion.addProperty('schema', function schemaProperty() {
    const collection = this._obj
    const label = collectionLabel(collection)
    this.assert(
      collectionAttachedSchema(collection),
      `expected ${label} to have an attached schema`,
      `expected ${label} to not have an attached schema`,
    )
  })

  Assertion.addMethod('index', function indexMethod(fields) {
    const collection = this._obj
    const label = collectionLabel(collection)
    const matchingIndex = collection.indexes.find((idx) => {
      const keys = Object.entries(idx.keys)
      return fields.every((f, i) => typeof f === 'string' ? f === keys[i][0] : isEqual(Object.entries(f)[0], keys[i]))
    })
    this.assert(
      matchingIndex,
      `expected ${label} to have an index #{exp} from #{act}`,
      `expected ${label} to not have an index #{exp}`,
      fields,
      collection.indexes.map(idx => idx.keys),
    )
  })

}

import isEqual from 'lodash/isEqual'

import { collectionAttachedSchema } from '../schemaHelper'

const collectionLabel = collection =>
  collection._name ? `collection named "${collection._name}"` : '#{this}'

function assetTestMongo() {
  const collection = this._obj
  this.assert(
    collection.constructor && collection.constructor.name === 'TestMongo',
    'expected an instance of TestMongo',
    'expected not an instance of TestMongo',
  )
}

export const plugin = (chai) => {
  const Assertion = chai.Assertion

  Assertion.addProperty('schema', function schemaProperty() {
    assetTestMongo()
    const collection = this._obj
    const label = collectionLabel(collection)
    this.assert(
      collectionAttachedSchema(collection),
      `expected ${label} to have an attached schema`,
      `expected ${label} to not have an attached schema`,
    )
  })

  Assertion.addMethod('index', function indexMethod(fields) {
    assetTestMongo()
    const collection = this._obj
    const label = collectionLabel(collection)
    const matchingIndex = collection.indexes.find((idx) => {
      const keys = Object.entries(idx.keys)
      return fields.every((f, i) => typeof f === 'string' ? f === keys[i][0] : isEqual(Object.entries(f)[0], keys[i]))
    })
    this.assert(
      matchingIndex,
      `expected ${label} to have an index #{exp} from #{act}`,
      `expected ${label} to not have an index #{exp}`,
      fields,
      collection.indexes.map(idx => idx.keys),
    )
  })

}

Check in Chai assertions that they have been given TestMongo


export const CLIENT_ID = "ca49494ef26794d2427f";
export const GATEKEEPER_AUTH_URL = "https://gatekeeper-server.herokuapp.com/authenticate/";
export const OAUTH_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
export const OAUTH_PROVIDER_NAME = "GitHub";
export const OAUTH_GH_REPO_STATUS_SCOPE = "repo:status";

export const GITHUB_USER_NAME = "compumike08";
export const GITHUB_REPO_NAME = "GitHub_Status_API_GUI";

export const GITHUB_ERR_BAD_CREDENTIALS = "Bad credentials";

export const CLIENT_ID = "ca49494ef26794d2427f";
export const GATEKEEPER_AUTH_URL = "https://gatekeeper-server.herokuapp.com/authenticate/";
export const OAUTH_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
export const OAUTH_PROVIDER_NAME = "GitHub";
export const OAUTH_GH_REPO_STATUS_SCOPE = "repo:status";

export const GITHUB_USER_NAME = "compumike08";
export const GITHUB_REPO_NAME = "node.js";

export const GITHUB_ERR_BAD_CREDENTIALS = "Bad credentials";

Change 'GITHUB_REPO_NAME' constant to point to my node.js GitHub repo


'use strict';

var errorHandler = require('./errors.server.controller');

/**
 * Render the main application page
 */
exports.renderIndex = function(req, res) {

  var currentUser = null;

  // Expose user
  if(req.user) {
    currentUser = req.user;
    // Don't just expose everything to the view...
    delete currentUser.emailToken;
  }

  res.render('modules/core/server/views/index', {
    user: currentUser
  });
};

/**
 * Render the server not found responses
 * Performs content-negotiation on the Accept HTTP header
 */
exports.renderNotFound = function(req, res) {
  res.status(404).format({
    'text/html': function() {
      res.render('modules/core/server/views/404');
    },
    'application/json': function() {
      res.json({ message: errorHandler.getErrorMessageByKey('not-found') });
    },
    'default': function() {
      res.send( errorHandler.getErrorMessageByKey('not-found') );
    }
  });
};

'use strict';

var errorHandler = require('./errors.server.controller');

/**
 * Render the main application page
 */
exports.renderIndex = function(req, res) {

  var currentUser = null;

  // Expose user
  if(req.user) {
    currentUser = req.user;
    // Don't just expose everything to the view...
    delete currentUser.resetPasswordToken;
    delete currentUser.resetPasswordExpires;
    delete currentUser.emailToken;
    delete currentUser.password;
    delete currentUser.salt;
  }

  res.render('modules/core/server/views/index', {
    user: currentUser
  });
};

/**
 * Render the server not found responses
 * Performs content-negotiation on the Accept HTTP header
 */
exports.renderNotFound = function(req, res) {
  res.status(404).format({
    'text/html': function() {
      res.render('modules/core/server/views/404');
    },
    'application/json': function() {
      res.json({ message: errorHandler.getErrorMessageByKey('not-found') });
    },
    'default': function() {
      res.send( errorHandler.getErrorMessageByKey('not-found') );
    }
  });
};

Hide certain values from initial view to logged in user


// @flow
/*global it*/

import DragEventAcceptor from './DragEventAcceptor'

const FailIfCalled = () => {
  throw new Error('Should not have been called')
}

it('Should not evaluate for events without dataTransfer', () => {
  const BadEvent: any = {}
  DragEventAcceptor(FailIfCalled)(BadEvent)
})

it('Should not evaluate for events without dataTransfer.files', () => {
  const BadEvent: any = {
    dataTransfer: {},
    preventDefault: () => {},
  }
  DragEventAcceptor(FailIfCalled)(BadEvent)
})

it('Should not evaluate for events with no files', () => {
  const BadEvent: any = {
    dataTransfer: {
      files: {
        length: 0,
      },
    },
    preventDefault: () => {},
  }
  DragEventAcceptor(FailIfCalled)(BadEvent)
})

it('Should evaluate for events with files', done => {
  const ShouldBeCalled = () => done()

  const GoodEvent: any = {
    dataTransfer: {
      files: {
        length: 1,
        files: [],
      },
    },
    preventDefault: () => {},
  }

  DragEventAcceptor(ShouldBeCalled)(GoodEvent)
})

// @flow
/*global it expect jest*/

import DragEventAcceptor from './DragEventAcceptor'

const FailIfCalled = () => {
  throw new Error('Should not have been called')
}

it('Should not evaluate for events without dataTransfer', () => {
  const BadEvent: any = {
    preventDefault: jest.fn(),
    stopPropagation: jest.fn(),
  }

  DragEventAcceptor(FailIfCalled)(BadEvent)
  expect(BadEvent.preventDefault).toHaveBeenCalledTimes(0)
  expect(BadEvent.stopPropagation).toHaveBeenCalledTimes(0)
})

it('Should not evaluate for events without dataTransfer.files', () => {
  const BadEvent: any = {
    dataTransfer: {},
    preventDefault: jest.fn(),
    stopPropagation: jest.fn(),
  }

  DragEventAcceptor(FailIfCalled)(BadEvent)

  expect(BadEvent.preventDefault).toHaveBeenCalledTimes(1)
  expect(BadEvent.stopPropagation).toHaveBeenCalledTimes(1)
})

it('Should not evaluate for events with no files', () => {
  const BadEvent: any = {
    dataTransfer: {
      files: {
        length: 0,
      },
    },
    preventDefault: jest.fn(),
    stopPropagation: jest.fn(),
  }

  DragEventAcceptor(FailIfCalled)(BadEvent)

  expect(BadEvent.preventDefault).toHaveBeenCalledTimes(1)
  expect(BadEvent.stopPropagation).toHaveBeenCalledTimes(1)
})

it('Should evaluate for events with files', done => {
  const GoodEvent: any = {
    dataTransfer: {
      files: {
        length: 1,
        files: [],
      },
    },
    preventDefault: jest.fn(),
    stopPropagation: jest.fn(),
  }

  const ShouldBeCalled = () => {
    expect(GoodEvent.dataTransfer.dropEffect).toBe('copy')
    expect(GoodEvent.preventDefault).toHaveBeenCalledTimes(1)
    expect(GoodEvent.stopPropagation).toHaveBeenCalledTimes(1)
    done()
  }

  DragEventAcceptor(ShouldBeCalled)(GoodEvent)
})

Test calls to preventDefault and stopPropagation in DragEventAcceptor


var HTMLCS_RUNNER = new function() {
    this.run = function(standard) {
        var self = this;

        // At the moment, it passes the whole DOM document.
        HTMLCS.process(standard, document, function() {
            var messages = HTMLCS.getMessages();
            var length   = messages.length;
            for (var i = 0; i < length; i++) {
                self.output(messages[i]);
            }

            console.log('done');
        });
    };

    this.output = function(msg) {
        // Simple output for now.
        console.log(msg.type + '|' + msg.code + '|' + msg.msg);
    };

};

var HTMLCS_RUNNER = new function() {
    this.run = function(standard) {
        var self = this;

        // At the moment, it passes the whole DOM document.
        HTMLCS.process(standard, document, function() {
            var messages = HTMLCS.getMessages();
            var length   = messages.length;
            for (var i = 0; i < length; i++) {
                self.output(messages[i]);
            }

            console.log('done');
        });
    };

    this.output = function(msg) {
        // Simple output for now.
        var typeName = 'UNKNOWN';
        switch (msg.type) {
            case HTMLCS.ERROR:
                typeName = 'ERROR';
            break;

            case HTMLCS.WARNING:
                typeName = 'WARNING';
            break;

            case HTMLCS.NOTICE:
                typeName = 'NOTICE';
            break;
        }//end switch

        console.log(typeName + '|' + msg.code + '|' + msg.msg);
    };

};

Replace level 1,2,3 with ERROR, WARNING, NOTICE.


angular.module('umbraco.resources')
    .factory('nuPickers.Shared.DataSource.DataSourceResource',
    ['$http', 'editorState',
        function ($http, editorState) {

            return {

                getEditorDataItems: function (model, typeahead) {

                    // returns [{"key":"","label":""},{"key":"","label":""}...]
                    return $http({
                        method: 'POST',
                        url: 'backoffice/nuPickers/' + model.config.dataSource.apiController + '/GetEditorDataItems',
                        params: {
                            'currentId': editorState.current.id,
                            'parentId': editorState.current.parentId,
                            'propertyAlias': model.alias
                        },
                        data: {
                            'config': model.config,
                            'typeahead': typeahead
                        }
                    });

                }

            };
        }
    ]);

angular.module('umbraco.resources')
    .factory('nuPickers.Shared.DataSource.DataSourceResource',
    ['$http', 'editorState',
        function ($http, editorState) {

            return {

                getEditorDataItems: function (model, typeahead) {

                    var parentId = 0;
                    var currentId = 0;

                    if (editorState.current) {
                        currentId = editorState.current.id;
			            parentId = editorState.current.parentId;
                    }

                    // returns [{"key":"","label":""},{"key":"","label":""}...]
                    return $http({
                        method: 'POST',
                        url: 'backoffice/nuPickers/' + model.config.dataSource.apiController + '/GetEditorDataItems',
                        params: {
                            'currentId': currentId,
                            'parentId': parentId,
                            'propertyAlias': model.alias
                        },
                        data: {
                            'config': model.config,
                            'typeahead': typeahead
                        }
                    });

                }

            };
        }
    ]);

Allow for the pickers to be used in custom dashboards


'use strict'

/* global it */

import actionLogger from './action_logger'

export const asyncIt = (description, test, config) => {
  const decoratedTest = _decorateTest(test, config)
  it(description, decoratedTest)
}

asyncIt.only = (description, test) => {
  const decoratedTest = _decorateTest(test)
  it.only(description, decoratedTest)
}

asyncIt.skip = (description, test) => {
  const decoratedTest = _decorateTest(test)
  it.skip(description, decoratedTest)
}

export const _decorateTest = (test, config) => {
  return async () => {
    if (config === 'debug') {
      actionLogger.startTestOnlyLogging()
    }

    try {
      await test()
      actionLogger.stopTestOnlyLogging()
    } catch (err) {
      actionLogger.stopTestOnlyLogging()
      throw err
    }
  }
}

'use strict'

/* global it */

import actionLogger from './action_logger'

export const asyncIt = (description, test, config) => {
  const decoratedTest = _decorateTest(test, config)
  it(description, decoratedTest)
}

asyncIt.only = (description, test, config) => {
  const decoratedTest = _decorateTest(test, config)
  it.only(description, decoratedTest)
}

asyncIt.skip = (description, test, config) => {
  const decoratedTest = _decorateTest(test, config)
  it.skip(description, decoratedTest)
}

export const _decorateTest = (test, config) => {
  return async () => {
    if (config === 'debug') {
      actionLogger.startTestOnlyLogging()
    }

    try {
      await test()
      actionLogger.stopTestOnlyLogging()
    } catch (err) {
      actionLogger.stopTestOnlyLogging()
      throw err
    }
  }
}

Fix action logging for asyncIt.only


let fs = require('fs');

module.exports = WatchTimestampsPlugin;

function WatchTimestampsPlugin(patterns) {
	this.patterns = patterns;
}

WatchTimestampsPlugin.prototype.apply = function (compiler) {
	compiler.plugin('watch-run', (watch, callback) => {
		let patterns = this.patterns;
		let timestamps = watch.fileTimestamps || watch.compiler.fileTimestamps;

		Object.keys(timestamps).forEach( filepath => {
			if (patterns.some( pat => pat instanceof RegExp ? pat.test(filepath) : filepath.indexOf(pat)===0 )) {
				let time = fs.statSync(filepath).mtime;
				if (timestamps instanceof Map) timestamps.set(filepath, time);
				else timestamps[filepath] = time;
			}
		});
		callback();
	});
};

const fs = require('fs');

module.exports = class WatchTimestampsPlugin {
	constructor(patterns) {
		this.patterns = patterns;
	}

	apply(compiler) {
		compiler.plugin('watch-run', (watch, callback) => {
			let patterns = this.patterns;
			let timestamps = watch.fileTimestamps || watch.compiler.fileTimestamps;

			Object.keys(timestamps).forEach(filepath => {
				if (patterns.some(pat => pat instanceof RegExp ? pat.test(filepath) : filepath.indexOf(pat) === 0)) {
					let time = fs.statSync(filepath).mtime;
					if (timestamps instanceof Map) timestamps.set(filepath, time);
					else timestamps[filepath] = time;
				}
			});
			callback();
		});
	}
};

Use classes for webpack plugins.


module.exports = class Entity {

  constructor() {
    this.guid = Math.random() * 1000000 | 0;
  }

};

const {EventEmitter} = require('events');

module.exports = class Entity extends EventEmitter {

  constructor() {
    super();
    this.guid = Math.random() * 1000000 | 0;
  }

};

Allow entities to emit events


  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-47486779-1', 'hr0nix.github.io');
  ga('send', 'pageview');

  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','http://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-47486779-1', 'hr0nix.github.io');
  ga('send', 'pageview');

Fix google analytics hangs when viewing locally.


$(document).foundation();

$('a.disabled').click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  e.stopImmediatePropagation();
});

// Show shadow when content slides under the page header
$(document).ready(function() {
  var $content = $('#site-body .content');
  var $header = $('#page-head .inner');

  if ($header.length > 0) {
    $content.css('margin-top', $header.outerHeight());

    $(document).resize(function() {
      $content.css('margin-top', $header.outerHeight());
    });

    $(window).scroll(function() {
      if ($(this).scrollTop() > 0) {
        $header.addClass('overlay');
      } else {
        $header.removeClass('overlay');
      }
    });
  }

  // Expand element.
  $('[data-expand]').click(function(e) {
    e.preventDefault();
    var id = $(this).attr('data-expand');
    $('#' + id).toggleClass('revealed');
  });
});

$(document).foundation();

$('a.disabled').click(function(e) {
  e.preventDefault();
  // Workaround for when links loads with disabled and later is removed.
  if ($(this).hasClass('disabled')) {
    e.stopPropagation();
    e.stopImmediatePropagation();
  }
});

// Show shadow when content slides under the page header
$(document).ready(function() {
  var $content = $('#site-body .content');
  var $header = $('#page-head .inner');

  if ($header.length > 0) {
    $content.css('margin-top', $header.outerHeight());

    $(document).resize(function() {
      $content.css('margin-top', $header.outerHeight());
    });

    $(window).scroll(function() {
      if ($(this).scrollTop() > 0) {
        $header.addClass('overlay');
      } else {
        $header.removeClass('overlay');
      }
    });
  }

  // Expand element.
  $('[data-expand]').click(function(e) {
    e.preventDefault();
    var id = $(this).attr('data-expand');
    $('#' + id).toggleClass('revealed');
  });
});

Fix problem with Halt button on enketo colletion


import React from 'react';
import { getImageUrlFromProp } from '../../helpers';

class PostTile extends React.Component {
  render() {
    const post = this.props.details;

    return (

    )
  }
}

export default PostTile;

import React from 'react';
import PropTypes from 'prop-types';
import { getImageUrlFromProp } from '../../helpers';

class PostTile extends React.Component {
  render() {
    const post = this.props.details;

    return (

    )
  }
}

PostTile.propTypes = {
  details: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};

export default PostTile;

Add proptype validation to PostTile component


/**
 * (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
 *
 * @emails oncall+ads_integration_management
 * @flow strict-local
 * @format
 * @oncall ads_integration_management
 */

'use strict';

const MAX_ASCII_CHARACTER = 127;

/**
 * Serializes strings with non-ASCII characters to their Unicode escape
 * sequences (eg. \u2022), to avoid hitting this lint rule:
 * "Source code should only include printable US-ASCII bytes"
 */
const NonASCIIStringSnapshotSerializer = {
  test(val: mixed): boolean {
    if (typeof val !== 'string') {
      return false;
    }
    for (let i = 0; i < val.length; i++) {
      if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) {
        return true;
      }
    }
    return false;
  },

  print: (val: string): string => {
    return (
      '"' +
      val
        .split('')
        .map((char) => {
          const code = char.charCodeAt(0);
          return code > MAX_ASCII_CHARACTER
            ? '\\u' + code.toString(16).padStart(4, '0')
            : char;
        })
        .join('')
        // Keep the same behaviour as Jest's regular string snapshot
        // serialization, which escapes double quotes.
        .replace(/"/g, '\\"') +
      '"'
    );
  },
};

module.exports = NonASCIIStringSnapshotSerializer;

/**
 * (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
 *
 * @flow strict-local
 * @format
 * @oncall ads_integration_management
 */

'use strict';

const MAX_ASCII_CHARACTER = 127;

/**
 * Serializes strings with non-ASCII characters to their Unicode escape
 * sequences (eg. \u2022), to avoid hitting this lint rule:
 * "Source code should only include printable US-ASCII bytes"
 */
const NonASCIIStringSnapshotSerializer = {
  test(val: mixed): boolean {
    if (typeof val !== 'string') {
      return false;
    }
    for (let i = 0; i < val.length; i++) {
      if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) {
        return true;
      }
    }
    return false;
  },

  print: (val: string): string => {
    return (
      '"' +
      val
        .split('')
        .map((char) => {
          const code = char.charCodeAt(0);
          return code > MAX_ASCII_CHARACTER
            ? '\\u' + code.toString(16).padStart(4, '0')
            : char;
        })
        .join('')
        // Keep the same behaviour as Jest's regular string snapshot
        // serialization, which escapes double quotes.
        .replace(/"/g, '\\"') +
      '"'
    );
  },
};

module.exports = NonASCIIStringSnapshotSerializer;

Remove @emails from non-generated files (91/n)


/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var assert = require('assert');

assert.match = function assertMatches(string, matcher, message) {
  assert.ok(expected.match(matcher), message ||
    'Expected ' + string + ' to match ' + matcher);
};

assert.contains = function assertContains(list, matcher, message) {
  var found = false;
  for (var i in list) {
    if (!list.hasOwnProperty(i)) continue;
    if (typeof matcher === 'function') {
      found = matcher(list[i]);
    } else {
      found = (list[i] === matcher);
    }
    if (found) return;
  }
  assert.fail(list, matcher, message, 'does not contain');
};

assert.compare = function assertComparison(actual, operator, expected, message) {
  var compare = actual + ' ' + operator + ' ' + expected;
  assert.ok(eval(compare), message || compare);
}

module.exports = {
  assert: assert
};

/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var assert = require('assert');

assert.match = function assertMatches(string, matcher, message) {
  assert.ok(string.match(matcher), message ||
    'Expected ' + string + ' to match ' + matcher);
};

assert.contains = function assertContains(list, matcher, message) {
  var found = false;
  for (var i in list) {
    if (!list.hasOwnProperty(i)) continue;
    if (typeof matcher === 'function') {
      found = matcher(list[i]);
    } else {
      found = (list[i] === matcher);
    }
    if (found) return;
  }
  assert.fail(list, matcher, message, 'does not contain');
};

assert.compare = function assertComparison(actual, operator, expected, message) {
  var compare = actual + ' ' + operator + ' ' + expected;
  assert.ok(eval(compare), message || compare);
}

module.exports = {
  assert: assert
};

Fix assert.match integration test helper


import styled from 'styled-components';

const SpinnerWrapper = styled.span`
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
`;

export default SpinnerWrapper;

import styled from 'styled-components';

const SpinnerWrapper = styled.span`
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
`;

export default SpinnerWrapper;

Fix positioning of the spinner inside the button


(function() {
  "use strict";

  describe('A nick list', function() {
    var win = {};
    var item = function(index) {
      if (index === -1) {
        return items().last();
      }
      return $(items()[index]);
    };
    var items = function() {
      return $('#nicks-container .nicks .nick');
    };
    beforeEach(function() {
      mocks.dom.setUp();
      win = new chat.Window('name');
      win.attach();
      return spyOn(win.nicks, 'emit');
    });
    afterEach(function() {
      win.detach();
      return mocks.dom.tearDown();
    });
    return it("emits a dblclicked event when a nick is double-clicked", function() {
      win.nicks.add('foo');
      item(0).trigger(new MouseEvent('dblclick'));
      return expect(win.nicks.emit).toHaveBeenCalledWith('dblclicked', 'foo');
    });
  });

}).call(this);

(function() {
  "use strict";

  describe('A nick list', function() {
    var win = {};
    var item = function(index) {
      if (index === -1) {
        return items().last();
      }
      return $(items()[index]);
    };
    var items = function() {
      return $('#nicks-container .nicks .nick');
    };
    var textOfItem = function(index) {
      return $('.content-item', item(index)).text();
    };
    beforeEach(function() {
      mocks.dom.setUp();
      win = new chat.Window('name');
      win.attach();
      return spyOn(win.nicks, 'emit');
    });
    afterEach(function() {
      win.detach();
      return mocks.dom.tearDown();
    });
    it("sorts entries properly", function() {
      win.nicks.add('_psi');
      win.nicks.add('epsilon');
      win.nicks.add('Delta');
      win.nicks.add('gamma');
      win.nicks.add('Beta');
      win.nicks.add('alpha');
      expect(textOfItem(0)).toBe('_psi');
      expect(textOfItem(1)).toBe('alpha');
      expect(textOfItem(2)).toBe('Beta');
      expect(textOfItem(3)).toBe('Delta');
      expect(textOfItem(4)).toBe('epsilon');
      expect(textOfItem(5)).toBe('gamma');
    });
    return it("emits a dblclicked event when a nick is double-clicked", function() {
      win.nicks.add('foo');
      item(0).trigger(new MouseEvent('dblclick'));
      return expect(win.nicks.emit).toHaveBeenCalledWith('dblclicked', 'foo');
    });
  });

}).call(this);

Add test for sort order in the nick list.


/**
 * This plugin helps to properly load the Hypothes.is client with Readium.
 * Enable this plugin if you want to add the Hypothesis client to your reader
 * so that visitors can annotate EPUBs without having to install
 * the Hypothesis browser extension.
 */

define(['readium_js_plugins'], function (Plugins) {

    var H_EMBED_URL = 'https://hypothes.is/embed.js';

    Plugins.register("hypothesis", function () {
        // The script for Hypothesis needs to be included once
        // Readium has been fully loaded by the RequireJS/AMD shim.
        // We can do this here in this callback when this plugin is invoked.

        // Inject the script
        var script = document.createElement('script');
        script.setAttribute('src', H_EMBED_URL);
        script.setAttribute('async', 'true');
        document.head.appendChild(script);
    });
});

/**
 * This plugin helps to properly load the Hypothes.is client with Readium.
 * Enable this plugin if you want to add the Hypothesis client to your reader
 * so that visitors can annotate EPUBs without having to install
 * the Hypothesis browser extension.
 */

define(['readium_js_plugins'], function (Plugins) {

    var H_EMBED_URL = 'https://hypothes.is/embed.js';

    Plugins.register("hypothesis", function () {
        var self = this;

        // Request that the UI controls make space for the Hypothesis sidebar
        window.hypothesisConfig = function () {
            return {
                onLayoutChange: function(state) {
                    self.emit('offsetPageButton', state.width);
                    if (!state.expanded) {
                        self.emit('offsetNavBar', state.width);
                    }
                }
            };
        };

        // The script for Hypothesis needs to be included once
        // Readium has been fully loaded by the RequireJS/AMD shim.
        // We can do this here in this callback when this plugin is invoked.

        // Inject the script
        var script = document.createElement('script');
        script.setAttribute('src', H_EMBED_URL);
        script.setAttribute('async', 'true');
        document.head.appendChild(script);
    });
});

Add Hypothesis config hooks to plugin for UI tweaks


var isFunction = require('lodash/lang/isFunction');
var dispatcher = require('focus').dispatcher;
module.exports = {
    /**
     * Register the cartridge.
     */
    _registerCartridge: function registerCartridge(){
      if(!isFunction(this.cartridgeConfiguration)){
        this.cartridgeConfiguration = function cartridgeConfiguration(){
          return {};
        };
        console.warn(`
          Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
          It should be a component attribute return by a function.
          function cartridgeConfiguration(){
            var cartridgeConfiguration = {
              summary: {component: "A React Component", props: {id: this.props.id}},
              cartridge: {component: "A React Component"},
              actions: {components: "react actions"}
            };
            return cartridgeConfiguration;
          }
        `);
      }
      var cartridgeConf = this.cartridgeConfiguration();
      dispatcher.handleViewAction({
        data: {
          cartridgeComponent: cartridgeConf.cartridge,
          summaryComponent: cartridgeConf.summary,
          actions: cartridgeConf.actions
        },
        type: 'update'
      });
    },
    componentWillMount: function pageMixinWillMount(){
      this._registerCartridge();
    }
};

var isFunction = require('lodash/lang/isFunction');
var dispatcher = require('focus').dispatcher;
module.exports = {
    /**
     * Register the cartridge.
     */
    _registerCartridge: function registerCartridge(){
      this.cartridgeConfiguration = this.cartridgeConfiguration || this.props.cartridgeConfiguration;
      if(!isFunction(this.cartridgeConfiguration)){
        this.cartridgeConfiguration = function cartridgeConfiguration(){
          return {};
        };
        console.warn(`
          Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
          It should be a component attribute return by a function.
          function cartridgeConfiguration(){
            var cartridgeConfiguration = {
              summary: {component: "A React Component", props: {id: this.props.id}},
              cartridge: {component: "A React Component"},
              actions: {components: "react actions"}
            };
            return cartridgeConfiguration;
          }
        `);
      }
      var cartridgeConf = this.cartridgeConfiguration();
      dispatcher.handleViewAction({
        data: {
          cartridgeComponent: cartridgeConf.cartridge,
          summaryComponent: cartridgeConf.summary,
          actions: cartridgeConf.actions
        },
        type: 'update'
      });
    },
    componentWillMount: function pageMixinWillMount(){
      this._registerCartridge();
    }
};

Add mixin for the cartridge


const express = require('express');
const app = express();
const path = require('path');

app.use('/public', express.static(path.join(__dirname, 'public')))
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')))

app.get('/', (req, res) => {
  res.sendFile(__dirname +'/index.html');
});

app.listen(3000, () => {
  console.log('App runs on port 3000');
});

const express = require('express');
const app = express();
const path = require('path');

app.use('/public', express.static(path.join(__dirname, 'public')))
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')))

app.get('/', (req, res) => {
  res.sendFile(__dirname +'/index.html');
});

app.listen(8082, () => {
  console.log('Production app runs on port 8082');
});

Change port for production to 8082


'use strict';

angular.module('core').controller('HeaderController', ['$scope', '$window', 'Authentication', 'Menus', '$state', '$rootScope',
	function($scope, $window, Authentication, Menus, $state, $rootScope) {
		$scope.authentication = Authentication;
		$scope.isCollapsed = false;
		$scope.menu = Menus.getMenu('topbar');

		$scope.toggleCollapsibleMenu = function() {
			$scope.isCollapsed = !$scope.isCollapsed;
		};

        $(document).keydown(function (e) {
			if (e.keyCode == 80 && e.ctrlKey) {
                $window.open('/slideshow#!/player', '_blank');
            }
        });

        $scope.isItemSelected = function (item) {
			var currentUrl = $state.current.url.substring(1); // Remove leading slash.

			if (item.link === currentUrl) {
				return true;
			} else {
				return _.some(item.items, { link: currentUrl });
			}
        };

		// Collapsing the menu after navigation
		$scope.$on('$stateChangeSuccess', function() {
			$scope.isCollapsed = false;
		});
	}
]);

'use strict';

angular.module('core').controller('HeaderController', ['$scope', '$window', 'Authentication', 'Menus', '$state', '$rootScope',
	function($scope, $window, Authentication, Menus, $state, $rootScope) {
		$scope.authentication = Authentication;
		$scope.isCollapsed = false;
		$scope.menu = Menus.getMenu('topbar');

		$scope.toggleCollapsibleMenu = function() {
			$scope.isCollapsed = !$scope.isCollapsed;
		};

        $(document).keydown(function (e) {
			if (e.keyCode == 80 && e.ctrlKey) {
				e.preventDefault();
                $window.open('/slideshow#!/player', '_blank');
            }
        });

        $scope.isItemSelected = function (item) {
			var currentUrl = $state.current.url.substring(1); // Remove leading slash.

			if (item.link === currentUrl) {
				return true;
			} else {
				return _.some(item.items, { link: currentUrl });
			}
        };

		// Collapsing the menu after navigation
		$scope.$on('$stateChangeSuccess', function() {
			$scope.isCollapsed = false;
		});
	}
]);

Disable print dialog in Firefox because Ctrl + P is used to open the player.


'use strict';

// FIXME: clean-up once split is ready
// var splitStream = require( '@stdlib/streams/utils/split' );
var joinStream = require( './../lib' );

var split;
var join;
var i;

// Create a split stream for tab delimited data:
// split = splitStream({
// 	'sep': /\t/
// });

// Create a stream to make newline delimited data:
join = joinStream({
	'sep': '\n'
});

// Create a stream pipeline:
// split
// 	.pipe( join )
// 	.pipe( process.stdout );
join.pipe( process.stdout );

// Write values to the split stream...
for ( i = 0; i < 10; i++ ) {
	// split.write( i+'\t', 'utf8'  );
	join.write( ''+i, 'utf8' )
}
// split.end();
join.end();

'use strict';

// FIXME: clean-up once split is ready
// var splitStream = require( '@stdlib/streams/utils/split' );
var joinStream = require( './../lib' );

var split;
var join;
var i;

// Create a split stream for tab delimited data:
// split = splitStream({
// 	'sep': /\t/
// });

// Create a stream to make newline delimited data:
join = joinStream({
	'sep': '\n'
});

// TODO: do not use process.stdout; replace with a map stream which outputs using `console.log`; ditto in the README and src examples
// Create a stream pipeline:
// split
// 	.pipe( join )
// 	.pipe( process.stdout );
join.pipe( process.stdout );

// Write values to the split stream...
for ( i = 0; i < 10; i++ ) {
	// split.write( i+'\t', 'utf8'  );
	join.write( ''+i, 'utf8' )
}
// split.end();
join.end();

Add TODO item to make examples browser compatible


import React from 'react';
import { storiesOf } from '@kadira/storybook';

import ClubLayout from 'vclub/views/clubLayout/ClubLayout';
import clubReducer from 'vclub/reducers/club';

const book = storiesOf('views.clubLayout.ClubLayout', module);

book.setInitialStateFromReducer(clubReducer);

book.addReduxStory('Default', dispatch => (
  <ClubLayout dispatch={dispatch} />
));

book.addReduxStory('Default2', dispatch => (
  <ClubLayout dispatch={dispatch} />
), {
  data: {
    authenticated: true,
  },
});

import React from 'react';
import { storiesOf } from '@kadira/storybook';

import ClubLayout from 'vclub/views/clubLayout/ClubLayout';
import initialState from 'vclub/redux/initialState';

const book = storiesOf('views.clubLayout.ClubLayout', module);

book.setInitialState(initialState.club);

book.addReduxStory('Default', dispatch => (
  <ClubLayout dispatch={dispatch} />
));

book.addReduxStory('Default2', dispatch => (
  <ClubLayout dispatch={dispatch} />
), {
  data: {
    authenticated: true,
  },
});

Fix stories according to new structure


'use strict';

var defaults = require('lodash.defaults');
var through = require('through2');
var gs = require('glob-stream');
var File = require('vinyl');

var getContents = require('./getContents');
var getStats = require('./getStats');

function createFile (globFile, enc, cb) {
  cb(null, new File(globFile));
}

function src(glob, opt) {
  if (!isValidGlob(glob)) {
    throw new Error('Invalid glob argument');
  }

  var options = defaults({}, opt, {
    read: true,
    buffer: true
  });

  var globStream = gs.create(glob, options);

  // when people write to use just pass it through
  var outputStream = globStream
    .pipe(through.obj(createFile))
    .pipe(getStats(options));

  if (options.read !== false) {
    outputStream = outputStream
      .pipe(getContents(options));
  }

  return outputStream
    .pipe(through.obj());
}

function isValidGlob(glob) {
  if (typeof glob === 'string') {
    return true;
  }
  if (Array.isArray(glob) && glob.length !== 0) {
    return true;
  }
  return false;
}

module.exports = src;

'use strict';

var defaults = require('lodash.defaults');
var through = require('through2');
var gs = require('glob-stream');
var File = require('vinyl');

var getContents = require('./getContents');
var getStats = require('./getStats');

function createFile (globFile, enc, cb) {
  cb(null, new File(globFile));
}

function src(glob, opt) {
  if (!isValidGlob(glob)) {
    throw new Error('Invalid glob argument: ' + glob);
  }

  var options = defaults({}, opt, {
    read: true,
    buffer: true
  });

  var globStream = gs.create(glob, options);

  // when people write to use just pass it through
  var outputStream = globStream
    .pipe(through.obj(createFile))
    .pipe(getStats(options));

  if (options.read !== false) {
    outputStream = outputStream
      .pipe(getContents(options));
  }

  return outputStream
    .pipe(through.obj());
}

function isValidGlob(glob) {
  if (typeof glob === 'string') {
    return true;
  }
  if (Array.isArray(glob) && glob.length !== 0) {
    return true;
  }
  return false;
}

module.exports = src;

Include the invalid glob in error message


import React, { PropTypes } from 'react';
import cx from 'classnames';

import s from '../Markdown/Markdown.css';

const CodeRenderer = ({ className, children }) => (
	{children}
);

CodeRenderer.propTypes = {
	className: PropTypes.string,
	children: PropTypes.node,
};

export default CodeRenderer;

import React, { PropTypes } from 'react';

import s from '../Markdown/Markdown.css';

const CodeRenderer = ({ className, children }) => (

		{children}

);

CodeRenderer.propTypes = {
	className: PropTypes.string,
	children: PropTypes.node,
};

export default CodeRenderer;

Fix regression: colors in props table.


module.exports = (function() {
  var Router = require('router'),
      Connection = require('lib/connection');

  // App namespace.
  window.Boards = {
    Models: {},
    Collections: {}
  };

  // Load helpers.
  require('lib/helpers');

  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      xhr.setRequestHeader('Authorization', 'JWT ' + _.getModel('User').get('token'));
    }
  });

  // Register Swag Helpers.
  Swag.registerHelpers();

  // Initialize Router.
  Boards.Router = new Router();

  // Create a Connection object to communicate with the server through web sockets.
  // The `connection` object will be added to the `Application` object so it's available through
  // `window.Application.connection`.
  Boards.Connection = new Connection({
    type: APPLICATION_CONNECTION,
    httpUrl: APPLICATION_HTTP_URL,
    socketUrl: APPLICATION_WEBSOCKET_URL
  });

  // Connect to the server.
  Boards.Connection.create().done(function() {
    Boards.Router.start();
  }).fail(function() {
    console.log('Connection Error', arguments);
  });
})();

module.exports = (function() {
  var Router = require('router'),
      Connection = require('lib/connection');

  // App namespace.
  window.Boards = {
    Models: {},
    Collections: {}
  };

  // Load helpers.
  require('lib/helpers');

  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      var token = _.getModel('User').get('token');
      if (token) xhr.setRequestHeader('Authorization', 'JWT ' + token);
    }
  });

  // Register Swag Helpers.
  Swag.registerHelpers();

  // Initialize Router.
  Boards.Router = new Router();

  // Create a Connection object to communicate with the server through web sockets.
  // The `connection` object will be added to the `Application` object so it's available through
  // `window.Application.connection`.
  Boards.Connection = new Connection({
    type: APPLICATION_CONNECTION,
    httpUrl: APPLICATION_HTTP_URL,
    socketUrl: APPLICATION_WEBSOCKET_URL
  });

  // Connect to the server.
  Boards.Connection.create().done(function() {
    Boards.Router.start();
  }).fail(function() {
    console.log('Connection Error', arguments);
  });
})();

Send JWT token in HTTP requests only when available.