#!/usr/bin/env node

"use strict";

var program = require('commander'),
    pkg = require('../package.json');

program
    .version(pkg.version)
    .option('-p, --port [port]', 'Server Port (Defaults to 8000)')
    .option('-r, --root [root]', 'Server Root (Defaults to current directory)')
    .option('-i, --index [index]', 'Index file (Defaults to index.html)')
    .parse(process.argv);

process.title = 'web-server';

require('../lib/web-server')(program.port || process.env.PORT || 8000, program.root || './', program.index || 'index.html');

#!/usr/bin/env node

"use strict";

var program = require('commander'),
    pkg = require('../package.json');

program
    .version(pkg.version)
    .option('-p, --port [port]', 'Server Port (Defaults to 8000)')
    .option('-r, --root [root]', 'Server Root (Defaults to current directory)')
    .option('-i, --index [index]', 'Index file (Defaults to index.html)')
    .option('-h, --hidden', 'Show hidden files')
    .parse(process.argv);

process.title = 'web-server';

require('../lib/web-server')(program.port || process.env.PORT || 8000, program.root || './', program.index || 'index.html', program.hidden);

Add CLI paramater for showing hidden files


var DeprecatedClass = require('../../../lib/helpers/deprecated-class');

describe('lib/helpers/deprecated-class', function() {
  it('should raise exception for getOptionName', function() {
    global.expect(function() {
      var sut = new DeprecatedClass();
      sut.getOptionName();
    }).to.throw('Needs to be implemented');
  });

  it('should raise exception for getErrorString', function() {
    global.expect(function() {
      var sut = new DeprecatedClass();
      sut.getErrorString({});
    }).to.throw('Needs to be implemented');
  });
});

var DeprecatedClass = require('../../../lib/helpers/deprecated-class');

describe('lib/helpers/deprecated-class', function() {
  it('should raise exception for getOptionName', function() {
    global.expect(function() {
      var sut = new DeprecatedClass();
      sut.getOptionName();
    }).to.throw('Needs to be implemented');
  });

  it('should raise exception for getErrorString', function() {
    global.expect(function() {
      var sut = new DeprecatedClass();
      sut.getErrorString({});
    }).to.throw('Needs to be implemented');
  });

  it('should raise exception for getDeprecatedClass', function() {
    global.expect(function() {
      var sut = new DeprecatedClass();
      sut.getDeprecatedClass();
    }).to.throw('Needs to be implemented');
  });
});

Add test for getDeprecatedClass() function on abstract class


import React from 'react';
import { connect } from 'react-redux';
// Components
import { Route, Redirect } from 'react-router';
import { Button, Glyphicon } from 'react-bootstrap';
import DashNav from '../components/dashboard/DashNav'

// actions
import { logOut } from '../actions/login'

const DashboardContainer = (props) => {
  if(props.loggedIn){
    return (
      <div className="dashboard">
        <DashNav />
        <Button onClick={props.logOut}>Log out <Glyphicon glyph="log-out" /></Button>
      </div>
    )
  } else {
    return <Redirect to="/login"/>
  }
}

function mapStateToProps(state, ownProps) {
  return {
    loggedIn: state.login.logged_in,
  }
}

export default connect(mapStateToProps, { logOut })(DashboardContainer)

import React from 'react';
import { connect } from 'react-redux';
// Components
import { Route, Redirect } from 'react-router';
import DashNav from '../components/dashboard/DashNav';
// Styles
import '../styles/dashboard/index.css';

const DashboardContainer = (props) => {
  if(props.loggedIn){
    return (

        <DashNav />

    )
  } else {
    return <Redirect to="/login"/>
  }
}

function mapStateToProps(state, ownProps) {
  return {
    loggedIn: state.login.logged_in,
  }
}

export default connect(mapStateToProps)(DashboardContainer)

Remove dispatcher and unwanted boilerplate


import bus from '../src/bus.js';

beforeEach(function () {
  bus.stopListenAll();
});

it('sends and listens', function () {
  var obj = {
    value: 57
  };
  bus.listen('test', function (e, msg) {
    expect(msg).toBe(obj);
  });
  bus.send('test', obj);
});

it('stops listening', function () {
  function callback() {
    fail('Callback has been called');
  }

  bus.listen('test', callback);
  bus.stopListen('test', callback);
  bus.send('test');
});

it('stops listening all', function () {
  function callback() {
    fail('Callback has been called');
  }

  bus.listen('test', callback);
  bus.stopListenAll();
  bus.send('test');
});

it('calls subsequent listeners on fail', function (done) {
  bus.listen('test', function () {
    throw new Error('');
  });
  bus.listen('test', function () {
    done();
  });
  bus.send('test');
});

Add test for failing listener


var port = process.env.PORT || 3000;
var express = require('express');
var app = express();

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

app.use(function(req, res, next) {
  res.sendfile('/public/index.html');
});

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

var port = process.env.PORT || 3000;
var express = require('express');
var app = express();

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

app.use(function(req, res, next) {
  res.sendfile(__dirname + '/public/index.html');
});

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

Include __dirname to properly route index.html


/*
 * Melodycoder, an personal webside.
 * http://botobe.net/
 *
 * Copyright (c) 2013 Kai.XU
 * Licensed under the MIT license.
 */

var express = require('express'), map = require('./map'), http = require('http'), path = require('path'), db = require('./model/db'), config = require('./config').config;

var app = express();

app.configure(function() {
	app.use(express.cookieParser());
	app.use(express.session({
		secret : config.SESSION_SECRET
	}));
	app.use(db.initialize());
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
});

// 开发环境
app.configure('development', function() {
	app.use(express.logger('dev'));
	app.use(express.errorHandler());
});

// 生产环境
app.configure('production', function() {
	app.use(express.compress());
});

map(app);
http.createServer(app).listen(app.get('port'));

/*
 * Melodycoder, an personal webside.
 * http://botobe.net/
 *
 * Copyright (c) 2013 Kai.XU
 * Licensed under the MIT license.
 */

var express = require('express'), map = require('./map'), http = require('http'), path = require('path'), db = require('./model/db'), config = require('./config').config;

var app = express();

// 开发环境
app.configure('development', function() {
	app.use(express.logger('dev'));
	app.use(express.errorHandler());
});

// 生产环境
app.configure('production', function() {
	app.use(express.compress());
});

app.configure(function() {
	app.use(express.cookieParser());
	app.use(express.session({
		secret : config.SESSION_SECRET
	}));
	app.use(db.initialize());
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
});

map(app);
http.createServer(app).listen(app.get('port'));

Move the compress middleware to the top.


const express = require('express')
const app = express()
const http = require('http').Server(app)
const path = require('path')
const bodyParser = require('body-parser')
const register = require('./routes/register')
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

// Looks for external JS file holding front-end logic
app.use(express.static(path.join(__dirname, '/public')))

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.get('/', (req, res) => {
  res.render('chat_ui')
})
app.get('/register', register.form)
app.post('/register', register.submit)

http.listen(3000, () => {
  console.log('Server is listening at * 3000')
})

const socket = require('./lib/chat_server')
socket.listen(http)

const express = require('express')
const app = express()
const http = require('http').Server(app)
const path = require('path')
const bodyParser = require('body-parser')
const register = require('./routes/register')
const login = require('./routes/login')
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

// Looks for external JS file holding front-end logic
app.use(express.static(path.join(__dirname, '/public')))

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.get('/', (req, res) => {
  res.render('chat_ui')
})
app.get('/register', register.form)
app.post('/register', register.submit)

app.get('/login', login.form)
app.post('/login', login.submit)

http.listen(3000, () => {
  console.log('Server is listening at * 3000')
})

const socket = require('./lib/chat_server')
socket.listen(http)

Add routes to handle login GET and POST


require('dotenv').load();

var moment = require('moment');
var fixturesEpl = require('./fixtures/epl.json')['fixtures'];
var fixturesCl = require('./fixtures/cl.json')['fixtures'];
var postMessage = require('./lib/postMessage.js');

var matches_rn = [];
var now        = moment().utc();

fixturesEpl.forEach(function(entry) {
    // set the entry date to be the entry date in utc and a unix number
    entry.date = moment(entry.date).utc();

    // if the match is within 10 minutes of the current time,
    // and it has not been sent, then add the match to the lest of matches_rn
    if(    (0 <= entry.date - now)
        && (entry.date.diff(now, 'minutes') <= 10)
        && (!entry.hasOwnProperty('sent'))
      ) {
        matches_rn.push(entry.homeTeamName + ' vs ' + entry.awayTeamName);
    }
});

if(matches_rn.length > 0) {
    if(matches_send == 1) {
        plural = 'match';
    }
    else {
        plural = 'matches';
    }

    // post a message using the BOT_ID and matches_rn
    postMessage(process.env.BOT_ID,
        matches_rn.length + ' ' + plural + ' kicking off soon:\n' +
        matches_rn.join(',\n')
    );
}
else {
    console.log('no matches found');
}

require('dotenv').load();

var moment = require('moment');
var fixturesEpl = require('./fixtures/epl.json')['fixtures'];
var fixturesCl = require('./fixtures/cl.json')['fixtures'];
var postMessage = require('./lib/postMessage.js');

var matches_rn = [];
var now        = moment().utc();

fixturesEpl.forEach(function(entry) {
    // set the entry date to be the entry date in utc and a unix number
    entry.date = moment(entry.date).utc();

    // if the match is within 10 minutes of the current time,
    // and it has not been sent, then add the match to the lest of matches_rn
    if(    (0 <= entry.date - now)
        && (entry.date.diff(now, 'minutes') <= 10)
        && (!entry.hasOwnProperty('sent'))
      ) {
        matches_rn.push(entry.homeTeamName + ' vs ' + entry.awayTeamName);
    }
});

if(matches_rn.length > 0) {
    if(matches_rn.length == 1) {
        plural = 'match';
    }
    else {
        plural = 'matches';
    }

    // post a message using the BOT_ID and matches_rn
    postMessage(process.env.BOT_ID,
        matches_rn.length + ' ' + plural + ' kicking off soon:\n' +
        matches_rn.join(',\n')
    );
}
else {
    console.log('no matches found');
}

Fix incorrect variable on line 26


import { buildFilterProductsQuery } from '@vue-storefront/store/helpers'

export default {
  name: 'CategorySidebar',
  props: {
    filters: {
      type: Object,
      required: true
    }
  },
  computed: {
    category () {
      return this.$store.state.category.current
    },
    vuexFilters () {
      return this.$store.state.category.filters
    }
  },
  methods: {
    sortById (filters) {
      return [...filters].sort((a, b) => { return a.id - b.id })
    },
    resetAllFilters () {
      this.$bus.$emit('filter-reset')
      this.$store.dispatch('category/resetFilters')
      const filterQr = buildFilterProductsQuery(this.category, this.vuexFilters.chosen)
      const fsC = Object.assign({}, this.vuexFilters.chosen)
      this.$store.state.category.current_product_query = Object.assign(this.$store.state.category.current_product_query, {
        searchProductQuery: filterQr,
        configuration: fsC
      })
      this.$store.dispatch('category/products', this.$store.state.category.current_product_query)
    }
  }
}

import { buildFilterProductsQuery } from '@vue-storefront/store/helpers'

export default {
  name: 'CategorySidebar',
  props: {
    filters: {
      type: Object,
      required: true
    }
  },
  computed: {
    category () {
      return this.$store.state.category.current
    },
    vuexFilters () {
      return this.$store.state.category.filters
    }
  },
  methods: {
    sortById (filters) {
      return [...filters].sort((a, b) => { return a.id - b.id })
    },
    resetAllFilters () {
      this.$bus.$emit('filter-reset')
      this.$store.dispatch('category/resetFilters')
      const filterQr = buildFilterProductsQuery(this.category, this.vuexFilters.chosen)
      this.$store.state.category.current_product_query = Object.assign(this.$store.state.category.current_product_query, {
        searchProductQuery: filterQr
      })
      this.$store.dispatch('category/products', this.$store.state.category.current_product_query)
    }
  }
}

Remove unnecessary config from product query


// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    remapIstanbulReporter: {
      reports: {
        html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'karma-remap-istanbul']
              : ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    remapIstanbulReporter: {
      reports: {
        html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'karma-remap-istanbul']
              : ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

Fix how .ts files are served by karma.


'use strict';

// TODO:
  //  - Rename to .min for minified js - get paths right for components.

var gulp = require('gulp'),
    nib = require('nib'),
    $ = require('gulp-load-plugins')({ lazy: false });

var paths = require('./paths.js');

module.exports = {

  copyAssets: function () {
    return function () {
      var assets = gulp.src(paths.src.assets)
        .pipe(gulp.dest(paths.dest.root));
      return assets;
    };
  },

  buildHTML: function () {
    return function () {
      return gulp.src(paths.src.jade)
        // 'pretty' jade means uncompressed.
        .pipe($.jade({pretty: paths.isDev}))
        .pipe(gulp.dest(paths.dest.root));
    };
  },

  buildCSS: function () {
    return function () {
      return gulp.src(paths.src.cssMaster)
        // 'nib' adds autoprefixing and some other niceties.
        .pipe($.stylus({use: nib(), compress: !paths.isDev}))
        .pipe($.if(paths.isDev, $.rename('app.css'), $.rename('app.min.css')))
        .pipe(gulp.dest(paths.dest.root));
    };
  },

  buildJS: function () {
    return function () {
      return gulp.src(paths.src.js)
        .pipe($.angularFilesort())
        .pipe($.if(!paths.isDev, $.uglify({preserveComments: 'some'})))
        // .pipe($.if(!paths.isDev, $.rename('app.min.js')))
        .pipe(gulp.dest(paths.dest.root));
    };
  },
};

'use strict';

var gulp = require('gulp'),
    nib = require('nib'),
    $ = require('gulp-load-plugins')({ lazy: false });

var paths = require('./paths.js');

module.exports = {

  copyAssets: function () {
    return function () {
      var assets = gulp.src(paths.src.assets)
        .pipe(gulp.dest(paths.dest.root));
      return assets;
    };
  },

  buildHTML: function () {
    return function () {
      return gulp.src(paths.src.jade)
        // 'pretty' jade means uncompressed.
        .pipe($.jade({pretty: paths.isDev}))
        .pipe(gulp.dest(paths.dest.root));
    };
  },

  buildCSS: function () {
    return function () {
      return gulp.src(paths.src.cssMaster)
        // 'nib' adds autoprefixing and some other niceties.
        .pipe($.stylus({use: nib(), compress: !paths.isDev}))
        .pipe($.if(paths.isDev, $.rename('app.css'), $.rename('app.min.css')))
        .pipe(gulp.dest(paths.dest.root));
    };
  },

  buildJS: function () {
    return function () {
      return gulp.src(paths.src.js)
        .pipe($.angularFilesort())
        .pipe($.if(!paths.isDev, $.uglify({preserveComments: 'some'})))
        .pipe($.rename({extname: '.min.js'}))
        .pipe(gulp.dest(paths.dest.root));
    };
  }

};

Add .min name to minified .js


/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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
*
*    http://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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name arcsine
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/random/iterators/arcsine}
*/
setReadOnly( ns, 'arcsine', require( '@stdlib/random/iterators/arcsine' ) );

// EXPORTS //

module.exports = ns;

/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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
*
*    http://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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name arcsine
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/random/iterators/arcsine}
*/
setReadOnly( ns, 'arcsine', require( '@stdlib/random/iterators/arcsine' ) );

/**
* @name bernoulli
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/random/iterators/bernoulli}
*/
setReadOnly( ns, 'bernoulli', require( '@stdlib/random/iterators/bernoulli' ) );

// EXPORTS //

module.exports = ns;

Add Bernoulli iterator to namespace


const url = process.env.NODE_ENV === 'production'
  ? 'https://gene-info.org/api'
  : 'http://localhost:8002';

chrome.runtime.onMessage.addListener((request, sender, callback) => {
  if (request.action === 'xhttp') {
    const xhr = new XMLHttpRequest();
    const method = request.method ? request.method.toUpperCase() : 'GET';
    xhr.onload = () => {
      callback({
        result: xhr.response,
        status: xhr.status,
      });
    };
    xhr.onerror = () => {
      callback({
        result: null,
        status: xhr.status,
      });
    };
    xhr.open(method, `${url}/extension${request.route}`, true);
    xhr.responseType = 'json';
    xhr.send();
    return true;
  }
  return false;
});

const url = process.env.NODE_ENV === 'production'
  ? 'https://api.gene-info.org/api'
  : 'http://localhost:8002';

chrome.runtime.onMessage.addListener((request, sender, callback) => {
  if (request.action === 'xhttp') {
    const xhr = new XMLHttpRequest();
    const method = request.method ? request.method.toUpperCase() : 'GET';
    xhr.onload = () => {
      callback({
        result: xhr.response,
        status: xhr.status,
      });
    };
    xhr.onerror = () => {
      callback({
        result: null,
        status: xhr.status,
      });
    };
    xhr.open(method, `${url}/extension${request.route}`, true);
    xhr.responseType = 'json';
    xhr.send();
    return true;
  }
  return false;
});

Change api endpoint in extension


/**
 *
 */

var changeCaseKeys = require('change-case-keys');

var Legislator = require('../../../../models').Legislator;
var resHelpers = require('../helpers/response');
var sunlight = require('../../../services/third-party-apis/sunlight');

var get = function (req, res) {
  var bioguideId = req.params.bioguideId;

  sunlight.fetchActiveLegislatorBioViaSunlight(bioguideId, req.app.locals.CONFIG, function(err, data) {
    if (err) {
      res.status(400).json(resHelpers.makeError(err));
    }

    var modelData = new Legislator(changeCaseKeys(data['results'][0], 'camelize'));
    res.json(resHelpers.makeResponse(modelData));
  });
};

module.exports.get = get;

/**
 *
 */

var Congress = require('../../../services/congress');
var resHelpers = require('../helpers/response');

var get = function (req, res) {
  var bioguideId = req.params.bioguideId;

  if (!Object.keys(Congress.Members).includes(bioguideId))
    res.status(400).json(resHelpers.makeError({ message: "No legislators match this bioguide id" }));
  else
    res.json(resHelpers.makeResponse(Congress.Members[bioguideId]));
};

module.exports.get = get;

Use new Congress module to find legislator by bioId


var fs = require('fs')
var natural = require('natural')
var inflector = new natural.NounInflector()
var _ = require('lodash-node/modern')

var config = require('../lib/config')
var Page = require('../lib/page')
var Taxonomy = require('../lib/taxonomy')

var layoutExists = function(layout) {
  return fs.existsSync(config.layoutsDirectory + '/' + layout + '.html')
}

module.exports = function() {

  this.events.on('beforeBuild', function() {

    Taxonomy.each(function(taxonomy) {
      if (layoutExists(taxonomy.type.toLowerCase())) {
        var obj = {
          content: '',
          title: taxonomy.value,
          permalink: (taxonomy.typePlural + '/' + taxonomy.value).toLowerCase(),
          layout: taxonomy.type.toLowerCase()
        }
        // add the taxonomy type and value to the page data
        obj[taxonomy.type] = taxonomy.value

        // add the taxonomy to the query params
        obj.query = {}
        obj.query[taxonomy.type] = taxonomy.value

        taxonomy.page = new Page(obj)
      }
    })

  })

}

var fs = require('fs')
var natural = require('natural')
var inflector = new natural.NounInflector()
var _ = require('lodash-node/modern')

module.exports = function() {

  var Page = this.Page
  var Taxonomy = this.Taxonomy
  var config = this.config

  function layoutExists(layout) {
    return fs.existsSync(config.layoutsDirectory + '/' + layout + '.html')
  }

  this.events.on('beforeBuild', function() {

    Taxonomy.each(function(taxonomy) {
      if (layoutExists(taxonomy.type.toLowerCase())) {
        var obj = {
          content: '',
          title: taxonomy.value,
          permalink: (taxonomy.typePlural + '/' + taxonomy.value).toLowerCase(),
          layout: taxonomy.type.toLowerCase()
        }
        // add the taxonomy type and value to the page data
        obj[taxonomy.type] = taxonomy.value

        // add the taxonomy to the query params
        obj.query = {}
        obj.query[taxonomy.type] = taxonomy.value

        taxonomy.page = new Page(obj)
      }
    })

  })

}

Refactor the taxonomy pages plugin to use site.config data.


Template['modifyBookModal'].helpers({
  header: function() {
    if (Session.get('modifyBookModal.doc')) {
      return "Modify book";
    } else {
      return "Add a new book";
    }
  },
  type: function() {
    return Session.get('modifyBookModal.doc') ? 'update' : 'insert';
  },
  doc: function() {
    return Session.get('modifyBookModal.doc');
  },
  showDeleteButton: function() {
    return !!Session.get('modifyBookModal.doc');
  },
  categoryOptions: function() {
    return Categories.find().map(function(c) {
      return { label: c.name, value: c._id };
    });
  }
});

Template['modifyBookModal'].events({
  'click #remove-book-button': function(event, template) {
    var book = Session.get('modifyBookModal.doc');
    Books.remove(book._id);
  }
});

Template['modifyBookModal'].onRendered(function() {
  $('#modify-book-modal').modal({
    detachable: false,
    onShow: function() {
      AutoForm.resetForm("modifyBookForm");
    }
  });
});

Template['modifyBookModal'].helpers({
  header: function() {
    if (Session.get('modifyBookModal.doc')) {
      return "Modify book";
    } else {
      return "Add a new book";
    }
  },
  type: function() {
    return Session.get('modifyBookModal.doc') ? 'update' : 'insert';
  },
  doc: function() {
    return Session.get('modifyBookModal.doc');
  },
  showDeleteButton: function() {
    return !!Session.get('modifyBookModal.doc');
  },
  categoryOptions: function() {
    return Categories.find().map(function(c) {
      return { label: c.name, value: c._id };
    });
  }
});

Template['modifyBookModal'].events({
  'click #remove-book-button': function(event, template) {
    var book = Session.get('modifyBookModal.doc');
    Books.remove(book._id);
    $('#modify-book-modal').modal('hide');
  }
});

Template['modifyBookModal'].onRendered(function() {
  $('#modify-book-modal').modal({
    detachable: false,
    onShow: function() {
      AutoForm.resetForm("modifyBookForm");
    }
  });
});

Fix bug where modal doesn't disappear on delete


var express = require('express');
var app = express();
var FalcorServer = require('falcor-server');
var Cache = require('../../data/Cache');
var falcor = require('../../../index');
var Rx = require('rx');
var edgeCaseCache = require('./../../data/EdgeCase')();
var fullCacheModel = new falcor.Model({cache: Cache()}).materialize();
var edgeCaseModel = new falcor.Model({cache: edgeCaseCache}).materialize();

// Simple middleware to handle get/post
app.use('/falcor', FalcorServer.expressMiddleware(function() {
    return {
        get: function(paths) {
            return fullCacheModel.
                get.apply(fullCacheModel, paths).
                toJSONG();
        }
    };
}));
app.use('/falcor.edge', FalcorServer.expressMiddleware(function() {
    return {
        get: function(paths) {
            return edgeCaseModel.
                get.apply(edgeCaseModel, paths).
                toJSONG();
        }
    };
}));

module.exports = function(port) {
    // Note: Will never complete unless explicitly closed.
    return Rx.Observable.create(function(observer) {
        var server = app.listen(port, function(err) {
            if (err) {
                observer.onError(err);
                return;
            }

            observer.onNext();
        });

        return function() {
            server.close();
        };
    });
};

var express = require('express');
var app = express();
var FalcorServer = require('falcor-express');
var Cache = require('../../data/Cache');
var falcor = require('../../../index');
var Rx = require('rx');
var edgeCaseCache = require('./../../data/EdgeCase')();
var fullCacheModel = new falcor.Model({cache: Cache()}).materialize();
var edgeCaseModel = new falcor.Model({cache: edgeCaseCache}).materialize();

// Simple middleware to handle get/post
app.use('/falcor', FalcorServer.expressMiddleware(function() {
    return {
        get: function(paths) {
            return fullCacheModel.
                get.apply(fullCacheModel, paths).
                toJSONG();
        }
    };
}));
app.use('/falcor.edge', FalcorServer.expressMiddleware(function() {
    return {
        get: function(paths) {
            return edgeCaseModel.
                get.apply(edgeCaseModel, paths).
                toJSONG();
        }
    };
}));

module.exports = function(port) {
    // Note: Will never complete unless explicitly closed.
    return Rx.Observable.create(function(observer) {
        var server = app.listen(port, function(err) {
            if (err) {
                observer.onError(err);
                return;
            }

            observer.onNext();
        });

        return function() {
            server.close();
        };
    });
};

Change package name from falcor-server to falcor-express


export let c = 0;
export function increment() {
  ++c;
  module.export();
};

export var c = 0;
export function increment() {
  ++c;
  module.export();
};

Use var instead of let to fix tests in older Node versions.


(function () {
  'use strict';

  moj.Modules.FieldHelp = {
    moreInfos: [],

    init: function() {
      this.cacheEls();
      this.bindEvents();
      this.addMoreInfoLink();
    },

    bindEvents: function() {
      this.moreInfos.parent()
        .on('click', 'a', this.handleToggle);
    },

    handleToggle: function(evt) {
      $(evt.target).parent().toggleClass('s-expanded');
    },

    addMoreInfoLink: function() {
      $.each(this.moreInfos, function(i, el) {
        $('more info').insertBefore($(el));
      });
    },

    cacheEls: function() {
      this.moreInfos = $('.field-more-info');
    }
  };
}());

(function () {
  'use strict';

  moj.Modules.FieldHelp = {
    moreInfos: [],

    init: function() {
      this.cacheEls();
      this.bindEvents();
      this.addMoreInfoLink();
    },

    bindEvents: function() {
      this.moreInfos.parent()
        .on('click', 'a', this.handleToggle);
    },

    handleToggle: function(evt) {
      var $fieldHelp = $(evt.target).parent();
      $fieldHelp
        .toggleClass('s-expanded')
        .find('.field-more-info')
          .attr('aria-expanded', function() {
            return $(this).attr('aria-expanded') === 'false';
          });
    },

    addMoreInfoLink: function() {
      $.each(this.moreInfos, function(i, el) {
        $(this).attr('aria-expanded', 'false');
        $('more info')
          .insertBefore($(el));
      });
    },

    cacheEls: function() {
      this.moreInfos = $('.field-more-info');
    }
  };
}());

Add ARIA role and state on field-help


app.views.PlanListView = Backbone.View.extend({
    tagName:'ul',
    className:'table-view',
    initialize:function () {
        var self = this;
        this.model.on("reset", this.render, this);
        this.model.on("add", function (plan) {
            self.$el.append(new app.views.PlanListItemView({model:plan}).render().el);
        });
    },

    render:function () {
        this.$el.empty();
        _.each(this.model.models, function (plan) {
            this.$el.append(new app.views.PlanListItemView({model:plan}).render().el);
        }, this);
        return this;
    }
});

app.views.PlanListItemView = Backbone.View.extend({
    tagName:"li",
    appendParamsToLi: function(){
        $("a", this.$el).attr("href",  "#formulary/4692/1838/nm");
        $("a", this.$el).removeClass("pull-right");
    },
    className: "table-view-cell",

    initialize:function () {
        this.model.on("change", this.render, this);
        this.model.on("destroy", this.close, this);
    },

    render:function () {
        this.model.attributes["drug_id"] = 1838;
        this.$el.html(this.template(this.model.attributes));
        this.appendParamsToLi();
        return this;
    }

});

app.views.PlanListView = Backbone.View.extend({
    tagName:'ul',
    className:'table-view',
    initialize:function () {
        var self = this;
        this.model.on("reset", this.render, this);
        this.model.on("add", function (plan) {
            self.$el.append(new app.views.PlanListItemView({model:plan}).render().el);
        });
    },

    render:function () {
        this.$el.empty();
        _.each(this.model.models, function (plan) {
            this.$el.append(new app.views.PlanListItemView({model:plan}).render().el);
        }, this);
        return this;
    }
});

app.views.PlanListItemView = Backbone.View.extend({
    tagName:"li",
    appendParamsToLi: function(){
        //$("a", this.$el).attr("href",  "#formulary/4692/1838/nm");
        $("a", this.$el).removeClass("pull-right");
    },
    className: "table-view-cell",

    initialize:function () {
        this.model.on("change", this.render, this);
        this.model.on("destroy", this.close, this);
    },

    render:function () {
        this.model.attributes["drug_id"] = 1838;
        this.$el.html(this.template(this.model.attributes));
        this.appendParamsToLi();
        return this;
    }

});

Update List View Item View with live urls. Waiting for API to get more data.


// Middleware generally used for actions needing parsed queryStrings
import queryString from 'query-string'

import {enablePresentationMode} from 'src/shared/actions/app'
import {templateVariablesSelectedByName} from 'src/dashboards/actions'

export const queryStringConfig = () => next => action => {
  next(action)
  const qs = queryString.parse(window.location.search)

  // Presentation Mode
  if (qs.present === 'true') {
    next(enablePresentationMode())
  }

  // Select Template Variable By Name
  const dashboardRegex = /\/sources\/(\d+?)\/dashboards\/(\d+?)/
  if (dashboardRegex.test(window.location.pathname)) {
    const dashboardID = window.location.pathname.match(dashboardRegex)[2]
    next(templateVariablesSelectedByName(+dashboardID, qs))
  }
}

// Middleware generally used for actions needing parsed queryStrings
import queryString from 'query-string'

import {enablePresentationMode} from 'src/shared/actions/app'
import {templateVariablesSelectedByName} from 'src/dashboards/actions'

export const queryStringConfig = () => {
  let prevPath
  return next => action => {
    next(action)
    const qs = queryString.parse(window.location.search)

    // Presentation Mode
    if (qs.present === 'true') {
      next(enablePresentationMode())
    }

    // Select Template Variable By Name
    const dashboardRegex = /\/sources\/(\d+?)\/dashboards\/(\d+?)/
    if (dashboardRegex.test(window.location.pathname)) {
      const currentPath = window.location.pathname
      const dashboardID = currentPath.match(dashboardRegex)[2]
      if (currentPath !== prevPath) {
        next(templateVariablesSelectedByName(+dashboardID, qs))
      }

      prevPath = currentPath
    }
  }
}

Fix edit annotation rendering speed


var connect = require('connect');
var server = connect.createServer();

server.use(connect.static(__dirname));
server.use(require('browserify')({
  require: ['cucumber-html',
            {'cucumber': './lib/cucumber.js'},
            {'./gherkin/lexer/en': 'gherkin/lib/gherkin/lexer/en'}],
  ignore: ['./cucumber/cli', 'connect']
}));
var port = process.env.PORT || 9797;
server.listen(port);
console.log('Accepting connection on port '+port+'...');

var connect = require('connect');
var server = connect.createServer();

server.use(connect.static(__dirname));
server.use(require('browserify')({
  require: ['cucumber-html', './lib/cucumber', {'./gherkin/lexer/en': 'gherkin/lib/gherkin/lexer/en'}],
  ignore: ['./cucumber/cli', 'connect']
}));
var port = process.env.PORT || 9797;
server.listen(port);
console.log('Accepting connection on port '+port+'...');

Fix browserify setup for example page load


import semver from 'semver';

const {major, minor, patch} = semver.parse(atom.appVersion);
const atomVersion = `${major}.${minor}.${patch}`;
const requiredVersion = '>=1.13.0';

if (atom.inDevMode() || atom.inSpecMode() || semver.satisfies(atomVersion, requiredVersion)) {
  module.exports = startPackage();
} else {
  module.exports = versionMismatch();
}

function versionMismatch() {
  return {
    activate: () => {
      atom.notifications.addWarning('Incompatible Atom Version', {
        description: `The GitHub packages requires Atom ${requiredVersion}. You are running ${atomVersion}.`,
        dismissable: true,
      });
    },
  };
}

function startPackage() {
  const GithubPackage = require('./github-package').default;

  return new GithubPackage(
    atom.workspace, atom.project, atom.commands, atom.notifications,
  );
}

const semver = require('semver');

const {major, minor, patch} = semver.parse(atom.appVersion);
const atomVersion = `${major}.${minor}.${patch}`;
const requiredVersion = '>=1.13.0';

if (atom.inDevMode() || atom.inSpecMode() || semver.satisfies(atomVersion, requiredVersion)) {
  module.exports = startPackage();
} else {
  module.exports = versionMismatch();
}

function versionMismatch() {
  return {
    activate: () => {
      atom.notifications.addWarning('Incompatible Atom Version', {
        description: 'The GitHub packages requires Atom ' + requiredVersion +
          '. You are running ' + atomVersion + '. Please check for updates and try again.',
        dismissable: true,
      });
    },
  };
}

function startPackage() {
  const GithubPackage = require('./github-package').default;

  return new GithubPackage(
    atom.workspace, atom.project, atom.commands, atom.notifications,
  );
}

Fix an atom version check oopsie


#! /usr/bin/env node
"use strict";

var argv = require("optimist").argv;
var pjson = require("../package.json");
var defaultConfig = require("./default-config");
var cliUtils = require("./cli").utils;
var cliInfo = require("./cli-info").info;

/**
 * Handle Command-line usage
 */
if (require.main === module) {
    if (argv.version || argv.v) {
        return cliInfo.getVersion(pjson);
    }
    if (argv._[0] === "init") {
        return cliInfo.makeConfig();
    }
    var config   = cliUtils.getConfig(defaultConfig, argv),
        filesArg = cliUtils.getFilesArg(argv, config),
        files    = cliUtils.getFiles(filesArg);
    if (config.exclude) {
        files = cliUtils.mergeFiles(files, config.exclude);
    }
    cliUtils._start(files, config, pjson.version);
}

/**
 * @param {String|Array} [files]
 * @param {Object} [userConfig]
 */
module.exports.init = function (files, userConfig) {
    var config = defaultConfig;
    if (userConfig) {
        config = cliUtils.mergeConfigObjects(defaultConfig, userConfig || {});
        if (files && userConfig.exclude) {
            files = cliUtils.mergeFiles(files, userConfig.exclude);
        }
    }
    return cliUtils._start(files, config, pjson.version);
};

#! /usr/bin/env node
"use strict";

var argv = require("optimist").argv;
var pjson = require("../package.json");
var defaultConfig = require("./default-config");
var cliUtils = require("./cli").utils;
var cliInfo = require("./cli-info").info;

/**
 * Handle Command-line usage
 */
if (require.main === module) {
    if (argv.version || argv.v) {
        return cliInfo.getVersion(pjson);
    }
    if (argv._[0] === "init") {
        return cliInfo.makeConfig();
    }
    var config   = cliUtils.getConfig(defaultConfig, argv),
        filesArg = cliUtils.getFilesArg(argv, config),
        files    = cliUtils.getFiles(filesArg);
    if (config.exclude) {
        files = cliUtils.mergeFiles(files, config.exclude);
    }
    cliUtils._start(files, config, pjson.version);
}

/**
 * Return init method for external use
 * @param {String|Array} [files]
 * @param {Object} [userConfig]
 */
module.exports.init = function (files, userConfig) {
    var config = defaultConfig;
    if (userConfig) {
        config = cliUtils.mergeConfigObjects(defaultConfig, userConfig || {});
        if (files && userConfig.exclude) {
            files = cliUtils.mergeFiles(files, userConfig.exclude);
        }
    }
    return cliUtils._start(files, config, pjson.version);
};

Use read stream to ensure file is greater than 0 bytes


var Mehdown;

if (typeof exports === 'object' && typeof require === 'function') {
    Mehdown = exports;
}
else {
    Mehdown = {};
}

Mehdown.usernameRegExp = /(^|[^@\w])@(\w{1,15})\b/g;

Mehdown.parse = function(text) {
	// Hashtags
	text = text.replace(/(^|[^#\w])#([a-z0-9_-]+)\b/gi, '$1' + Mehdown.hashtag('$2'));

	// Usernames
	text = text.replace(Mehdown.usernameRegExp, '$1' + Mehdown.username('$2'));

	return text;
};

Mehdown.hashtag = function(hashtag) {
	return '#' + hashtag + '';
}

Mehdown.username = function(username) {
	//return '@' + username + '';
	return '@' + username + '';
}

var Mehdown;

if (typeof exports === 'object' && typeof require === 'function') {
    Mehdown = exports;
}
else {
    Mehdown = {};
}

Mehdown.usernameRegExp = /(^|[^@\w])@(\w{1,15})\b/g;

Mehdown.parse = function(text) {
    // Replace newlines with
 tags
    text = text.replace(/\n/g, '
\n');

    // Hashtags
    text = text.replace(/(^|[^#\w])#([a-z0-9_-]+)\b/gi, '$1' + Mehdown.hashtag('$2'));

    // Usernames
    text = text.replace(Mehdown.usernameRegExp, '$1' + Mehdown.username('$2'));

    return text;
};

Mehdown.hashtag = function(hashtag) {
    return '#' + hashtag + '';
}

Mehdown.username = function(username) {
    //return '@' + username + '';
    return '@' + username + '';
}

Replace newlines with <br /> tags


/*jshint browser:true, node:true*/

'use strict';

/**
 * @preserve Create and manage a DOM event delegator.
 *
 * @version 0.3.0
 * @codingstandard ftlabs-jsv2
 * @copyright The Financial Times Limited [All Rights Reserved]
 * @license MIT License (see LICENSE.txt)
 */
var Delegate = require('./delegate');

module.exports = function(root) {
  return new Delegate(root);
};

module.exports.Delegate = Delegate;

/*jshint browser:true, node:true*/

'use strict';

/**
 * @preserve Create and manage a DOM event delegator.
 *
 * @codingstandard ftlabs-jsv2
 * @copyright The Financial Times Limited [All Rights Reserved]
 * @license MIT License (see LICENSE.txt)
 */
var Delegate = require('./delegate');

module.exports = function(root) {
  return new Delegate(root);
};

module.exports.Delegate = Delegate;

Remove version out of date version number


var email = new (require('./emailer'))(),
  backdrop = new (require('./integrations/backdrop'))(),
  stagecraft = new (require('./integrations/stagecraft'))(),
  message = new (require('./message'))(),
  Q = require('q'),
  queue = [];

// Query backdrop for out of date datasets
backdrop.getDataSets().then(function (data) {
  // console.log('datasets', data);
  // Got some datasets, now find emails for them
  data.data_sets.forEach( function (dataSet) {

    // Set email message
    dataSet.message = message.dataSetReminder(dataSet);

    // Queue up email query for this dataset
    queue.push(stagecraft.queryEmail(dataSet));
  });

  // When all the email queries are finished, send some notifications
  return Q.all(queue).then( function (dataSets) {
    console.log(dataSets);
    // email.send({
    //   to: config.notificationsEmail,
    //   subject: 'Datasets out of date',
    //   text: 'There are ' + data.message + '\n\n' + JSON.stringify(data.data_sets)
    // });
  });
}).fail(function (err) {
  throw err;
}).done();

var email = new (require('./emailer'))(),
  backdrop = new (require('./integrations/backdrop'))(),
  stagecraft = new (require('./integrations/stagecraft'))(),
  message = new (require('./message'))(),
  Q = require('q'),
  queue = [];

// Query backdrop for out of date datasets
backdrop.getDataSets().then(function (data) {
  // console.log('datasets', data);
  // Got some datasets, now find emails for them
  data.data_sets.forEach( function (dataSet) {

    // Set email message
    dataSet.message = message.dataSetReminder(dataSet);

    // Queue up email query for this dataset
    queue.push(stagecraft.queryEmail(dataSet));
  });

  // When all the email queries are finished, send some notifications
  return Q.all(queue).then( function (dataSets) {
    console.log(dataSets);
    dataSets.forEach( function (dataSet) {
      email.send({
        to: dataSet.emails.toString(),
        subject: 'Datasets out of date',
        text: dataSet.message
      });
    });
  });
}).fail(function (err) {
  throw err;
}).done();

Send emails once we have them


// Apply login on current session and change session id for security reasons.

'use strict';

var rnd = require('nodeca.core/lib/rnd');

module.exports = function login(env, userId) {
  env.session.user_id = userId;
  env.origin.req.sid = rnd(); // Generate cryptostrong random hex string.
};

// Apply login on current session and change session id for security reasons.

'use strict';

var rnd = require('nodeca.core/lib/rnd');

module.exports = function login(env, userId) {
  env.session.user_id = userId;
  env.session_id = rnd(); // Generate cryptostrong random hex string.
};

Use `env.session_id` instead of deprecated `req.sid`.


import React from 'react';
import { connect } from 'react-redux';

@connect(state => ({ tickTrade: state.tickTrade }))
export default class TickTradePane extends React.Component {

	render() {
		return (
			<div>
			</div>
		);
	}
}

import React from 'react';
import { connect } from 'react-redux';

@connect(state => ({ tickTrade: state.tickTrade }))
export default class TickTradePane extends React.Component {

	render() {
		return (

					<button>Change Time Settings</button>
					<fieldset>
						USD/JPY will RISE over next 5 ticks
					</fieldset>

CHART HERE

					<fieldset>
						Payout: USD<input type="number" defaultValue={15} /> <button>+</button><button>-</button>
					</fieldset>
					<fieldset>
						Price: USD 7.1<button>Buy!</button>
					</fieldset>

Buy Price	7.1

Final Price	15

Profit	7.3

Account Balance	45.53

					Select Underlying
					<fieldset>
						<button>Forex</button><button>Randoms</button>
					</fieldset>
					USD/JPY
					Select Trade
					<fieldset>
						<button>Up</button><button>Down</button><button>Digit Match</button><button>Digit Differs</button>
					</fieldset>
					<fieldset>
						No. ticks:<input type="number" defaultValue={5} /> <button>+</button><button>-</button>
					</fieldset>
					Select Amount
					<fieldset>
						<button>Payout</button><button>Stake</button>
					</fieldset>
					USD<input type="number" defaultValue={15} />
					<fieldset>
						<button>Save</button>
					</fieldset>

		);
	}
}

Add html code implementing the mockups for trading


// @flow
import {createSelector} from 'reselect'

import selectCurrentBundle from './current-bundle'

export default createSelector(
  (state) => state.scenario.feeds,
  selectCurrentBundle,
  (feeds, bundle) => feeds.map((feed) => {
    const bundleFeed = bundle && bundle.feeds
      .find(({feedId}) => feedId === feed.id)
    return bundleFeed
      ? {...feed, name: bundleFeed.name}
      : {...feed, name: feed.checksum}
  })
)

// @flow
import {createSelector} from 'reselect'

import selectCurrentBundle from './current-bundle'

export default createSelector(
  (state) => state.scenario.feeds,
  selectCurrentBundle,
  (feeds, bundle) => feeds.map((feed) => {
    const bundleFeed = bundle && bundle.feeds
      .find(({feedId}) => feedId === feed.id)
    return bundleFeed
      ? {...feed, name: bundleFeed.name}
      : {...feed, name: feed.id}
  })
)

Use feed id instead of checksum as back up feed name.


var Serializer = require("./serialization/serializer").Serializer,
    serialize = require("./serialization/serializer").serialize,
    Deserializer = require("./deserialization/deserializer").Deserializer,
    deserialize = require("./deserialization/deserializer").deserialize;

exports.Serializer = Serializer;
exports.serialize = serialize;

exports.Deserializer = Deserializer;
exports.deserialize = deserialize;

var serializer = require("./serialization/serializer"),
    deserializer = require("./deserialization/deserializer");

exports.Serializer = serializer.Serializer;
exports.serialize = serializer.serialize;

exports.Deserializer = deserializer.Deserializer;
exports.deserialize = deserializer.deserialize;

Make the root requires a bit nicer


// @license
// Copyright (c) 2017 Google Inc. All rights reserved.
// This code may only be used under the BSD style license found at
// http://polymer.github.io/LICENSE.txt
// Code distributed by Google as part of this project is also
// subject to an additional IP rights grant found at
// http://polymer.github.io/PATENTS.txt
"use strict";

class ParticleExecutionContext {
  constructor() {
  }

  // Instantiates `particle` in this context, connecting `views` to the particle's inputs and outputs.
  // `mutateCallback` will be called each time the particle mutates a view or entity.
  // Returns an identifier to refer to the particle (in `dispatch`).
  instantiate(particle, views, mutateCallback) {
    // views => [[name, viewId]]
    // returns particleId
    throw 'unimplemented';
  }

  // Dispatches an event to the particle identified by `particleId` for the view or entity identified
  // by `entityId` concerning `eventDetails. The `complete` flag indicates whether there are any further
  // events to be dispatched to the same particle.
  dispatch(particleId, entityId, eventDetails, complete) {
    throw 'unimplemented';
  }

  // Returns a promise which resolves when the PEC becomes idle (no known input processing).
  get idle() {
    throw 'unimplemented';
  }

  // TODO: Where did relevance go?
}

module.exports = ParticleExecutionContext;

// @license
// Copyright (c) 2017 Google Inc. All rights reserved.
// This code may only be used under the BSD style license found at
// http://polymer.github.io/LICENSE.txt
// Code distributed by Google as part of this project is also
// subject to an additional IP rights grant found at
// http://polymer.github.io/PATENTS.txt
"use strict";

class ParticleExecutionContext {
  constructor() {
  }

  // Instantiates `particle` in this context, connecting `views` to the particle's inputs and outputs.
  // `mutateCallback` will be called each time the particle mutates a view or entity.
  // Returns an identifier to refer to the particle (in `dispatch`).
  instantiate(particle, views, mutateCallback) {
    // views => {name => viewId}
    throw 'unimplemented';
  }

  // Dispatches an event to the particle identified by `particleId` for the view or entity identified
  // by `entityId` concerning `eventDetails. The `morePending` flag indicates whether there are any
  // known further events to be dispatched to the same particle.
  dispatch(particleId, entityId, eventDetails, morePending) {
    throw 'unimplemented';
  }

  // Returns a promise which resolves when the PEC becomes idle (no known input processing).
  get idle() {
    throw 'unimplemented';
  }

  // Returns a promise which resolves to a map from particle identifier to a list of the relevance
  // entries generated by that particle.
  get relevance() {
    throw 'unimplemented';
  }
}

module.exports = ParticleExecutionContext;

Rename complete => morePending, add relevance getter


import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { openModal, closeModal } from '../../actions/modals'
import ConfirmDialog from '../dialogs/ConfirmDialog'
import { DragIcon, DeleteIcon } from './EditorIcons'

class RegionTools extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
  };

  closeModal = () => {
    const { dispatch } = this.props
    dispatch(closeModal())
  };

  deleteContentConfirmed = () => {
    // const { dispatch } = this.props
    this.closeModal()
    // dispatch(commentActions.deleteComment(comment))
  };

  handleDeleteBlock = () => {
    const { dispatch } = this.props
    dispatch(openModal(
      <ConfirmDialog
        title="Remove this content?"
        onConfirm={ this.deleteCommentConfirmed }
        onRejected={ this.closeModal }
      />))
  };

  render() {
    return (
      <div className="RegionTools">
        <button
          onClick={this.handleDeleteBlock}
        >
          <DeleteIcon />
        </button>
        <button>
          <DragIcon />
        </button>
      </div>
    )
  }
}

export default connect()(RegionTools)

import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { openModal, closeModal } from '../../actions/modals'
import ConfirmDialog from '../dialogs/ConfirmDialog'
import { DragIcon, DeleteIcon } from './EditorIcons'

class RegionTools extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
  };

  closeModal = () => {
    const { dispatch } = this.props
    dispatch(closeModal())
  };

  deleteContentConfirmed = () => {
    // const { dispatch } = this.props
    this.closeModal()
    // dispatch(commentActions.deleteComment(comment))
  };

  handleDeleteBlock = () => {
    const { dispatch } = this.props
    dispatch(openModal(
      <ConfirmDialog
        title="Remove this content?"
        onConfirm={ this.deleteContentConfirmed }
        onRejected={ this.closeModal }
      />))
  };

  render() {
    return (
      <div className="RegionTools">
        <button
          onClick={this.handleDeleteBlock}
        >
          <DeleteIcon />
        </button>
        <button>
          <DragIcon />
        </button>
      </div>
    )
  }
}

export default connect()(RegionTools)

Call through to the correct method


const RSBuddy = `
	type RSBuddy {
		ts: String
		buyingPrice: Int
		buyingCompleted: Int
		sellingPrice: Int
		sellingCompleted: Int
		overallPrice: Int
		overallCompleted: Int
	}
`

export default RSBuddy

const RSBuddy = `
	type RSBuddy {
		ts: String
		buyingPrice: String
		buyingCompleted: String
		sellingPrice: String
		sellingCompleted: String
		overallPrice: String
		overallCompleted: String
	}
`

export default RSBuddy

Change ints to strings for Int32 errors


pageflow.ConfigurationEditorView.register('video', {
  configure: function() {
    this.tab('general', function() {
      this.group('general');

      this.input('additional_title', pageflow.TextInputView);
      this.input('additional_description', pageflow.TextAreaInputView, {size: 'short'});
    });

    this.tab('files', function() {
      this.input('video_file_id', pageflow.FileInputView, {
        collection: pageflow.videoFiles,
        positioning: false
      });
      this.input('poster_image_id', pageflow.FileInputView, {
        collection: pageflow.imageFiles,
        positioning: false
      });
      this.input('thumbnail_image_id', pageflow.FileInputView, {
        collection: pageflow.imageFiles,
        positioning: false
      });
      this.input('mobile_poster_image_id', pageflow.FileInputView, {
        collection: pageflow.imageFiles,
        imagePositioning: false
      });
    });

    this.tab('options', function() {
      this.input('autoplay', pageflow.CheckBoxInputView);

      if (pageflow.features.isEnabled('auto_change_page')) {
        this.input('auto_change_page_on_ended', pageflow.CheckBoxInputView);
      }

      this.group('options');
    });
  }
});

pageflow.ConfigurationEditorView.register('video', {
  configure: function() {
    this.tab('general', function() {
      this.group('general');

      this.input('additional_title', pageflow.TextInputView);
      this.input('additional_description', pageflow.TextAreaInputView, {size: 'short'});
    });

    this.tab('files', function() {
      this.input('video_file_id', pageflow.FileInputView, {
        collection: pageflow.videoFiles,
        positioning: false
      });
      this.input('poster_image_id', pageflow.FileInputView, {
        collection: pageflow.imageFiles,
        positioning: false
      });
      this.input('thumbnail_image_id', pageflow.FileInputView, {
        collection: pageflow.imageFiles,
        positioning: false
      });
      this.input('mobile_poster_image_id', pageflow.FileInputView, {
        collection: pageflow.imageFiles,
        imagePositioning: false
      });
    });

    this.tab('options', function() {
      this.input('autoplay', pageflow.CheckBoxInputView);

      if (pageflow.features.isEnabled('auto_change_page')) {
        this.input('auto_change_page_on_ended', pageflow.CheckBoxInputView);
      }

      this.group('options', {canPauseAtmo: true});
    });
  }
});

Allow Pausing Atmo for Video Playback


var fs = require('fs');
var browserify = require('browserify');
var uglifyify = require('uglifyify');

var path = function (d) {
  var p = require('path');
  return p.resolve(__dirname, d);
};

var b = browserify({ cache: {}, entries: [path('../public/javascripts/index.js')], packageCache: {} });
b.transform({
    global: true,
    sourcemap: false
}, 'uglifyify');

var prod = function () {
  b.bundle().pipe(fs.createWriteStream(path('../public/javascripts/scripts.js')));
};

if (module.parent) {
  module.exports = prod;
} else {
  prod();
}

var fs = require('fs');
var browserify = require('browserify');
var uglifyify = require('uglifyify');

var path = function (d) {
  var p = require('path');
  return p.resolve(__dirname, d);
};

var b = browserify({ cache: {}, entries: [path('../public/javascripts/index.js')], packageCache: {} });
b.transform({
    global: true,
    sourcemap: false
}, uglifyify);

var prod = function () {
  b.bundle().pipe(fs.createWriteStream(path('../public/javascripts/scripts.js')));
};

if (module.parent) {
  module.exports = prod;
} else {
  prod();
}

Remove quotes to import uglifyify


import React from 'react';

import ChronosStore from '../../stores/ChronosStore';
import DescriptionList from '../../components/DescriptionList';

class JobRunHistoryTable extends React.Component {
  render() {
    let job = ChronosStore.getJobDetail(this.props.jobID);

    return (
      <DescriptionList
        hash={{
          Command: job.getCommand(),
          Schedule: job.getSchedule().schedule
        }} />
    );
  }
}

module.exports = JobRunHistoryTable;

import React from 'react';

import ChronosStore from '../../stores/ChronosStore';
import DescriptionList from '../../components/DescriptionList';

class JobRunHistoryTable extends React.Component {
  render() {
    let job = ChronosStore.getJob(this.props.jobID);

    return (
      <DescriptionList
        hash={{
          Command: job.getCommand(),
          Schedule: job.getSchedules()[0].cron
        }} />
    );
  }
}

module.exports = JobRunHistoryTable;

Fix bad method calls from rebase error


(function sceneHighlight() {
  'use strict';

  function highlightLines(query) {
    var elements = document.querySelectorAll(query);

    Array.from(document.querySelectorAll('.highlight')).forEach(function removePreviousHighlight(element) {
      element.classList.remove('.highlight');
    });

    Array.from(elements).forEach(function iterateElements(element) {
      element.classList.add('highlight');
    });

    elements[0].scrollIntoView({behavior: 'smooth'});

  }

  window.addEventListener('hashchange', function hashChangeCallback(event) {
    var query = '.' + event.newURL.split('#')[1];
    highlightLines(query);
  });

  window.addEventListener('load', function loadCallback(event) {
    var query = window.location.hash;
    if (query) {
      highlightLines('.' + query.split('#')[1]);
    }
  });

})();

(function sceneHighlight() {
  'use strict';

  function highlightLines(query) {
    var elements = document.querySelectorAll(query);

    Array.from(document.querySelectorAll('.highlight')).forEach(function removePreviousHighlight(element) {
      element.classList.remove('.highlight');
    });

    Array.from(elements).forEach(function iterateElements(element) {
      element.classList.add('highlight');
    });

    elements[0].scrollIntoView({behavior: 'smooth'});

  }

  window.addEventListener('hashchange', function hashChangeCallback(event) {
    var query = '.' + event.newURL.split('#')[1];
    highlightLines(query);
  });

  window.addEventListener('load', function loadCallback() {
    var query = window.location.hash;
    if (query) {
      highlightLines('.' + query.split('#')[1]);
    }
  });

})();

Remove event from scene highlight params


$(document).ready(function () {
    var height = $(window).innerHeight();
    var headerHeight = $('header').innerHeight();
    $('main').css('height', height);
    window.scrollTo(0, headerHeight);
});

$(document).ready(function () {
    if ($('.oe_website_login_container').length) {
        var height = $(window).innerHeight();
        var headerHeight = $('header').innerHeight();
        $('main').css('height', height);
        window.scrollTo(0, headerHeight);
    }
});

Add check if its correct page


// ==UserScript==
// @name         UkBay without clicking
// @namespace    https://github.com/rohanorton
// @version      0.1
// @description  Go straight to Piratebay mirror without having to click image
// @author       Rohan Orton
// @match        https://ukbay.org/
// @grant        none
// ==/UserScript==

// Why?
// ====
// I couldn't be bothered clicking on the image, and having it open a pop up
// window. This all seemed unecessary.

/*jslint browser:true */
/*globals randomlinks */

(function (randomlinks) {
  "use strict";
    window.location = (randomlinks[Math.floor(Math.random()*randomlinks.length)]);
} (randomlinks));

// ==UserScript==
// @name         UkBay without clicking
// @namespace    https://github.com/rohanorton
// @version      0.1
// @description  Go straight to Piratebay mirror without having to click image
// @author       Rohan Orton
// @include      https://ukbay.*
// @grant        none
// ==/UserScript==

// Why?
// ====
// I couldn't be bothered clicking on the image, and having it open a pop up
// window. This all seemed unecessary.

/*jslint browser:true */
/*globals randomlinks */

(function (randomlinks) {
  "use strict";

  function random(n) {
    return Math.floor(Math.random() * n);
  }

  function getLink() {
    var index = random(randomlinks.length));
    return randomlinks[index]
  }

  if (randomlinks) {
    window.location = getLink();
  }
} (randomlinks));

Make ukbay script to work on different ukbay URLs


// Reverse Array In Place

/*RULES:
  Take array as parameter
    Reverse array
    Return reversed array

  NOTES:
  Can't create new empty array to push in
  Must modify given array
  Can't use array.reverse();
*/

/*PSEUDOCODE

  1) Find array length
  2) Create variable "stopper" for last element in array
  2) (array.length - 1) times do:
    2a) Push element previous to "stopper" to the end of the array
    2b) Splice that same element out from in front of 'stopper'
  3) When done, return reversed array
*/

function reverseArray(arr){
  var count = arr.length;
  var stopper = arr[count - 1];

  for (var i = 0; i < count; i++){
    arr.push(arr[arr.indexOf(stopper) - 1]);
    arr.splice((arr.indexOf(stopper) - 1), 1);
  }

  return arr;
}

// Reverse Array In Place

/*RULES:
  Take array as parameter
    Reverse array
    Return reversed array

  NOTES:
  Can't create new empty array to push in
  Must modify given array
  Can't use array.reverse();
*/

/*PSEUDOCODE

  1) Find array length
  2) Create variable "stopper" for last element in array
  2) (array.length - 1) times do:
    2a) Push element previous to "stopper" to the end of the array
    2b) Splice that same element out from in front of 'stopper'
  3) When done, return reversed array
*/

// This is the solution I came up with and it works!  But, will add the course solution underneath.  Considerably faster, since it only loops through half of the array rather than the whole array like mine does.

// function reverseArray(arr){
//   var count = arr.length;
//   var stopper = arr[count - 1];

//   for (var i = 0; i < count; i++){
//     arr.push(arr[arr.indexOf(stopper) - 1]);
//     arr.splice((arr.indexOf(stopper) - 1), 1);
//   }

//   return arr;
// }

function reverseArrayInPlace(arr) {
  for (var i = 0; i < arr.length / 2; i++) {
    var tempVar = arr[i];
    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = tempVar;
  }

  return arr;
}

Comment out initial solution, include faster course solution


'use strict';

angular.module('Teem')
  .directive('needWidget', function() {
    return {
      scope: {},
      controller: [
      '$scope',
      function($scope) {
        $scope.toggleCompleted = function (need) {
          event.stopPropagation();
          // Needed by the magic of material design
          event.preventDefault();

          $scope.project.toggleNeedCompleted(need);
        };
      }],
      templateUrl: 'pad/need-widget.html'
    };
  });

'use strict';

angular.module('Teem')
  .directive('needWidget', function() {
    return {
      scope: {},
      controller: [
      '$scope',
      function($scope) {
        $scope.toggleCompleted = function (need, event) {
          event.stopPropagation();
          // Needed by the magic of material design
          event.preventDefault();

          $scope.project.toggleNeedCompleted(need);
        };
      }],
      templateUrl: 'pad/need-widget.html'
    };
  });

Add missing reference to event


import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'

import Notification from 'src/shared/components/Notification'

const Notifications = ({notifications, inPresentationMode}) =>
  <div
    className={`${inPresentationMode
      ? 'notification-center__presentation-mode'
      : 'notification-center'}`}
  >
    {notifications.map(n => <Notification key={n.id} notification={n} />)}
  </div>

const {arrayOf, bool, number, shape, string} = PropTypes

Notifications.propTypes = {
  notifications: arrayOf(
    shape({
      id: string.isRequired,
      type: string.isRequired,
      message: string.isRequired,
      duration: number.isRequired,
      icon: string,
    })
  ),
  inPresentationMode: bool,
}

const mapStateToProps = ({
  notifications,
  app: {ephemeral: {inPresentationMode}},
}) => ({
  notifications,
  inPresentationMode,
})

export default connect(mapStateToProps, null)(Notifications)

import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'

import Notification from 'shared/components/Notification'

const Notifications = ({notifications, inPresentationMode}) =>
  <div
    className={`${inPresentationMode
      ? 'notification-center__presentation-mode'
      : 'notification-center'}`}
  >
    {notifications.map(n => <Notification key={n.id} notification={n} />)}
  </div>

const {arrayOf, bool, number, shape, string} = PropTypes

Notifications.propTypes = {
  notifications: arrayOf(
    shape({
      id: string.isRequired,
      type: string.isRequired,
      message: string.isRequired,
      duration: number.isRequired,
      icon: string,
    })
  ),
  inPresentationMode: bool,
}

const mapStateToProps = ({
  notifications,
  app: {ephemeral: {inPresentationMode}},
}) => ({
  notifications,
  inPresentationMode,
})

export default connect(mapStateToProps, null)(Notifications)

Replace reference to src/shared/ with shared/


/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Promise
 * @flow
 */
'use strict';

const Promise = require('fbjs/lib/Promise.native');

if (__DEV__) {
  require('promise/setimmediate/rejection-tracking').enable({
    allRejections: true,
    onUnhandled: (id, error) => {
      const {message, stack} = error;
      const warning =
        `Possible Unhandled Promise Rejection (id: ${id}):\n` +
        (message == null ? '' : `${message}\n`) +
        (stack == null ? '' : stack);
      console.warn(warning);
    },
    onHandled: (id) => {
      const warning =
        `Promise Rejection Handled (id: ${id})\n` +
        'This means you can ignore any previous messages of the form ' +
        `"Possible Unhandled Promise Rejection (id: ${id}):"`;
      console.warn(warning);
    },
  });
}

module.exports = Promise;

/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Promise
 * @flow
 */
'use strict';

const Promise = require('fbjs/lib/Promise.native');

if (__DEV__) {
  require('promise/setimmediate/rejection-tracking').enable({
    allRejections: true,
    onUnhandled: (id, error = {}) => {
      const {message = null, stack = null} = error;
      const warning =
        `Possible Unhandled Promise Rejection (id: ${id}):\n` +
        (message == null ? '' : `${message}\n`) +
        (stack == null ? '' : stack);
      console.warn(warning);
    },
    onHandled: (id) => {
      const warning =
        `Promise Rejection Handled (id: ${id})\n` +
        'This means you can ignore any previous messages of the form ' +
        `"Possible Unhandled Promise Rejection (id: ${id}):"`;
      console.warn(warning);
    },
  });
}

module.exports = Promise;

Make onUnhandled safe for undefined errors


var fs = require('fs');

var home = process.env.HOME;
var fname = home + '/.nodewar';

module.exports = {
  save:function(session){
    var fd = fs.openSync(fname, 'w', 0600);

    if (fs.writeSync(fd, session)){
      console.log('Session configuration saved');
    } else {
      console.warn('Failed to write configuration');
    }
  },

  read:function(){
    return fs.readFileSync(fname).toString();
  }
};

var fs = require('fs');

var home = process.env.HOME;
var fname = home + '/.nodewar';

module.exports = {
  save:function(session){
    var fd = fs.openSync(fname, 'w', 0600);

    if (fs.writeSync(fd, session)){
      console.log('Session configuration saved');
    } else {
      console.warn('Failed to write configuration');
    }
  },

  read:function(){
    var fd = fs.openSync(fname, 'w', 0600);
    return fs.readFileSync(fname).toString();
  }
};

Create .nodewar if it doesn't exist.


import { injectCSS } from 'src/search-injection/dom'
import { setupRibbonUI } from './components'

export function loader(promiseCreator) {
    let promise

    return (...args) => {
        if (!promise) {
            promise = promiseCreator(...args).then(res => {
                promise.loaded = true
                return res
            })
        }

        return promise
    }
}

export const bodyLoader = loader(() => {
    return new Promise(resolve => {
        if (
            document.readyState === 'complete' ||
            document.readyState === 'interactive'
        ) {
            return resolve()
        }

        document.addEventListener('DOMContentLoaded', resolve)
    })
})

const init = async () => {
    await bodyLoader()

    const target = document.createElement('div')
    target.setAttribute('id', 'memex-annotations-ribbon')
    document.body.appendChild(target)

    const cssFile = browser.extension.getURL('content_script.css')
    injectCSS(cssFile)

    setupRibbonUI(target)
}

init()

import { injectCSS } from 'src/search-injection/dom'
import { setupRibbonUI } from './components'
import { bodyLoader } from 'src/util/loader'

import { getLocalStorage } from 'src/util/storage'
import { TOOLTIP_STORAGE_NAME } from 'src/content-tooltip/constants'

const init = async () => {
    const isTooltipEnabled = await getLocalStorage(TOOLTIP_STORAGE_NAME)
    if (!isTooltipEnabled) return

    await bodyLoader()

    const target = document.createElement('div')
    target.setAttribute('id', 'memex-annotations-ribbon')
    document.body.appendChild(target)

    const cssFile = browser.extension.getURL('content_script.css')
    injectCSS(cssFile)

    setupRibbonUI(target)
}

init()

Disable Ribbon if Memex.Link is disabled.


function setAriaCurrent() {
	var id = document.getElementById("inicio");
	id.textContent = document.title
}

setAriaCurrent();

function setAriaCurrent() {
	var title = document.title;
	if title== "Comunidad hispanohablante de NVDA" {
		var id = "inicio"
	}
	document.getElementById(id).setAttribute("aria-current", "page");
}

setAriaCurrent();

Set aria-current for first link of nav


import Promise from 'bluebird';
import express from 'express';
import assert from 'assert';
import request from 'superagent'

const ROTTEN_TOMATOES_API_KEY = process.env.ROTTEN_TOMATOES_API_KEY;
assert(ROTTEN_TOMATOES_API_KEY, 'Application needs a rotten tomatoes API key.');
const ROTTEN_TOMATOES_SEARCH_URL = `http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=${ROTTEN_TOMATOES_API_KEY}`;

const router = new express.Router();
export default router;

router.get('/search', (req, res) => {
  const query = req.query.q;
  const page = req.query.page || '1';
  const finalUrl = ROTTEN_TOMATOES_SEARCH_URL + '&q=' + query + '&page=' + page
  return request.get(
    finalUrl
  ).end((err, response) => {
    res.send(JSON.parse(response.text));
  });
});

import express from 'express';
import assert from 'assert';
import request from 'superagent';

const apikey = process.env.ROTTEN_TOMATOES_API_KEY;
assert(apikey, 'Application needs a rotten tomatoes API key.');
const ROTTEN_TOMATOES_SEARCH_URL = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json';

const router = new express.Router();
export default router;

router.get('/search', async ({query: {q, page}}, res) => {
  const response = await request.get(
    ROTTEN_TOMATOES_SEARCH_URL
  ).query({q, page, apikey});
  res.send(JSON.parse(response.text));
});

Tidy up handler a bit


import Ember from 'ember';

export default function(app, prefix) {
  var regex = new RegExp('^' + prefix + '\/((?:instance-)?initializers)\/');
  var getKeys = (Object.keys || Ember.keys);
  var moduleNames = getKeys(requirejs._eak_seen);

  for (var i = 0; i < moduleNames.length; i++) {
    var moduleName = moduleNames[i];
    var matches = regex.exec(moduleName);

    if (matches && matches.length === 2) {
      var module = require(moduleName, null, null, true);
      if (!module) { throw new Error(moduleName + ' must export an initializer.'); }

      var initializerType = Ember.String.camelize(matches[1].substring(0, matches[1].length - 1));
      var initializer = module['default'];
      if (!initializer.name) {
        var initializerName = moduleName.match(/[^\/]+\/?$/)[0];
        initializer.name = initializerName;
      }

      if (app[initializerType]) {
        app[initializerType](initializer);
      }
    }
  }
}

function resolveInitializer(moduleName) {
  var module = require(moduleName, null, null, true);
  if (!module) {
    throw new Error(moduleName + ' must export an initializer.');
  }
  var initializer = module['default'];
  if (!initializer.name) {
    initializer.name = moduleName.slice(moduleName.lastIndexOf('/') + 1);
  }
  return initializer;
}

function registerInitializers(app, moduleNames) {
  for (var i = 0; i < moduleNames.length; i++) {
    app.initializer(resolveInitializer(moduleNames[i]));
  }
}

function registerInstanceInitializers(app, moduleNames) {
  for (var i = 0; i < moduleNames.length; i++) {
    app.instanceInitializer(resolveInitializer(moduleNames[i]));
  }
}

export default function (app, prefix) {
  var initializerPrefix =  prefix + '/initializers/';
  var instanceInitializerPrefix =  prefix + '/instance-initializers/';
  var initializers = [];
  var instanceInitializers = [];
  // this is 2 pass because generally the first pass is the problem
  // and is reduced, and resolveInitializer has potential to deopt
  var moduleNames = Object.keys(requirejs._eak_seen);
  for (var i = 0; i < moduleNames.length; i++) {
    var moduleName = moduleNames[i];
    if (moduleName.lastIndexOf(initializerPrefix, 0) === 0) {
      initializers.push(moduleName);
    } else if (moduleName.lastIndexOf(instanceInitializerPrefix, 0) === 0) {
      instanceInitializers.push(moduleName);
    }
  }
  registerInitializers(app, initializers);
  registerInstanceInitializers(app, instanceInitializers);
}

Fix deopt with regex matches field load optimizing to undefined.


"use strict";
var
  OS = require('os'),
  Net = require('net'),
  CPP = require('childprocess-promise');
class Main{
  constructor(Port){
    this.Port = Port;
    this.Server = null;
    this.Children = [];
  }
  Run(){
    let NumCPUs = OS.cpus().length;
    let SupportedEvents = [];
    for(let Name in Main){
      if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action')
        SupportedEvents.push(Name.substr(6));
    }
    for(var i = 0; i < NumCPUs; ++i){
      let Child = new CPP(__dirname + '/../Main.js');
      SupportedEvents.forEach(function(Event){
        Child.on(Event, Main['Action' + Event].bind(this, Child));
      }.bind(this));
      Child.Send('SupportedEvents', SupportedEvents);
      this.Children.push(Child);
    }
    let Server = this.Server = Net.createServer();
    this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){
      Child.Target.send('Server', Server);
    }));
  }
}
var Inst = new Main(9004, 4);
Inst.Run();

"use strict";
var
  OS = require('os'),
  Net = require('net'),
  CPP = require('childprocess-promise');
class Main{
  constructor(Port){
    this.Port = Port;
    this.Server = null;
    this.Children = [];
    this.DataBase = new Map();
  }
  Run(){
    let NumCPUs = OS.cpus().length;
    let SupportedEvents = [];
    for(let Name in Main){
      if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action')
        SupportedEvents.push(Name.substr(6));
    }
    for(var i = 0; i < NumCPUs; ++i){
      let Child = new CPP(__dirname + '/../Main.js');
      SupportedEvents.forEach(function(Event){
        Child.on(Event, Main['Action' + Event].bind(this, Child));
      }.bind(this));
      Child.Send('SupportedEvents', SupportedEvents);
      this.Children.push(Child);
    }
    let Server = this.Server = Net.createServer();
    this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){
      Child.Target.send('Server', Server);
    }));
  }
}
var Inst = new Main(9004, 4);
Inst.Run();

Use ES6 Map as Database


var chai = require('chai');
var expect = chai.expect;
var jsdom = require('mocha-jsdom');

var helpers = require('../spec-helpers');

describe('DrawerTabsView', function() {
  jsdom();

  describe('::initialize', function() {
    describe('with forceOpen', function() {
      var $fixture, view;

      beforeEach(function() {
        var DrawerTabsView = require('../../../source/views/drawer/drawer-tabs-view');

        $fixture = $('

');
        $fixture.append('

'

        ).appendTo('body');

        view = new DrawerTabsView({forceOpen: true});
      });

      afterEach(function() {
        view.remove();
        $fixture.remove();
      });

      it('is in the open state', function() {
        expect(view).to.be.ok;
        expect(view.drawerState).to.eql('open');
        expect(view.$toggleArrow.attr('class')).to.match(/\bopen\b/);
      });
    });
  });
});

var chai = require('chai');
var expect = chai.expect;
var jsdom = require('mocha-jsdom');

describe('DrawerTabsView', function() {
  jsdom();

  describe('::initialize', function() {
    describe('with forceOpen', function() {
      var $fixture, view;

      beforeEach(function() {
        var DrawerTabsView = require('../../../source/views/drawer/drawer-tabs-view');

        $fixture = $('

');
        $fixture.append('

'

        ).appendTo('body');

        view = new DrawerTabsView({forceOpen: true});
      });

      afterEach(function() {
        view.remove();
        $fixture.remove();
      });

      it('is in the open state', function() {
        expect(view).to.be.ok;
        expect(view.drawerState).to.eql('open');
        expect(view.$toggleArrow.attr('class')).to.match(/\bopen\b/);
      });
    });
  });
});

Remove reference to non-existent file


define(['jquery', 'controllers/analystController', 'Ladda'], function ($, analystController, Ladda) {

  function sessionView() {

    $(function () {
      $('#generate').on('click', function (e) {
        e.preventDefault();

        var la = Ladda.create(document.getElementById('generate'));
        la.start();

        analystController.generateSession('infoDiv', 'sessionID', 'passwordID', 'pubkeyID', 'privkeyID', 'link-id', 'session-title', 'session-description')
          .then(function () {
            la.stop();
            $('#session-details').removeClass('hidden');
          });
      });
    });
  }

  return sessionView;
});

define(['jquery', 'controllers/analystController', 'Ladda'], function ($, analystController, Ladda) {

  function sessionView() {

    $(function () {
      $('#generate').on('click', function (e) {
        e.preventDefault();

        var la = Ladda.create(document.getElementById('generate'));
        la.start();

        var result = analystController.generateSession('infoDiv', 'sessionID', 'passwordID', 'pubkeyID', 'privkeyID', 'link-id', 'session-title', 'session-description');
        if (result == null) {
          la.stop();
        } else {
          result.then(function () {
            la.stop();
            $('#session-details').removeClass('hidden');
          });
        }
      });
    });
  }

  return sessionView;
});

Fix in creating session error message


const express = require('express');
const router = express.Router();
const cms = require('../cms.js');
const mongoose = require('mongoose');
const Shuttle = require("../schema/shuttle.js");
const helperLib = require("../helper.js").helpers;
const helper = new helperLib();
module.exports = router;
router.get('/', function(req, res) {

	//checks if user is logged in
	if (!req.session || !req.session.cas_user) {
		res.redirect("/login");
		return;
	}

	var rcs_id = req.session.cas_user.toLowerCase();
	//if the user is an admin
	if (helper.isAdmin(rcs_id)) {
		//query the database and return all information on all shuttles
		var query = Shuttle.find({}).lean();
		query.exec(function(err, docs) {
			res.send(docs);
		});
	} else {
		var query = Shuttle.find({}).lean();
		// Ensure non-admin users cannot see other riders, nor the waitlist for a shuttle.
		query.select('-riders');
		query.select('-waitlist');
		query.exec(function(err, docs) {
			res.send(docs);
		});
	}
});

const express = require('express');
const router = express.Router();
const cms = require('../cms.js');
const mongoose = require('mongoose');
const Shuttle = require("../schema/shuttle.js");
const helperLib = require("../helper.js").helpers;
const helper = new helperLib();
module.exports = router;
router.get('/', function(req, res) {

	//checks if user is logged in
	if (!req.session || !req.session.cas_user) {
		res.redirect("/login");
		return;
	}

	var rcs_id = req.session.cas_user.toLowerCase();
	//if the user is an admin
	if (helper.isAdmin(rcs_id)) {
		//query the database and return all information on all shuttles
		var query = Shuttle.find({}).lean();
		query.exec(function(err, docs) {

			res.send({"data":docs});
		});
	} else {
		var query = Shuttle.find({}).lean();
		// Ensure non-admin users cannot see other riders, nor the waitlist for a shuttle.
		query.select('-riders');
		query.select('-waitlist');
		query.exec(function(err, docs) {
			res.send(docs);
		});
	}
});

Make get shuttles api route more secure by encapsulating array in data key


import Ember from 'ember';

const FONT_SIZE_PATTERN = /font-size/;

export default Ember.Helper.helper(function ([prefix, ...classNames]) {
  return classNames.reduce(function(string, name) {
    if (!name) return string;

    let trimmedName = name.replace(/\s/g, '');
    if (trimmedName === '') return string;

    switch (true) {
      case (trimmedName === ':component'):
        return string += `${prefix} `;
      case (FONT_SIZE_PATTERN.test(trimmedName)):
        return string += `${trimmedName} `;
      default:
        return string += `${prefix}${trimmedName} `;
    }
  }, '');
});

import Ember from 'ember';

const FONT_SIZE_PATTERN = /font-size/;

export default Ember.Helper.helper(function ([prefix, ...classNames]) {
  let normalizedClassNames = classNames.reduce(function(names, name) {
    name.split(/\s/).forEach(function(part) {
      if (part && part !== '') {
        names.push(part);
      }
    });

    return names;
  }, []);

  return normalizedClassNames.reduce(function(string, name) {
    switch (true) {
      case (name === ':component'):
        return string += `${prefix} `;
      case (FONT_SIZE_PATTERN.test(name)):
        return string += `${name} `;
      default:
        return string += `${prefix}${name} `;
    }
  }, '');
});

Normalize class names before prefixing


Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'notFound',
  waitOn: function() { return Meteor.subscribe('posts'); }
});

Router.route('/', {name: 'postsList'});

Router.route('/posts/:_id', {
  name: 'postPage',
  data: function() { return Posts.findOne(this.params._id); }
});

Router.route('/submit', {name: 'postSubmit'});

var requireLogin = function() {
  if (! Meteor.user()) {
    this.render('accessDenied');
  } else {
    this.next();
  }
}

Router.onBeforeAction('dataNotFound', {only: 'postPage'});
Router.onBeforeAction(requireLogin, {only: 'postSubmit'});

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'notFound',
  waitOn: function() { return Meteor.subscribe('posts'); }
});

Router.route('/', {name: 'postsList'});

Router.route('/posts/:_id', {
  name: 'postPage',
  data: function() { return Posts.findOne(this.params._id); }
});

Router.route('/submit', {name: 'postSubmit'});

var requireLogin = function() {
  if (! Meteor.user()) {
    if (Meteor.loggingIn()) {
      this.render(this.loadingTemplate);
    } else {
      this.render('accessDenied');
    }
  } else {
    this.next();
  }
}

Router.onBeforeAction('dataNotFound', {only: 'postPage'});
Router.onBeforeAction(requireLogin, {only: 'postSubmit'});

Access denied post will no longer show up when logged in


'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp',
      ['myApp.config', 'myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'firebase', 'ngRoute', 'waitForAuth']
   )

   // configure views; note the authRequired parameter for authenticated pages
   .config(['$routeProvider', function($routeProvider) {
      $routeProvider.when('/home', {
         templateUrl: 'partials/home.html',
         controller: 'HomeCtrl'
      });

      $routeProvider.when('/chat', {
         templateUrl: 'partials/chat.html',
         controller: 'ChatCtrl'
      });

      $routeProvider.when('/account', {
         authRequired: true, // must authenticate before viewing this page
         templateUrl: 'partials/account.html',
         controller: 'AccountCtrl'
      });

      $routeProvider.when('/login', {
         templateUrl: 'partials/login.html',
         controller: 'LoginCtrl'
      });

      $routeProvider.otherwise({redirectTo: '/home'});
   }])

   // double-check that the app has been configured
   .run(['FBURL', function(FBURL) {
      if( FBURL === 'https://INSTANCE.firebaseio.com' ) {
         angular.element(document.body).html('
Please configure app/js/config.js before running!
');
      }
   }])

   // establish authentication
   .run(['loginService', '$rootScope', 'FBURL', function(loginService, $rootScope, FBURL) {
      $rootScope.auth = loginService.init('/login');
      $rootScope.FBURL = FBURL;
   }]);

'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp',
      ['myApp.config', 'myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'firebase', 'ngRoute', 'waitForAuth']
   )

   // configure views; note the authRequired parameter for authenticated pages
   .config(['$routeProvider', function($routeProvider) {
      $routeProvider.when('/home', {
         templateUrl: 'partials/home.html',
         controller: 'HomeCtrl'
      });

      $routeProvider.when('/chat', {
         templateUrl: 'partials/chat.html',
         controller: 'ChatCtrl'
      });

      $routeProvider.when('/account', {
         authRequired: true, // must authenticate before viewing this page
         templateUrl: 'partials/account.html',
         controller: 'AccountCtrl'
      });

      $routeProvider.when('/login', {
         templateUrl: 'partials/login.html',
         controller: 'LoginCtrl'
      });

      $routeProvider.otherwise({redirectTo: '/home'});
   }])

   // establish authentication
   .run(['loginService', '$rootScope', 'FBURL', function(loginService, $rootScope, FBURL) {
      if( FBURL === 'https://INSTANCE.firebaseio.com' ) {
         // double-check that the app has been configured
         angular.element(document.body).html('
Please configure app/js/config.js before running!
');
         setTimeout(function() {
            angular.element(document.body).removeClass('hide');
         }, 250);
      }
      else {
         $rootScope.auth = loginService.init('/login');
         $rootScope.FBURL = FBURL;
      }
   }]);

Fix config check to work with ngCloakAuth


(function () {
    var indicator = document.createElement("h1");
    indicator.innerHTML = "Press a key on your keyboard.";
    document.body.appendChild(indicator);

    window.addEventListener("keyup", function (e) {
        buster.multicastClient.emit("update", e.keyCode);
    }, false);

    buster.multicastClient.on("update", function (event) {
        indicator.innerHTML = String.fromCharCode(event.data);
    });
}());

(function () {
    var indicator = document.createElement("h1");
    indicator.innerHTML = "Press a key on your keyboard.";
    document.body.appendChild(indicator);

    window.addEventListener("keyup", function (e) {
        buster.multicastClient.emit("update", e.keyCode);
    }, false);

    buster.multicastClient.on("update", function (event) {
        indicator.innerHTML += String.fromCharCode(event.data);
    });
}());

Append HTML in demo app - much more fun to watch :)


define([
    'backbone',
    'models/noteModel',
    'underscore',
    'jquery',
    'text!templates/noteTemplate.html',
    'jquery.extensions'
], function (Backbone, model, _, $, template) {
    'use strict';

    var NoteView = Backbone.View.extend({
        template: _.template(template),
        events: {
            'click': 'click',
            'click button.close': 'close'
        },
        initialize: function () {
            this.listenTo(this.model, 'destroy', this.remove);
        },
        render: function () {
            var $el   = this.$el;

            this.$el.
                html(this.template(this.model.attributes)).
                addClass('note').
                children('.head').drags({handle:$el}).end().
                offset(this.model.get('offset'));

            return this;
        },
        click: function (e) {
            e.stopPropagation();
            e.preventDefault();
        },
        close: function () {
            this.model.destroy();
        }
    });

    return NoteView;
});

define([
    'backbone',
    'models/noteModel',
    'underscore',
    'jquery',
    'text!templates/noteTemplate.html',
    'jquery.extensions'
], function (Backbone, model, _, $, template) {
    'use strict';

    var NoteView = Backbone.View.extend({
        template: _.template(template),
        events: {
            'click': 'click',
            'click button.close': 'close'
        },
        initialize: function () {
            this.listenTo(this.model, 'destroy', this.remove);
        },
        render: function () {
            var $el   = this.$el,
                model = this.model;

            $el.
                html(this.template(this.model.attributes)).
                addClass('note').
                children('.head').drags({
                    handle:$el,
                    ondragstop: function (e) {
                        model.save('offset', $(e.target).offset());
                    }
                }).end().
                offset(this.model.get('offset'));

            return this;
        },
        click: function (e) {
            e.stopPropagation();
            e.preventDefault();
        },
        close: function () {
            this.model.destroy();
        }
    });

    return NoteView;
});

Add synchronization of note position after dragdrop between tabs


/* eslint-env browser */

const isFunction = require('lodash/isFunction');
const isObject = require('lodash/isObject');
const isString = require('lodash/isString');

const { deferredToPromise } = require('../deferred_to_promise');

const closeDatabase = name =>
  new Promise((resolve, reject) => {
    const request = window.indexedDB.open(name);
    request.onblocked = () => {
      reject(new Error(`Database '${name}' blocked`));
    };
    request.onupgradeneeded = (event) => {
      reject(new Error('Unexpected database upgraded needed:' +
        ` oldVersion: ${event.oldVersion}, newVersion: ${event.newVersion}`));
    };
    request.onerror = (event) => {
      reject(event.target.error);
    };
    request.onsuccess = (event) => {
      const connection = event.target.result;
      connection.close();
      resolve();
    };
  });

exports.runMigrations = async ({ Backbone, database } = {}) => {
  if (!isObject(Backbone) || !isObject(Backbone.Collection) ||
      !isFunction(Backbone.Collection.extend)) {
    throw new TypeError('"Backbone" is required');
  }

  if (!isObject(database) || !isString(database.id) ||
      !Array.isArray(database.migrations)) {
    throw new TypeError('"database" is required');
  }

  const migrationCollection = new (Backbone.Collection.extend({
    database,
    storeName: 'items',
  }))();

  await deferredToPromise(migrationCollection.fetch());
  await closeDatabase(database.id);
};

/* eslint-env browser */

const isFunction = require('lodash/isFunction');
const isObject = require('lodash/isObject');
const isString = require('lodash/isString');

const { deferredToPromise } = require('../deferred_to_promise');

const closeDatabase = name =>
  new Promise((resolve, reject) => {
    const request = window.indexedDB.open(name);
    request.onblocked = () => {
      reject(new Error(`Database '${name}' blocked`));
    };
    request.onupgradeneeded = (event) => {
      reject(new Error('Unexpected database upgraded needed:' +
        ` oldVersion: ${event.oldVersion}, newVersion: ${event.newVersion}`));
    };
    request.onerror = (event) => {
      reject(event.target.error);
    };
    request.onsuccess = (event) => {
      const connection = event.target.result;
      connection.close();
      resolve();
    };
  });

exports.runMigrations = async ({ Backbone, database } = {}) => {
  if (!isObject(Backbone) || !isObject(Backbone.Collection) ||
      !isFunction(Backbone.Collection.extend)) {
    throw new TypeError('"Backbone" is required');
  }

  if (!isObject(database) || !isString(database.id) ||
      !Array.isArray(database.migrations)) {
    throw new TypeError('"database" is required');
  }

  const migrationCollection = new (Backbone.Collection.extend({
    database,
    storeName: 'items',
  }))();

  await deferredToPromise(migrationCollection.fetch({ limit: 1 }));
  await closeDatabase(database.id);
};

Reduce work for verifying transaction completion


export class AppTemplate {
    static update(render) {
        /* eslint-disable indent */
        return render`

                    <basket></basket>
                    <assets></assets>
                    <most-used></most-used>
                    <latest></latest>
                    <other></other>

                    <stats></stats>

        `;
        /* eslint-enable indent */
    }
}

Add horizontal margin to the app.