/*
 * grunt-css-flip
 * https://github.com/twbs/grunt-css-flip
 *
 * Copyright (c) 2014 Chris Rebert
 * Licensed under the MIT License.
 */

'use strict';

var flip = require('css-flip');

module.exports = function(grunt) {
  grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () {
    var options = this.options({});

    this.files.forEach(function (f) {
      var originalCss = grunt.file.read(f.src);

      var flippedCss = null;
      try {
        flippedCss = flip(originalCss, options);
      }
      catch (err) {
        grunt.fail.warn(err);
      }

      grunt.file.write(f.dest, flippedCss);

      grunt.log.writeln('File "' + f.dest.cyan + '" created.');
    });
  });
};

/*
 * grunt-css-flip
 * https://github.com/twbs/grunt-css-flip
 *
 * Copyright (c) 2014 Chris Rebert
 * Licensed under the MIT License.
 */

'use strict';

var flip = require('css-flip');

module.exports = function (grunt) {
  grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () {
    var options = this.options({});

    this.files.forEach(function (f) {
      var originalCss = grunt.file.read(f.src);

      var flippedCss = null;
      try {
        flippedCss = flip(originalCss, options);
      }
      catch (err) {
        grunt.fail.warn(err);
      }

      grunt.file.write(f.dest, flippedCss);

      grunt.log.writeln('File "' + f.dest.cyan + '" created.');
    });
  });
};

Add missing space before paren


export default function({ types }) {
    return {
        visitor: {
            Function: function parseFunctionPath(path) {
                (path.get('params') || []).reverse().forEach(function(param) {
                    const decorators = param.node.decorators.reverse();

                    if (param.node && Array.isArray(decorators)) {
                        let currentDecorator;

                        decorators.forEach(function(decorator) {

                            /**
                             * TODO: Validate the name of the decorator is not
                             * the same as any of the passed params
                             */
                            const callNode = types.callExpression(
                                decorator.expression, [
                                    currentDecorator ||
                                    types.Identifier(`_${param.node.name}`)
                                ]
                            );

                            currentDecorator = callNode;
                        });

                        param.parentPath.get('body').unshiftContainer(
                            'body', types.variableDeclaration('var', [
                                types.variableDeclarator(
                                    types.Identifier(param.node.name),
                                    currentDecorator
                                )
                            ])
                        );

                        param.replaceWith(
                            types.Identifier(`_${param.node.name}`)
                        );
                    }
                });
            }
        }
    };
}

export default function({ types }) {
    return {
        visitor: {
            Function: function parseFunctionPath(path) {
                (path.get('params') || []).reverse().forEach(function(param) {
                    let currentDecorator;

                    (param.node.decorators || []).reverse()
                        .forEach(function(decorator) {

                            /**
                             * TODO: Validate the name of the decorator is not
                             * the same as any of the passed params
                             */
                            currentDecorator = types.callExpression(
                                decorator.expression, [
                                    currentDecorator ||
                                    types.Identifier(`_${param.node.name}`)
                                ]
                            );
                        });

                    param.parentPath.get('body').unshiftContainer(
                        'body', types.variableDeclaration('var', [
                            types.variableDeclarator(
                                types.Identifier(param.node.name),
                                currentDecorator
                            )
                        ])
                    );

                    param.replaceWith(
                        types.Identifier(`_${param.node.name}`)
                    );
                });
            }
        }
    };
}

Fix issue with the existence of the decorators array introduced by syntax changes


import Promise from 'bluebird';
import process from 'process';
import util from 'util';
import { withRetries } from 'killrvideo-nodejs-common';
import { Scheduler } from './scheduler';
import * as availableTasks from './tasks';
import { initCassandraAsync } from './utils/cassandra';
import { initializeSampleDataAsync } from './sample-data/initialize';

// Allow promise cancellation
Promise.config({ cancellation: true });

/**
 * Async start the application.
 */
async function startAsync() {
  let scheduler = null;

  try {
    // Make sure C* is ready to go
    await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false);

    // Initialize sample data
    await initializeSampleDataAsync();

    // Start scheduled tasks
    scheduler = new Scheduler(availableTasks);
    scheduler.start();
    return scheduler;
  } catch (err) {
    if (scheduler !== null) scheduler.stop();

    console.error('Unable to start Sample Data Generator');
    console.error(err);
    process.exitCode = 1;
  }
}

// Start the app
let startPromise = startAsync();

// Handler for attempting to gracefully shutdown
function onStop() {
  console.log('Attempting to shutdown');

  if (startPromise.isFulfilled()) {
    let s = startPromise.value();
    s.stop();
  } else {
    startPromise.cancel();
  }

  process.exit(0);
}

// Attempt to shutdown on SIGINT
process.on('SIGINT', onStop);

import Promise from 'bluebird';
import process from 'process';
import util from 'util';
import { withRetries } from 'killrvideo-nodejs-common';
import { Scheduler } from './scheduler';
import * as availableTasks from './tasks';
import { initCassandraAsync } from './utils/cassandra';
import { initializeSampleDataAsync } from './sample-data/initialize';

// Allow promise cancellation
Promise.config({ cancellation: true });

/**
 * Async start the application.
 */
async function startAsync() {
  let scheduler = null;

  try {
    // Make sure C* is ready to go
    await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false);

    // Initialize sample data
    await initializeSampleDataAsync();

    // Start scheduled tasks
    scheduler = new Scheduler(availableTasks);
    scheduler.start();
    return scheduler;
  } catch (err) {
    if (scheduler !== null) scheduler.stop();

    console.error('Unable to start Sample Data Generator');
    console.error(err);
    process.exit(1);
  }
}

// Start the app
let startPromise = startAsync();

// Handler for attempting to gracefully shutdown
function onStop() {
  console.log('Attempting to shutdown');

  if (startPromise.isFulfilled()) {
    let s = startPromise.value();
    s.stop();
  } else {
    startPromise.cancel();
  }

  process.exit(0);
}

// Attempt to shutdown on SIGINT
process.on('SIGINT', onStop);

Make sure we actually exit when we fail on startup


/**
 * @copyright 2015, Prometheus Research, LLC
 */

import {createValue} from './Value';

export Fieldset       from './Fieldset';
export Field          from './Field';
export {createValue};
export WithFormValue  from './WithFormValue';
export * as Schema    from './Schema';
export Input          from './Input';
export ErrorList      from './ErrorList';

export function Value(schema, value, onChange, params, errorList) {
  console.error("`import {Value} from 'react-forms'` is deprecated, \
                 change it to 'import {createvalue} from `'react-forms'`");
  return createValue({schema, value, onChange, params, errorList});
}

/**
 * @copyright 2015, Prometheus Research, LLC
 */

import {createValue} from './Value';

export Fieldset       from './Fieldset';
export Field          from './Field';
export {createValue};
export WithFormValue  from './WithFormValue';
export * as Schema    from './Schema';
export Input          from './Input';
export ErrorList      from './ErrorList';

export function Value(schema, value, onChange, params, errorList) {
  console.error("`import {Value} from 'react-forms'` is deprecated, \
                 change it to 'import {createValue} from `'react-forms'`");
  return createValue({schema, value, onChange, params, errorList});
}

Fix typo: createvalue -> createValue


/**
 * Create a copy of an object, omitting provided keys.
 * @param {Object} obj Object to copy
 * @param {Array} arr Keys to omit
 * @returns {Object}
 */
export const omit = (obj, arr) => Object.keys(obj).reduce((res, key) => {
  if (arr.indexOf(key) === -1) {
    res[key] = obj[key]
  }

  return res
}, {})

export const getQueryStringValue = (key) => {
  return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1'))
}

/**
 * Get key value from location hash
 * @param {string} key Key to get value from
 * @returns {string|null}
 */
export const getHashValue = (key) => {
  const matches = window.location.hash.match(new RegExp(`${key}=([^&]*)`))

  return matches ? matches[1] : null
}

/**
 * Create a copy of an object, omitting provided keys.
 * @param {Object} obj Object to copy
 * @param {Array} arr Keys to omit
 * @returns {Object}
 */
export const omit = (obj, arr) => Object.keys(obj).reduce((res, key) => {
  if (arr.indexOf(key) === -1) {
    res[key] = obj[key]
  }

  return res
}, {})

/**
 * Get key value from url query strings
 * @param {string} key Key to get value from
 * @returns {string}
 */
export const getQueryStringValue = (key) => {
  return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1'))
}

/**
 * Get key value from location hash
 * @param {string} key Key to get value from
 * @returns {string|null}
 */
export const getHashValue = (key) => {
  const matches = window.location.hash.match(new RegExp(`${key}=([^&]*)`))

  return matches ? matches[1] : null
}

export const responseTextToObject = (text, key) => {
  const keyValuePairs = text.split('&')

  if (!keyValuePairs || keyValuePairs.length === 0) {
    return {}
  }

  return keyValuePairs.reduce((result, pair) => {
    const [key, value] = pair.split('=')

    result[key] = decodeURIComponent(value)

    return result
  }, {})
}

Add util to parse response from GitHub access token request


export function getInterfaceLanguage() {
  if (!!navigator && !!navigator.language) {
    return navigator.language;
  } else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
    return navigator.languages[0];
  } else if (!!navigator && !!navigator.userLanguage) {
    return navigator.userLanguage;
  } else if (!!navigator && !!navigator.browserLanguage) {
    return navigator.browserLanguage;
  }
  return 'en-US';
}

export function validateProps(props) {
  const reservedNames = [
    '_interfaceLanguage',
    '_language',
    '_defaultLanguage',
    '_defaultLanguageFirstLevelKeys',
    '_props',
  ];
  Object.keys(props).forEach(key => {
    if (reservedNames.indexOf(key)>=0) throw new Error(`${key} cannot be used as a key. It is a reserved word.`)
  });
}

export function getInterfaceLanguage() {
  if (!!navigator && !!navigator.language) {
    return navigator.language;
  } else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
    return navigator.languages[0];
  } else if (!!navigator && !!navigator.userLanguage) {
    return navigator.userLanguage;
  } else if (!!navigator && !!navigator.browserLanguage) {
    return navigator.browserLanguage;
  }
  return 'en-US';
}

export function validateProps(props) {
  const reservedNames = [
    '_interfaceLanguage',
    '_language',
    '_defaultLanguage',
    '_defaultLanguageFirstLevelKeys',
    '_props',
  ];
  Object.keys(props).forEach(key => {
    if (reservedNames.includes(key)) throw new Error(`${key} cannot be used as a key. It is a reserved word.`)
  });
}

Use includes to make code simplier


'use strict';

var fs = require('fs');

/*
 * read *.<type> files at given `path',
 * return array of files and their
 * textual content
 */
exports.read = function (path, type, callback) {

    var textFiles = {};
    var regex = new RegExp("\\." + type);

    fs.readdir(path, function (error, files) {
        if (error) throw new Error("Error reading from path: " + path);

        for (var file = 0; file < files.length; file++) {
            if (files[file].match(regex)) {
                textFiles[files[file]
                  .slice(0, (type.length * -1) - 1 )] = fs.readFileSync(path
                    + '/'
                    + files[file]
                    , 'utf8');
            }
        }
        if (typeof callback === 'function') {
            callback(textFiles);
        }
    });
}

'use strict';

var fs = require('fs');

/*
 * read *.<type> files at given `path',
 * return array of files and their
 * textual content
 */
exports.read = function (path, type, callback) {

    var textFiles = {};
    var regex = new RegExp("\\." + type);
    var typeLen = (type.length * -1) -1;

    fs.readdir(path, function (error, files) {
        if (error) throw new Error("Error reading from path: " + path);

        for (var file = 0; file < files.length; file++) {
            if (files[file].match(regex)) {
                // load textFiles with content
                textFiles[files[file]
                  .slice(0, typeLen] = fs.readFileSync(path
                    + '/'
                    + files[file]
                    , 'utf8');
            }
        }
        if (typeof callback === 'function') {
            callback(textFiles);
        }
    });
}

Split up assignment logic and add elucidating comment


/**
 * @author {{{author}}}
 * @since {{{date}}}
 */

(function () {
    'use strict';

    angular
        .module({{{moduleName}}})
        .constant({{{elementName}}},
        // Add your values here
        );
    });
})();

/**
 * @author {{{author}}}
 * @since {{{date}}}
 */

(function () {
    'use strict';

    angular
        .module('{{{moduleName}}}')
        .constant('{{{elementName}}}',
        // Add your values here
        );
    });
})();

Add missing quotes to template


/*global mocha, mochaPhantomJS, sinon:true, window */
'use strict';

var $ = require('jquery'),
    chai = require('chai'),
    sinon = require('sinon'),
    sinonChai = require('sinon-chai'),
    toggles;

// Expose jQuery globals
window.$ = window.jQuery = $;

toggles = require('../../libs/jquery-toggles/toggles.min');

// Load Sinon-Chai
chai.use(sinonChai);

mocha.timeout(2000);

// Expose tools in the global scope
window.chai = chai;
window.describe = describe;
window.expect = chai.expect;
window.it = it;
window.sinon = sinon;
<<<<<<< HEAD
=======

require('./tabbedLayoutTest');
require('./ButtonComponentTest.js');
require('./FlashMessageComponentTest.js');
require('./PulsarFormComponentTest.js');
require('./HelpTextComponentTest.js');
require('./PulsarUIComponentTest.js');
// require('./signinTest');
//require('./MasterSwitchComponentTest');

if (typeof mochaPhantomJS !== 'undefined') {
    mochaPhantomJS.run();
} else {
    mocha.run();
}
>>>>>>> develop

/*global mocha, mochaPhantomJS, sinon:true, window */
'use strict';

var $ = require('jquery'),
    chai = require('chai'),
    sinon = require('sinon'),
    sinonChai = require('sinon-chai'),
    toggles;

// Expose jQuery globals
window.$ = window.jQuery = $;

toggles = require('../../libs/jquery-toggles/toggles.min');

// Load Sinon-Chai
chai.use(sinonChai);

mocha.timeout(2000);

// Expose tools in the global scope
window.chai = chai;
window.describe = describe;
window.expect = chai.expect;
window.it = it;
window.sinon = sinon;

require('./tabbedLayoutTest');
require('./ButtonComponentTest.js');
require('./FlashMessageComponentTest.js');
require('./PulsarFormComponentTest.js');
require('./HelpTextComponentTest.js');
require('./PulsarUIComponentTest.js');

if (typeof mochaPhantomJS !== 'undefined') {
    mochaPhantomJS.run();
} else {
    mocha.run();
}

Fix merge conflict in js tests


'use strict';
// Handles params concerning configuration files in the $routeProvider phase
angular.module('arethusa.core').factory('confUrl', [
  'CONF_PATH',
  '$route',
  function (CONF_PATH, $route) {
    return function (useDefault) {
      var params = $route.current.params;
      var confPath = CONF_PATH + '/';
      // Fall back to default and wrong paths to conf files
      // need to be handled separately eventually
      if (params.conf) {
        return confPath + params.conf + '.json';
      } else if (params.conf_file) {
        return params.conf_file;
      } else {
        if (useDefault) {
          return confPath + 'default.json';
        }
      }
    };
  }
]);

'use strict';
// Handles params concerning configuration files in the $routeProvider phase
angular.module('arethusa.core').factory('confUrl', [
  'CONF_PATH',
  '$route',
  function (CONF_PATH, $route) {
    // The default route is deprectated and can be refactored away
    return function (useDefault) {
      var params = $route.current.params;
      var confPath = CONF_PATH + '/';
      // Fall back to default and wrong paths to conf files
      // need to be handled separately eventually
      if (params.conf) {
        return confPath + params.conf + '.json';
      } else if (params.conf_file) {
        return params.conf_file;
      } else {
        if (useDefault) {
          return confPath + 'default.json';
        }
      }
    };
  }
]);

Add comment about future work in confUrl


module.exports = function(grunt) {

    //grunt-sass
    grunt.config('sass', {
        options: {
            outputStyle: 'expanded',
            imagePath: '../<%= config.image.dir  %>'
        },
        dist: {
            files: {
                '<%= config.css.dir  %>/<%= config.css.file  %>': '<%= config.scss.dir  %>/<%= config.scss.file  %>'
            }
        }
    });

    //grunt-autoprefixer
    grunt.config('autoprefixer', {
        options: {
            browsers: ['> 1%', 'last 2 versions', 'ie 8', 'ie 9', 'ie 10']
        },
        dist: {
            files: {
                '<%= config.css.dir  %>/<%= config.css.file  %>': '<%= config.css.dir  %>/<%= config.css.file  %>'
            }
        }
    });

    //grunt-contrib-cssmin
    grunt.config('cssmin', {
        target: {
            src: '<%= config.css.dir  %>/<%= config.css.file  %>',
            dest: '<%= config.css.dir  %>/<%= config.css.file  %>'
        }
    });

    //grunt-contrib-csslint
    grunt.config('csslint', {
        options: {
            csslintrc: 'grunt/.csslintrc'
        },
        strict: {
            src: ['<%= config.css.dir  %>/*.css']
        }
    });
};

module.exports = function(grunt) {

    //grunt-sass
    grunt.config('sass', {
        options: {
            outputStyle: 'expanded',
            //includePaths: ['<%= config.scss.includePaths  %>'],
            imagePath: '../<%= config.image.dir  %>'
        },
        dist: {
            files: {
                '<%= config.css.dir  %>/<%= config.css.file  %>': '<%= config.scss.dir  %>/<%= config.scss.file  %>'
            }
        }
    });

    //grunt-autoprefixer
    grunt.config('autoprefixer', {
        options: {
            browsers: ['> 1%', 'last 2 versions', 'ie 8', 'ie 9', 'ie 10']
        },
        dist: {
            files: {
                '<%= config.css.dir  %>/<%= config.css.file  %>': '<%= config.css.dir  %>/<%= config.css.file  %>'
            }
        }
    });

    //grunt-contrib-cssmin
    grunt.config('cssmin', {
        target: {
            src: '<%= config.css.dir  %>/<%= config.css.file  %>',
            dest: '<%= config.css.dir  %>/<%= config.css.file  %>'
        }
    });

    //grunt-contrib-csslint
    grunt.config('csslint', {
        options: {
            csslintrc: 'grunt/.csslintrc'
        },
        strict: {
            src: ['<%= config.css.dir  %>/*.css']
        }
    });
};

Add commented includePaths parameters for grunt-sass in case of Foundation usage


module.exports = (function(){

	// GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME>
	return function* collection(id) {

		// Twitter Requests
		var TwitterManager = require('../media/twitter');
		var twitterGranuals = yield TwitterManager.search(this.request.url)

		var InstagramManager = require('../media/instagram');
		var instagramGranuals = yield InstagramManager.search(this.request.url)

		// Flickr Requests
		// var FlickrManager = require('../media/flickr');
		// var flickrGranuals = yield FlickrManager.search(this.request.url);

    // Creating a universal capsul object
    var capsul = {
      "user_id": id,
      "latitude": require('../../helpers').paramsForUrl(this.request.url).lat,
      "longitude": require('../../helpers').paramsForUrl(this.request.url).lng,
      "timestamp": require('../../helpers').paramsForUrl(this.request.url).time,
      "data": []
    }

    capsul.data.push(instagramGranuals);
    capsul.data.push(twitterGranuals);
    delete instagramGranuals;
    delete twitterGranuals;

		this.body = yield capsul;
	}
})();

module.exports = (function(){

	// GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME>
	return function* collection(id) {

		// Twitter Requests
    var twitterDef = require('q').defer()
    var TwitterManager = require('../media/twitter');
    var twitterGranuals = twitterDef.promise.then(TwitterManager.search);
  //   var twitterDef = require('q').defer()

    // var instagramDef = require('q').defer()
    var InstagramManager = require('../media/instagram');
    // var instagramGranuals = instagramDef.promise.then(InstagramManager.search);
    var instagramGranuals = InstagramManager.search(this.request.url);

    // Flickr Requests
    // var FlickrManager = require('../media/flickr');
    // var flickrGranuals = yield FlickrManager.search(this.request.url);

    // Creating a universal capsul object
    var capsul = {
      "user_id": id,
      "latitude": require('../../helpers').paramsForUrl(this.request.url).lat,
      "longitude": require('../../helpers').paramsForUrl(this.request.url).lng,
      "timestamp": require('../../helpers').paramsForUrl(this.request.url).time,
      "data": []
    }

    // def.resolve(this.request.url)
    // var instaGranuals = def.promise.then(InstagramManager.search);
    // capsul.data.push(instagramGranuals)

    twitterDef.resolve(this.request.url)
    // instagramDef.resolve(this.request.url)

    capsul.data.push(twitterGranuals);
    capsul.data.push(instagramGranuals)

		this.body = yield capsul;
	}
})();

Refactor the twitter manager search methods with promises.


"use strict";

angular.module("hikeio").
	directive("giveFocus", function() {
	return {
		link: function(scope, element, attributes) {
			scope.$watch(attributes.giveFocus, function(value) {
				if (value) {
					setTimeout(function() {
						element.focus();
					});
				}
			});
		}
	};
});

"use strict";

angular.module("hikeio").
	directive("giveFocus", ["$timeout", function($timeout) {
	return {
		link: function(scope, element, attributes) {
			scope.$watch(attributes.giveFocus, function(value) {
				if (value) {
					$timeout(function() {
						element.focus();
					});
				}
			});
		}
	};
}]);

Use angular timeout directive instead of setTimeout.


/*******************************
          Default Paths
*******************************/

module.exports = {
  base : '',

  theme  : './src/theme.config',

  docs  : {
    source : '../docs/server/files/release/',
    output : '../docs/release/'
  },

  // files cleaned after install
  setupFiles: [
    './src/theme.config.example',
    './semantic.json.example',
    './src/_site'
  ],

  // modified to create configs
  templates: {
    config : './semantic.json.example',
    site   : './src/_site',
    theme  : './src/theme.config.example'
  },

  regExp: {
    themeRoot: /.*\/themes\/.*?\//mg
  },

  // folder pathsr
  folders: {
    config : './',
    site   : './src/site',
    theme  : './src/'
  },

  // file paths
  files: {
    composer : 'composer.json',
    config   : './semantic.json',
    npm      : './package.json',
    site     : './src/site',
    theme    : './src/theme.config'
  },

  // same as semantic.json.example
  paths: {
    source: {
      config      : 'src/theme.config',
      definitions : 'src/definitions/',
      site        : 'src/site/',
      themes      : 'src/themes/'
    },
    output: {
      packaged     : 'dist/',
      uncompressed : 'dist/components/',
      compressed   : 'dist/components/',
      themes       : 'dist/themes/'
    },
    clean : 'dist/'
  }
};

/*******************************
          Default Paths
*******************************/

module.exports = {
  base : '',

  theme  : './src/theme.config',

  docs  : {
    source : '../docs/server/files/release/',
    output : '../docs/release/'
  },

  // files cleaned after install
  setupFiles: [
    './src/theme.config.example',
    './semantic.json.example',
    './src/_site'
  ],

  // modified to create configs
  templates: {
    config : './semantic.json.example',
    site   : './src/_site',
    theme  : './src/theme.config.example'
  },

  regExp: {
    themePath: /.*\/themes\/.*?\//mg
  },

  // folder pathsr
  folders: {
    config : './',
    site   : './src/site',
    theme  : './src/'
  },

  // file paths
  files: {
    composer : 'composer.json',
    config   : './semantic.json',
    npm      : './package.json',
    site     : './src/site',
    theme    : './src/theme.config'
  },

  // same as semantic.json.example
  paths: {
    source: {
      config      : 'src/theme.config',
      definitions : 'src/definitions/',
      site        : 'src/site/',
      themes      : 'src/themes/'
    },
    output: {
      packaged     : 'dist/',
      uncompressed : 'dist/components/',
      compressed   : 'dist/components/',
      themes       : 'dist/themes/'
    },
    clean : 'dist/'
  }
};

Fix regexp for theme changes


import { langSelector } from './';

// This enhancers sole purpose is to add the lang prop to route actions so that
// they do not need to be explicitally added when using a RFR route action.
export default function addLangToRouteEnhancer(routesMap) {
  return createStore => (...args) => {
    const store = createStore(...args);

    return {
      ...store,
      dispatch(action) {
        if (
          routesMap[action.type] &&
          (action && action.payload && !action.payload.lang)
        ) {
          action = {
            ...action,
            payload: {
              ...action.payload,
              lang: langSelector(store.getState()) || 'en'
            }
          };
        }
        return store.dispatch(action);
      }
    };
  };
}

import { langSelector } from './';

// This enhancers sole purpose is to add the lang prop to route actions so that
// they do not need to be explicitly added when using a RFR route action.
export default function addLangToRouteEnhancer(routesMap) {
  return createStore => (...args) => {
    const store = createStore(...args);

    return {
      ...store,
      dispatch(action) {
        if (
          routesMap[action.type] &&
          (!action.payload || !action.payload.lang)
        ) {
          action = {
            ...action,
            payload: {
              ...action.payload,
              lang: langSelector(store.getState()) || 'en'
            }
          };
        }
        return store.dispatch(action);
      }
    };
  };
}

Add lang to payload if payload doesn't exist


'use strict';

var express = require('express');
var supertest = require('supertest');
var logger = require('log4js').getLogger('Unit-Test');
var nconf = require('nconf');
nconf.argv()
		 .env()
		 .file({ file: 'config.json' });

var request = supertest(app);

exports['Check view health'] = function(test){

	request.get('/sendmessage').end(function(err,res)){

  test.equal(err,null,'It should not had any error!');

	test.equal(res,200,'It should return 200!');

	test.done();

	}
}

exports['Test send message'] = {

	'Test send message success':function(test){

		request.post('/sendmessage'),
		.send({'receiver':'','text':'Hello World'!})
		.end(function(err,res)){

		  test.equal(err,null,'It should not had any error!')

			test.equal(res,201,'It should return 201!');

		}
	}
}

'use strict';

var express = require('express');
var supertest = require('supertest');
var logger = require('log4js').getLogger('Unit-Test');
var nconf = require('nconf');
nconf.argv()
		 .env()
		 .file({ file: 'config.json' });

var request = supertest(app);

exports['Check view health'] = function(test){

	request.get('/message').end(function(err,res)){

  test.equal(err,null,'It should not had any error!');

	test.equal(res,200,'It should return 200!');

	test.done();

	}
}

exports['Test send message'] = {

	'Test send message success':function(test){

		request.post('/message'),
		.send({'receiver':'','text':'Hello World'!})
		.end(function(err,res)){

		  test.equal(err,null,'It should not had any error!')

			test.equal(res,201,'It should return 201!');

		}
	}
}

Fix the url of message


/*
Copyright 2016 Mozilla

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

import { takeEvery } from 'redux-saga/effects';
import opn from 'opn';

import SharedActions from '../../../shared/actions/shared-actions';

function create({ payload: { url } }) {
  console.log(`Chrome frontend hosted at ${url}`); // eslint-disable-line no-console
  opn(url);
}

export default function* () {
  yield [
    takeEvery(SharedActions.commands.fromServer.toRunner.app.window.create, create),
  ];
}

/*
Copyright 2016 Mozilla

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

import { takeEvery } from 'redux-saga/effects';
import opn from 'opn';

import logger from '../../logger';

import SharedActions from '../../../shared/actions/shared-actions';

function create({ payload: { url } }) {
  logger.log(`Chrome frontend hosted at ${url}`);
  opn(url);
}

export default function* () {
  yield [
    takeEvery(SharedActions.commands.fromServer.toRunner.app.window.create, create),
  ];
}

Use logger module instead of console for the dummy browser runner sagas


module.exports = function() {
  return {
    presets: ['module:metro-react-native-babel-preset'],
    plugins: [
      [
        'babel-plugin-module-resolver',
        {
          alias: {
            'react-native-vector-icons': '@expo/vector-icons',
          },
        },
      ],
      ['@babel/plugin-proposal-decorators', { legacy: true }],
    ],
  };
};

module.exports = function(api) {
  const isWeb = api.caller(isTargetWeb);

  return {
    presets: ['module:metro-react-native-babel-preset'],
    plugins: [
      [
        'babel-plugin-module-resolver',
        {
          alias: {
            'react-native-vector-icons': '@expo/vector-icons',
          },
        },
      ],
      ['@babel/plugin-proposal-decorators', { legacy: true }],
    ],
  };
};

function isTargetWeb(caller) {
  return caller && caller.name === 'babel-loader';
}

Update preset to be able to detect if it's run from Webpack's babel-loader


var mongoose = require('mongoose');
var schema = require('validate');

var Event = mongoose.model('Event', {
  name: String,
  start: Date,
  end: Date,
  group: String,
  notify: Boolean
});

var validate = function (event) {
  var test = schema({
    name: {
      type: 'string',
      required: true,
      message: 'You must provide a name for the event.'
    },
    start: {
      type: 'date',
      required: true,
      message: 'You must provide a start time.'
    },
    end: {
      type: 'date',
      required: true,
      message: 'You must provide an end time.'
    },
    group: {
      type: 'string',
      required: false
    },
    notify: {
      type: 'boolean',
      required: false
    }
  }, {typecast: true});
  return test.validate(event);
};

module.exports = Event;
module.exports.validate = validate;

var mongoose = require('mongoose');
var schema = require('validate');

var Event = mongoose.model('Event', {
  name: String,
  start: Date,
  end: Date,
  group: {type: String, enum: ['attendee', 'staff', 'admin'], default: 'attendee'},
  notify: {type: Boolean, default: true}
});

var validate = function (event) {
  var test = schema({
    name: {
      type: 'string',
      required: true,
      message: 'You must provide a name for the event.'
    },
    start: {
      type: 'date',
      required: true,
      message: 'You must provide a start time.'
    },
    end: {
      type: 'date',
      required: true,
      message: 'You must provide an end time.'
    },
    group: {
      type: 'string'
    },
    notify: {
      type: 'boolean'
    }
  }, {typecast: true});
  return test.validate(event);
};

module.exports = Event;
module.exports.validate = validate;

Fix validation issue on events


'use strict';

import passport from 'passport';
import {Strategy as LocalStrategy} from 'passport-local';

function localAuthenticate(User, email, password, done) {
  User.findOneAsync({
    email: email.toLowerCase()
  })
    .then(user => {
      if (!user) {
        return done(null, false, {
          message: 'This email is not registered.'
        });
      }
      user.authenticate(password, function(authError, authenticated) {
        if (authError) {
          return done(authError);
        }
        if (!authenticated) {
          return done(null, false, { message: 'This password is not correct.' });
        } else {
          return done(null, user);
        }
      });
    })
    .catch(err => done(err));
}

export function setup(User, config) {
  passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password' // this is the virtual field on the model
  }, function(email, password, done) {
    return localAuthenticate(User, email, password, done);
  }));
}

'use strict';

import passport from 'passport';
import {Strategy as LocalStrategy} from 'passport-local';

function localAuthenticate(User, email, password, done) {
  User.findOne({
    email: email.toLowerCase()
  })
    .then(user => {
      if (!user) {
        return done(null, false, {
          message: 'This email is not registered.'
        });
      }
      user.authenticate(password, function(authError, authenticated) {
        if (authError) {
          return done(authError);
        }
        if (!authenticated) {
          return done(null, false, { message: 'This password is not correct.' });
        } else {
          return done(null, user);
        }
      });
    })
    .catch(err => done(err));
}

export function setup(User, config) {
  passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password' // this is the virtual field on the model
  }, function(email, password, done) {
    return localAuthenticate(User, email, password, done);
  }));
}

Remove async from mongosoe query


Meteor.publish('allGroups', function () {
  return Groups.find();
});

Meteor.publish('allGroups', function () {
  // Publish all groups
  return Groups.find();
});

Meteor.publish('singleGroup', function (groupId) {
  // Publish only one group, specified as groupId
  return Groups.find(groupId);
});

Add singleGroup publication, clarifying comments


var fs = require('fs'),
    Libraries = require('../lib/libraries'),
    should = require('should');

describe('Libraries', function() {
  describe('#bowerLibraries', function() {
    var readdirSync = fs.readdirSync,
        statSync = fs.statSync,

        context = {
          event: {emit: function() {}}
        };
    before(function() {
      fs.statSync = function(path) {
        if (/bar\//.test(path)) {
          throw new Error();
        }
      };
    });
    after(function() {
      fs.readdirSync = readdirSync;
      fs.statSync = statSync;
    });

    it('should return all modules in bower directory', function() {
      fs.readdirSync = function(path) {
        return ['foo', 'bar', 'baz'];
      };

      var library = new Libraries();
      library.bowerLibraries(context).should.eql(['bower_components/foo', 'bower_components/baz']);
    });
    it('should not error on fs error', function() {
      fs.readdirSync = function(path) {
        throw new Error();
      };

      var library = new Libraries();
      should.not.exist(library.bowerLibraries(context));
    });
  });
});

var fs = require('fs'),
    Libraries = require('../lib/libraries'),
    should = require('should');

describe('Libraries', function() {
  describe('#bowerLibraries', function() {
    beforeEach(function() {
      require('bower').config.directory = 'bower_components';
    });

    var readdirSync = fs.readdirSync,
        statSync = fs.statSync,

        context = {
          event: {emit: function() {}}
        };
    before(function() {
      fs.statSync = function(path) {
        if (/bar\//.test(path)) {
          throw new Error();
        }
      };
    });
    after(function() {
      fs.readdirSync = readdirSync;
      fs.statSync = statSync;
    });

    it('should return all modules in bower directory', function() {
      fs.readdirSync = function(path) {
        return ['foo', 'bar', 'baz'];
      };

      var library = new Libraries();
      library.bowerLibraries(context).should.eql(['bower_components/foo', 'bower_components/baz']);
    });
    it('should not error on fs error', function() {
      fs.readdirSync = function(path) {
        throw new Error();
      };

      var library = new Libraries();
      should.not.exist(library.bowerLibraries(context));
    });
  });
});

Fix bower config value for tests


require('ts-node').register({ fast: true, compilerOptions: { target: 'es2015',  } })
require('source-map-support/register')
require('jsdom-global/register')
require('raf').polyfill(global)

const enzyme = require('enzyme')
const chai = require('chai')
const chaiEnzyme = require('chai-enzyme')
const sinonChai = require('sinon-chai')
const EnzymeAdapter = require('enzyme-adapter-react-16')
const chaiAsPromised = require("chai-as-promised")

enzyme.configure({
  adapter: new EnzymeAdapter()
})

console.error = () => {}

chai.use(chaiEnzyme())
chai.use(sinonChai)
chai.use(chaiAsPromised)

require('ts-node').register({ fast: true, compilerOptions: { target: 'es2015' } })
require('source-map-support').install({ hookRequire: true })
require('jsdom-global/register')
require('raf').polyfill(global)

const enzyme = require('enzyme')
const chai = require('chai')
const chaiEnzyme = require('chai-enzyme')
const sinonChai = require('sinon-chai')
const EnzymeAdapter = require('enzyme-adapter-react-16')
const chaiAsPromised = require("chai-as-promised")

enzyme.configure({
  adapter: new EnzymeAdapter()
})

console.error = () => {}
console.warn = () => {}

chai.use(chaiEnzyme())
chai.use(sinonChai)
chai.use(chaiAsPromised)

Fix testcase source maps and hide console.warn messages


var chai = require('chai'),
    expect = chai.expect,
    sql = require('../psql');

describe('select', function() {
  it('should generate a select statement with an asterisk with no arguments', function() {
    expect(sql.select().from('users').toQuery().text).to.equal('select * from users');
  });

  it('should generate a select statement with a single column name', function() {
    expect(sql.select('id').from('users').toQuery().text).to.equal('select id from users');
  })

  it('should generate a select statement with column names', function() {
    expect(sql.select('id', 'email').from('users').toQuery().text).to.equal('select id, email from users');
  });
});

var chai = require('chai'),
    expect = chai.expect,
    sql = require('../psql');

describe('select', function() {
  it('should generate a select statement with an asterisk with no arguments', function() {
    expect(sql.select().from('users').toQuery().text).to.equal('select * from users');
  });

  it('should generate a select statement with a single column name', function() {
    expect(sql.select('id').from('users').toQuery().text).to.equal('select id from users');
  })

  it('should generate a select statement with column names', function() {
    expect(sql.select('id', 'email').from('users').toQuery().text).to.equal('select id, email from users');
  });

  it('should handle json columns', function() {
    expect(sql.select('id', "data->>'name' as name").from('users').toQuery().text).to.equal("select id, data->>'name' as name from users")
  });

  //SELECT id, data->'author'->>'first_name' as author_first_name FROM books;
  it('should handle json column nesting', function() {
    expect(sql.select('id', "data->'author'->>'first_name' as author_first_name").from('books').toQuery().text)
    .to.equal("select id, data->'author'->>'first_name' as author_first_name from books")
  });
});

Add select test for json columns


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

process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = function (config) {
  config.set({
    basePath: '.',
    frameworks: ['mocha'],
    reporters: ['mocha'],
    client: {
      captureConsole: true,
      mocha: {
        timeout : 10000, // 10 seconds - upped from 2 seconds
        retries: 3 // Allow for slow server on CI.
      }
    },
    files: [
      {pattern: path.resolve('./build/injector.js'), watched: false},
      {pattern: process.env.KARMA_FILE_PATTERN, watched: false}
    ],
    preprocessors: {
      'build/injector.js': ['webpack'],
      'src/*.spec.ts': ['webpack', 'sourcemap']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    webpack: webpack,
    webpackMiddleware: {
      noInfo: true,
      stats: 'errors-only'
    },
    browserNoActivityTimeout: 31000, // 31 seconds - upped from 10 seconds
    browserDisconnectTimeout: 31000, // 31 seconds - upped from 2 seconds
    browserDisconnectTolerance: 2,
    port: 9876,
    colors: true,
    singleRun: true,
    logLevel: config.LOG_INFO
  });
};

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

process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = function (config) {
  config.set({
    basePath: '.',
    frameworks: ['mocha'],
    reporters: ['mocha'],
    client: {
      captureConsole: true,
    },
    files: [
      {pattern: path.resolve('./build/injector.js'), watched: false},
      {pattern: process.env.KARMA_FILE_PATTERN, watched: false}
    ],
    preprocessors: {
      'build/injector.js': ['webpack'],
      'src/*.spec.ts': ['webpack', 'sourcemap']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    webpack: webpack,
    webpackMiddleware: {
      noInfo: true,
      stats: 'errors-only'
    },
    port: 9876,
    colors: true,
    singleRun: true,
    logLevel: config.LOG_INFO
  });
};

Decrease high timeout in ci


import { app, html } from "flea"

const model = 0

const view = (model, dispatch) => html`

${model}

        <button onclick=${_ => dispatch("INCREMENT")}>+</button>
        <button onclick=${_ => dispatch("DECREMENT")}>-</button>

`

const update = {
    INCREMENT: model => model + 2,
    DECREMENT: model => model - 1
}

app(model, view, update)

import { app, html } from "flea"

const model = 0

const view = (model, dispatch) => html`

        <button onclick=${_ => dispatch("INCREMENT")}>+</button>

${model}

        <button onclick=${_ => dispatch("DECREMENT")} disabled=${model <= 0}>-</button>

`

const update = {
    INCREMENT: model => model + 1,
    DECREMENT: model => model - 1
}

app(model, view, update)

Increment by one. Show how to use disabled attribute with boolean var.


'use strict';

var JsonExtension = require('../../src/json');

var expect = require('chai').expect;

describe('JsonExtension', function () {
  var ext;

  beforeEach(function() {
    ext = new JsonExtension();
  });

  describe('extension applicability', function() {
    it('should apply when application/json content type', function() {
      expect(ext.applies({}, { 'content-type': 'application/json' })).to.be.true;
    });
    it('should apply to application/json content type with params', function() {
      expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true;
    });
  });

  describe('data parser', function() {
    it('should return the data', function() {
      var data = ext.dataParser({ name: 'John Doe' }, {});
      expect(data).to.eql({ name: 'John Doe' });
    });
  });

  it('should have application/json media types', function() {
    expect(ext.mediaTypes).to.eql(['application/json']);
  });
});

'use strict';

var JsonExtension = require('../../src/json');

var expect = require('chai').expect;

describe('JsonExtension', function () {
  var ext;

  beforeEach(function() {
    ext = new JsonExtension();
  });

  describe('extension applicability', function() {
    it('should apply when application/json content type', function() {
      expect(ext.applies({}, { 'content-type': 'application/json' })).to.be.true;
    });
    it('should apply to application/json content type with params', function() {
      expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true;
    });

    it('should not apply when no content type at all (e.g. 204 response)', function() {
      expect(ext.applies({}, {}, 204)).to.be.false;
    });
  });

  describe('data parser', function() {
    it('should return the data', function() {
      var data = ext.dataParser({ name: 'John Doe' }, {});
      expect(data).to.eql({ name: 'John Doe' });
    });
  });

  it('should have application/json media types', function() {
    expect(ext.mediaTypes).to.eql(['application/json']);
  });
});

Test JSON extension deoes not apply for 204 status responses.


const {VM} = require('vm2')
const exec = require('child_process').exec

module.exports = {
  js: code => {
    const vm = new VM()
    try {
      return vm.run(code).toString()
    } catch (e) {
      return e.toString();
    }
  },
  rb: code => {
    return new Promise((resolve, reject) => {
      const unsafe = new RegExp(/(`|%x|system|exec|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g')
      const formattedCode = code.replace(/'/g, '"')
      if(unsafe.test(formattedCode)){
        resolve('Unsafe characters found')
      } else {
        exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => {
          if(err){ reject(err) }
          resolve(stdout)
        })
      }
    })
  }
}

const {VM} = require('vm2')
const exec = require('child_process').exec

module.exports = {
  js: code => {
    const vm = new VM()
    try {
      return vm.run(code).toString()
    } catch (e) {
      return e.toString();
    }
  },
  rb: code => {
    return new Promise((resolve, reject) => {
      const unsafe = new RegExp(/(`|%x|system|exec|method|call|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g')
      const formattedCode = code.replace(/'/g, '"')
      if(unsafe.test(formattedCode)){
        resolve('Unsafe characters found')
      } else {
        exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => {
          if(err){ reject(err) }
          resolve(stdout)
        })
      }
    })
  }
}

Add more keywords to ruby sandbox


const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  entry: {
    main: __dirname + "/src/DragRange.jsx",
    viewer: __dirname + "/src/index.js",
  },

  output: {
    filename: "[name].js",
    path: __dirname + "/dist",
  },

  devtool: "source-map",

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: [/node_modules/],
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: true },
          }
        ]
      },
    ],
  },

  plugins: [
    new HtmlWebPackPlugin({
      template: __dirname + "/src/index.html",
      filename: __dirname + "/index.html",
    })
  ],
}

const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  entry: {
    main: __dirname + "/src/DragRange.jsx",
    viewer: __dirname + "/src/index.js",
  },

  output: {
    filename: "[name].js",
    path: __dirname + "/dist",
  },

  devtool: "source-map",

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: [/node_modules/],
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: true },
          }
        ]
      },
    ],
  },

  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html",
    })
  ],
}

Use relative path for html plugin


const path = require("path")

const PATHS = {
  app: path.join(__dirname, 'src/index.tsx'),
}

module.exports = {
  entry: {
    app: PATHS.app,
  },
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js',
    publicPath: "http://localhost:8080/"
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.(js|jsx|tsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        include: /src/
      },
      {
        test: /\.jsx?$/,
        use: 'react-hot-loader/webpack',
        include: /node_modules/,
      }
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  devServer: {
    index: 'index.html',
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
    }
  },
  devtool: 'inline-source-map'
}

const path = require("path")

const PATHS = {
  app: path.join(__dirname, 'src/index.tsx'),
}

module.exports = {
  entry: {
    app: PATHS.app,
  },
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js',
    publicPath: "http://localhost:8080/"
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        include: /src/
      },
      {
        test: /\.jsx?$/,
        use: 'react-hot-loader/webpack',
        include: /node_modules/,
      }
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  devServer: {
    index: 'index.html',
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
    }
  },
  devtool: 'inline-source-map'
}

Add .ts files to loader


var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: [
    path.resolve(__dirname, "src", "r3test.js"),
    "webpack/hot/dev-server",
    "webpack-dev-server/client?http://localhost:8081"
  ],

  output: {
    path: path.resolve(__dirname, "scripts"),
    publicPath: "/scripts/",
    filename: "r3test.js"
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
	test: /\.js$/,
	loaders: ['react-hot', 'babel'],
	exclude: /node_modules/,
	include: path.join(__dirname, 'src')
      }
    ]
  }
}

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: [
    path.resolve(__dirname, "src", "r3test.js"),
    "webpack/hot/dev-server",
    "webpack-dev-server/client?http://localhost:8081"
  ],

  output: {
    path: path.resolve(__dirname, "scripts"),
    publicPath: "/scripts/",
    filename: "r3test.js"
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
	test: /\.js$/,
	loader: 'babel',
	exclude: /node_modules/,
	include: path.join(__dirname, 'src'),
        query: {
          presets: ['es2015', 'stage-2', 'react'],
          plugins: ['transform-runtime']
        }
      }
    ]
  }
}

Switch to new babel/react-transform build pipeline


require('core-js'); // es2015 polyfill
var path = require('path');
var plopBase = require('./modules/plop-base');
var generatorRunner = require('./modules/generator-runner');

/**
 * Main node-plop module
 *
 * @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with
 * @returns {object} the node-plop API for the plopfile requested
 */
module.exports = function (plopfilePath) {

	const plop = plopBase();
	const runner = generatorRunner(plop);

	plopfilePath = path.resolve(plopfilePath);

	plop.setPlopfilePath(plopfilePath);
	require(plopfilePath)(plop);

	/////
	// external API for node-plop
	//
	return {
		getGeneratorList: plop.getGeneratorList,
		getGenerator: function (genName) {
			const genObject = plop.getGenerator(genName);
			return Object.assign(genObject, {
				runActions: (data) => runner.runGeneratorActions(genObject, data),
				runPrompts: () => runner.runGeneratorPrompts(genObject)
			});
		},
		runActions: runner.runGeneratorActions,
		runPrompts: runner.runGeneratorPrompts
	};

};

require('core-js'); // es2015 polyfill
var path = require('path');
var plopBase = require('./modules/plop-base');
var generatorRunner = require('./modules/generator-runner');

/**
 * Main node-plop module
 *
 * @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with
 * @returns {object} the node-plop API for the plopfile requested
 */
module.exports = function (plopfilePath) {

	const plop = plopBase();
	const runner = generatorRunner(plop);

	if (plopfilePath) {
		plopfilePath = path.resolve(plopfilePath);
		plop.setPlopfilePath(plopfilePath);
		require(plopfilePath)(plop);
	}

	/////
	// external API for node-plop
	//
	return {
		getGeneratorList: plop.getGeneratorList,
		getGenerator: function (genName) {
			const genObject = plop.getGenerator(genName);
			return Object.assign(genObject, {
				runActions: (data) => runner.runGeneratorActions(genObject, data),
				runPrompts: () => runner.runGeneratorPrompts(genObject)
			});
		},
		setGenerator: plop.setGenerator,
		runActions: runner.runGeneratorActions,
		runPrompts: runner.runGeneratorPrompts
	};

};

Make plop file optional, and expose plop.setGenerator() function to allow dynamic creation of generator configs.


import React from 'react'
import { render } from 'react-dom'
import './index.css'
import '../semantic/dist/semantic.min.css';

import Exame from './Exame.js'
import Result from './Result.js'
import { Route, BrowserRouter } from 'react-router-dom'

let TO_ANSWER_GROUPS = require('.//GROUP_DEFINITION.json')

render(
	<BrowserRouter>
		<div>
			<Route exact path="/" component={() => <Exame groups={TO_ANSWER_GROUPS}></Exame>}/>
			<Route path="/result" component={Result}/>
		</div>
	</BrowserRouter>,
	document.getElementById('root')
)

import React from 'react'
import { render } from 'react-dom'
import './index.css'
import '../semantic/dist/semantic.min.css';

import Exame from './Exame.js'
import Result from './Result.js'
import { Route, HashRouter } from 'react-router-dom'

let TO_ANSWER_GROUPS = require('.//GROUP_DEFINITION.json')

render(
	<HashRouter>
		<div>
			<Route exact path="/" component={() => <Exame groups={TO_ANSWER_GROUPS}></Exame>}/>
			<Route path="/result" component={Result}/>
		</div>
	</HashRouter>,
	document.getElementById('root')
)

Use HashRouter for fix gh-page routing.


import Ember from 'ember';

export default Ember.Component.extend({

    didInsertElement() {
        Chart.defaults.global.responsive = true;
        Chart.defaults.global.legend.display =false
    },

    didRender() {
        let data = this.get('data');

        let toGraph = {
            labels: [],
            datasets: [{
                data: []
            }]
        }

        data.forEach(item => {
            toGraph.labels.push(item.get('name'));
            toGraph.datasets[0].data.push(item.get('value'));
        });

        let options = {
            type: 'bar',
            data: toGraph,
            options: {
                scales: {
                    yAxes: [
                        {
                            ticks: {beginAtZero: true}
                        }
                    ]
                }
            }
        }
        console.log(this.elementId);
        let ctx = this.$().children(".bar-chart").first();//.getContext('2d');
        let statsChart = new Chart(ctx, options);
    }
});

import Ember from 'ember';

export default Ember.Component.extend({

    didInsertElement() {
        Chart.defaults.global.responsive = true;
        Chart.defaults.global.legend.display =false
    },

    didRender() {
        let data = this.get('data');

        let toGraph = {
            labels: [],
            datasets: [{
                data: []
            }]
        }

        data.forEach(item => {
            toGraph.labels.push(item.get('name'));
            toGraph.datasets[0].data.push(item.get('value'));
        });

        let options = {
            type: 'bar',
            data: toGraph,
            options: {
                scales: {
                    yAxes: [
                        {
                            ticks: {beginAtZero: true}
                        }
                    ]
                }
            }
        }
        let ctx = this.$().children(".bar-chart").first();//.getContext('2d');
        let statsChart = new Chart(ctx, options);
    }
});

Remove console logging from figuring out graphjs.


/** @babel */

import { applyMiddleware, createStore } from 'redux'
import createLogger from 'redux-logger'
import createSagaMiddleware from 'redux-saga'
import reducers, { initialState } from './reducers'
import rootSaga from './sagas'
import { isAtomInDebugMode } from './debug'

const saga = createSagaMiddleware()
let middlewares = [saga]
if (isAtomInDebugMode) {
  const logger = createLogger({ collapsed: true })
  middlewares.push(logger)
}

export const store = createStore(
  reducers,
  applyMiddleware(...middlewares)
)

saga.run(rootSaga, initialState)

/** @babel */

import { applyMiddleware, createStore } from 'redux'
import createLogger from 'redux-logger'
import createSagaMiddleware from 'redux-saga'
import reducers, { initialState } from './reducers'
import rootSaga from './sagas'
import { isAtomInDebugMode } from './debug'

const saga = createSagaMiddleware()
let middlewares = [saga]
if (isAtomInDebugMode()) {
  const logger = createLogger({ collapsed: true })
  middlewares.push(logger)
}

export const store = createStore(
  reducers,
  applyMiddleware(...middlewares)
)

saga.run(rootSaga, initialState)

Use loggin on debug mode


var express = require('express');
var router = express.Router();

var TaxonPresenter = require('./presenters/taxon-presenter.js');

router.get('/', function (req, res) {
  res.render('index');
});

router.get('/tabbed/:taxonSlug', function (req, res) {
  var presenter = new TaxonPresenter(req, 'all');
  res.render(presenter.viewTemplateName, presenter);
});

router.get('/mvp/:taxonSlug', function (req, res) {
  var presenter = new TaxonPresenter(req, 'all');
  res.render(presenter.viewTemplateName, presenter);
});

router.get('/tabless/:taxonSlug', function (req, res) {
  var presenter = new TaxonPresenter(req, 'base');
  presenter.curatedContent = presenter.allContent.slice(4);
  presenter.latestContent = presenter.allContent.slice(-3).reverse();
  res.render(presenter.viewTemplateName, presenter);
});

module.exports = router;

var express = require('express');
var router = express.Router();

var TaxonPresenter = require('./presenters/taxon-presenter.js');

router.get('/', function (req, res) {
  res.render('index');
});

router.get('/tabbed/:taxonSlug', function (req, res) {
  var presenter = new TaxonPresenter(req, 'all');
  res.render(presenter.viewTemplateName, presenter);
});

router.get('/mvp/:taxonSlug', function (req, res) {
  var presenter = new TaxonPresenter(req, 'all');
  res.render(presenter.viewTemplateName, presenter);
});

router.get('/tabless/:taxonSlug', function (req, res) {
  var presenter = new TaxonPresenter(req, 'base');
  presenter.curatedContent = presenter.allContent.slice(0,3);
  presenter.latestContent = presenter.allContent.slice(-3).reverse();
  res.render(presenter.viewTemplateName, presenter);
});

module.exports = router;

Fix item list length bug when rendering tabless design


import React, { Component } from 'react'
import PropTypes from 'prop-types'

export const getContextualizer = (propTypes, targetProp) => {
  class ContextProps extends Component {
    getChildContext () {
      const props = Object.keys(this.props).reduce((x, key) => {
        if (key !== 'children') {
          x[key] = this.props[key]
        }

        return x
      }, {})

      return targetProp ? { [targetProp]: props } : props
    }

    render () {
      return <span>{this.props.children}</span>
    }
  }

  ContextProps.displayName = 'ContextProps'

  ContextProps.childContextTypes = targetProp
    ? { [targetProp]: PropTypes.shape(propTypes) }
    : propTypes
  return ContextProps
}

export const withPropsFromContext = propList => Target => {
  class WithPropsFromContext extends Component {
    render () {
      const props = {
        ...propList.reduce((x, prop) => {
          x[prop] = this.context[prop]

          return x
        }, {}),
        ...this.props
      }

      return <Target {...props} />
    }
  }

  WithPropsFromContext.contextTypes = propList.reduce((x, prop) => {
    x[prop] = PropTypes.any
    return x
  }, {})

  WithPropsFromContext.displayName = Target.displayName || Target.name

  return WithPropsFromContext
}

import React, { Component } from 'react'
import PropTypes from 'prop-types'

export const getContextualizer = (propTypes, targetProp) => {
  class ContextProps extends Component {
    getChildContext () {
      const props = Object.keys(this.props).reduce((x, key) => {
        if (key !== 'children') {
          x[key] = this.props[key]
        }

        return x
      }, {})

      return targetProp ? { [targetProp]: props } : props
    }

    render () {
      return <span>{this.props.children}</span>
    }
  }

  ContextProps.displayName = 'ContextProps'

  ContextProps.childContextTypes = targetProp
    ? { [targetProp]: PropTypes.shape(propTypes) }
    : propTypes
  return ContextProps
}

export const withPropsFromContext = propList => Target => {
  class WithPropsFromContext extends Component {
    render () {
      const props = {
        ...propList.reduce((x, prop) => {
          x[prop] = this.context[prop]

          return x
        }, {}),
        ...this.props
      }

      return <Target {...props} />
    }
  }

  WithPropsFromContext.contextTypes = propList.reduce((x, prop) => {
    x[prop] = PropTypes.any
    return x
  }, {})

  WithPropsFromContext.displayName = `withPropsFromContext(${Target.displayName || Target.name})`

  return WithPropsFromContext
}

Update displayName of wrapped component to include HoC name


const { createLogger, LEVELS: { INFO } } = require('./loggers')
const logFunctionConsole = require('./loggers/console')
const Cluster = require('./cluster')
const createProducer = require('./producer')
const createConsumer = require('./consumer')

module.exports = class Client {
  constructor({
    brokers,
    ssl,
    sasl,
    clientId,
    connectionTimeout,
    retry,
    logLevel = INFO,
    logFunction = logFunctionConsole,
  }) {
    this.logger = createLogger({ level: logLevel, logFunction })
    this.cluster = new Cluster({
      logger: this.logger,
      brokers,
      ssl,
      sasl,
      clientId,
      connectionTimeout,
      retry,
    })
  }

  producer({ createPartitioner, retry } = {}) {
    return createProducer({
      cluster: this.cluster,
      logger: this.logger,
      createPartitioner,
      retry,
    })
  }

  consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) {
    return createConsumer({
      cluster: this.cluster,
      logger: this.logger,
      groupId,
      createPartitionAssigner,
      sessionTimeout,
      retry,
    })
  }
}

const { createLogger, LEVELS: { INFO } } = require('./loggers')
const logFunctionConsole = require('./loggers/console')
const Cluster = require('./cluster')
const createProducer = require('./producer')
const createConsumer = require('./consumer')

module.exports = class Client {
  constructor({
    brokers,
    ssl,
    sasl,
    clientId,
    connectionTimeout,
    retry,
    logLevel = INFO,
    logFunction = logFunctionConsole,
  }) {
    this.logger = createLogger({ level: logLevel, logFunction })
    this.createCluster = () =>
      new Cluster({
        logger: this.logger,
        brokers,
        ssl,
        sasl,
        clientId,
        connectionTimeout,
        retry,
      })
  }

  /**
   * @public
   */
  producer({ createPartitioner, retry } = {}) {
    return createProducer({
      cluster: this.createCluster(),
      logger: this.logger,
      createPartitioner,
      retry,
    })
  }

  /**
   * @public
   */
  consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) {
    return createConsumer({
      cluster: this.createCluster(),
      logger: this.logger,
      groupId,
      createPartitionAssigner,
      sessionTimeout,
      retry,
    })
  }
}

Create different instances of the cluster for producers and consumers


/**
 * Returns a very important number.
 *
 * @returns {number} - The number.
 */
export default function theDefaultExport() {
  return 40;
}

/**
 * Value that can be incremented.
 *
 * @type {number}
 */
export let value = 0;

/**
 * Increments the value by one.
 */
export function incrementValue() {
  value++;
}

/**
 * Returns a cool value.
 *
 * @returns {string} The cool value.
 */
export function feature() {
  return 'cool';
}

/**
 *  Returns something.
 *
 * @returns {string} - Something.
 */
export function something() {
  return 'something';
}

/**
 * Returns a very important number.
 *
 * @returns {number} - The number.
 */
export default function theDefaultExport() {
  return 42;
}

/**
 * Value that can be incremented.
 *
 * @type {number}
 */
export let value = 0;

/**
 * Increments the value by one.
 */
export function incrementValue() {
  value++;
}

/**
 * Returns a cool value.
 *
 * @returns {string} The cool value.
 */
export function feature() {
  return 'cool';
}

/**
 *  Returns something.
 *
 * @returns {string} - Something.
 */
export function something() {
  return 'something';
}

Revert "test: make test fail"


import React from 'react';
import ReactDOM from 'react-dom';

// Create a new component to produce some html
const App = function () {   // const means that this is the final value. Here we are making a component.
  return
Hello!
; // This is JSX, which gets transpiled to javascript.
                            // Test here: http://babeljs.io/repl
}
// Put the component HTML into the DOM
ReactDOM.render(<App />, document.querySelector('.container'));   // To make an instance of the App class, we wrap it in a JSX tag

import React from 'react';
import ReactDOM from 'react-dom';

// Create a new component to produce some html
const App = () => {   // const means that this is the final value. Here we are making a component.
  return
Hello!
; // This is JSX, which gets transpiled to javascript.
                            // Test here: http://babeljs.io/repl
}
// Put the component HTML into the DOM
ReactDOM.render(<App />, document.querySelector('.container'));   // To make an instance of the App class, we wrap it in a JSX tag

Use ES6 syntax fat arrow instead of using 'function'


import h from 'snabbdom/h'
import extend from 'extend'

const sanitizeProps = (props) => {

  props = props === null ? {} : props

  Object.keys(props).map((prop) => {
    const keysRiver = prop.split('-').reverse()

    if(keysRiver.length > 1) {
      let newObject = keysRiver.reduce(
        (object, key) => ({ [key]: object }),
        props[prop]
      )
      extend(true, props, newObject)

      delete props[prop]
    }
    else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) {
      extend(true, props, {props: { [prop]: props[prop] } })

      delete props[prop]
    }

  })

  return props

}

const sanitizeChilds = (children) => {

  return children.length === 1 && typeof children[0] === 'string' ?
    children[0] : children

}

export const createElement = (type, props, ...children) => {

  return h(type, sanitizeProps(props), sanitizeChilds(children))

}

export default {
  createElement
}

import h from 'snabbdom/h'
import extend from 'extend'

const sanitizeProps = (props) => {

  props = props === null ? {} : props

  Object.keys(props).map((prop) => {
    const keysRiver = prop.split('-').reverse()

    if(keysRiver.length > 1) {
      let newObject = keysRiver.reduce(
        (object, key) => ({ [key]: object }),
        props[prop]
      )
      extend(true, props, newObject)

      delete props[prop]
    }
    else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) {
      extend(true, props, {props: { [prop]: props[prop] } })

      delete props[prop]
    }

  })

  return props

}

const sanitizeChilds = (children) => {

  return children.length === 1 && typeof children[0] === 'string' ?
    children[0] : children

}

export const createElement = (type, props, ...children) => {

  return (typeof type === 'function') ?
    type(props, children) :
    h(type, sanitizeProps(props), sanitizeChilds(children))

}

export default {
  createElement
}

Add component as function support


import { createFilter } from 'rollup-pluginutils';
import { resolve as resolveSourceMap } from 'source-map-resolve';
import { readFile } from 'fs';

export default function sourcemaps({ include, exclude } = {}) {
  const filter = createFilter(include, exclude);

  return {
    name: 'sourcemaps',

    load(id) {
      if (!filter(id)) {
        return null;
      }

      return new Promise(resolve => {
        readFile(id, 'utf8', (err, code) => {
          if (err) {
            // Failed reading file, let the next plugin deal with it
            resolve(null);
          } else {
            resolveSourceMap(code, id, readFile, (err, sourceMap) => {
              if (err || sourceMap === null) {
                // Either something went wrong, or there was no source map
                resolve(code);
              } else {
                const { map, sourcesContent } = sourceMap;
                map.sourcesContent = sourcesContent;
                resolve({ code, map });
              }
            });
          }
        });
      });
    },
  };
}

import { createFilter } from 'rollup-pluginutils';
import { resolve as resolveSourceMap } from 'source-map-resolve';
import * as fs from 'fs';

export default function sourcemaps({ include, exclude, readFile = fs.readFile } = {}) {
  const filter = createFilter(include, exclude);

  return {
    name: 'sourcemaps',

    load(id) {
      if (!filter(id)) {
        return null;
      }

      return new Promise(resolve => {
        readFile(id, 'utf8', (err, code) => {
          if (err) {
            // Failed reading file, let the next plugin deal with it
            resolve(null);
          } else {
            resolveSourceMap(code, id, readFile, (err, sourceMap) => {
              if (err || sourceMap === null) {
                // Either something went wrong, or there was no source map
                resolve(code);
              } else {
                const { map, sourcesContent } = sourceMap;
                map.sourcesContent = sourcesContent;
                resolve({ code, map });
              }
            });
          }
        });
      });
    },
  };
}

Add the ability to override the readFile function


module.exports = {
  plugins: {
    '@wearegenki/ui-postcss': {},
  },
};

// TODO: Put this in the docs (both ways, depending on array or object type of config):

// https://github.com/michael-ciniawsky/postcss-load-config

// const { uiPostcssPreset } = require('@wearegenki/ui');

// module.exports = {
//   plugins: [
//     uiPostcssPreset({
//       // importPath: ['src'],
//       mixinsDir: 'src/css/mixins',
//       // verbose: true,
//     }),
//   ],
// };

// module.exports = {
//   plugins: {
//     '@wearegenki/ui-postcss': {
//       // importPath: ['src'],
//       mixinsDir: 'src/css/mixins',
//       // verbose: true,
//     },
//   },
// };

Add comments about ui-postcss in docs


//
// textEditView
// Modify text based on a textarea
//

import ItemView from 'base/item-view';

export default ItemView.extend({
  template: 'editTextView',

  tagName: 'textarea',

  className: 'gistbook-textarea',

  // Get the value of the element
  value() {
    return this.el.value;
  }
});

//
// textEditView
// Modify text based on a textarea
//

import ItemView from 'base/item-view';

export default ItemView.extend({
  template: 'editTextView',

  tagName: 'textarea',

  className: 'gistbook-textarea',

  // Get the value of the element,
  // stripping line breaks from the
  // start and end
  value() {
    return this.el.value.replace(/^\s+|\s+$/g, '');
  }
});

Remove new lines from text areas on save.


/* eslint-disable no-console */
import { createFilter } from 'rollup-pluginutils';
import { resolveSourceMap } from 'source-map-resolve';
import { readFile } from 'fs';
import { promisify } from './utils';

const readFileAsync = promisify(readFile);
const resolveSourceMapAsync = promisify(resolveSourceMap);

export default function sourcemaps({ include, exclude } = {}) {
  const filter = createFilter(include, exclude);

  return {
    async load(id) {
      if (!filter(id)) {
        return null;
      }

      let code;
      try {
        code = await readFileAsync(id, 'utf8');
      } catch (err) {
        // Failed, let Rollup deal with it
        return null;
      }

      let sourceMap;
      try {
        sourceMap = await resolveSourceMapAsync(code, id, readFile);
      } catch (err) {
        console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`);
        return code;
      }

      // No source map detected, return code
      if (sourceMap === null) {
        return code;
      }

      const { map } = sourceMap;

      return { code, map };
    },
  };
}

/* eslint-disable no-console */
import { createFilter } from 'rollup-pluginutils';
import { resolve } from 'source-map-resolve';
import { readFile } from 'fs';
import { promisify } from './utils';

const readFileAsync = promisify(readFile);
const resolveSourceMapAsync = promisify(resolve);

export default function sourcemaps({ include, exclude } = {}) {
  const filter = createFilter(include, exclude);

  return {
    async load(id) {
      if (!filter(id)) {
        return null;
      }

      let code;
      try {
        code = await readFileAsync(id, 'utf8');
      } catch (err) {
        // Failed, let Rollup deal with it
        return null;
      }

      let sourceMap;
      try {
        sourceMap = await resolveSourceMapAsync(code, id, readFile);
      } catch (err) {
        console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`);
        return code;
      }

      // No source map detected, return code
      if (sourceMap === null) {
        return code;
      }

      const { map, sourcesContent } = sourceMap;

      map.sourcesContent = sourcesContent;

      return { code, map };
    },
  };
}

Include sourcesContent in source map


import React from 'react';
import { render } from 'react-dom';
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import App from "./containers/App";
import rootReducer from "./reducers";
import { getTodosIfNeeded } from "./actions";

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(rootReducer)

store.dispatch(getTodosIfNeeded())

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector('#root')
);

import React from 'react';
import { render } from 'react-dom';
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import injectTapEventPlugin from "react-tap-event-plugin";
import App from "./containers/App";
import rootReducer from "./reducers";
import { getTodosIfNeeded } from "./actions";

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(rootReducer)

store.dispatch(getTodosIfNeeded())
injectTapEventPlugin();

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector('#root')
);

Add react tap event plugin


//Get the required shit together
const config = require("./config.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];

//Login to Discord
client.login(config.API.discord);

//Include all files in the commands directory
fs.readdir("./commands/", function(err, items) {
	items.forEach(function(item) {
		var file = item.replace(/['"]+/g, '');
		command[file] = require(file);
	})
})

client.on('ready', function() {
	console.log("Successfully connected to Discord!");
	client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version);
});

client.on('message', function(message) {
	if (!message.content.startsWith(config.MSS.prefix)) return false;
	let input = message.content.replace (/\n/g, "").split(" ");
	input[0] = input[0].substring(config.MSS.prefix.length);

	if (input[0] === "eval" && message.author.id === "190519304972664832") {
		eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
	}
});

//Get the required shit together
const config = require("./config.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];

//Login to Discord
client.login(config.API.discord);

//Include all files in the commands directory
fs.readdir("./commands/", function(err, items) {
	items.forEach(function(item) {
		var file = item.replace(/['"]+/g, '');
		command[file] = require("./commands/" + file);
	})
})

client.on('ready', function() {
	console.log("Successfully connected to Discord!");
	client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version);
});

client.on('message', function(message) {
	if (!message.content.startsWith(config.MSS.prefix)) return false;
	let input = message.content.replace (/\n/g, "").split(" ");
	input[0] = input[0].substring(config.MSS.prefix.length);

	if (input[0] === "eval" && message.author.id === "190519304972664832") {
		eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
	}
});

Include from the functions directory


define([
    "text!src/templates/command.html"
], function(commandTemplate) {
    var commands = codebox.require("core/commands");
    var dialogs = codebox.require("utils/dialogs");

    commands.register({
        id: "palette.open",
        title: "Open Command Palette",
        shortcuts: [
            "mod+shift+p"
        ],
        run: function() {
            return dialogs.list(commands, {
                template: commandTemplate,
                filter: function(command) {
                    return command.get("palette") !== false && command.isValidContext();
                }
            })
            .then(function(command) {
                return command.run();
            });
        }
    });
});

define([
    "text!src/templates/command.html"
], function(commandTemplate) {
    var commands = codebox.require("core/commands");
    var dialogs = codebox.require("utils/dialogs");

    commands.register({
        id: "palette.open",
        title: "Command Palette: Open",
        shortcuts: [
            "mod+shift+p"
        ],
        palette: false,
        run: function() {
            return dialogs.list(commands, {
                template: commandTemplate,
                filter: function(command) {
                    return command.get("palette") !== false && command.isValidContext();
                }
            })
            .then(function(command) {
                return command.run();
            });
        }
    });
});

Change command title and hide from palette


import React from "react";
import { render } from "react-dom";
import Root from "./Root";

render(
  React.createElement(Root),
  document.getElementById("root")
);

import React from "react";
import { render } from "react-dom";
import "./index.css";
import Root from "./Root";

render(
  React.createElement(Root),
  document.getElementById("root")
);

Fix missing root css import


import React from 'react'
import { render } from 'react-dom'
import createStore from './createStore'

const store = createStore()

render(

Hello from React
,
  document.getElementById('react')
)

import React from 'react'
import { render } from 'react-dom'
import createStore from './createStore'
import App from './components/App'

const store = createStore()

render(
  <App />,
  document.getElementById('react')
)

Use App component in render


import pf from 'portfinder';

export function homedir() {
  return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
}

export function wait (time) {
  return new Promise(resolve => {
    setTimeout(() => resolve(), time);
  });
}

export function getPort () {
  return new Promise((resolve, reject) => {
    pf.getPort((err, port) => {
      if (err) return reject(err);
      resolve(port);
    });
  });
}

import fs from 'fs';
import pf from 'portfinder';

export function homedir() {
  return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
}

export function wait (time) {
  return new Promise(resolve => {
    setTimeout(() => resolve(), time);
  });
}

export function getPort () {
  return new Promise((resolve, reject) => {
    pf.getPort({ host: '127.0.0.1' }, (err, port) => {
      if (err) return reject(err);
      resolve(port);
    });
  });
}

export function readFile (filename) {
  return new Promise((resolve, reject) => {
    fs.readFile(filename, (err, data) => {
      if (err) return reject(err);
      resolve(data);
    });
  });
}

Fix getPort and add readFile


import { lazyFunctionRequire } from 'roc';

import config from '../config/roc.config.js';
import meta from '../config/roc.config.meta.js';

const lazyRequire = lazyFunctionRequire(require);

export default {
    config,
    meta,
    actions: [
        {
            hook: 'server-started',
            description: 'Run dredd tests',
            action: lazyRequire('../actions/dredd'),
        },
    ],
    commands: {
        development: {
            dredd: {
                command: lazyRequire('../commands/dredd'),
                description: 'Runs dredd in current project',
                settings: true,
            },
        },
    },
    hooks: {
        'run-dev-command': {
            description: 'Used to start dev server used for dredd testing',
        },
    },
};

import { lazyFunctionRequire } from 'roc';

import config from '../config/roc.config.js';
import meta from '../config/roc.config.meta.js';

const lazyRequire = lazyFunctionRequire(require);

export default {
    config,
    meta,
    actions: [
        {
            hook: 'server-started',
            description: 'Run dredd tests',
            action: lazyRequire('../actions/dredd'),
        },
    ],
    commands: {
        development: {
            dredd: {
                command: lazyRequire('../commands/dredd'),
                description: 'Runs dredd in current project',
            },
        },
    },
    hooks: {
        'run-dev-command': {
            description: 'Used to start dev server used for dredd testing',
        },
    },
};

Remove superflous settings option on dredd command


define([
  'underscore',
  'backbone',
  'models/section',
  'config'
], function (_, Backbone, Section, config) {
  'use strict';

  var SectionCollection = Backbone.Collection.extend({
    model: Section,

    initialize: function(models, options) {
      if (options) { this.resume = options.resume; }
      this.fetched = false;
      this.listenTo(this, 'reset', function() { this.fetched = true });
    },

    url: function() {
      if (this.resume) {
        return config.domain + '/rez/resumes/' + this.resume.id + '/sections';
      } else {
        return config.domain + '/rez/sections';
      }
    },

    parse: function(response, options) {
      return response.sections;
    }
  });

  return SectionCollection;
});

define([
  'underscore',
  'backbone',
  'models/section',
  'config'
], function (_, Backbone, Section, config) {
  'use strict';

  var SectionCollection = Backbone.Collection.extend({
    model: Section,

    initialize: function(models, options) {
      if (options) { this.resume = options.resume; }
      this.fetched = false;
      this.listenTo(this, 'reset', function() { this.fetched = true });
    },

    url: function() {
      return config.domain + '/rez/sections';
    },

    parse: function(response, options) {
      return response.sections;
    }
  });

  return SectionCollection;
});

Fix url to be not nested.


var path = require('path');
var fs = require('extfs');
var mongoose = require('mongoose');
import { AbstractDB } from './AbstractDB';
import { Core } from '../Core/Core';

export class Mongo extends AbstractDB {

  constructor(uri, options) {
    super(uri, options);
  }

  /**
   * Connect to mongodb
   *
   * @return {Promise}
   */
  connect() {
    this._linkMongoose();
    return new Promise((resolve, reject) => {
      mongoose.connect(this.uri, this.options);
      this.connection = mongoose.connection;
      this.connection.on('connected', () => {
        this.isOpen = true;
        resolve(this.connection)
      });
      this.connection.on('error', reject);
    });
  }

  /**
   * Close connection with mongodb
   */
  close() {
    this.isOpen = false;
    return this.connection.close();
  }

  /**
   * If the app has mongoose installed, replace its mongoose module with the mongoose module of rode
   *
   * @private
   */
  _linkMongoose() {
    var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose');
    var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose');
    if (fs.existsSync(appMongoosePath)) {
      fs.removeSync(appMongoosePath);
      fs.symlinkSync(mongoosePath, appMongoosePath);
    }
  }

}

var path = require('path');
var fs = require('extfs');
var mongoose = require('mongoose');
import { AbstractDB } from './AbstractDB';
import { Core } from '../Core/Core';

export class Mongo extends AbstractDB {

  constructor(uri, options) {
    super(uri, options);
  }

  /**
   * Connect to mongodb
   *
   * @return {Promise}
   */
  connect() {
    this._linkMongoose();
    return new Promise((resolve, reject) => {
      mongoose.connect(this.uri, this.options);
      this.connection = mongoose.connection;
      this.connection.on('connected', () => {
        this.isOpen = true;
        resolve(this.connection)
      });
      this.connection.on('error', reject);
    });
  }

  /**
   * Close connection with mongodb
   */
  close() {
    this.isOpen = false;
    return this.connection.close();
  }

  /**
   * If the app has mongoose installed, replace its mongoose module with the mongoose module of rode
   *
   * @private
   */
  _linkMongoose() {
    var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose');
    var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose');
    if (fs.existsSync(mongoosePath) && fs.existsSync(appMongoosePath)) {
      fs.removeSync(appMongoosePath);
      fs.symlinkSync(mongoosePath, appMongoosePath);
    }
  }

}

Fix a bug if mongoose path does not exist


var Disk = require( '../' )
var BlockDevice = require( 'blockdevice' )
var assert = require( 'assert' )

const DISK_IMAGE = __dirname + '/data/bootcamp-osx-win.bin'

describe( 'Disk', function( t ) {

  var device = null
  var disk = null

  it( 'init block device', function() {
    assert.doesNotThrow( function() {
      device = new BlockDevice({
        path: DISK_IMAGE,
        mode: 'r',
        blockSize: 512
      })
    })
  })

  it( 'init disk with device', function() {
    assert.doesNotThrow( function() {
      disk = new Disk( device )
    })
  })

  it( 'disk.open()', function( next ) {
    disk.open( function( error ) {
      next( error )
    })
  })

  it( 'repeat disk.open()', function( next ) {
    disk.open( function( error ) {
      next( error )
    })
  })

  it( 'disk.close()', function( next ) {
    disk.close( function( error ) {
      next( error )
    })
  })

})

var Disk = require( '../' )
var BlockDevice = require( 'blockdevice' )
var assert = require( 'assert' )

;[
  'apple-mac-osx-10.10.3.bin',
  'bootcamp-osx-win.bin',
  'usb-thumb-exfat.bin',
  'usb-thumb-fat.bin'
].forEach( function( filename ) {

  const DISK_IMAGE = __dirname + '/data/' + filename

  describe( 'Disk ' + filename, function( t ) {

    var device = null
    var disk = null

    it( 'init block device', function() {
      assert.doesNotThrow( function() {
        device = new BlockDevice({
          path: DISK_IMAGE,
          mode: 'r',
          blockSize: 512
        })
      })
    })

    it( 'init disk with device', function() {
      assert.doesNotThrow( function() {
        disk = new Disk( device )
      })
    })

    it( 'disk.open()', function( next ) {
      disk.open( function( error ) {
        next( error )
      })
    })

    it( 'repeat disk.open()', function( next ) {
      disk.open( function( error ) {
        next( error )
      })
    })

    it( 'disk.close()', function( next ) {
      disk.close( function( error ) {
        next( error )
      })
    })

  })

})

Update test: Run against all test images


// jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle"
// https://github.com/jquery/jquery#how-to-build-your-own-jquery
var $ = require("./lib/jquery.min.js");

var MARGIN = 12;

var page = tabris.create("Page", {
  title: "XMLHttpRequest",
  topLevel: true
});

var createLabel = function(labelText) {
  tabris.create("Label", {
    text: labelText,
    markupEnabled: true,
    layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]}
  }).appendTo(page);
};

$.getJSON("http://www.telize.com/geoip", function(json) {
  createLabel("The IP address is: " + json.ip);
  createLabel("Latitude: " + json.latitude);
  createLabel("Longitude: " + json.longitude);
});

page.open();

// jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle"
// https://github.com/jquery/jquery#how-to-build-your-own-jquery
var $ = require("./lib/jquery.min.js");

var MARGIN = 12;

var page = tabris.create("Page", {
  title: "XMLHttpRequest",
  topLevel: true
});

var createTextView = function(text) {
  tabris.create("TextView", {
    text: text,
    markupEnabled: true,
    layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]}
  }).appendTo(page);
};

$.getJSON("http://www.telize.com/geoip", function(json) {
  createTextView("The IP address is: " + json.ip);
  createTextView("Latitude: " + json.latitude);
  createTextView("Longitude: " + json.longitude);
});

page.open();

Rename "Label" to "TextView" in jquery example


var Trie = require('../app/trie');

describe('Trie', function() {
  var trie;

  beforeEach(function() {
    trie = new Trie();
  });

  it('should be an object', function() {
    expect(trie).to.be.ok;
  });

  it('should have a root', function() {
    expect(trie.root).to.be.ok;
  });

  it('should have add method', function() {
    expect(trie.add).to.be.an.instanceof(Function);
  });

  it('should have search method', function() {
    expect(trie.search).to.be.an.instanceof(Function);
  });

  it('should have find method', function() {
    expect(trie.find).to.be.an.instanceof(Function);
  });

  it('should add string to trie', function() {
    expect(trie.add('test')).to.be.undefined;
  });

  it('should correctly find an added string', function() {
    trie.add('test');
    expect(trie.find('test')).to.be.true;
  });

  it('should trim leading/trailing spaces when adding a string', function() {
    trie.add('  test   ');
    expect(trie.find('test')).to.be.true;
  });

});

var Trie = require('../app/trie');

describe('Trie', function() {
  var trie;

  beforeEach(function() {
    trie = new Trie();
  });

  it('should be an object', function() {
    expect(trie).to.be.ok;
  });

  it('should have a root', function() {
    expect(trie.root).to.be.ok;
  });

  it('should have add method', function() {
    expect(trie.add).to.be.an.instanceof(Function);
  });

  it('should have search method', function() {
    expect(trie.search).to.be.an.instanceof(Function);
  });

  it('should have find method', function() {
    expect(trie.find).to.be.an.instanceof(Function);
  });

  it('should add string without errors', function() {
    expect(trie.add('test')).to.be.undefined;
  });

  it('should find an added string', function() {
    trie.add('test');
    expect(trie.find('test')).to.be.true;
  });

  it('should trim leading/trailing spaces when adding a string', function() {
    trie.add('  test   ');
    expect(trie.find('test')).to.be.true;
  });

});

Reword test for add string and find string


jQuery(function(){
    var body = jQuery('body');
    var settings_path = body.data('settings-path');

    body.on('settingssave', function( event, key_or_settings, value )
    {
        if (!settings_path)
        {
            return;
        }

        var settings = key_or_settings;
        if (typeof settings === "string")
        {
            settings = {};
            settings[key_or_settings] = value;
        }

        jQuery.ajax({
            url:  settings_path,
            data: { "settings": settings},
            headers: {
                'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')
            },
            type: 'POST',
            dataType: 'json'
        });
    });
});

jQuery(function(){
    var body = jQuery('body');
    var settings_path = body.data('settings-path');

    body.on('settingssave', function( event, key_or_settings, value )
    {
        if (!settings_path)
        {
            return;
        }

        var settings = key_or_settings;
        if (typeof settings === "string")
        {
            settings = {};
            settings[key_or_settings] = value;
        }

        LiteAjax.ajax({ url: settings_path, method: 'POST', data:  { "settings": settings}, json: true })
    });
});

Use vanilla-ujs LiteAjax for user settings sending


#!/usr/bin/env node

'use strict';

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

var fs    = require('fs');
var path  = require('path');
var spawn = require('child_process').spawn;

cli
  .version( pkg.version )
  .parse( process.argv );

var cwd = process.cwd();
var colliderFile = path.join( cwd, 'project', '.collider');

// Check if a Collider-file exists in the current working directory before running Gulp.
fs.access( colliderFile, fs.F_OK, function(error) {
  if(error) {
    console.log('A Collider-file could not be found in this directory.');
  } else {
    spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' });
  }
});

#!/usr/bin/env node

'use strict';

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

var createError  = require('../lib/createError');
var logErrorExit = require('../lib/logErrorExit');

var fs    = require('fs');
var path  = require('path');
var spawn = require('child_process').spawn;

cli
  .version( pkg.version )
  .parse( process.argv );

var cwd = process.cwd();
var colliderFile = path.join( cwd, 'project', '.collider');

// Check if a Collider-file exists in the current working directory before running Gulp.
fs.access( colliderFile, fs.F_OK, function(err) {
  if(err) {
    var err = createError("a Collider-file couldn't be found. Is this a Collider project?");
    logErrorExit( err, true );
  } else {
    spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' });
  }
});

Use creatError and logErrorExit to handle errors