<commit_before>var path = require('path')

const downgraded = [
  'class-methods-use-this',
  'consistent-return',
  'eqeqeq',
  'no-async-promise-executor',
  'no-await-in-loop',
  'no-self-compare',
  'no-shadow',
  'no-underscore-dangle',
  'no-use-before-define',
]

module.exports = {
  extends: '@ln-zap',
  rules: downgraded.reduce(
    (acc, next) => {
      acc[next] = 'warn'
      return acc
    },
    {
      'no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],
      'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
      'no-restricted-syntax': 'off',
    }
  ),
  settings: {
    'import/resolver': {
      'babel-module': {},
    },
    node: {
      moduleDirectory: ['renderer', 'node_modules'],
    },
    webpack: {
      config: path.resolve(__dirname, 'webpack', 'webpack.config.eslint.js'),
    },
  },
}
<commit_msg>style(lint): upgrade no-self-compare lint rule from warn to error<commit_after>var path = require('path')

const downgraded = [
  'class-methods-use-this',
  'consistent-return',
  'eqeqeq',
  'no-async-promise-executor',
  'no-await-in-loop',
  'no-shadow',
  'no-underscore-dangle',
  'no-use-before-define',
]

module.exports = {
  extends: '@ln-zap',
  rules: downgraded.reduce(
    (acc, next) => {
      acc[next] = 'warn'
      return acc
    },
    {
      'no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],
      'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
      'no-restricted-syntax': 'off',
    }
  ),
  settings: {
    'import/resolver': {
      'babel-module': {},
    },
    node: {
      moduleDirectory: ['renderer', 'node_modules'],
    },
    webpack: {
      config: path.resolve(__dirname, 'webpack', 'webpack.config.eslint.js'),
    },
  },
}
<|endoftext|>


<commit_before>(function(angular){
    'use strict';

    var app = angular.module('contracts', [
        'contracts.controllers',
        'contracts.services',
        'ngFileUpload',
        'ngRoute',
        'ngSanitize',
        'ui.bootstrap',
        'ui.select',
        'ui.tinymce',
        'header',
    ]);

    app.config(['$locationProvider', '$routeProvider',
        function config($locationProvider, $routeProvider) {
            $locationProvider.hashPrefix('!');

            $routeProvider.
                when('/new', {
                    templateUrl: '/paralapraca/contract-edit.html',
                    controller: 'NewContractCtrl'
                }).
                when('/:cardId/edit', {
                    templateUrl: '/paralapraca/contract-edit.html',
                    controller: 'EditContractCtrl'
                }).
                when('/:contractId', {
                    templateUrl: '/paralapraca/contract-detail.html',
                    controller: 'ContractDetailsCtrl'
                }).
                when('/', {
                    templateUrl: '/paralapraca/contracts-list.html',
                    controller: 'ContractsCtrl'
                }).
                otherwise('/');
        }
    ]);

})(angular);
<commit_msg>Fixed typo on routing.<commit_after>(function(angular){
    'use strict';

    var app = angular.module('contracts', [
        'contracts.controllers',
        'contracts.services',
        'ngFileUpload',
        'ngRoute',
        'ngSanitize',
        'ui.bootstrap',
        'ui.select',
        'ui.tinymce',
        'header',
    ]);

    app.config(['$locationProvider', '$routeProvider',
        function config($locationProvider, $routeProvider) {
            $locationProvider.hashPrefix('!');

            $routeProvider.
                when('/new', {
                    templateUrl: '/paralapraca/contract-edit.html',
                    controller: 'NewContractCtrl'
                }).
                when('/:contractId/edit', {
                    templateUrl: '/paralapraca/contract-edit.html',
                    controller: 'EditContractCtrl'
                }).
                when('/:contractId', {
                    templateUrl: '/paralapraca/contract-detail.html',
                    controller: 'ContractDetailsCtrl'
                }).
                when('/', {
                    templateUrl: '/paralapraca/contracts-list.html',
                    controller: 'ContractsCtrl'
                }).
                otherwise('/');
        }
    ]);

})(angular);
<|endoftext|>


<commit_before>var request = require('request');
var io = require('../websocket').connection;
var db = require('../db');

var droneRef = db.ref('/drones');

var flaskUrl = 'http://localhost:5000/dronesym/api/flask';

io.on('connection', function(socket){
	console.log('FEED_SUBSCRIPTION');

  //Initial drone data sent to client on first connection
	droneRef.once("value", function(snapshot){
    io.emit('SOCK_FEED_UPDATE', snapshot);
  })
});

//Send update drone data upon change to firebase
droneRef.on("value", function(snapshot){
	io.emit('SOCK_FEED_UPDATE', snapshot);
})

exports.createDrone = function(location, callBack){
	var droneKey = droneRef.push({'location': location });

	request.post(`${flaskUrl}/spawn`, { json : { droneId: droneKey.key, location: location } },
	function(error, response, body){
		console.log(body);
		callBack(body);
	})
}

exports.getDroneIds = function(callBack){
	var drones = [];

	droneRef.orderByKey().once("value")
	.then(function(snapshot){
		snapshot.forEach(function(drone){
			drones.push(drone.key);
		});

		callBack(drones);
	});
}

exports.updateDroneStatus = function(id, status){
	var timestamp = new Date();
	status["timestamp"] = timestamp.valueOf();
	droneRef.child(id).update(status, function(err){
		if(err){
			console.log(err);
			return;
		}
	});
}

exports.getDroneById = function(id, callBack){
	droneRef.orderByKey().equalTo(id)
	.once("value", function(snapshot){
		callBack(snapshot.child(id));
	});
}

exports.takeoffDrone = function(id, waypoints, callBack){
	var waypoints = waypoints || [];

	request.post(`${flaskUrl}/${id}/takeoff`, { json: { waypoints: waypoints }},
		function(err, response, body){
			callBack(body);
		}
	);
}

exports.landDrone = function(id, callBack){
	request.post(`${flaskUrl}/${id}/land`, function(err, response, body){
		callBack(body);
	});
}<commit_msg>Send drone data through socket<commit_after>var request = require('request');
var io = require('../websocket').connection;
var db = require('../db');

var droneRef = db.ref('/drones');

var flaskUrl = 'http://localhost:5000/dronesym/api/flask';

var sendSnapsot = function(snapshot){
  var array = [];

  snapshot.forEach(function(item){
    itemVal = item.val();
    itemVal['key'] = item.key;
    array.push(itemVal);
  });

  io.emit('SOCK_FEED_UPDATE', array);
}

io.on('connection', function(socket){
	console.log('FEED_SUBSCRIPTION');

  //Initial drone data sent to client on first connection
	droneRef.once("value", function(snapshot){
    sendSnapsot(snapshot);
  })
});

//Send update drone data upon change to firebase
droneRef.on("value", function(snapshot){
	sendSnapsot(snapshot);
})

exports.createDrone = function(location, callBack){
	var droneKey = droneRef.push({'location': location });

	request.post(`${flaskUrl}/spawn`, { json : { droneId: droneKey.key, location: location } },
	function(error, response, body){
		console.log(body);
		callBack(body);
	})
}

exports.getDroneIds = function(callBack){
	var drones = [];

	droneRef.orderByKey().once("value")
	.then(function(snapshot){
		snapshot.forEach(function(drone){
			drones.push(drone.key);
		});

		callBack(drones);
	});
}

exports.updateDroneStatus = function(id, status){
	var timestamp = new Date();
	status["timestamp"] = timestamp.valueOf();
	droneRef.child(id).update(status, function(err){
		if(err){
			console.log(err);
			return;
		}
	});
}

exports.getDroneById = function(id, callBack){
	droneRef.orderByKey().equalTo(id)
	.once("value", function(snapshot){
		callBack(snapshot.child(id));
	});
}

exports.takeoffDrone = function(id, waypoints, callBack){
	var waypoints = waypoints || [];

	request.post(`${flaskUrl}/${id}/takeoff`, { json: { waypoints: waypoints }},
		function(err, response, body){
			callBack(body);
		}
	);
}

exports.landDrone = function(id, callBack){
	request.post(`${flaskUrl}/${id}/land`, function(err, response, body){
		callBack(body);
	});
}<|endoftext|>


<commit_before>/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

"use strict";

import Center from './Center';
import microtime from 'microtime';
import FileTransformer from './FileTransformer';

let os = require('os');

process.title = 'ExpoSE Distributor';

process.on('disconnect', function() {
    Log.log('Premature termination - Parent exit');
    process.exit();
});

function getTarget() {
    return process.argv[process.argv.length - 1];
}

function argToType(arg, type) {
    if (type == 'number') {
        return parseInt(arg);
    }
    return arg;
}

function getArgument(name, type, dResult) {
    return process.env[name] ? argToType(process.env[name], type) : dResult;
}

if (process.argv.length >= 3) {
    let target = getTarget();

    let numCpuCores = os.cpus().length;
    let defaultTestCases = numCpuCores;

    if (!getArgument('EXPOSE_MAX_CONCURRENT', 'number', undefined)) {
        console.log(`Number of CPU cores: ${numCpuCores}`);
        console.log(`Defaulting to ${defaultTestCases} concurrent test cases`);
    }

    let options = {
        maxConcurrent: getArgument('EXPOSE_MAX_CONCURRENT', 'number', defaultTestCases), //max number of tests to run concurrently
        maxPaths: getArgument('EXPOSE_MAX_PATHS', 'number', 100), //Max paths spawned
        jsonOut: getArgument('EXPOSE_JSON_OUT', 'number', false), //By default ExpoSE should not print JSON results into STDOUT
        printPaths: getArgument('EXPOSE_PRINT_PATHS', 'number', false), //By default do not print paths to stdout
        testMaxTime: getArgument('EXPOSE_TEST_TIMEOUT', 'number', 1000 * 60 * 15), //10 minutes default time
        printDeltaCoverage: getArgument('EXPOSE_PRINT_COVERAGE', 'number', false),
        analyseScript: getArgument('EXPOSE_PLAY_SCRIPT', 'string', './scripts/play')
    };

    console.log('ExpoSE Master: ' + target + ' max concurrent: ' + options.maxConcurrent + ' max paths: ' + options.maxPaths);

    let start = microtime.now();

    new Center(options).done((center, done, errors, coverage) => {

        if (options.jsonOut) {
            console.log('\nExpoSE JSON: ' + JSON.stringify({
                source: getTarget(),
                start: start,
                end: microtime.now(),
                done: done
            }) + '\nEND JSON');
        }

        function round(num, precision) {
            return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
        }

        function formatSeconds(v) {
            return round((v / 1000 / 1000), 4);
        }

        done.forEach(item => {
            let testStartSeconds = item.startTime - start;
            console.log('*-- Test Case ' + JSON.stringify(item.input) + ' start ' + formatSeconds(testStartSeconds) + ' took ' + formatSeconds(item.time) + 's');

            if (item.errors.length != 0) {
                console.log('*-- Errors occured in test ' + JSON.stringify(item.input));
                item.errors.forEach(error => console.log('* Error: ' + error.error));
                console.log('*-- Replay with ' + item.replay);
            }
        });

        console.log('*-- Coverage Data');

        coverage.final().forEach(d => {
            console.log('*- File ' + d.file + '. Coverage: ' + Math.round(d.data.coverage * 100) + '%');
        });

        if (options.printDeltaCoverage) {
            let touched = coverage.getTouched();

            for (let filename in touched) {
                FileTransformer(filename).then(data => {
                    console.log(`*- Experimental Line Coverage for ${filename} *-`);
                    let lines = data.split('\n');
                    lines.map((line, idx) => touched[filename].find(i => i == idx + 1) ? ('+' + line) : ('-' + line)).forEach((line, idx) => console.log(`{idx+1}: ${line}`));
                });
            }
        }

        console.log('** ExpoSE Finished. ' + done.length + ' paths with ' + errors + ' errors **');
        process.exitCode = errors;
    }).start(target);
} else {
    console.log('Wrong number of arguments');
    console.log('Usage Distributor --concurrent XX --max_paths 999 test_script');
}
<commit_msg>Fix delta<commit_after>/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

"use strict";

import Center from './Center';
import microtime from 'microtime';
import FileTransformer from './FileTransformer';

let os = require('os');

process.title = 'ExpoSE Distributor';

process.on('disconnect', function() {
    Log.log('Premature termination - Parent exit');
    process.exit();
});

function getTarget() {
    return process.argv[process.argv.length - 1];
}

function argToType(arg, type) {
    if (type == 'number') {
        return parseInt(arg);
    }
    return arg;
}

function getArgument(name, type, dResult) {
    return process.env[name] ? argToType(process.env[name], type) : dResult;
}

if (process.argv.length >= 3) {
    let target = getTarget();

    let numCpuCores = os.cpus().length;
    let defaultTestCases = numCpuCores;

    if (!getArgument('EXPOSE_MAX_CONCURRENT', 'number', undefined)) {
        console.log(`Number of CPU cores: ${numCpuCores}`);
        console.log(`Defaulting to ${defaultTestCases} concurrent test cases`);
    }

    let options = {
        maxConcurrent: getArgument('EXPOSE_MAX_CONCURRENT', 'number', defaultTestCases), //max number of tests to run concurrently
        maxPaths: getArgument('EXPOSE_MAX_PATHS', 'number', 100), //Max paths spawned
        jsonOut: getArgument('EXPOSE_JSON_OUT', 'number', false), //By default ExpoSE should not print JSON results into STDOUT
        printPaths: getArgument('EXPOSE_PRINT_PATHS', 'number', false), //By default do not print paths to stdout
        testMaxTime: getArgument('EXPOSE_TEST_TIMEOUT', 'number', 1000 * 60 * 15), //10 minutes default time
        printDeltaCoverage: getArgument('EXPOSE_PRINT_COVERAGE', 'number', false),
        analyseScript: getArgument('EXPOSE_PLAY_SCRIPT', 'string', './scripts/play')
    };

    console.log('ExpoSE Master: ' + target + ' max concurrent: ' + options.maxConcurrent + ' max paths: ' + options.maxPaths);

    let start = microtime.now();

    new Center(options).done((center, done, errors, coverage) => {

        if (options.jsonOut) {
            console.log('\nExpoSE JSON: ' + JSON.stringify({
                source: getTarget(),
                start: start,
                end: microtime.now(),
                done: done
            }) + '\nEND JSON');
        }

        function round(num, precision) {
            return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
        }

        function formatSeconds(v) {
            return round((v / 1000 / 1000), 4);
        }

        done.forEach(item => {
            let testStartSeconds = item.startTime - start;
            console.log('*-- Test Case ' + JSON.stringify(item.input) + ' start ' + formatSeconds(testStartSeconds) + ' took ' + formatSeconds(item.time) + 's');

            if (item.errors.length != 0) {
                console.log('*-- Errors occured in test ' + JSON.stringify(item.input));
                item.errors.forEach(error => console.log('* Error: ' + error.error));
                console.log('*-- Replay with ' + item.replay);
            }
        });

        console.log('*-- Coverage Data');

        coverage.final().forEach(d => {
            console.log('*- File ' + d.file + '. Coverage: ' + Math.round(d.data.coverage * 100) + '%');
        });

        if (options.printDeltaCoverage) {
            let touched = coverage.getTouched();

            for (let filename in touched) {
                FileTransformer(filename).then(data => {
                    console.log(`*- Experimental Line Coverage for ${filename} `);
                    let lines = data.split('\n');
                    lines.map((line, idx) => touched[filename].find(i => i == idx + 1) ? ('+:' + line) : ('-:' + line)).forEach((line, idx) => console.log(`${idx+1}${line}`));
                });
            }
        } else {
            console.log('*- Re-run with EXPOSE_PRINT_COVERAGE=1 to print line by line coverage information');
        }

        console.log('** ExpoSE Finished. ' + done.length + ' paths with ' + errors + ' errors **');
        process.exitCode = errors;
    }).start(target);
} else {
    console.log('Wrong number of arguments');
    console.log('Usage Distributor --concurrent XX --max_paths 999 test_script');
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    parserOptions: {
        sourceType: 'module'
    },
    plugins: [
        'fp',
        'import',
        'json',
        'promise',
        'unicorn'
    ],
    rules: {
        'fp/no-arguments': 'off',
        'fp/no-class': 'error',
        'fp/no-delete': 'off',
        'fp/no-events': 'error',
        'fp/no-get-set': 'error',
        'fp/no-let': 'off',
        'fp/no-loops': 'error',
        'fp/no-mutating-assign': 'off',
        'fp/no-mutating-methods': 'off',
        'fp/no-mutation': 'off',
        'fp/no-nil': 'off',
        'fp/no-proxy': 'error',
        'fp/no-rest-parameters': 'off',
        'fp/no-this': 'off',
        'fp/no-throw': 'off',
        'fp/no-unused-expression': 'off',
        'fp/no-valueof-field': 'error',

        'promise/always-return': 'error',
        'promise/always-catch': 'off',
        'promise/catch-or-return': 'error',
        'promise/no-native': 'error',
        'promise/no-return-wrap': 'off',
        'promise/param-names': 'error',
        'promise/prefer-await-to-callbacks': 'off',
        'promise/prefer-await-to-then': 'off',

        'import/default': 'error',
        'import/export': 'error',
        'import/extensions': 'error',
        'import/first': 'error',
        'import/imports-first': 'error',
        'import/max-dependencies': 'off',
        'import/named': 'error',
        'import/namespace': 'error',
        'import/newline-after-import': 'error',
        'import/no-absolute-path': 'error',
        'import/no-amd': 'error',
        'import/no-commonjs': 'off',
        'import/no-deprecated': 'error',
        'import/no-duplicates': 'error',
        'import/no-dynamic-require': 'error',
        'import/no-extraneous-dependencies': 'error',
        'import/no-internal-modules': 'off',
        'import/no-mutable-exports': 'error',
        'import/no-named-as-default-member': 'error',
        'import/no-named-as-default': 'error',
        'import/no-namespace': 'off',
        'import/no-nodejs-modules': 'off',
        'import/no-restricted-paths': 'off',
        'import/no-unassigned-import': 'off',
        'import/no-unresolved': 'error',
        'import/no-webpack-loader-syntax': 'error',
        'import/order': ['error', {'newlines-between': 'ignore'}],
        'import/prefer-default-export': 'error',
        'import/unambiguous': 'off',

        'unicorn/catch-error-name': 'off',
        'unicorn/explicit-length-check': 'error',
        'unicorn/filename-case': ['error', {'case': 'kebabCase'}],
        'unicorn/no-abusive-eslint-disable': 'error',
        'unicorn/no-process-exit': 'error',
        'unicorn/throw-new-error': 'error',

        'accessor-pairs': 'off',
        'array-bracket-spacing': ['error', 'never'],
        'array-callback-return': 'error',
        'arrow-body-style': 'off',
        'arrow-parens': ['error', 'as-needed'],
        'arrow-spacing': 'error',
        'block-scoped-var': 'error',
        'block-spacing': 'off',
        'brace-style': 'off',
        'callback-return': ['error', ['callback', 'cb', 'next']],
        'camelcase': 'off',
        'class-methods-use-this': 'error',
        'comma-dangle': ['error', 'never'],
        'comma-spacing': 'error',
        'comma-style': ['error', 'last'],
        'complexity': ['off', 11],
        'computed-property-spacing': ['error', 'never'],
        'consistent-return': 'off',
        'consistent-this': 'off',
        'constructor-super': 'error',
        'curly': 'off',
        'default-case': 'off',
        'dot-location': ['error', 'property'],
        'dot-notation': 'error',
        'eol-last': 'error',
        'eqeqeq': 'error',
        'func-call-spacing': ['error', 'never'],
        'func-name-matching': 'off',
        'func-names': 'off',
        'func-style': 'off',
        'generator-star-spacing': 'off',
        'global-require': 'off',
        'guard-for-in': 'error',
        'handle-callback-err': 'off',
        'id-blacklist': 'off',
        'id-length': 'off',
        'id-match': 'off',
        'indent': ['error', 2, { 'SwitchCase': 1 }],
        'init-declarations': 'off',
        'jsx-quotes': 'off',
        'key-spacing': 'error',
        'keyword-spacing': ['error', {
            'overrides': {
                'catch': { 'after': true },
                'do': { 'after': true },
                'else': { 'after': true },
                'for': { 'after': true },
                'if': { 'after': true },
                'switch': { 'after': true },
                'try': { 'after': true },
                'while': { 'after': true },
                'default': { 'after': false }
            }
        }],
        'line-comment-position': 'off',
        'linebreak-style': 'error',
        'lines-around-comment': 'off',
        'lines-around-directive': ['error', {'before': 'never', 'after': 'always'}],
        'max-depth': ['error', 4],
        'max-len': ['error', 120],
        'max-lines': 'off',
        'max-nested-callbacks': 'off',
        'max-params': 'off',
        'max-statements-per-line': ['error', { 'max': 1 }],
        'max-statements': 'off',
        'multiline-ternary': 'off',
        'new-cap': 'off',
        'new-parens': 'off',
        'newline-after-var': 'off',
        'newline-before-return': 'off',
        'newline-per-chained-call': 'off',
        'no-alert': 'error',
        'no-array-constructor': 'error',
        'no-bitwise': 'off',
        'no-caller': 'error',
        'no-case-declarations': 'error',
        'no-catch-shadow': 'off',
        'no-class-assign': 'error',
        'no-cond-assign': 'error',
        'no-confusing-arrow': 'error',
        'no-console': 'error',
        'no-const-assign': 'error',
        'no-constant-condition': 'error',
        'no-continue': 'error',
        'no-control-regex': 'error',
        'no-debugger': 'error',
        'no-delete-var': 'error',
        'no-div-regex': 'off',
        'no-dupe-args': 'error',
        'no-dupe-class-members': 'error',
        'no-dupe-keys': 'error',
        'no-duplicate-case': 'error',
        'no-duplicate-imports': 'off',
        'no-else-return': 'off',
        'no-empty-character-class': 'error',
        'no-empty-function': 'off',
        'no-empty-pattern': 'error',
        'no-empty': 'error',
        'no-eq-null': 'error',
        'no-eval': 'error',
        'no-ex-assign': 'error',
        'no-extend-native': 'error',
        'no-extra-bind': 'error',
        'no-extra-boolean-cast': 'error',
        'no-extra-label': 'off',
        'no-extra-parens': 'off',
        'no-extra-semi': 'error',
        'no-fallthrough': 'error',
        'no-floating-decimal': 'off',
        'no-func-assign': 'error',
        'no-global-assign': 'error',
        'no-implicit-coercion': 'off',
        'no-implicit-globals': 'off',
        'no-implied-eval': 'error',
        'no-inline-comments': 'off',
        'no-inner-declarations': 'error',
        'no-invalid-regexp': 'error',
        'no-invalid-this': 'off',
        'no-irregular-whitespace': 'error',
        'no-iterator': 'off',
        'no-label-var': 'off',
        'no-labels': 'error',
        'no-lone-blocks': 'error',
        'no-lonely-if': 'error',
        'no-loop-func': 'error',
        'no-magic-numbers': 'off',
        'no-mixed-operators': 'error',
        'no-mixed-requires': 'off',
        'no-mixed-spaces-and-tabs': 'error',
        'no-multi-spaces': 'error',
        'no-multi-str': 'error',
        'no-multiple-empty-lines': ['error', {'max': 1}],
        'no-native-reassign': 'error',
        'no-negated-condition': 'off',
        'no-negated-in-lhs': 'error',
        'no-nested-ternary': 'error',
        'no-new-func': 'off',
        'no-new-object': 'off',
        'no-new-require': 'off',
        'no-new-symbol': 'error',
        'no-new-wrappers': 'error',
        'no-new': 'error',
        'no-obj-calls': 'error',
        'no-octal-escape': 'off',
        'no-octal': 'error',
        'no-param-reassign': 'error',
        'no-path-concat': 'off',
        'no-plusplus': 'off',
        'no-process-env': 'off',
        'no-process-exit': 'off',
        'no-proto': 'off',
        'no-prototype-builtins': 'off',
        'no-redeclare': 'error',
        'no-regex-spaces': 'error',
        'no-restricted-globals': 'off',
        'no-restricted-imports': 'off',
        'no-restricted-modules': 'off',
        'no-restricted-properties': ['error', {
            object: 'Promise',
            property: 'longStackTraces'
        }],
        'no-restricted-syntax': 'off',
        'no-return-assign': 'error',
        'no-script-url': 'error',
        'no-self-assign': 'error',
        'no-self-compare': 'error',
        'no-sequences': 'error',
        'no-shadow-restricted-names': 'error',
        'no-shadow': ['error', {builtinGlobals: true, hoist: 'all', 'allow': ['Promise']}],
        'no-spaced-func': 'error',
        'no-sparse-arrays': 'error',
        'no-sync': 'off',
        'no-tabs': 'off',
        'no-template-curly-in-string': 'error',
        'no-ternary': 'off',
        'no-this-before-super': 'error',
        'no-throw-literal': 'error',
        'no-trailing-spaces': 'error',
        'no-undef-init': 'off',
        'no-undef': 'error',
        'no-undefined': 'off',
        'no-underscore-dangle': 'off',
        'no-unexpected-multiline': 'error',
        'no-unmodified-loop-condition': 'off',
        'no-unneeded-ternary': 'error',
        'no-unreachable': 'error',
        'no-unsafe-finally': 'error',
        'no-unsafe-negation': 'error',
        'no-unused-expressions': 'off',
        'no-unused-labels': 'error',
        'no-unused-vars': ['error', { 'vars': 'all', 'args': 'none' }],
        'no-use-before-define': 'error',
        'no-useless-call': 'error',
        'no-useless-computed-key': 'error',
        'no-useless-concat': 'error',
        'no-useless-constructor': 'off',
        'no-useless-escape': 'error',
        'no-useless-rename': 'error',
        'no-useless-return': 'off',
        'no-var': 'off',
        'no-void': 'error',
        'no-warning-comments': 'warn',
        'no-whitespace-before-property': 'error',
        'no-with': 'error',
        'object-curly-newline': 'off',
        'object-curly-spacing': 'off',
        'object-property-newline': 'off',
        'object-shorthand': 'off',
        'one-var-declaration-per-line': 'off',
        'one-var': 'off',
        'operator-assignment': 'off',
        'operator-linebreak': ['error', 'after'],
        'padded-blocks': ['error', 'never'],
        'prefer-arrow-callback': 'off',
        'prefer-const': 'off',
        'prefer-numeric-literals': 'error',
        'prefer-reflect': 'off',
        'prefer-rest-params': 'off',
        'prefer-spread': 'off',
        'prefer-template': 'off',
        'quote-props': ['error', 'as-needed'],
        'quotes': ['error', 'single', 'avoid-escape'],
        'radix': 'off',
        'require-jsdoc': 'off',
        'require-yield': 'error',
        'rest-spread-spacing': 'error',
        'semi-spacing': 'error',
        'semi': ['error', 'always'],
        'sort-imports': 'off',
        'sort-keys': 'off',
        'sort-vars': 'off',
        'space-before-blocks': ['error', 'always'],
        'space-before-function-paren': ['error', 'never'],
        'space-in-parens': ['error', 'never'],
        'space-infix-ops': 'error',
        'space-unary-ops': ['error', { 'words': false, 'nonwords': false }],
        'spaced-comment': ['error', 'always'],
        'strict': ['error', 'global'],
        'symbol-description': 'error',
        'template-curly-spacing': ['error', 'never'],
        'unicode-bom': 'error',
        'use-isnan': 'error',
        'valid-jsdoc': 'off',
        'valid-typeof': 'error',
        'vars-on-top': 'off',
        'wrap-iife': ['error', 'any'],
        'wrap-regex': 'off',
        'yield-star-spacing': 'off',
        'yoda': ['error', 'never', { 'exceptRange': true }],
    },
    'settings': {
      'import/ignore': ['node_modules', '\\.css$']
    }
};
<commit_msg>Bump e-p-import to 2.1.0<commit_after>'use strict';

module.exports = {
    parserOptions: {
        sourceType: 'module'
    },
    plugins: [
        'fp',
        'import',
        'json',
        'promise',
        'unicorn'
    ],
    rules: {
        'fp/no-arguments': 'off',
        'fp/no-class': 'error',
        'fp/no-delete': 'off',
        'fp/no-events': 'error',
        'fp/no-get-set': 'error',
        'fp/no-let': 'off',
        'fp/no-loops': 'error',
        'fp/no-mutating-assign': 'off',
        'fp/no-mutating-methods': 'off',
        'fp/no-mutation': 'off',
        'fp/no-nil': 'off',
        'fp/no-proxy': 'error',
        'fp/no-rest-parameters': 'off',
        'fp/no-this': 'off',
        'fp/no-throw': 'off',
        'fp/no-unused-expression': 'off',
        'fp/no-valueof-field': 'error',

        'promise/always-return': 'error',
        'promise/always-catch': 'off',
        'promise/catch-or-return': 'error',
        'promise/no-native': 'error',
        'promise/no-return-wrap': 'off',
        'promise/param-names': 'error',
        'promise/prefer-await-to-callbacks': 'off',
        'promise/prefer-await-to-then': 'off',

        'import/default': 'error',
        'import/export': 'error',
        'import/extensions': 'error',
        'import/first': 'error',
        'import/imports-first': 'error',
        'import/max-dependencies': 'off',
        'import/named': 'error',
        'import/namespace': 'error',
        'import/newline-after-import': 'error',
        'import/no-absolute-path': 'error',
        'import/no-amd': 'error',
        'import/no-commonjs': 'off',
        'import/no-deprecated': 'error',
        'import/no-duplicates': 'error',
        'import/no-dynamic-require': 'error',
        'import/no-extraneous-dependencies': 'error',
        'import/no-internal-modules': 'off',
        'import/no-mutable-exports': 'error',
        'import/no-named-as-default-member': 'error',
        'import/no-named-as-default': 'error',
        'import/no-named-default': 'error',
        'import/no-namespace': 'off',
        'import/no-nodejs-modules': 'off',
        'import/no-restricted-paths': 'off',
        'import/no-unassigned-import': 'off',
        'import/no-unresolved': 'error',
        'import/no-webpack-loader-syntax': 'error',
        'import/order': ['error', {'newlines-between': 'ignore'}],
        'import/prefer-default-export': 'error',
        'import/unambiguous': 'off',

        'unicorn/catch-error-name': 'off',
        'unicorn/explicit-length-check': 'error',
        'unicorn/filename-case': ['error', {'case': 'kebabCase'}],
        'unicorn/no-abusive-eslint-disable': 'error',
        'unicorn/no-process-exit': 'error',
        'unicorn/throw-new-error': 'error',

        'accessor-pairs': 'off',
        'array-bracket-spacing': ['error', 'never'],
        'array-callback-return': 'error',
        'arrow-body-style': 'off',
        'arrow-parens': ['error', 'as-needed'],
        'arrow-spacing': 'error',
        'block-scoped-var': 'error',
        'block-spacing': 'off',
        'brace-style': 'off',
        'callback-return': ['error', ['callback', 'cb', 'next']],
        'camelcase': 'off',
        'class-methods-use-this': 'error',
        'comma-dangle': ['error', 'never'],
        'comma-spacing': 'error',
        'comma-style': ['error', 'last'],
        'complexity': ['off', 11],
        'computed-property-spacing': ['error', 'never'],
        'consistent-return': 'off',
        'consistent-this': 'off',
        'constructor-super': 'error',
        'curly': 'off',
        'default-case': 'off',
        'dot-location': ['error', 'property'],
        'dot-notation': 'error',
        'eol-last': 'error',
        'eqeqeq': 'error',
        'func-call-spacing': ['error', 'never'],
        'func-name-matching': 'off',
        'func-names': 'off',
        'func-style': 'off',
        'generator-star-spacing': 'off',
        'global-require': 'off',
        'guard-for-in': 'error',
        'handle-callback-err': 'off',
        'id-blacklist': 'off',
        'id-length': 'off',
        'id-match': 'off',
        'indent': ['error', 2, { 'SwitchCase': 1 }],
        'init-declarations': 'off',
        'jsx-quotes': 'off',
        'key-spacing': 'error',
        'keyword-spacing': ['error', {
            'overrides': {
                'catch': { 'after': true },
                'do': { 'after': true },
                'else': { 'after': true },
                'for': { 'after': true },
                'if': { 'after': true },
                'switch': { 'after': true },
                'try': { 'after': true },
                'while': { 'after': true },
                'default': { 'after': false }
            }
        }],
        'line-comment-position': 'off',
        'linebreak-style': 'error',
        'lines-around-comment': 'off',
        'lines-around-directive': ['error', {'before': 'never', 'after': 'always'}],
        'max-depth': ['error', 4],
        'max-len': ['error', 120],
        'max-lines': 'off',
        'max-nested-callbacks': 'off',
        'max-params': 'off',
        'max-statements-per-line': ['error', { 'max': 1 }],
        'max-statements': 'off',
        'multiline-ternary': 'off',
        'new-cap': 'off',
        'new-parens': 'off',
        'newline-after-var': 'off',
        'newline-before-return': 'off',
        'newline-per-chained-call': 'off',
        'no-alert': 'error',
        'no-array-constructor': 'error',
        'no-bitwise': 'off',
        'no-caller': 'error',
        'no-case-declarations': 'error',
        'no-catch-shadow': 'off',
        'no-class-assign': 'error',
        'no-cond-assign': 'error',
        'no-confusing-arrow': 'error',
        'no-console': 'error',
        'no-const-assign': 'error',
        'no-constant-condition': 'error',
        'no-continue': 'error',
        'no-control-regex': 'error',
        'no-debugger': 'error',
        'no-delete-var': 'error',
        'no-div-regex': 'off',
        'no-dupe-args': 'error',
        'no-dupe-class-members': 'error',
        'no-dupe-keys': 'error',
        'no-duplicate-case': 'error',
        'no-duplicate-imports': 'off',
        'no-else-return': 'off',
        'no-empty-character-class': 'error',
        'no-empty-function': 'off',
        'no-empty-pattern': 'error',
        'no-empty': 'error',
        'no-eq-null': 'error',
        'no-eval': 'error',
        'no-ex-assign': 'error',
        'no-extend-native': 'error',
        'no-extra-bind': 'error',
        'no-extra-boolean-cast': 'error',
        'no-extra-label': 'off',
        'no-extra-parens': 'off',
        'no-extra-semi': 'error',
        'no-fallthrough': 'error',
        'no-floating-decimal': 'off',
        'no-func-assign': 'error',
        'no-global-assign': 'error',
        'no-implicit-coercion': 'off',
        'no-implicit-globals': 'off',
        'no-implied-eval': 'error',
        'no-inline-comments': 'off',
        'no-inner-declarations': 'error',
        'no-invalid-regexp': 'error',
        'no-invalid-this': 'off',
        'no-irregular-whitespace': 'error',
        'no-iterator': 'off',
        'no-label-var': 'off',
        'no-labels': 'error',
        'no-lone-blocks': 'error',
        'no-lonely-if': 'error',
        'no-loop-func': 'error',
        'no-magic-numbers': 'off',
        'no-mixed-operators': 'error',
        'no-mixed-requires': 'off',
        'no-mixed-spaces-and-tabs': 'error',
        'no-multi-spaces': 'error',
        'no-multi-str': 'error',
        'no-multiple-empty-lines': ['error', {'max': 1}],
        'no-native-reassign': 'error',
        'no-negated-condition': 'off',
        'no-negated-in-lhs': 'error',
        'no-nested-ternary': 'error',
        'no-new-func': 'off',
        'no-new-object': 'off',
        'no-new-require': 'off',
        'no-new-symbol': 'error',
        'no-new-wrappers': 'error',
        'no-new': 'error',
        'no-obj-calls': 'error',
        'no-octal-escape': 'off',
        'no-octal': 'error',
        'no-param-reassign': 'error',
        'no-path-concat': 'off',
        'no-plusplus': 'off',
        'no-process-env': 'off',
        'no-process-exit': 'off',
        'no-proto': 'off',
        'no-prototype-builtins': 'off',
        'no-redeclare': 'error',
        'no-regex-spaces': 'error',
        'no-restricted-globals': 'off',
        'no-restricted-imports': 'off',
        'no-restricted-modules': 'off',
        'no-restricted-properties': ['error', {
            object: 'Promise',
            property: 'longStackTraces'
        }],
        'no-restricted-syntax': 'off',
        'no-return-assign': 'error',
        'no-script-url': 'error',
        'no-self-assign': 'error',
        'no-self-compare': 'error',
        'no-sequences': 'error',
        'no-shadow-restricted-names': 'error',
        'no-shadow': ['error', {builtinGlobals: true, hoist: 'all', 'allow': ['Promise']}],
        'no-spaced-func': 'error',
        'no-sparse-arrays': 'error',
        'no-sync': 'off',
        'no-tabs': 'off',
        'no-template-curly-in-string': 'error',
        'no-ternary': 'off',
        'no-this-before-super': 'error',
        'no-throw-literal': 'error',
        'no-trailing-spaces': 'error',
        'no-undef-init': 'off',
        'no-undef': 'error',
        'no-undefined': 'off',
        'no-underscore-dangle': 'off',
        'no-unexpected-multiline': 'error',
        'no-unmodified-loop-condition': 'off',
        'no-unneeded-ternary': 'error',
        'no-unreachable': 'error',
        'no-unsafe-finally': 'error',
        'no-unsafe-negation': 'error',
        'no-unused-expressions': 'off',
        'no-unused-labels': 'error',
        'no-unused-vars': ['error', { 'vars': 'all', 'args': 'none' }],
        'no-use-before-define': 'error',
        'no-useless-call': 'error',
        'no-useless-computed-key': 'error',
        'no-useless-concat': 'error',
        'no-useless-constructor': 'off',
        'no-useless-escape': 'error',
        'no-useless-rename': 'error',
        'no-useless-return': 'off',
        'no-var': 'off',
        'no-void': 'error',
        'no-warning-comments': 'warn',
        'no-whitespace-before-property': 'error',
        'no-with': 'error',
        'object-curly-newline': 'off',
        'object-curly-spacing': 'off',
        'object-property-newline': 'off',
        'object-shorthand': 'off',
        'one-var-declaration-per-line': 'off',
        'one-var': 'off',
        'operator-assignment': 'off',
        'operator-linebreak': ['error', 'after'],
        'padded-blocks': ['error', 'never'],
        'prefer-arrow-callback': 'off',
        'prefer-const': 'off',
        'prefer-numeric-literals': 'error',
        'prefer-reflect': 'off',
        'prefer-rest-params': 'off',
        'prefer-spread': 'off',
        'prefer-template': 'off',
        'quote-props': ['error', 'as-needed'],
        'quotes': ['error', 'single', 'avoid-escape'],
        'radix': 'off',
        'require-jsdoc': 'off',
        'require-yield': 'error',
        'rest-spread-spacing': 'error',
        'semi-spacing': 'error',
        'semi': ['error', 'always'],
        'sort-imports': 'off',
        'sort-keys': 'off',
        'sort-vars': 'off',
        'space-before-blocks': ['error', 'always'],
        'space-before-function-paren': ['error', 'never'],
        'space-in-parens': ['error', 'never'],
        'space-infix-ops': 'error',
        'space-unary-ops': ['error', { 'words': false, 'nonwords': false }],
        'spaced-comment': ['error', 'always'],
        'strict': ['error', 'global'],
        'symbol-description': 'error',
        'template-curly-spacing': ['error', 'never'],
        'unicode-bom': 'error',
        'use-isnan': 'error',
        'valid-jsdoc': 'off',
        'valid-typeof': 'error',
        'vars-on-top': 'off',
        'wrap-iife': ['error', 'any'],
        'wrap-regex': 'off',
        'yield-star-spacing': 'off',
        'yoda': ['error', 'never', { 'exceptRange': true }],
    },
    'settings': {
      'import/ignore': ['node_modules', '\\.css$']
    }
};
<|endoftext|>


<commit_before>if (!org.bustany.TrackerBird.TrackerSparql || !org.bustany.TrackerBird.TrackerSparql.__initialized)
org.bustany.TrackerBird.TrackerSparql = {
	__initialized: true,

	_trackerSparqlPath: "libtracker-sparql-0.10.so",
	_lib: null,

	init: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		// Safeguard just in case a fool would call that twice
		if (tracker._lib) {
			return true;
		}

		Components.utils.import ("resource://gre/modules/ctypes.jsm");

		try {
			tracker._lib = ctypes.open (tracker._trackerSparqlPath);
		} catch (e) {
		}

		tracker._trackerSparqlPath = "libtracker-sparql-0.11.so";

		try {
			tracker._lib = ctypes.open (tracker._trackerSparqlPath);
		} catch (e) {
			dump ("Could not load libtracker-sparql 0.10 or 0.11: " + e + "\n");
			return false;
		}

		// GLib types
		tracker.Cancellable = new ctypes.StructType ("GCancellable");
		tracker.Error = new ctypes.StructType ("GError", [
			{domain  : ctypes.uint32_t},
			{code    : ctypes.int32_t},
			{message : ctypes.char.ptr}
		]);

		// TrackerSparql types
		tracker.Connection = ctypes.StructType ("TrackerSparqlConnection");
		tracker.Cursor = ctypes.StructType ("TrackerSparqlCursor");

		// GLib methods
		tracker.object_unref = tracker._lib.declare (
			"g_object_unref",
			ctypes.default_abi,
			ctypes.void_t,
			ctypes.void_t.ptr // Binding GObject* as a void* since we don't have GObject binding...
		);

		tracker.error_free = tracker._lib.declare (
			"g_error_free",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Error.ptr
		);

		// TrackerSparql methods (name, ABI, args with first arg = return type)
		tracker.connection_open = tracker._lib.declare (
			"tracker_sparql_connection_get",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_query = tracker._lib.declare (
			"tracker_sparql_connection_query",
			ctypes.default_abi,
			tracker.Cursor.ptr,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_update = tracker._lib.declare (
			"tracker_sparql_connection_update",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			ctypes.int32_t,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_next = tracker._lib.declare (
			"tracker_sparql_cursor_next",
			ctypes.default_abi,
			ctypes.bool,
			tracker.Cursor.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_get_string = tracker._lib.declare (
			"tracker_sparql_cursor_get_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			tracker.Cursor.ptr,
			ctypes.int,
			ctypes.long.ptr
		);

		tracker.escape_string = tracker._lib.declare (
			"tracker_sparql_escape_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			ctypes.char.ptr
		);

		return true;
	},

	shutdown: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		if (this._connection) {
			tracker.object_unref(this._connection);
		}

		if (this._lib) {
			this._lib.close ();
		}
	}
}
<commit_msg>Fix logic in 0.11 fallback<commit_after>if (!org.bustany.TrackerBird.TrackerSparql || !org.bustany.TrackerBird.TrackerSparql.__initialized)
org.bustany.TrackerBird.TrackerSparql = {
	__initialized: true,

	_trackerSparqlPath: "libtracker-sparql-0.10.so",
	_lib: null,

	init: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		// Safeguard just in case a fool would call that twice
		if (tracker._lib) {
			return true;
		}

		Components.utils.import ("resource://gre/modules/ctypes.jsm");

		try {
			tracker._lib = ctypes.open (tracker._trackerSparqlPath);
		} catch (e) {
			tracker._trackerSparqlPath = "libtracker-sparql-0.11.so";

			try {
				tracker._lib = ctypes.open (tracker._trackerSparqlPath);
			} catch (e) {
				dump ("Could not load libtracker-sparql 0.10 or 0.11: " + e + "\n");
				return false;
			}
		}

		// GLib types
		tracker.Cancellable = new ctypes.StructType ("GCancellable");
		tracker.Error = new ctypes.StructType ("GError", [
			{domain  : ctypes.uint32_t},
			{code    : ctypes.int32_t},
			{message : ctypes.char.ptr}
		]);

		// TrackerSparql types
		tracker.Connection = ctypes.StructType ("TrackerSparqlConnection");
		tracker.Cursor = ctypes.StructType ("TrackerSparqlCursor");

		// GLib methods
		tracker.object_unref = tracker._lib.declare (
			"g_object_unref",
			ctypes.default_abi,
			ctypes.void_t,
			ctypes.void_t.ptr // Binding GObject* as a void* since we don't have GObject binding...
		);

		tracker.error_free = tracker._lib.declare (
			"g_error_free",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Error.ptr
		);

		// TrackerSparql methods (name, ABI, args with first arg = return type)
		tracker.connection_open = tracker._lib.declare (
			"tracker_sparql_connection_get",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_query = tracker._lib.declare (
			"tracker_sparql_connection_query",
			ctypes.default_abi,
			tracker.Cursor.ptr,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_update = tracker._lib.declare (
			"tracker_sparql_connection_update",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			ctypes.int32_t,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_next = tracker._lib.declare (
			"tracker_sparql_cursor_next",
			ctypes.default_abi,
			ctypes.bool,
			tracker.Cursor.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_get_string = tracker._lib.declare (
			"tracker_sparql_cursor_get_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			tracker.Cursor.ptr,
			ctypes.int,
			ctypes.long.ptr
		);

		tracker.escape_string = tracker._lib.declare (
			"tracker_sparql_escape_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			ctypes.char.ptr
		);

		return true;
	},

	shutdown: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		if (this._connection) {
			tracker.object_unref(this._connection);
		}

		if (this._lib) {
			this._lib.close ();
		}
	}
}
<|endoftext|>


<commit_before>'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var pageDataMgr = require('./pageDataMgr');
var request = require('request');
var fs = require('fs');
var _ = require('lodash');
var URI = require('URIjs');

var blacklistedEmails = require('./blacklistedEmails.json')

var collegeNamesDB = require('./databases/collegeNamesDB');
var termsDB = require('./databases/termsDB');
var subjectsDB = require('./databases/subjectsDB');
var classesDB = require('./databases/classesDB');
var sectionsDB = require('./databases/sectionsDB');

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

//tell all the db's to update every 15 min
collegeNamesDB.startUpdates();
termsDB.startUpdates();
subjectsDB.startUpdates();
classesDB.startUpdates();
sectionsDB.startUpdates();

var app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies

function logData (req) {
	console.log(JSON.stringify({
	  'ip':req.connection.remoteAddress,
	  'time':new Date().getTime(),
	  'userAgent':req.get('User-Agent'),
	  'referer':req.get('Referer'),
	  'method':req.method,
	  'url':req.url,
	  'body':req.body
	}));
}

//catch errors with invalid requests
app.use(function (err,req, res, next) {
	if (err) {
		logData(req);
		console.log('error: 400: ',err)
		res.status(400)
		res.send('ya dun goofed')
		res.end()
	}
	else {
		next();
	}
});

//change the url to lowercase
app.use(function (req,res,next) {
  req.url = req.url.toLowerCase();
  next();
})

// http://stackoverflow.com/a/46181/11236
// this is also done client side
function validateEmail(email) {
	if (!email) {
		return false;
	};

	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	if (!re.test(email)) {
		console.log('email failed regex',email)
		return false;
	}

	for (var i = 0; i < blacklistedEmails.length; i++) {
		if (_(email).endsWith(blacklistedEmails[i])) {
			console.log('email is blacklisted',email);
			return false;
		}
	}
	return true;
}

app.use(function (req, res, next) {
	logData(req);
	next()
});

//if no user agent present, drop request
app.use(function (req, res, next) {

	var ua = req.get('User-Agent');
	if (!ua) {
		console.log('info: dropping request without ua')
		res.status(418)
		res.send('trolololololol');
	}
	else {
		next()
	}
});

// app.post('/urlDetails', function(req, res) {

// 	if (!req.body || !req.body.url) {
// 		console.log('invalid req from '+req.ip);
// 		return;
// 	};

// 	//dont keep invalid emails
// 	if (!validateEmail(req.body.email)) {
// 		console.log('Invalid email rejected',req.body.email)
// 		req.body.email = null;
// 	};

// 	console.log('inbound data:',req.body)

// 	//client sent a (possibly) valid url, check and parse page

// 	var pageData = pageDataMgr.create({
// 		ip:req.connection.remoteAddress,
// 		email:req.body.email,
// 		dbData:{
// 			url:req.body.url
// 		}});

// 	pageDataMgr.go(pageData, function (err,pageData) {

// 		if (err) {
// 			//oh no! no modules support url
// 			res.send(JSON.stringify({
// 				reason:err
// 			}));
// 		}
// 		else {

// 			res.send(JSON.stringify({
// 				reason:"SUCCESS",
// 				clientString:pageData.getClientString()
// 			}));
// 		}
// 	});
// });

app.post('/listColleges',function (req,res) {
	collegeNamesDB.find({},{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,names) {
		if (err) {
			console.log('error college names failed',req.url,err);
			res.status(500);
			res.send('internal server error :/');
			return;
		};

		res.send(JSON.stringify(names));
	});
})

app.post('/listTerms',function (req,res) {

	if (!req.body.host) {
		console.log('error, no host given body:');
		console.log(req.body)
		res.send('{"error":"no host given (expected JSON)"}')
		return;
	};

	termsDB.find({host:req.body.host},{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,terms) {
		if (err) {
			res.status(500);
			res.send('internal server error :/')
			return;
		};

		res.send(JSON.stringify(terms));
	})
})

app.post('/listSubjects',function (req,res) {

	if (!req.body.host || !req.body.termId) {
		console.log('error, no host or termId given body:');
		console.log(req.body)
		res.status(400);
		res.send('{"error":"no host or termId given (expected JSON)"}')
		return;
	};

	subjectsDB.find({
		host:req.body.host,
		termId:req.body.termId
	},{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,subjects) {
		if (err) {
			console.log(err)
			res.status(500);
			res.send('internal server error :/')
			return;
		};

		res.send(JSON.stringify(subjects));
	})
})

app.post('/listClasses',function (req,res) {

	if (!req.body.host || !req.body.termId || !req.body.subject) {
		console.log('error, no host or termId or subject given body:');
		console.log(req.body)
		res.status(400);
		res.send('{"error":"no host or termId or subject given (expected JSON)"}')
		return;
	};

	var lookup = {
		host:req.body.host,
		termId:req.body.termId,
		subject:req.body.subject
	}

	//add classs id if its given
	if (req.body.classId) {
		lookup.classId=req.body.classId;
	};

	classesDB.find(lookup,{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,classes) {
		if (err) {
			console.log(err)
			res.status(500);
			res.send('internal server error :/')
			return;
		};
		res.send(JSON.stringify(classes));
	})
})

app.post('/listSections',function (req,res) {

	if (!req.body.host || !req.body.termId || !req.body.subject || !req.body.classId) {
		console.log('error, no host or termId or subject or classId given body:');
		console.log(req.body)
		res.send('{"error":"no host or termId or subject or classId given (expected JSON)"}')
		return;
	};

	var lookup = {
		host:req.body.host,
		termId:req.body.termId,
		subject:req.body.subject,
		classId:req.body.classId
	}

	if (req.body.crn) {
		lookup.crn = req.body.crn;
	}

	sectionsDB.find(lookup,{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,classes) {
		if (err) {
			console.log(err)
			res.status(500);
			res.send('internal server error :/')
			return;
		};
		res.send(JSON.stringify(classes));
	})
})

app.post('/search',function(req,res) {
  if (!req.body.value || !req.body.host || !req.body.termId || !req.body.subject) {
    console.log('error:no search value,host,termid, or subject given');
    console.log(req.body);
    res.send('ya dun goofed lol');
    return;
  }

  search.search(req.body,function (err,results) {
  	if (err) {
  		console.log(err);
  		res.send('{"error":"uh oh"}');
  		return;
  	}

  	console.log(JSON.stringify({count:results.length,searchTerm:req.body.value}));

  	res.send(results);
  }.bind(this));

  // console.log('searching for ')

  //add all of these attributes together and make sure each element of search.split(' ') is in the sum of strings

  //search through class descrption, classId, name subject

  //search through section crn, meetings(profs, where)

})

// serve the webpage
app.get('/', function (req, res) {
	res.sendFile('frontend/static/index.html',{"root": __dirname});
});

// add cache forever to external js libraries
app.get('/*', function (req, res,next) {
	if (_(req.path).startsWith('/js/external') || _(req.path).startsWith('/fonts')) {
	    res.setHeader('Cache-Control', 'public, max-age=31557600'); // one year
	}
	next()
});

app.use(express.static('frontend/static'));

app.get("/*", function(req, res, next) {

	console.log('error: 404: '+req.url)
	res.status(404);
	res.send('404, yo')
});

app.post("/*", function(req, res, next) {

	console.log('error: 404: '+req.url)
	res.status(404);
	res.send('404, yo')
});

app.listen(80);
<commit_msg>redirect to coursepro.io if not no coursepro.io or localhost<commit_after>'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var pageDataMgr = require('./pageDataMgr');
var request = require('request');
var fs = require('fs');
var _ = require('lodash');
var URI = require('URIjs');

var blacklistedEmails = require('./blacklistedEmails.json')

var collegeNamesDB = require('./databases/collegeNamesDB');
var termsDB = require('./databases/termsDB');
var subjectsDB = require('./databases/subjectsDB');
var classesDB = require('./databases/classesDB');
var sectionsDB = require('./databases/sectionsDB');

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

//tell all the db's to update every 15 min
collegeNamesDB.startUpdates();
termsDB.startUpdates();
subjectsDB.startUpdates();
classesDB.startUpdates();
sectionsDB.startUpdates();

var app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies

function logData (req) {
	console.log(JSON.stringify({
	  'ip':req.connection.remoteAddress,
	  'time':new Date().getTime(),
	  'userAgent':req.get('User-Agent'),
	  'referer':req.get('Referer'),
	  'method':req.method,
	  'url':req.url,
	  'body':req.body
	}));
}

//catch errors with invalid requests
app.use(function (err,req, res, next) {
	if (err) {
		logData(req);
		console.log('error: 400: ',err)
		res.status(400)
		res.send('ya dun goofed')
		res.end()
	}
	else {
		next();
	}
});

//if you didnt go to courespro.io, redirect to coursepro.io (going direcly to ip, etc)
app.use(function (req,res,next) {
	//send redirect request
	if (req.hostname!='coursepro.io' && req.hostname!='localhost') {
		console.log('Info: not on coursepro, on',req.hostname,'redirecting to coursepro.io')
		res.redirect('http://coursepro.io');
	}
	else {
	  next();
	}
})

//change the url to lowercase
app.use(function (req,res,next) {
  req.url = req.url.toLowerCase();
  next();
})

// http://stackoverflow.com/a/46181/11236
// this is also done client side
function validateEmail(email) {
	if (!email) {
		return false;
	};

	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	if (!re.test(email)) {
		console.log('email failed regex',email)
		return false;
	}

	for (var i = 0; i < blacklistedEmails.length; i++) {
		if (_(email).endsWith(blacklistedEmails[i])) {
			console.log('email is blacklisted',email);
			return false;
		}
	}
	return true;
}

app.use(function (req, res, next) {
	logData(req);
	next()
});

//if no user agent present, drop request
app.use(function (req, res, next) {

	var ua = req.get('User-Agent');
	if (!ua) {
		console.log('info: dropping request without ua')
		res.status(418)
		res.send('trolololololol');
	}
	else {
		next()
	}
});

// app.post('/urlDetails', function(req, res) {

// 	if (!req.body || !req.body.url) {
// 		console.log('invalid req from '+req.ip);
// 		return;
// 	};

// 	//dont keep invalid emails
// 	if (!validateEmail(req.body.email)) {
// 		console.log('Invalid email rejected',req.body.email)
// 		req.body.email = null;
// 	};

// 	console.log('inbound data:',req.body)

// 	//client sent a (possibly) valid url, check and parse page

// 	var pageData = pageDataMgr.create({
// 		ip:req.connection.remoteAddress,
// 		email:req.body.email,
// 		dbData:{
// 			url:req.body.url
// 		}});

// 	pageDataMgr.go(pageData, function (err,pageData) {

// 		if (err) {
// 			//oh no! no modules support url
// 			res.send(JSON.stringify({
// 				reason:err
// 			}));
// 		}
// 		else {

// 			res.send(JSON.stringify({
// 				reason:"SUCCESS",
// 				clientString:pageData.getClientString()
// 			}));
// 		}
// 	});
// });

app.post('/listColleges',function (req,res) {
	collegeNamesDB.find({},{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,names) {
		if (err) {
			console.log('error college names failed',req.url,err);
			res.status(500);
			res.send('internal server error :/');
			return;
		};

		res.send(JSON.stringify(names));
	});
})

app.post('/listTerms',function (req,res) {

	if (!req.body.host) {
		console.log('error, no host given body:');
		console.log(req.body)
		res.send('{"error":"no host given (expected JSON)"}')
		return;
	};

	termsDB.find({host:req.body.host},{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,terms) {
		if (err) {
			res.status(500);
			res.send('internal server error :/')
			return;
		};

		res.send(JSON.stringify(terms));
	})
})

app.post('/listSubjects',function (req,res) {

	if (!req.body.host || !req.body.termId) {
		console.log('error, no host or termId given body:');
		console.log(req.body)
		res.status(400);
		res.send('{"error":"no host or termId given (expected JSON)"}')
		return;
	};

	subjectsDB.find({
		host:req.body.host,
		termId:req.body.termId
	},{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,subjects) {
		if (err) {
			console.log(err)
			res.status(500);
			res.send('internal server error :/')
			return;
		};

		res.send(JSON.stringify(subjects));
	})
})

app.post('/listClasses',function (req,res) {

	if (!req.body.host || !req.body.termId || !req.body.subject) {
		console.log('error, no host or termId or subject given body:');
		console.log(req.body)
		res.status(400);
		res.send('{"error":"no host or termId or subject given (expected JSON)"}')
		return;
	};

	var lookup = {
		host:req.body.host,
		termId:req.body.termId,
		subject:req.body.subject
	}

	//add classs id if its given
	if (req.body.classId) {
		lookup.classId=req.body.classId;
	};

	classesDB.find(lookup,{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,classes) {
		if (err) {
			console.log(err)
			res.status(500);
			res.send('internal server error :/')
			return;
		};
		res.send(JSON.stringify(classes));
	})
})

app.post('/listSections',function (req,res) {

	if (!req.body.host || !req.body.termId || !req.body.subject || !req.body.classId) {
		console.log('error, no host or termId or subject or classId given body:');
		console.log(req.body)
		res.send('{"error":"no host or termId or subject or classId given (expected JSON)"}')
		return;
	};

	var lookup = {
		host:req.body.host,
		termId:req.body.termId,
		subject:req.body.subject,
		classId:req.body.classId
	}

	if (req.body.crn) {
		lookup.crn = req.body.crn;
	}

	sectionsDB.find(lookup,{
		shouldBeOnlyOne:false,
		sanatize:true
	},function (err,classes) {
		if (err) {
			console.log(err)
			res.status(500);
			res.send('internal server error :/')
			return;
		};
		res.send(JSON.stringify(classes));
	})
})

app.post('/search',function(req,res) {
  if (!req.body.value || !req.body.host || !req.body.termId || !req.body.subject) {
    console.log('error:no search value,host,termid, or subject given');
    console.log(req.body);
    res.send('ya dun goofed lol');
    return;
  }

  search.search(req.body,function (err,results) {
  	if (err) {
  		console.log(err);
  		res.send('{"error":"uh oh"}');
  		return;
  	}

  	console.log(JSON.stringify({count:results.length,searchTerm:req.body.value}));

  	res.send(results);
  }.bind(this));

  // console.log('searching for ')

  //add all of these attributes together and make sure each element of search.split(' ') is in the sum of strings

  //search through class descrption, classId, name subject

  //search through section crn, meetings(profs, where)

})

// serve the webpage
app.get('/', function (req, res) {
	res.sendFile('frontend/static/index.html',{"root": __dirname});
});

// add cache forever to external js libraries
app.get('/*', function (req, res,next) {
	if (_(req.path).startsWith('/js/external') || _(req.path).startsWith('/fonts')) {
	    res.setHeader('Cache-Control', 'public, max-age=31557600'); // one year
	}
	next()
});

app.use(express.static('frontend/static'));

app.get("/*", function(req, res, next) {

	console.log('error: 404: '+req.url)
	res.status(404);
	res.send('404, yo')
});

app.post("/*", function(req, res, next) {

	console.log('error: 404: '+req.url)
	res.status(404);
	res.send('404, yo')
});

app.listen(80);
<|endoftext|>


<commit_before>'use strict';
const ora       = require('ora');
const chalk     = require('chalk');
const execa     = require('execa');
const Listr     = require('listr');
const Table     = require('cli-table2');
const assign    = require('lodash/assign');
const Promise   = require('bluebird');
const inquirer  = require('inquirer');
const stripAnsi = require('strip-ansi');
const isFunction = require('lodash/isFunction');
const isObject = require('lodash/isObject');

const errors = require('../errors');
const CLIRenderer = require('./renderer');

const defaultOptions = {
    stdin: process.stdin,
    stdout: process.stdout,
    stderr: process.stderr,
    verbose: false,
    allowPrompt: true
};

class UI {
    constructor(options) {
        this.options = assign(defaultOptions, options);

        // Set up i/o streams
        this.stdin = this.options.stdin;
        this.stdout = this.options.stdout;
        this.stderr = this.options.stderr;
        this.verbose = this.options.verbose;
        this.allowPrompt = this.options.allowPrompt;

        // Add custom prompt module that uses the
        // specified streams
        this.inquirer = inquirer.createPromptModule({
            input: this.stdin,
            output: this.stdout
        });

        CLIRenderer.ui = this;
    }

    run(promiseOrFunction, name, options) {
        options = options || {};
        options.text = options.text || name;
        options.spinner = options.spinner || 'hamburger';
        options.stream = this.stdout;

        this.spinner = ora(options).start();

        return Promise.resolve(isFunction(promiseOrFunction) ? promiseOrFunction() : promiseOrFunction)
            .then((result) => {
                this.spinner.succeed();

                return Promise.resolve(result);
            }).catch((error) => {
                this.spinner.fail();

                return Promise.reject(error);
            }).finally(() => {
                this.spinner = null;
            });
    }

    table(head, body, options) {
        let table = new Table(assign({head: head}, options || {}));

        table.push.apply(table, body);
        this.log(table.toString());
    }

    prompt(prompts) {
        if (!this.allowPrompt) {
            throw new errors.SystemError('Prompts have been disabled, please provide options via command line flags');
        }

        return this.noSpin(() => this.inquirer(prompts));
    }

    listr(tasks, context, options) {
        let listrOpts = Object.assign({
            renderer: this.verbose ? 'verbose' : CLIRenderer
        }, options);

        let listr = new Listr(tasks, listrOpts);
        return context === false ? listr : listr.run(Object.assign(context || {}, { ui: this }));
    }

    sudo(command, options) {
        this.log(`Running sudo command: ${command}`, 'gray');

        return this.noSpin(() => {
            let execaOptions = assign({
                stdio: 'inherit'
            }, options || {});

            return execa.shell(
                `sudo ${command.replace(/^ghost/, process.argv.slice(0, 2).join(' '))}`,
                execaOptions
            );
        });
    }

    noSpin(promiseOrFunc) {
        if (this.spinner) {
            this.spinner.stop();
            this.spinner.paused = true;
        }

        return Promise.resolve(isFunction(promiseOrFunc) ? promiseOrFunc() : promiseOrFunc).then((result) => {
            if (this.spinner) {
                this.spinner.start();
                this.spinner.paused = false;
            }

            return result;
        });
    }

    log(message, color, stderr) {
        if (color) {
            message = chalk[color](message);
        }

        let stream = stderr ? 'stderr' : 'stdout';

        this[stream].write(`${this.spinner ? '\r' : ''}${message}\n`);
    }

    success(message) {
        return this.log(message, 'green');
    }

    fail(message) {
        return this.log(message, 'red');
    }

    /**
     * Error handler for the CLI. Takes a given error and outputs a formated and more human-readable
     * error to the specified out stream.
     *
     * @param {Error|Object} error Error to handle
     * @param {System} System object
     */
    error(error, system) {
        let debugInfo = this._formatDebug(system);

        if (error instanceof errors.CliError) {
            // Error is one that is generated by CLI usage (as in, the CLI itself
            // maunally generates this error)
            this.log(`A ${error.type} occured.\n`, 'red');

            // We always want to output the verbose error to the logfile, so we go ahead and get it now
            let verboseOutput = error.toString(true);

            // Log the verbose error if verbose is set, otherwise log the non-verbose error output
            this.log(this.verbose ? verboseOutput : error.toString(false), null, true);
            this.log(debugInfo, 'yellow');

            if (error.logToFile()) {
                let logLocation = system.writeErrorLog(stripAnsi(`${debugInfo}\n${verboseOutput}`));
                this.log(`\nAdditional log info available in: ${logLocation}`);
            }
        } else if (error instanceof Error) {
            // System errors or regular old errors go here.
            let output = `An error occurred.\n${chalk.yellow('Message:')} '${error.message}'\n\n`;

            if (!this.verbose) {
                this.log(output, 'red', true);
            }

            if (error.stack) {
                output += `${chalk.yellow('Stack:')} ${error.stack}\n`;
            }

            if (error.code) {
                output += `${chalk.yellow('Code:')} ${error.code}\n`;
            }

            if (error.path) {
                output += `${chalk.yellow('Path:')} ${error.path}\n`;
            }

            if (this.verbose) {
                this.log(output, 'red', true);
            }

            this.log(debugInfo, 'yellow');
            let logLocation = system.writeErrorLog(stripAnsi(`${debugInfo}\n${output}`));
            this.log(`\nAdditional log info available in: ${logLocation}`);
        } else if (isObject(error)) {
            // TODO: find better way to handle object errors?
            this.log(JSON.stringify(error), null, true);
        } else if (error !== false) {
            // If the error is false, we're just exiting (makes the promise chains easier)
            this.log('An unknown error occured.', null, true);
        }
    }

    _formatDebug(system) {
        return 'Debug Information:\n' +
            `    Node Version: ${process.version}\n` +
            `    Ghost-CLI Version: ${system.cliVersion}\n` +
            `    Environment: ${system.environment}\n` +
            `    Command: 'ghost ${process.argv.slice(2).join(' ')}'`;
    }
}

module.exports = UI;
<commit_msg>fix(ui): make the log method work better with spinners<commit_after>'use strict';
const ora       = require('ora');
const chalk     = require('chalk');
const execa     = require('execa');
const Listr     = require('listr');
const Table     = require('cli-table2');
const assign    = require('lodash/assign');
const Promise   = require('bluebird');
const inquirer  = require('inquirer');
const stripAnsi = require('strip-ansi');
const isFunction = require('lodash/isFunction');
const isObject = require('lodash/isObject');

const errors = require('../errors');
const CLIRenderer = require('./renderer');

const defaultOptions = {
    stdin: process.stdin,
    stdout: process.stdout,
    stderr: process.stderr,
    verbose: false,
    allowPrompt: true
};

class UI {
    constructor(options) {
        this.options = assign(defaultOptions, options);

        // Set up i/o streams
        this.stdin = this.options.stdin;
        this.stdout = this.options.stdout;
        this.stderr = this.options.stderr;
        this.verbose = this.options.verbose;
        this.allowPrompt = this.options.allowPrompt;

        // Add custom prompt module that uses the
        // specified streams
        this.inquirer = inquirer.createPromptModule({
            input: this.stdin,
            output: this.stdout
        });

        CLIRenderer.ui = this;
    }

    run(promiseOrFunction, name, options) {
        options = options || {};
        options.text = options.text || name;
        options.spinner = options.spinner || 'hamburger';
        options.stream = this.stdout;

        this.spinner = ora(options).start();

        return Promise.resolve(isFunction(promiseOrFunction) ? promiseOrFunction() : promiseOrFunction)
            .then((result) => {
                this.spinner.succeed();

                return Promise.resolve(result);
            }).catch((error) => {
                this.spinner.fail();

                return Promise.reject(error);
            }).finally(() => {
                this.spinner = null;
            });
    }

    table(head, body, options) {
        let table = new Table(assign({head: head}, options || {}));

        table.push.apply(table, body);
        this.log(table.toString());
    }

    prompt(prompts) {
        if (!this.allowPrompt) {
            throw new errors.SystemError('Prompts have been disabled, please provide options via command line flags');
        }

        return this.noSpin(() => this.inquirer(prompts));
    }

    listr(tasks, context, options) {
        let listrOpts = Object.assign({
            renderer: this.verbose ? 'verbose' : CLIRenderer
        }, options);

        let listr = new Listr(tasks, listrOpts);
        return context === false ? listr : listr.run(Object.assign(context || {}, { ui: this }));
    }

    sudo(command, options) {
        this.log(`Running sudo command: ${command}`, 'gray');

        return this.noSpin(() => {
            let execaOptions = assign({
                stdio: 'inherit'
            }, options || {});

            return execa.shell(
                `sudo ${command.replace(/^ghost/, process.argv.slice(0, 2).join(' '))}`,
                execaOptions
            );
        });
    }

    noSpin(promiseOrFunc) {
        if (this.spinner) {
            this.spinner.stop();
            this.spinner.paused = true;
        }

        return Promise.resolve(isFunction(promiseOrFunc) ? promiseOrFunc() : promiseOrFunc).then((result) => {
            if (this.spinner) {
                this.spinner.start();
                this.spinner.paused = false;
            }

            return result;
        });
    }

    log(message, color, stderr) {
        if (color) {
            message = chalk[color](message);
        }

        if (this.spinner) {
            this.spinner.stop();
            this.spinner.paused = true;
        }

        let stream = stderr ? 'stderr' : 'stdout';
        this[stream].write(`${message}\n`);

        if (this.spinner) {
            this.spinner.start();
            this.spinner.paused = false;
        }
    }

    success(message) {
        return this.log(message, 'green');
    }

    fail(message) {
        return this.log(message, 'red');
    }

    /**
     * Error handler for the CLI. Takes a given error and outputs a formated and more human-readable
     * error to the specified out stream.
     *
     * @param {Error|Object} error Error to handle
     * @param {System} System object
     */
    error(error, system) {
        let debugInfo = this._formatDebug(system);

        if (error instanceof errors.CliError) {
            // Error is one that is generated by CLI usage (as in, the CLI itself
            // maunally generates this error)
            this.log(`A ${error.type} occured.\n`, 'red');

            // We always want to output the verbose error to the logfile, so we go ahead and get it now
            let verboseOutput = error.toString(true);

            // Log the verbose error if verbose is set, otherwise log the non-verbose error output
            this.log(this.verbose ? verboseOutput : error.toString(false), null, true);
            this.log(debugInfo, 'yellow');

            if (error.logToFile()) {
                let logLocation = system.writeErrorLog(stripAnsi(`${debugInfo}\n${verboseOutput}`));
                this.log(`\nAdditional log info available in: ${logLocation}`);
            }
        } else if (error instanceof Error) {
            // System errors or regular old errors go here.
            let output = `An error occurred.\n${chalk.yellow('Message:')} '${error.message}'\n\n`;

            if (!this.verbose) {
                this.log(output, 'red', true);
            }

            if (error.stack) {
                output += `${chalk.yellow('Stack:')} ${error.stack}\n`;
            }

            if (error.code) {
                output += `${chalk.yellow('Code:')} ${error.code}\n`;
            }

            if (error.path) {
                output += `${chalk.yellow('Path:')} ${error.path}\n`;
            }

            if (this.verbose) {
                this.log(output, 'red', true);
            }

            this.log(debugInfo, 'yellow');
            let logLocation = system.writeErrorLog(stripAnsi(`${debugInfo}\n${output}`));
            this.log(`\nAdditional log info available in: ${logLocation}`);
        } else if (isObject(error)) {
            // TODO: find better way to handle object errors?
            this.log(JSON.stringify(error), null, true);
        } else if (error !== false) {
            // If the error is false, we're just exiting (makes the promise chains easier)
            this.log('An unknown error occured.', null, true);
        }
    }

    _formatDebug(system) {
        return 'Debug Information:\n' +
            `    Node Version: ${process.version}\n` +
            `    Ghost-CLI Version: ${system.cliVersion}\n` +
            `    Environment: ${system.environment}\n` +
            `    Command: 'ghost ${process.argv.slice(2).join(' ')}'`;
    }
}

module.exports = UI;
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import chroma from 'chroma-js'
import styled from 'styled-components'
import {Box, Text} from '@primer/components'
import {colors, getPaletteByName} from './color-variables'
import Table from './Table'

export function PaletteTable(props) {
  const {children, columns, name, type, sparse, prefix = type, ...rest} = props
  const cols = columns.map(name => PaletteTable.columns[name]).filter(d => d)
  let {values} = getPaletteByName(name)
  if (sparse && values) {
    values = values.filter(v => v.aliases[type])
  }
  if (!values || values.length === 0) {
    return null
  }
  return (

      {children}

          {cols.map(col => (
            {col.title}
          ))}

        {values.map(value => {
          const cellProps = {
            type,
            prefix,
            width: 1 / columns.length,
            ...value
          }
          return (

              {cols.map(({Cell, title}) => (
                <Cell key={title} {...cellProps} />
              ))}

          )
        })}

  )
}

PaletteTable.defaultProps = {
  type: 'bg',
  columns: ['alias', 'className', 'variable', 'value']
}

PaletteTable.columns = {
  variable: {
    title: 'Variable',
    Cell: props => (
      <PaletteCell {...props}>
        <Var>${props.variable}</Var>
      </PaletteCell>
    )
  },
  value: {
    title: 'Value',
    Cell: props => (
      <PaletteCell {...props}>
        <Var>{props.value}</Var>
      </PaletteCell>
    )
  },
  className: {
    title: 'Class',
    Cell: props => (
      <PaletteCell {...props}>
        <Var>
          .{props.prefix}-{props.slug}
        </Var>
      </PaletteCell>
    )
  },
  alias: {
    title: 'Alias',
    Cell: ({aliases, ...props}) =>
      aliases[props.type] ? (
        <PaletteCell {...props}>
          <Var>.{aliases[props.type]}</Var>
        </PaletteCell>
      ) : (

      )
  }
}

PaletteTable.propTypes = {
  columns: PropTypes.arrayOf(PropTypes.oneOf(Object.keys(PaletteTable.columns))),
  name: PropTypes.string.isRequired,
  prefix: PropTypes.string,
  type: PropTypes.string
}

export function PaletteCell({value, type, ...rest}) {
  const props = {}
  switch (type) {
    case 'fg':
    case 'text':
      props.color = value
      props.bg = overlayColor(value)
      break
    case 'border':
      props.bg = 'white'
      props.style = {border: `1px solid ${value} !important`}
      break
    case 'bg':
    default:
      props.bg = value
      props.color = overlayColor(value)
  }
  return <Box {...props} {...rest} />
}

PaletteCell.defaultProps = {
  as: 'td'
}

PaletteCell.propTypes = {
  type: PropTypes.oneOf(['text', 'border', 'bg']),
  value: PropTypes.string.isRequired
}

export const Var = styled(Text).attrs({
  as: 'var',
  fontFamily: 'mono',
  fontSize: 1,
  fontStyle: 'normal'
})`
  white-space: nowrap;
`

const overlayColorCache = new Map()
export function overlayColor(bg) {
  if (!bg) {
    throw new Error(`overlayColor() expects a color string, but got: ${JSON.stringify(bg)}`)
  }
  if (overlayColorCache.has(bg)) {
    return overlayColorCache.get(bg)
  } else {
    const result = chroma(bg).luminance() > 0.5 ? colors.black : colors.white
    overlayColorCache.set(bg, result)
    return result
  }
}
<commit_msg>refactor PaletteTable and make columns more configurable<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import chroma from 'chroma-js'
import styled from 'styled-components'
import {Box, Text} from '@primer/components'
import {colors, getPaletteByName} from './color-variables'
import Table from './Table'

export function PaletteTable(props) {
  const {children, columns, hasHeader, name, type, sparse, prefix = type, ...rest} = props
  const cols = columns.map(col => PaletteTable.columns[col] || col).filter(col => col)

  let values = props.values
  if (name) {
    values = getPaletteByName(name).values
  }
  if (sparse && values) {
    values = values.filter(v => v.aliases[type])
  }
  if (!values || values.length === 0) {
    return null
  }

  return (

      {children}
      {hasHeader ? (

            {cols.map(col => (
              {col.title}
            ))}

      ) : null}

        {values.map(row => {
          const cellProps = {type, width: 1 / columns.length, ...row}
          const valueProps = {prefix, type, ...row}
          return (

              {cols.map(({Cell = PaletteCell, Value = PaletteValue, title}) => (
                <Cell key={title} {...cellProps}>
                  <Value {...valueProps} />
                </Cell>
              ))}

          )
        })}

  )
}

PaletteTable.defaultProps = {
  type: 'bg',
  columns: ['alias', 'className', 'variable', 'value'],
  hasHeader: true
}

PaletteTable.propTypes = {
  columns: PropTypes.arrayOf(
    PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.shape({
        title: PropTypes.string,
        Cell: PropTypes.func
      })
    ])
  ),
  name: PropTypes.string,
  prefix: PropTypes.string,
  type: PropTypes.string,
  values: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.string,
      aliases: PropTypes.object
    })
  )
}

export function PaletteCell(props) {
  return <Box {...props} />
}

PaletteCell.defaultProps = {
  as: 'td'
}

PaletteCell.propTypes = {
  value: PropTypes.string.isRequired
}

PaletteCell.Alias = ({aliases, type, ...rest}) =>
  aliases && aliases[type] ? (
    <PaletteCell.Generic type={type} {...rest}>
      <Var>.{aliases[type]}</Var>
    </PaletteCell.Generic>
  ) : (

  )
PaletteCell.Alias.propTypes = {
  aliases: PropTypes.object.isRequired,
  type: PropTypes.string.isRequired
}

PaletteCell.Generic = ({type, ...rest}) => {
  switch (type) {
    case 'fg':
    case 'text':
      return <PaletteCell.Text {...rest} />
    case 'border':
      return <PaletteCell.Border {...rest} />
    case 'bg':
    default:
      return <PaletteCell.Background {...rest} />
  }
}

PaletteCell.Background = ({value, ...rest}) => <PaletteCell bg={value} color={overlayColor(value)} {...rest} />

PaletteCell.Text = ({value, ...rest}) => <PaletteCell color={value} bg={overlayColor(value)} {...rest} />

PaletteCell.Border = ({value, ...rest}) => (
  <PaletteCell bg="white" style={{border: `1px solid ${value} !important`}} {...rest} />
)

export function PaletteValue({value, ...rest}) {
  return <Var {...rest}>{value}</Var>
}

PaletteValue.Variable = ({variable}) => <Var>${variable}</Var>
PaletteValue.Variable.propTypes = {
  variable: PropTypes.string.isRequired
}

PaletteValue.PrefixedClass = ({prefix, slug}) => (
  <Var>
    .{prefix}-{slug}
  </Var>
)
PaletteValue.PrefixedClass.propTypes = {
  prefix: PropTypes.string.isRequired,
  slug: PropTypes.string.isRequired
}

PaletteTable.columns = {
  variable: {
    title: 'Variable',
    Cell: PaletteCell.Background,
    Value: PaletteValue.Variable
  },
  value: {
    title: 'Value',
    Cell: PaletteCell.Background,
    Value: PaletteValue
  },
  background: {
    title: 'Background',
    Cell: PaletteCell.Background,
    Value: PaletteCell.PrefixedClass
  },
  foreground: {
    title: 'Foreground',
    Cell: PaletteCell.Text,
    Value: PaletteCell.PrefixedClass
  },
  className: {
    title: 'Class',
    Cell: PaletteCell.Background,
    Value: PaletteValue.PrefixedClass
  },
  alias: {
    title: 'Alias',
    Cell: PaletteCell.Alias
  }
}

export const Var = styled(Text).attrs({
  as: 'var',
  fontFamily: 'mono',
  fontSize: 1,
  fontStyle: 'normal'
})`
  white-space: nowrap;
`

const overlayColorCache = new Map()
export function overlayColor(bg) {
  if (!bg) {
    throw new Error(`overlayColor() expects a color string, but got: ${JSON.stringify(bg)}`)
  }
  if (overlayColorCache.has(bg)) {
    return overlayColorCache.get(bg)
  } else {
    const result = chroma(bg).luminance() > 0.5 ? colors.black : colors.white
    overlayColorCache.set(bg, result)
    return result
  }
}
<|endoftext|>


<commit_before><commit_msg>add diagram of expected pixels in cspunit3 test<commit_after><|endoftext|>


<commit_before>const OFF = 0;
const WARN = 1;
const ERROR = 2;

module.exports = {
  'env': {
    'es6': true,
    'node': true,
    'mocha': true,
    'browser': true
  },
  'extends': 'eslint:recommended',
  'parser': 'babel-eslint',
  'parserOptions': {
    'sourceType': 'module'
  },
  'plugins': [
    'no-class'
  ],
  'rules': {
    // Possible Errors
    'no-extra-parens': [ERROR, 'all', {
      'conditionalAssign': false,
      'returnAssign': false,
      'nestedBinaryExpressions': false
    }],
    'no-template-curly-in-string': [ERROR],

    // Best Practices
    'accessor-pairs': [ERROR],
    'complexity': [ERROR, 20],
    'curly': [ERROR],
    'dot-location': [ERROR, 'property'],
    'dot-notation': [ERROR],
    'eqeqeq': [ERROR, 'smart'],
    'no-caller': [ERROR],
    'no-else-return': [ERROR],
    'no-extend-native': [ERROR],
    'no-extra-bind': [ERROR],
    'no-floating-decimal': [ERROR],
    'no-implied-eval': [ERROR],
    'no-iterator': [ERROR],
    'no-labels': [ERROR],
    'no-lone-blocks': [ERROR],
    'no-multi-str': [ERROR],
    'no-new': [ERROR],
    'no-new-func': [ERROR],
    'no-new-wrappers': [ERROR],
    'no-octal-escape': [ERROR],
    'no-param-reassign': [ERROR],
    'no-proto': [ERROR],
    'no-return-assign': [ERROR],
    'no-self-compare': [ERROR],
    'no-sequences': [ERROR],
    'no-throw-literal': [ERROR],
    'no-unmodified-loop-condition': [ERROR],
    'no-useless-call': [ERROR],
    'no-useless-escape': [ERROR],
    'no-void': [ERROR],
    'no-with': [ERROR],
    'wrap-iife': [ERROR, 'any'],
    'yoda': [ERROR],

    // Strict Mode
    'strict': [ERROR],

    // Variables
    'no-label-var': [ERROR],
    'no-shadow-restricted-names': [ERROR],
    'no-undef-init': [ERROR],

    // Stylistic Issues
    'array-bracket-spacing': [ERROR, 'never'],
    'block-spacing': [ERROR],
    'brace-style': [ERROR, '1tbs', {
      'allowSingleLine': true
    }],
    'camelcase': [ERROR, {
      'properties': 'never'
    }],
    'comma-spacing': [ERROR, {
      'before': false,
      'after': true
    }],
    'comma-style': [ERROR],
    'computed-property-spacing': [ERROR, 'never'],
    'consistent-this': [ERROR, 'self'],
    'eol-last': [ERROR],
    'func-call-spacing': [ERROR, 'never'],
    'func-name-matching': [ERROR],
    'indent': [ERROR, 2, {
      'SwitchCase': 1
    }],
    'key-spacing': [ERROR, {
      'beforeColon': false,
      'afterColon': true,
      'mode': 'minimum'
    }],
    'keyword-spacing': [ERROR],
    'max-len': [ERROR, 120],
    'max-lines': [ERROR, {
      'max': 300,
      'skipBlankLines': true,
      'skipComments': true
    }],
    'no-lonely-if': [ERROR],
    'no-multiple-empty-lines': [ERROR, {
      max: 1
    }],
    'no-new-object': [ERROR],
    'no-tabs': [ERROR],
    'no-trailing-spaces': [ERROR],
    'no-unneeded-ternary': [ERROR],
    'no-whitespace-before-property': [ERROR],
    'object-property-newline': [ERROR, {
      'allowMultiplePropertiesPerLine': true
    }],
    'one-var': [ERROR, {
      'initialized': 'never'
    }],
    'operator-linebreak': [ERROR],
    'padded-blocks': [ERROR, 'never'],
    'quotes': [ERROR, 'single'],
    'semi': [ERROR],
    'semi-spacing': [ERROR],
    'space-before-blocks': [ERROR],
    'space-before-function-paren': [ERROR, {
      'anonymous': 'always',
      'named': 'never',
      'asyncArrow': 'ignore'
    }],
    'space-in-parens': [ERROR, 'never'],
    'space-infix-ops': [ERROR],
    'space-unary-ops': [ERROR , {
      'words': true,
      'nonwords': false
    }],
    'spaced-comment': [ERROR, 'always', {
      'line': {
        'markers': ['/'],
        'exceptions': ['-', '+']
      },
      'block': {
        'markers': ['!'],
        'exceptions': ['*'],
        'balanced': true
      }
    }],

    // ECMAScript 6
    'arrow-parens': [ERROR, 'always'],
    'arrow-spacing': [ERROR],
    'generator-star-spacing': [ERROR],
    'no-duplicate-imports': [ERROR],
    'no-useless-computed-key': [ERROR],
    'no-useless-rename': [ERROR],
    'no-var': [ERROR],
    'object-shorthand': [ERROR],
    'prefer-arrow-callback': [ERROR],
    'prefer-const': [ERROR],
    'prefer-numeric-literals': [ERROR],
    'prefer-rest-params': [ERROR],
    'prefer-spread': [ERROR],
    'rest-spread-spacing': [ERROR],
    'template-curly-spacing': [ERROR],
    'yield-star-spacing': [ERROR],

    // Plugin rules
    'no-class/no-class': [ERROR]
  }
};
<commit_msg>Adjusted linter for generator star spacing<commit_after>const OFF = 0;
const WARN = 1;
const ERROR = 2;

module.exports = {
  'env': {
    'es6': true,
    'node': true,
    'mocha': true,
    'browser': true
  },
  'extends': 'eslint:recommended',
  'parser': 'babel-eslint',
  'parserOptions': {
    'sourceType': 'module'
  },
  'plugins': [
    'no-class'
  ],
  'rules': {
    // Possible Errors
    'no-extra-parens': [ERROR, 'all', {
      'conditionalAssign': false,
      'returnAssign': false,
      'nestedBinaryExpressions': false
    }],
    'no-template-curly-in-string': [ERROR],

    // Best Practices
    'accessor-pairs': [ERROR],
    'complexity': [ERROR, 20],
    'curly': [ERROR],
    'dot-location': [ERROR, 'property'],
    'dot-notation': [ERROR],
    'eqeqeq': [ERROR, 'smart'],
    'no-caller': [ERROR],
    'no-else-return': [ERROR],
    'no-extend-native': [ERROR],
    'no-extra-bind': [ERROR],
    'no-floating-decimal': [ERROR],
    'no-implied-eval': [ERROR],
    'no-iterator': [ERROR],
    'no-labels': [ERROR],
    'no-lone-blocks': [ERROR],
    'no-multi-str': [ERROR],
    'no-new': [ERROR],
    'no-new-func': [ERROR],
    'no-new-wrappers': [ERROR],
    'no-octal-escape': [ERROR],
    'no-param-reassign': [ERROR],
    'no-proto': [ERROR],
    'no-return-assign': [ERROR],
    'no-self-compare': [ERROR],
    'no-sequences': [ERROR],
    'no-throw-literal': [ERROR],
    'no-unmodified-loop-condition': [ERROR],
    'no-useless-call': [ERROR],
    'no-useless-escape': [ERROR],
    'no-void': [ERROR],
    'no-with': [ERROR],
    'wrap-iife': [ERROR, 'any'],
    'yoda': [ERROR],

    // Strict Mode
    'strict': [ERROR],

    // Variables
    'no-label-var': [ERROR],
    'no-shadow-restricted-names': [ERROR],
    'no-undef-init': [ERROR],

    // Stylistic Issues
    'array-bracket-spacing': [ERROR, 'never'],
    'block-spacing': [ERROR],
    'brace-style': [ERROR, '1tbs', {
      'allowSingleLine': true
    }],
    'camelcase': [ERROR, {
      'properties': 'never'
    }],
    'comma-spacing': [ERROR, {
      'before': false,
      'after': true
    }],
    'comma-style': [ERROR],
    'computed-property-spacing': [ERROR, 'never'],
    'consistent-this': [ERROR, 'self'],
    'eol-last': [ERROR],
    'func-call-spacing': [ERROR, 'never'],
    'func-name-matching': [ERROR],
    'indent': [ERROR, 2, {
      'SwitchCase': 1
    }],
    'key-spacing': [ERROR, {
      'beforeColon': false,
      'afterColon': true,
      'mode': 'minimum'
    }],
    'keyword-spacing': [ERROR],
    'max-len': [ERROR, 120],
    'max-lines': [ERROR, {
      'max': 300,
      'skipBlankLines': true,
      'skipComments': true
    }],
    'no-lonely-if': [ERROR],
    'no-multiple-empty-lines': [ERROR, {
      max: 1
    }],
    'no-new-object': [ERROR],
    'no-tabs': [ERROR],
    'no-trailing-spaces': [ERROR],
    'no-unneeded-ternary': [ERROR],
    'no-whitespace-before-property': [ERROR],
    'object-property-newline': [ERROR, {
      'allowMultiplePropertiesPerLine': true
    }],
    'one-var': [ERROR, {
      'initialized': 'never'
    }],
    'operator-linebreak': [ERROR],
    'padded-blocks': [ERROR, 'never'],
    'quotes': [ERROR, 'single'],
    'semi': [ERROR],
    'semi-spacing': [ERROR],
    'space-before-blocks': [ERROR],
    'space-before-function-paren': [ERROR, {
      'anonymous': 'always',
      'named': 'never',
      'asyncArrow': 'ignore'
    }],
    'space-in-parens': [ERROR, 'never'],
    'space-infix-ops': [ERROR],
    'space-unary-ops': [ERROR , {
      'words': true,
      'nonwords': false
    }],
    'spaced-comment': [ERROR, 'always', {
      'line': {
        'markers': ['/'],
        'exceptions': ['-', '+']
      },
      'block': {
        'markers': ['!'],
        'exceptions': ['*'],
        'balanced': true
      }
    }],

    // ECMAScript 6
    'arrow-parens': [ERROR, 'always'],
    'arrow-spacing': [ERROR],
    'generator-star-spacing': [ERROR, {
      'before': false,
      'after': true
    }],
    'no-duplicate-imports': [ERROR],
    'no-useless-computed-key': [ERROR],
    'no-useless-rename': [ERROR],
    'no-var': [ERROR],
    'object-shorthand': [ERROR],
    'prefer-arrow-callback': [ERROR],
    'prefer-const': [ERROR],
    'prefer-numeric-literals': [ERROR],
    'prefer-rest-params': [ERROR],
    'prefer-spread': [ERROR],
    'rest-spread-spacing': [ERROR],
    'template-curly-spacing': [ERROR],
    'yield-star-spacing': [ERROR],

    // Plugin rules
    'no-class/no-class': [ERROR]
  }
};
<|endoftext|>


<commit_before>a = [["]", "#_ARSCR"],
     ["[", "#_ARSCL"],
     ["(", "#_PARL"],
     [")", "#_PARR"],
     ["=", "#_EQOP"]]

load_lang = function() {
    obj = {rules:[]};
    a.forEach(function(v, i) {
	obj.rules.push([v[0], encodeURIComponent($(v[1]).val() || $(v[1]).attr('placeholder'))]);
    });
    return JSON.stringify(obj);
}

$(document).ready(function() {
    function showHiddenParagraphs() {
        $("p.hidden").fadeIn(500);
    }
    setTimeout(showHiddenParagraphs, 1000);
    a.forEach(function(v, i) {
	$(v[1]).change(function() {
	    $.ajax({
		url: "/translate",
		success: function(data) {
		    $("#thacode").text(data);
		},
		data: load_lang()
	    });
	});
    }
    $.ajax({
	url: "/translate",
	success: function(data) {
	    $("#thacode").text(data);
	},
	data: load_lang()
    });
    $("#code_reload").click(
	function() {
	    $.ajax({
		url: "/translate",
		success: function(data) {
		    $("#thacode").text(data);
		},
		data: load_lang()
	    });
	}
    );
});
<commit_msg>Fix typo<commit_after>a = [["]", "#_ARSCR"],
     ["[", "#_ARSCL"],
     ["(", "#_PARL"],
     [")", "#_PARR"],
     ["=", "#_EQOP"]]

load_lang = function() {
    obj = {rules:[]};
    a.forEach(function(v, i) {
	obj.rules.push([v[0], encodeURIComponent($(v[1]).val() || $(v[1]).attr('placeholder'))]);
    });
    return JSON.stringify(obj);
}

$(document).ready(function() {
    function showHiddenParagraphs() {
        $("p.hidden").fadeIn(500);
    }
    setTimeout(showHiddenParagraphs, 1000);
    a.forEach(function(v, i) {
	$(v[1]).change(function() {
	    $.ajax({
		url: "/translate",
		success: function(data) {
		    $("#thacode").text(data);
		},
		data: load_lang()
	    });
	});
    });
    $.ajax({
	url: "/translate",
	success: function(data) {
	    $("#thacode").text(data);
	},
	data: load_lang()
    });
    $("#code_reload").click(
	function() {
	    $.ajax({
		url: "/translate",
		success: function(data) {
		    $("#thacode").text(data);
		},
		data: load_lang()
	    });
	}
    );
});
<|endoftext|>


<commit_before><commit_msg>Refresh display on texture load for ground.<commit_after><|endoftext|>