commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
d5bd4d7464121bba9c3464cd0194beedee273cbc
client/lib/js/constants/application_constants.js
client/lib/js/constants/application_constants.js
export const FLASK_BASE_URL = process.env.FLASK_BASE_URL; export const API_PATH = `${FLASK_BASE_PATH}/api/`; export default { API_PATH, FLASK_BASE_URL };
export const FLASK_BASE_URL = process.env.FLASK_BASE_URL; export const API_PATH = `${FLASK_BASE_URL}/api/`; export default { API_PATH, FLASK_BASE_URL };
Fix variable typo for FLASK_BASE_URL in app constants
Fix variable typo for FLASK_BASE_URL in app constants
JavaScript
apache-2.0
bigchaindb/bigchaindb-examples,bigchaindb/bigchaindb-examples,bigchaindb/bigchaindb-examples
--- +++ @@ -1,5 +1,5 @@ export const FLASK_BASE_URL = process.env.FLASK_BASE_URL; -export const API_PATH = `${FLASK_BASE_PATH}/api/`; +export const API_PATH = `${FLASK_BASE_URL}/api/`; export default { API_PATH,
8b65390d14ef9e8da29a46092650866d24609042
browser-test-config/browserstack-karma.js
browser-test-config/browserstack-karma.js
var baseKarma = require('./base-karma') module.exports = function(config) { var baseConfig = baseKarma(config); config.set(Object.assign(baseConfig, { browsers: [ 'bs_firefox_android', 'bs_chrome_mac', 'bs_ie_11', 'bs_edge', ], reporters: [ 'mocha', 'BrowserStack', ], client: { mocha: { reporter: 'html', } }, browserStack: { startTunnel: true }, customLaunchers: { bs_firefox_android: { base: 'BrowserStack', browser: 'Android Browser', real_mobile: true, device: 'Samsung Galaxy S8', os: 'android', os_version: '7.0', }, bs_chrome_mac: { base: 'BrowserStack', browser: 'Chrome', browser_version: '66', os: 'OS X', os_version: 'High Sierra', }, bs_ie_11: { base: 'BrowserStack', browser: 'IE', browser_version: '11', os: 'Windows', os_version: '7', }, bs_edge: { base: 'BrowserStack', browser: 'Edge', browser_version: '16', os: 'Windows', os_version: '10', }, }, })); };
var baseKarma = require('./base-karma') module.exports = function(config) { var baseConfig = baseKarma(config); config.set(Object.assign(baseConfig, { browsers: [ 'bs_firefox_android', 'bs_chrome_mac', 'bs_ie_11', 'bs_edge', ], reporters: [ 'mocha', 'BrowserStack', ], client: { mocha: { reporter: 'html', } }, browserStack: { startTunnel: true }, customLaunchers: { bs_firefox_android: { base: 'BrowserStack', browser: 'Android Browser', real_mobile: true, device: 'Samsung Galaxy S8', os: 'android', os_version: '7.0', }, bs_chrome_mac: { base: 'BrowserStack', browser: 'Chrome', browser_version: '66', os: 'OS X', os_version: 'High Sierra', }, bs_ie_11: { base: 'BrowserStack', browser: 'IE', browser_version: '11', os: 'Windows', os_version: '7', }, bs_edge: { base: 'BrowserStack', browser: 'Edge', browser_version: '17', os: 'Windows', os_version: '10', }, }, })); };
Test Edge 17 instead of 16
Test Edge 17 instead of 16
JavaScript
apache-2.0
josdejong/mathjs,josdejong/mathjs,josdejong/mathjs,FSMaxB/mathjs,FSMaxB/mathjs,josdejong/mathjs,FSMaxB/mathjs,FSMaxB/mathjs,josdejong/mathjs,FSMaxB/mathjs
--- +++ @@ -48,7 +48,7 @@ bs_edge: { base: 'BrowserStack', browser: 'Edge', - browser_version: '16', + browser_version: '17', os: 'Windows', os_version: '10', },
3c2b0a9140c8dd101bf6e277550e156af3fc8acc
test/fluce-component.spec.js
test/fluce-component.spec.js
/* @flow */ import React from 'react' import {addons} from 'react/addons' var {TestUtils} = addons var {createRenderer} = TestUtils import Fluce from '../src/fluce-component' import createFluce from '../src/create-fluce' describe('<Fluce />', () => { it('Should throw when rendered with many children', () => { var renderer = createRenderer() var err: any try { renderer.render(<Fluce><div/><div/></Fluce>) } catch (e) { err = e } expect(err.message).toBe('Invariant Violation: onlyChild must be passed a children with exactly one child.') }) it('Should pass `fluce` to the child', () => { var fluce = createFluce() var renderer = createRenderer() renderer.render(<Fluce fluce={fluce}><div foo='bar' /></Fluce>) var result = renderer.getRenderOutput() expect(result.type).toBe('div') expect(result.props).toEqual({foo: 'bar', fluce}) }) it('This should fail', () => { expect(1).toBe(2) }) })
/* @flow */ import React from 'react' import {addons} from 'react/addons' var {TestUtils} = addons var {createRenderer} = TestUtils import Fluce from '../src/fluce-component' import createFluce from '../src/create-fluce' describe('<Fluce />', () => { it('Should throw when rendered with many children', () => { var renderer = createRenderer() var err: any try { renderer.render(<Fluce><div/><div/></Fluce>) } catch (e) { err = e } expect(err.message).toBe('Invariant Violation: onlyChild must be passed a children with exactly one child.') }) it('Should pass `fluce` to the child', () => { var fluce = createFluce() var renderer = createRenderer() renderer.render(<Fluce fluce={fluce}><div foo='bar' /></Fluce>) var result = renderer.getRenderOutput() expect(result.type).toBe('div') expect(result.props).toEqual({foo: 'bar', fluce}) }) })
Revert "check if travis works"
Revert "check if travis works" This reverts commit fbd645ae10b6b8c41befe416765ea7b6bc3343d9.
JavaScript
mit
rpominov/fluce,rpominov/fluce
--- +++ @@ -36,9 +36,5 @@ expect(result.props).toEqual({foo: 'bar', fluce}) }) - it('This should fail', () => { - expect(1).toBe(2) - }) - })
08e299491da581b1d64d8fda499a0fd94d8427a1
client/ember/tests/unit/models/config-test.js
client/ember/tests/unit/models/config-test.js
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('config'); test('it exists', function(assert) { var model = this.subject(); // var store = this.store(); assert.ok(!!model); });
import { moduleForModel, test } from 'ember-qunit'; import Ember from 'ember'; var configMock = { id: 1, images: { base_url: "http://image.tmdb.org/t/p/", secure_base_url: "https://image.tmdb.org/t/p/", backdrop_sizes: [ "w300", "w780", "w1280", "original" ], logo_sizes: [ "w45", "w92", "w154", "w185", "w300", "w500", "original" ], poster_sizes: [ "w92", "w154", "w185", "w342", "w500", "w780", "original" ], profile_sizes: [ "w45", "w185", "h632", "original" ], still_sizes: [ "w92", "w185", "w300", "original" ] } }; moduleForModel('config'); test('It stores movies', function() { var store = this.store(); var record = null; Ember.run(function() { store.createRecord('config', configMock); record = store.find('config', 1); }); equal(record.get('images.base_url'), configMock.images.base_url); equal(record.get('images.secure_base_url'), configMock.images.secure_base_url); equal(record.get('images.backdrop_sizes'), configMock.images.backdrop_sizes); });
Add test for config model
Add test for config model
JavaScript
mit
ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix
--- +++ @@ -1,12 +1,64 @@ import { moduleForModel, test -} from 'ember-qunit'; +} +from 'ember-qunit'; +import Ember from 'ember'; + +var configMock = { + id: 1, + images: { + base_url: "http://image.tmdb.org/t/p/", + secure_base_url: "https://image.tmdb.org/t/p/", + backdrop_sizes: [ + "w300", + "w780", + "w1280", + "original" + ], + logo_sizes: [ + "w45", + "w92", + "w154", + "w185", + "w300", + "w500", + "original" + ], + poster_sizes: [ + "w92", + "w154", + "w185", + "w342", + "w500", + "w780", + "original" + ], + profile_sizes: [ + "w45", + "w185", + "h632", + "original" + ], + still_sizes: [ + "w92", + "w185", + "w300", + "original" + ] + } +}; moduleForModel('config'); -test('it exists', function(assert) { - var model = this.subject(); - // var store = this.store(); - assert.ok(!!model); +test('It stores movies', function() { + var store = this.store(); + var record = null; + Ember.run(function() { + store.createRecord('config', configMock); + record = store.find('config', 1); + }); + equal(record.get('images.base_url'), configMock.images.base_url); + equal(record.get('images.secure_base_url'), configMock.images.secure_base_url); + equal(record.get('images.backdrop_sizes'), configMock.images.backdrop_sizes); });
4e771acd0015b67506747ff16ce0c971884fea8e
compiler/ast/FunctionDeclaration.js
compiler/ast/FunctionDeclaration.js
'use strict'; var Node = require('./Node'); var ok = require('assert').ok; class FunctionDeclaration extends Node { constructor(def) { super('FunctionDeclaration'); this.name = def.name; this.params = def.params; this.body = this.makeContainer(def.body); } generateCode(codegen) { var name = this.name; var params = this.params; var body = this.body; var statement = this.statement; if (name != null) { ok(typeof name === 'string', 'Function name should be a string'); } codegen.write('function' + (name ? ' ' + name : '') + '('); if (params && params.length) { for (let i=0, paramsLen = params.length; i<paramsLen; i++) { if (i !== 0) { codegen.write(', '); } var param = params[i]; if (typeof param === 'string') { codegen.write(param); } else { if (param.type !== 'Identifier') { throw new Error('Illegal param: ' + param); } codegen.generateCode(param); } } } codegen.write(') '); var oldInFunction = codegen.inFunction; codegen.inFunction = true; codegen.generateBlock(body); codegen.inFunction = oldInFunction; if (statement) { codegen.write('\n'); } } isCompoundExpression() { return true; } } module.exports = FunctionDeclaration;
'use strict'; var Node = require('./Node'); var ok = require('assert').ok; class FunctionDeclaration extends Node { constructor(def) { super('FunctionDeclaration'); this.name = def.name; this.params = def.params; this.body = this.makeContainer(def.body); } generateCode(codegen) { var name = this.name; var params = this.params; var body = this.body; var statement = this.statement; if (name != null) { ok(typeof name === 'string' || name.type === 'Identifier', 'Function name should be a string or Identifier'); } if (name) { codegen.write('function '); codegen.generateCode(name); codegen.write('('); } else { codegen.write('function('); } if (params && params.length) { for (let i=0, paramsLen = params.length; i<paramsLen; i++) { if (i !== 0) { codegen.write(', '); } var param = params[i]; if (typeof param === 'string') { codegen.write(param); } else { if (param.type !== 'Identifier') { throw new Error('Illegal param: ' + param); } codegen.generateCode(param); } } } codegen.write(') '); var oldInFunction = codegen.inFunction; codegen.inFunction = true; codegen.generateBlock(body); codegen.inFunction = oldInFunction; if (statement) { codegen.write('\n'); } } isCompoundExpression() { return true; } } module.exports = FunctionDeclaration;
Allow function declaration name to be an Identifier node
Allow function declaration name to be an Identifier node
JavaScript
mit
marko-js/marko,marko-js/marko
--- +++ @@ -18,10 +18,16 @@ var statement = this.statement; if (name != null) { - ok(typeof name === 'string', 'Function name should be a string'); + ok(typeof name === 'string' || name.type === 'Identifier', 'Function name should be a string or Identifier'); } - codegen.write('function' + (name ? ' ' + name : '') + '('); + if (name) { + codegen.write('function '); + codegen.generateCode(name); + codegen.write('('); + } else { + codegen.write('function('); + } if (params && params.length) { for (let i=0, paramsLen = params.length; i<paramsLen; i++) {
f6f4b6fc44b0e5e09ea38cfe92be0c0ff28a4cf1
src/stores/topicStore.js
src/stores/topicStore.js
import TopicReducer from "reducers/topicReducer"; import thunkMiddleware from "redux-thunk"; import {createStore, combineReducers, applyMiddleware} from 'redux'; import createLogger from 'redux-logger'; const loggerMiddleware = createLogger(); /** * Creates the topic store. * * This is designed to be used isomorphically. * @returns {*} */ export default function topicStore() { const reducer = combineReducers({TopicReducer}); const store = createStore(reducer, applyMiddleware(thunkMiddleware, loggerMiddleware)); return store; };
import TopicReducer from "reducers/topicReducer"; import thunkMiddleware from "redux-thunk"; import {createStore, combineReducers, applyMiddleware} from 'redux'; import createLogger from 'redux-logger'; const loggerMiddleware = createLogger(); const createTopicStore = function createTopicStore(middlewares, reducers) { const reducer = combineReducers(reducers); const store = createStore(reducer, applyMiddleware(...middlewares)); return store; }; /** * Creates the topic store. * * This is designed to be used isomorphically. * @returns {*} */ export default function topicStore() { return createTopicStore([thunkMiddleware, loggerMiddleware], {TopicReducer}); };
Make store creation more flexible.
Make store creation more flexible. This will help us to create stores with no logging middleware later if we want (amongst other things).
JavaScript
bsd-3-clause
Seinzu/word-cloud
--- +++ @@ -4,6 +4,12 @@ import createLogger from 'redux-logger'; const loggerMiddleware = createLogger(); + +const createTopicStore = function createTopicStore(middlewares, reducers) { + const reducer = combineReducers(reducers); + const store = createStore(reducer, applyMiddleware(...middlewares)); + return store; +}; /** * Creates the topic store. @@ -12,7 +18,5 @@ * @returns {*} */ export default function topicStore() { - const reducer = combineReducers({TopicReducer}); - const store = createStore(reducer, applyMiddleware(thunkMiddleware, loggerMiddleware)); - return store; + return createTopicStore([thunkMiddleware, loggerMiddleware], {TopicReducer}); };
638fea7b838166e3fe75a482835c06db7c12bdb1
client/webpack.config.js
client/webpack.config.js
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: './src/index.js', output: { filename: 'bundle.js', path: path.join(__dirname, 'public'), }, module: { rules: [ { use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env', '@babel/preset-react'], }, }, test: /\.js$/, exclude: /node_modules/, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html', }), ], };
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: './src/index.js', output: { filename: 'bundle.js', path: path.join(__dirname, 'public'), }, module: { rules: [ { use: { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', '@babel/preset-react', { plugins: ['@babel/plugin-proposal-class-properties'] }, ], }, }, test: /\.js$/, exclude: /node_modules/, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html', }), ], };
Set `@babel/plugin-proposal-class-properties` as option in webpack
Set `@babel/plugin-proposal-class-properties` as option in webpack Fixes webpack build error due to class properties https://stackoverflow.com/a/52693007/452233
JavaScript
mit
ultranaut/react-chat,ultranaut/react-chat
--- +++ @@ -15,7 +15,11 @@ use: { loader: 'babel-loader', options: { - presets: ['@babel/preset-env', '@babel/preset-react'], + presets: [ + '@babel/preset-env', + '@babel/preset-react', + { plugins: ['@babel/plugin-proposal-class-properties'] }, + ], }, }, test: /\.js$/, @@ -23,7 +27,6 @@ }, ], }, - plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html',
b110e315ecd6339108848f6cea23b7d336dabbf1
src/Resend.js
src/Resend.js
var MatrixClientPeg = require('./MatrixClientPeg'); var dis = require('./dispatcher'); module.exports = { resend: function(event) { MatrixClientPeg.get().resendEvent( event, MatrixClientPeg.get().getRoom(event.getRoomId()) ).done(function() { dis.dispatch({ action: 'message_sent', event: event }); }, function() { dis.dispatch({ action: 'message_send_failed', event: event }); }); dis.dispatch({ action: 'message_resend_started', event: event }); }, };
var MatrixClientPeg = require('./MatrixClientPeg'); var dis = require('./dispatcher'); module.exports = { resend: function(event) { MatrixClientPeg.get().resendEvent( event, MatrixClientPeg.get().getRoom(event.getRoomId()) ).done(function() { dis.dispatch({ action: 'message_sent', event: event }); }, function() { dis.dispatch({ action: 'message_send_failed', event: event }); }); dis.dispatch({ action: 'message_resend_started', event: event }); }, removeFromQueue: function(event) { MatrixClientPeg.get().getScheduler().removeEventFromQueue(event); var room = MatrixClientPeg.get().getRoom(event.getRoomId()); if (!room) { return; } room.removeEvents([event.getId()]); } };
Add removeFromQueue function to cancel sending a queued event
Add removeFromQueue function to cancel sending a queued event
JavaScript
apache-2.0
matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk
--- +++ @@ -21,4 +21,13 @@ event: event }); }, + + removeFromQueue: function(event) { + MatrixClientPeg.get().getScheduler().removeEventFromQueue(event); + var room = MatrixClientPeg.get().getRoom(event.getRoomId()); + if (!room) { + return; + } + room.removeEvents([event.getId()]); + } };
c0142bb488e5fa5edb0cefd205be96a806389ac6
server/models/essentials.js
server/models/essentials.js
const mongoose = require('mongoose'); const logger = require('../logging'); // connecting to db mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost'); const db = mongoose.connection; db.on('error', (err) => { logger.error('Could not connect to database.', { err }); });
const mongoose = require('mongoose'); const logger = require('../logging'); const DB_URL = process.env.SDF_DATABASE_URL; const DB_NAME = process.env.SDF_DATABASE_NAME || 'sdf'; const DB_CONN_STR = DB_URL || `mongodb://localhost/${DB_NAME}`; // connecting to db console.log(`Connecting to mongodb using '${DB_CONN_STR}'`); mongoose.Promise = global.Promise; mongoose.connect(DB_CONN_STR); const db = mongoose.connection; db.on('error', (err) => { logger.error('Could not connect to database.', { err }); });
Make connecting to mongodb a bit more pluggy
Make connecting to mongodb a bit more pluggy
JavaScript
mit
dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta
--- +++ @@ -1,9 +1,16 @@ const mongoose = require('mongoose'); const logger = require('../logging'); +const DB_URL = process.env.SDF_DATABASE_URL; +const DB_NAME = process.env.SDF_DATABASE_NAME || 'sdf'; + +const DB_CONN_STR = DB_URL || `mongodb://localhost/${DB_NAME}`; + // connecting to db + +console.log(`Connecting to mongodb using '${DB_CONN_STR}'`); mongoose.Promise = global.Promise; -mongoose.connect('mongodb://localhost'); +mongoose.connect(DB_CONN_STR); const db = mongoose.connection; db.on('error', (err) => {
cd4023e5f54afd97cf9d6cfa2f2d9e092cde8cee
snippets/sheets/is_range_a_cell/code.js
snippets/sheets/is_range_a_cell/code.js
/* eslint-disable camelcase */ /** * Checks if a range is a cell * @param {GoogleAppsScript.Spreadsheet.Range} range * @return {boolean} */ function isRangeACell_(range) { return !/:/.test(range.getA1Notation()); } /** * Run the snippet */ function run_test() { const cell = SpreadsheetApp.getActive().getRange('B3'); const range = SpreadsheetApp.getActive().getRange('B3:B4'); const active = SpreadsheetApp.getActiveRange(); console.log([cell, range, active].map(isRangeACell_)); }
/* eslint-disable camelcase */ /** * Checks if a range is a cell * @param {GoogleAppsScript.Spreadsheet.Range} range * @return {boolean} */ function isRangeACell_(range) { return !~range.getA1Notation().indexOf(':'); } /** * Run the snippet */ function run_test() { const cell = SpreadsheetApp.getActive().getRange('B3'); const range = SpreadsheetApp.getActive().getRange('B3:B4'); const active = SpreadsheetApp.getActiveRange(); console.log([cell, range, active].map(isRangeACell_)); }
Update is ceaal a reange
Update is ceaal a reange Signed-off-by: Alex Ivanov <141a92417f71895e56c4a5da05f3e98fc78e2220@contributor.pw>
JavaScript
unlicense
oshliaer/google-apps-script-snippets,oshliaer/google-apps-script-snippets,oshliaer/google-apps-script-snippets
--- +++ @@ -6,7 +6,7 @@ * @return {boolean} */ function isRangeACell_(range) { - return !/:/.test(range.getA1Notation()); + return !~range.getA1Notation().indexOf(':'); } /**
f001dbd00ba3741613f6d26f4d5a54db61444465
test/unit-test/ping-spec.js
test/unit-test/ping-spec.js
/* * Ping test suite */ var vows = require('vows'), assert = require('assert'); var quero = {}, urls = [ 'http://google.com', 'http://facebook.com', 'http://odesk.com', 'http://elance.com', 'http://parse.com', 'http://github.com', 'http://nodejs.org', 'http://npmjs.org' ]; function checkQueryResults (result) { return (result.hasOwnProperty('pinterest') || result.hasOwnProperty('stumbleupon') || result.hasOwnProperty('facebook') || result.hasOwnProperty('twitter') || result.hasOwnProperty('pinterest')); } vows.describe('Should handle URLs argument properly') .addBatch({ 'Load module': { topic: function () { quero = require('./../'); return quero; }, 'should be loaded': function (topic) { assert.isObject(topic); assert.isNotNull(topic); }, 'should have a ping function': function (topic) { assert.isFunction(topic.ping); }, 'Handle one URL': { topic: function (quero) { quero.ping([urls[0]], this.callback); }, 'should return a result if succeed': function (err, result) { console.log('result', result); assert.isNull(err); assert.isObject(result); assert.isTrue(checkQueryResults(result)); } } } }) .export(module);
/* * Ping test suite */ var vows = require('vows'), assert = require('assert'); var quero = {}, urls = [ 'http://google.com', 'http://facebook.com', 'http://odesk.com', 'http://elance.com', 'http://parse.com', 'http://github.com', 'http://nodejs.org', 'http://npmjs.org' ]; function checkQueryResults (result) { return (result.hasOwnProperty('linkedin') || result.hasOwnProperty('stumbleupon') || result.hasOwnProperty('facebook') || result.hasOwnProperty('twitter') || result.hasOwnProperty('pinterest')); } vows.describe('Should handle URLs argument properly') .addBatch({ 'Load module': { topic: function () { quero = require('./../'); return quero; }, 'should be loaded': function (topic) { assert.isObject(topic); assert.isNotNull(topic); }, 'should have a ping function': function (topic) { assert.isFunction(topic.ping); }, 'Handle one URL': { topic: function (quero) { quero.ping([urls[0]], this.callback); }, 'should return a result if succeed': function (err, result) { console.log('result', result); assert.isNull(err); assert.isObject(result); assert.isTrue(checkQueryResults(result)); } } } }) .export(module);
Make sure the returned results will contained LinkedIn count
Make sure the returned results will contained LinkedIn count
JavaScript
mit
muhammadghazali/quero
--- +++ @@ -21,7 +21,7 @@ function checkQueryResults (result) { - return (result.hasOwnProperty('pinterest') || + return (result.hasOwnProperty('linkedin') || result.hasOwnProperty('stumbleupon') || result.hasOwnProperty('facebook') || result.hasOwnProperty('twitter') ||
71776730dcd36f9d3e606b8f109434056d47beb7
lib/web/scripts/capabilities/home/HomeCapabilityView.js
lib/web/scripts/capabilities/home/HomeCapabilityView.js
const Marionette = require('backbone.marionette'); const HomeCardsView = require('./HomeCardsView.js'); module.exports = class HomeCapabilityView extends Marionette.View { template = Templates['capabilities/home/home']; className() { return 'home-capability'; } regions() { return {cards: '.cards-container'}; } serializeData() { const hour = (new Date()).getHours(); // XXX Force this to update occasionally return { greeting: (hour < 4 || hour >= 19) ? 'Good evening.' : ((hour < 12) ? 'Good morning.' : 'Good afternoon.') }; } onRender() { this.showChildView('cards', new HomeCardsView({collection: window.app.cards})); } }
const Marionette = require('backbone.marionette'); const HomeCardsView = require('./HomeCardsView.js'); module.exports = class HomeCapabilityView extends Marionette.View { template = Templates['capabilities/home/home']; className() { return 'home-capability'; } regions() { return {cards: '.cards-container'}; } initialize() { // Update the greeting... this.refreshInterval = setInterval(this.render.bind(this), 1000 * 60 * 5); } serializeData() { const hour = (new Date()).getHours(); return { greeting: (hour < 4 || hour >= 19) ? 'Good evening' : ((hour < 12) ? 'Good morning' : 'Good afternoon') }; } onRender() { this.showChildView('cards', new HomeCardsView({collection: window.app.cards})); } onDestroy() { clearInterval(this.refreshInterval); } }
Update the home screen greeting sometimes
Update the home screen greeting sometimes
JavaScript
mit
monitron/jarvis-ha,monitron/jarvis-ha
--- +++ @@ -12,12 +12,16 @@ return {cards: '.cards-container'}; } + initialize() { + // Update the greeting... + this.refreshInterval = setInterval(this.render.bind(this), 1000 * 60 * 5); + } + serializeData() { const hour = (new Date()).getHours(); - // XXX Force this to update occasionally return { - greeting: (hour < 4 || hour >= 19) ? 'Good evening.' : - ((hour < 12) ? 'Good morning.' : 'Good afternoon.') + greeting: (hour < 4 || hour >= 19) ? 'Good evening' : + ((hour < 12) ? 'Good morning' : 'Good afternoon') }; } @@ -25,4 +29,8 @@ this.showChildView('cards', new HomeCardsView({collection: window.app.cards})); } + + onDestroy() { + clearInterval(this.refreshInterval); + } }
568abc38f0d1ef58ede0af5fcdcc31d0e99d595d
src/game/vue-game-plugin.js
src/game/vue-game-plugin.js
import GameStateManager from "./GameStates/GameStateManager"; // import CommandParser from "./Commands/CommandParser"; import GenerateName from "./Generators/NameGenerator"; export default { install: (Vue) => { Vue.prototype.$game = { startGame() { return GameStateManager.StartGame(); }, generateName() { return GenerateName(); }, parseCommand(command) { // return CommandParser.ParseCommand(command); console.log("Parsing " + command); } } } }
import GameStateManager from "./GameStates/GameStateManager"; // import CommandParser from "./Commands/CommandParser"; import GenerateName from "./Generators/NameGenerator"; export default { install: (Vue) => { Vue.prototype.$game = { start() { GameStateManager.StartGame(); }, receiveInput(input) { console.log(input); GameStateManager.receiveInput(input); }, generateName() { return GenerateName(); }, parseCommand(command) { // return CommandParser.ParseCommand(command); console.log("Parsing " + command); }, getCurrentState() { return GameStateManager.currentState; } } } }
Add new game methods for state/input management
Add new game methods for state/input management
JavaScript
mit
Trymunx/Dragon-Slayer,Trymunx/Dragon-Slayer
--- +++ @@ -5,8 +5,12 @@ export default { install: (Vue) => { Vue.prototype.$game = { - startGame() { - return GameStateManager.StartGame(); + start() { + GameStateManager.StartGame(); + }, + receiveInput(input) { + console.log(input); + GameStateManager.receiveInput(input); }, generateName() { return GenerateName(); @@ -14,6 +18,9 @@ parseCommand(command) { // return CommandParser.ParseCommand(command); console.log("Parsing " + command); + }, + getCurrentState() { + return GameStateManager.currentState; } } }
1b55bfd142856c2d2fcda4a21a23df323e4ad5b1
addon/pods/components/frost-tabs/component.js
addon/pods/components/frost-tabs/component.js
import Ember from 'ember' import layout from './template' import PropTypesMixin, { PropTypes } from 'ember-prop-types' import uuid from 'ember-simple-uuid' export default Ember.Component.extend(PropTypesMixin, { // == Component properties ================================================== layout: layout, classNames: ['frost-tabs'], // == State properties ====================================================== propTypes: { tabs: PropTypes.array.isRequired, selectedTab: PropTypes.string, targetOutlet: PropTypes.string, onChange: PropTypes.func, hook: PropTypes.string }, getDefaultProps () { return { targetOutlet: `frost-tab-content-${uuid()}` } } })
import Ember from 'ember' import layout from './template' import PropTypesMixin, { PropTypes } from 'ember-prop-types' import uuid from 'ember-simple-uuid' export default Ember.Component.extend(PropTypesMixin, { // == Component properties ================================================== layout: layout, classNames: ['frost-tabs'], // == State properties ====================================================== propTypes: { tabs: PropTypes.array.isRequired, selectedTab: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, hook: PropTypes.string.isRequired, targetOutlet: PropTypes.string }, getDefaultProps () { return { targetOutlet: `frost-tab-content-${uuid()}` } } })
Put some property as required.
Put some property as required.
JavaScript
mit
ciena-frost/ember-frost-tabs,ciena-frost/ember-frost-tabs,ciena-frost/ember-frost-tabs
--- +++ @@ -13,10 +13,10 @@ propTypes: { tabs: PropTypes.array.isRequired, - selectedTab: PropTypes.string, - targetOutlet: PropTypes.string, - onChange: PropTypes.func, - hook: PropTypes.string + selectedTab: PropTypes.string.isRequired, + onChange: PropTypes.func.isRequired, + hook: PropTypes.string.isRequired, + targetOutlet: PropTypes.string }, getDefaultProps () {
254d2831fcab758f55302a01032fe73c3fe49e10
www/modules/core/components/session.service.js
www/modules/core/components/session.service.js
(function() { 'use strict'; angular.module('Core') .service('sessionService', sessionService); sessionService.$inject = ['commonService']; function sessionService(commonService) { var service = this; service.isUserLoggedIn = isUserLoggedIn; /* ======================================== Var ==================================================== */ service.userData = { }; /* ======================================== Services =============================================== */ /* ======================================== Public Methods ========================================= */ function isUserLoggedIn() { // Check if user is logged in } /* ======================================== Private Methods ======================================== */ function init() { } init(); } })();
(function() { 'use strict'; angular.module('Core') .service('sessionService', sessionService); sessionService.$inject = []; function sessionService() { var service = this; service.isUserLoggedIn = isUserLoggedIn; /* ======================================== Var ==================================================== */ service.userData = { }; /* ======================================== Services =============================================== */ /* ======================================== Public Methods ========================================= */ function isUserLoggedIn() { // Check if user is logged in } /* ======================================== Private Methods ======================================== */ function init() { } init(); } })();
Remove commonSvc dependency to prevent circular dependency
Remove commonSvc dependency to prevent circular dependency
JavaScript
mit
tlkiong/cxa_test,tlkiong/cxa_test
--- +++ @@ -5,9 +5,9 @@ angular.module('Core') .service('sessionService', sessionService); - sessionService.$inject = ['commonService']; + sessionService.$inject = []; - function sessionService(commonService) { + function sessionService() { var service = this; service.isUserLoggedIn = isUserLoggedIn;
5d464fd7642aa91501d09738ba345e2e252aaff9
index.js
index.js
var rules = require('./helpers/rules.js'); module.exports = function (options) { options = options || {}; if (options.rules) { Object.keys(options.rules).forEach(function (key) { rules[key] = options.rules[key]; }); } return function (module, controller) { module.alias('cerebral-module-forms'); module.addState({}); module.addSignals({ fieldAdded: require('./signals/fieldAdded.js'), fieldRemoved: require('./signals/fieldRemoved.js'), formAdded: require('./signals/formAdded.js'), formRemoved: require('./signals/formRemoved.js'), fieldChanged: {chain: require('./signals/fieldChanged.js'), sync: true} }); }; };
var rules = require('./helpers/rules.js'); module.exports = function (options) { options = options || {}; if (options.rules) { Object.keys(options.rules).forEach(function (key) { rules[key] = options.rules[key]; }); } return function (module, controller) { module.alias('cerebral-module-forms'); module.addState({}); module.addSignals({ fieldAdded: require('./signals/fieldAdded.js'), fieldRemoved: require('./signals/fieldRemoved.js'), formAdded: require('./signals/formAdded.js'), formRemoved: require('./signals/formRemoved.js'), fieldChanged: {chain: require('./signals/fieldChanged.js'), sync: true} }); }; };
Update to latest Cerebral, React. Removed deprecated warnings
Update to latest Cerebral, React. Removed deprecated warnings
JavaScript
mit
cerebral/cerebral-module-forms,cerebral/cerebral-module-forms
--- +++ @@ -23,6 +23,5 @@ formRemoved: require('./signals/formRemoved.js'), fieldChanged: {chain: require('./signals/fieldChanged.js'), sync: true} }); - }; };
e7bef4ca97a6c73ce6a0f547387f2864d2c61d6e
module.js
module.js
var fs = require("fs"); var cur_pid = parseInt(fs.readFileSync(".muon").toString()); if (!isNaN(cur_pid)){ console.log("Server already running: process id "+cur_pid); process.kill(); } fs.writeFileSync(".muon",process.pid); process.on('SIGINT', function() { fs.writeFileSync(".muon",""); process.kill(); }); module.exports = { "server": function() { return require("./lib/app.js") }, "plugin" : function() { return require("./server/plugin.js") } };
var fs = require("fs"); var cur_pid = parseInt(fs.readFileSync(".muon").toString()); if (cur_pid != process.pid && !isNaN(cur_pid)){ console.log("Server already running: process id "+cur_pid); process.kill(); } fs.writeFileSync(".muon",process.pid); process.on('SIGINT', function() { fs.writeFileSync(".muon",""); process.kill(); }); module.exports = { "server": function() { return require("./lib/app.js") }, "plugin" : function() { return require("./server/plugin.js") } };
Check process id when reloading
Check process id when reloading
JavaScript
mit
Kreees/muon,Kreees/muon
--- +++ @@ -1,6 +1,6 @@ var fs = require("fs"); var cur_pid = parseInt(fs.readFileSync(".muon").toString()); -if (!isNaN(cur_pid)){ +if (cur_pid != process.pid && !isNaN(cur_pid)){ console.log("Server already running: process id "+cur_pid); process.kill(); }
1b62d12de0c1f9c9b3a08290a1bb9cee14d3039d
index.js
index.js
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n\tAUTHOR_DATE " + chalk.grey(dateString) + "\n\tCOMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n\t" + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
Change tabular to 4 spaces
Change tabular to 4 spaces
JavaScript
mit
sam3d/git-date
--- +++ @@ -25,7 +25,7 @@ if (err) { console.log("fatal: Could not change the previous commit"); } else { - console.log("\nModified previous commit:\n\tAUTHOR_DATE " + chalk.grey(dateString) + "\n\tCOMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n\t" + chalk.bgWhite.black(command) + "\n"); + console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); } });
55dd1989d910d34fffdef9788192e7d0f7a7e48e
index.js
index.js
var git = require('edge-git'); var repo = new git.repository('./.git/'); console.log(repo.BranchesSync());
var git = require('edge-git'); var repo = new git.repository('./.git/'); console.log(repo.BranchesSync()[0].CommitsSync());
Add a more interesting example
Add a more interesting example
JavaScript
mit
itsananderson/edge-git-example
--- +++ @@ -2,4 +2,4 @@ var repo = new git.repository('./.git/'); -console.log(repo.BranchesSync()); +console.log(repo.BranchesSync()[0].CommitsSync());
a0a28e3ce6be7fd369b67159478d7ebbd619ce79
index.js
index.js
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-sentry', contentFor: function(type, config){ if (type === 'body' && !config.sentry.skipCdn) { return '<script src="' + config.sentry.cdn + '/' + config.sentry.version + '/ember,jquery,native/raven.min.js"></script>'; } } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-sentry', contentFor: function(type, config){ if (type === 'body-footer' && !config.sentry.skipCdn) { return '<script src="' + config.sentry.cdn + '/' + config.sentry.version + '/ember,jquery,native/raven.min.js"></script>'; } } };
Use 'body-footer' to ensure Raven is loaded after Ember.
Use 'body-footer' to ensure Raven is loaded after Ember. `{{content-for 'body'}}` is typically before the `vendor.js` file's script tag, so this switches to using `body-footer` to ensure `Raven` is loaded after Ember itself.
JavaScript
mit
pifantastic/ember-cli-sentry,dschmidt/ember-cli-sentry,damiencaselli/ember-cli-sentry,dschmidt/ember-cli-sentry,pifantastic/ember-cli-sentry,damiencaselli/ember-cli-sentry
--- +++ @@ -6,7 +6,7 @@ name: 'ember-cli-sentry', contentFor: function(type, config){ - if (type === 'body' && !config.sentry.skipCdn) { + if (type === 'body-footer' && !config.sentry.skipCdn) { return '<script src="' + config.sentry.cdn + '/' + config.sentry.version + '/ember,jquery,native/raven.min.js"></script>'; } }
81f103f34e711a5283762deee89704350aba20d6
index.js
index.js
#!/usr/bin/env node 'use strict'; const child_process = require('child_process'); const commander = require('commander'); const version = require('./package').version; commander .version(version) .usage('[options] <cmd...>'); commander.parse(process.argv); const args = process.argv.slice(2); if (args.length < 2) { commander.help(); } console.log(args); let proc = child_process.spawn(args[0], args.slice(1)); proc.on('close', (code) => { if (code !== 0) { console.error('HODOR!'); } else { console.log('Hodor.'); } });
#!/usr/bin/env node 'use strict'; const child_process = require('child_process'); const commander = require('commander'); const version = require('./package').version; commander .version(version) .usage('[options] <cmd...>'); commander.parse(process.argv); let args = process.argv.slice(2); if (!args.length) { commander.help(); } let proc = child_process.spawn(args[0], args.slice(1)); proc.on('close', (code) => { if (code !== 0) { console.error('HODOR!'); } else { console.log('Hodor.'); } });
Allow commands with no arguments
Allow commands with no arguments
JavaScript
mit
pjdietz/hodo
--- +++ @@ -11,12 +11,10 @@ .usage('[options] <cmd...>'); commander.parse(process.argv); -const args = process.argv.slice(2); -if (args.length < 2) { +let args = process.argv.slice(2); +if (!args.length) { commander.help(); } - -console.log(args); let proc = child_process.spawn(args[0], args.slice(1)); proc.on('close', (code) => {
8f5c1e3234dd32588143f3ca51c01281b577ea17
index.js
index.js
'use strict'; module.exports = function (str, opts) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } opts = opts || {}; return str + ' & ' + (opts.postfix || 'rainbows'); };
'use strict'; module.exports = function (str, opts) { var request = require('sync-request'); var options_obj = { 'headers': { 'user-agent': 'http://github.com/icyflame/gh-gist-owner' } }; var res = request('GET', 'https://api.github.com/gists/' + str, options_obj); var body = JSON.parse(res.getBody()); return body.owner.login; };
Complete the request and return username
Complete the request and return username Signed-off-by: Siddharth Kannan <805f056820c7a1cecc4ab591b8a0a604b501a0b7@gmail.com>
JavaScript
mit
icyflame/gh-gist-owner
--- +++ @@ -1,10 +1,17 @@ 'use strict'; module.exports = function (str, opts) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - opts = opts || {}; + var request = require('sync-request'); - return str + ' & ' + (opts.postfix || 'rainbows'); + var options_obj = { + 'headers': { + 'user-agent': 'http://github.com/icyflame/gh-gist-owner' + } + }; + var res = request('GET', 'https://api.github.com/gists/' + str, options_obj); + + var body = JSON.parse(res.getBody()); + + return body.owner.login; + };
e794cbfa89778eab9aae959a1ad90223afeea1e6
index.js
index.js
require( 'dotenv' ).config(); var dropboxModule = require( './modules/dropbox.js' ); var googleDocsModule = require( './modules/googleDocs.js' ); var paypalModule = require( './modules/paypal.js' ); var express = require( 'express' ); var app = express(); app.set( 'port', ( process.env.Port || 30000 ) ); app.use( express.static( __dirname + '/public' ) ); app.get( '/googleapitoken', function( request, response ) { googleDocsModule.googleAPIAuthorize( request, response ); }); app.get( '/trigger', function( request, response ) { googleDocsModule.verifySecrets() .then(function( res ) { console.log( 'Application verified! Fetching PayPal rate.' ); paypalModule.fetchPaypalRate(); response.send( 'Triggered!' ); }) .catch(function( error ) { var errorMessage = 'Failed to authenticate! (' + error + ')'; console.log( errorMessage ); response.send( errorMessage ); }); }); app.listen( app.get( 'port' ), function() { console.log( 'Node app is running at localhost:' + app.get( 'port' ) ); });
require( 'dotenv' ).config(); var dropboxModule = require( './modules/dropbox.js' ); var googleDocsModule = require( './modules/googleDocs.js' ); var paypalModule = require( './modules/paypal.js' ); var express = require( 'express' ); var app = express(); app.set( 'port', ( process.env.PORT ) ); app.use( express.static( __dirname + '/public' ) ); app.get( '/googleapitoken', function( request, response ) { googleDocsModule.googleAPIAuthorize( request, response ); }); app.get( '/trigger', function( request, response ) { googleDocsModule.verifySecrets() .then(function( res ) { console.log( 'Application verified! Fetching PayPal rate.' ); paypalModule.fetchPaypalRate(); response.send( 'Triggered!' ); }) .catch(function( error ) { var errorMessage = 'Failed to authenticate! (' + error + ')'; console.log( errorMessage ); response.send( errorMessage ); }); }); app.listen( app.get( 'port' ), function() { console.log( 'Node app is running at localhost:' + app.get( 'port' ) ); });
Fix a port related issue that persists.
Fix a port related issue that persists.
JavaScript
mit
kmgalanakis/node-js-paypal-rate
--- +++ @@ -5,7 +5,7 @@ var express = require( 'express' ); var app = express(); -app.set( 'port', ( process.env.Port || 30000 ) ); +app.set( 'port', ( process.env.PORT ) ); app.use( express.static( __dirname + '/public' ) ); app.get( '/googleapitoken', function( request, response ) {
22bbbd2febb2d9d7227fbd330ea8ce1b2101c95d
index.js
index.js
/* jshint node: true */ 'use strict'; var BasePlugin = require('ember-cli-deploy-plugin'); module.exports = { name: 'ember-cli-deploy-cloudfront', createDeployPlugin: function(options) { var DeployPlugin = BasePlugin.extend({ name: options.name, defaultConfig: { objectPaths: '/index.html' } requiredConfig: ['accessKeyId', 'secretAccessKey', 'distributionId'], didActivate: function(context) { var distributionId = this.readConfig('distributionId'); this.log('preparing to create invalidation for distribution' + distributionId); } }); return new DeployPlugin(); } };
/* jshint node: true */ 'use strict'; var BasePlugin = require('ember-cli-deploy-plugin'); module.exports = { name: 'ember-cli-deploy-cloudfront', createDeployPlugin: function(options) { var DeployPlugin = BasePlugin.extend({ name: options.name, defaultConfig: { objectPaths: '/index.html' } requiredConfig: ['accessKeyId', 'secretAccessKey', 'distributionId'], didActivate: function(context) { var distributionId = this.readConfig('distributionId'); this.log('preparing to create invalidation for distribution `' + distributionId + '``'); } }); return new DeployPlugin(); } };
Add backticks to preparing log message
Add backticks to preparing log message
JavaScript
mit
kpfefferle/ember-cli-deploy-cloudfront
--- +++ @@ -18,7 +18,7 @@ var distributionId = this.readConfig('distributionId'); - this.log('preparing to create invalidation for distribution' + distributionId); + this.log('preparing to create invalidation for distribution `' + distributionId + '``'); } });
f71c6785131adcc85b91789da0d0a0b9f1a9713f
index.js
index.js
var path = require('path'); module.exports = function (source) { if (this.cacheable) { this.cacheable(); } var matches = 0, processedSource; processedSource = source.replace(/React\.createClass/g, function (match) { matches++; return '__hotUpdateAPI.createClass'; }); if (!matches) { return source; } return [ 'var __hotUpdateAPI = (function () {', ' var React = require("react");', ' var getHotUpdateAPI = require(' + JSON.stringify(require.resolve('./getHotUpdateAPI')) + ');', ' return getHotUpdateAPI(React, ' + JSON.stringify(path.basename(this.resourcePath)) + ', module.id);', '})();', processedSource, 'if (module.hot) {', ' module.hot.accept();', ' module.hot.dispose(function () {', ' var nextTick = require(' + JSON.stringify(require.resolve('next-tick')) + ');', ' nextTick(__hotUpdateAPI.updateMountedInstances);', ' });', '}' ].join('\n'); };
var path = require('path'); module.exports = function (source) { if (this.cacheable) { this.cacheable(); } var matches = 0, processedSource; processedSource = source.replace(/React\.createClass\s*\(\s*\{/g, function (match) { matches++; return '__hotUpdateAPI.createClass({'; }); if (!matches) { return source; } return [ 'var __hotUpdateAPI = (function () {', ' var React = require("react");', ' var getHotUpdateAPI = require(' + JSON.stringify(require.resolve('./getHotUpdateAPI')) + ');', ' return getHotUpdateAPI(React, ' + JSON.stringify(path.basename(this.resourcePath)) + ', module.id);', '})();', processedSource, 'if (module.hot) {', ' module.hot.accept();', ' module.hot.dispose(function () {', ' var nextTick = require(' + JSON.stringify(require.resolve('next-tick')) + ');', ' nextTick(__hotUpdateAPI.updateMountedInstances);', ' });', '}' ].join('\n'); };
Use more precise React.createClass call regex to avoid matching own code
Use more precise React.createClass call regex to avoid matching own code
JavaScript
mit
gaearon/react-hot-loader,gaearon/react-hot-loader
--- +++ @@ -8,9 +8,9 @@ var matches = 0, processedSource; - processedSource = source.replace(/React\.createClass/g, function (match) { + processedSource = source.replace(/React\.createClass\s*\(\s*\{/g, function (match) { matches++; - return '__hotUpdateAPI.createClass'; + return '__hotUpdateAPI.createClass({'; }); if (!matches) {
562375c8256c65be9223fb8622fc7ad4fde90b31
index.js
index.js
var buildContents = require('./lib/buildContents'); var buildImports = require('./lib/buildImports'); var buildSection = require('./lib/buildSection'); var extend = require('util')._extend; var fs = require('fs'); var path = require('path'); var processSassDoc = require('./lib/processSassDoc'); var sassdoc = require('sassdoc'); module.exports = function(files, options, cb) { options = extend({ title: 'Settings', output: '_settings.scss', groups: {}, imports: [] }, options); sassdoc.parse(files).then(parse); function parse(data) { var outputPath = path.join(process.cwd(), options.output); data = processSassDoc(data, options.groups); // Erase the existing file if necessary if (fs.existsSync(outputPath)) { fs.unlinkSync(outputPath); } var outputStream = fs.createWriteStream(outputPath, {flags: 'w'}); // Generate the table of contents var titleText = buildContents(options.title, Object.keys(data)); outputStream.write(titleText); // Generate the import list var importText = buildImports(options.imports); outputStream.write(importText); // Iterate through each component var n = 1; for (var i in data) { outputStream.write(buildSection(i, n, data[i])); n++; } cb(); } }
var buildContents = require('./lib/buildContents'); var buildImports = require('./lib/buildImports'); var buildSection = require('./lib/buildSection'); var extend = require('util')._extend; var fs = require('fs'); var path = require('path'); var processSassDoc = require('./lib/processSassDoc'); var sassdoc = require('sassdoc'); module.exports = function(files, options, cb) { options = extend({ title: 'Settings', output: '_settings.scss', groups: {}, imports: [] }, options); if (typeof files === 'string') { files = [files]; } sassdoc.parse(files).then(parse); function parse(data) { var outputPath = path.join(process.cwd(), options.output); data = processSassDoc(data, options.groups); // Erase the existing file if necessary if (fs.existsSync(outputPath)) { fs.unlinkSync(outputPath); } var outputStream = fs.createWriteStream(outputPath, {flags: 'w'}); // Generate the table of contents var titleText = buildContents(options.title, Object.keys(data)); outputStream.write(titleText); // Generate the import list var importText = buildImports(options.imports); outputStream.write(importText); // Iterate through each component var n = 1; for (var i in data) { outputStream.write(buildSection(i, n, data[i])); n++; } cb(); } }
Allow glob search pattern to be passed as a string
Allow glob search pattern to be passed as a string
JavaScript
mit
zurb/octophant,zurb/foundation-settings-parser
--- +++ @@ -14,6 +14,10 @@ groups: {}, imports: [] }, options); + + if (typeof files === 'string') { + files = [files]; + } sassdoc.parse(files).then(parse);
0be5cfbe8579f116666d2cd444f8c5c6de330d64
index.js
index.js
var Promise = require('bluebird'); var mapValues = require('lodash.mapvalues'); var assign = require('lodash.assign'); var curry = require('lodash.curry'); function FileWebpackPlugin(files) { this.files = files || {}; } FileWebpackPlugin.prototype.apply = function(compiler) { var self = this; compiler.plugin('emit', function(compiler, done) { var data = {}; var assetPromises = mapValues(self.files, function(asyncTemplate, filename) { return Promise .fromNode(asyncTemplate.bind(null, data)) .then(createAssetFromContents); }); Promise.props(assetPromises) .then(addAssetsToCompiler(compiler)) .nodeify(done); }); }; var addAssetsToCompiler = curry(function(compiler, assets) { assign(compiler.assets, assets); }); function createAssetFromContents(contents) { return { source: function() { return contents; }, size: function() { return contents.length; } }; } module.exports = FileWebpackPlugin;
var Promise = require('bluebird'); var mapValues = require('lodash.mapvalues'); var assign = require('lodash.assign'); var curry = require('lodash.curry'); function FileWebpackPlugin(files) { this.files = files || {}; } FileWebpackPlugin.prototype.apply = function(compiler) { var self = this; compiler.plugin('emit', function(compiler, done) { var data = {}; var assetPromises = mapValues(self.files, function(asyncTemplate, filename) { return Promise .fromNode(asyncTemplate.bind(null, data)) .then(createAssetFromContents); }); Promise.props(assetPromises) .then(addAssetsToCompiler(compiler)) .nodeify(done); }); }; var createAssetFromContents = function(contents) { return { source: function() { return contents; }, size: function() { return contents.length; } }; }; var addAssetsToCompiler = curry(function(compiler, assets) { assign(compiler.assets, assets); }); module.exports = FileWebpackPlugin;
Sort functions in order of usage
Sort functions in order of usage
JavaScript
mit
markdalgleish/file-webpack-plugin
--- +++ @@ -24,11 +24,7 @@ }); }; -var addAssetsToCompiler = curry(function(compiler, assets) { - assign(compiler.assets, assets); -}); - -function createAssetFromContents(contents) { +var createAssetFromContents = function(contents) { return { source: function() { return contents; @@ -37,6 +33,10 @@ return contents.length; } }; -} +}; + +var addAssetsToCompiler = curry(function(compiler, assets) { + assign(compiler.assets, assets); +}); module.exports = FileWebpackPlugin;
ab4c9d88e6afa89fac479dc417e485036cb62deb
index.js
index.js
'use strict'; var jade = require('jade'); var fs = require('fs'); exports.name = 'jade'; exports.outputFormat = 'xml'; exports.compile = function (source, options) { var fn = jade.compile(source, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileClient = function (source, options) { return jade.compileClientWithDependenciesTracked(source, options); }; exports.compileFile = function (path, options) { var fn = jade.compileFile(path, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileFileClient = function (path, options) { // There is no compileFileClientWithDependenciesTracked so gotta do it // manually. options = options || {}; options.filename = options.filename || path; return exports.compileClient(fs.readFileSync(path, 'utf8'), options); };
'use strict'; var jade = require('jade'); var fs = require('fs'); exports.name = 'jade'; exports.outputFormat = 'html'; exports.compile = function (source, options) { var fn = jade.compile(source, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileClient = function (source, options) { return jade.compileClientWithDependenciesTracked(source, options); }; exports.compileFile = function (path, options) { var fn = jade.compileFile(path, options); return {fn: fn, dependencies: fn.dependencies} }; exports.compileFileClient = function (path, options) { // There is no compileFileClientWithDependenciesTracked so gotta do it // manually. options = options || {}; options.filename = options.filename || path; return exports.compileClient(fs.readFileSync(path, 'utf8'), options); };
Use `'html'` as output format
Use `'html'` as output format Per jstransformers/jstransformer#3.
JavaScript
mit
jstransformers/jstransformer-pug,jstransformers/jstransformer-jade,jstransformers/jstransformer-jade,jstransformers/jstransformer-pug
--- +++ @@ -4,7 +4,7 @@ var fs = require('fs'); exports.name = 'jade'; -exports.outputFormat = 'xml'; +exports.outputFormat = 'html'; exports.compile = function (source, options) { var fn = jade.compile(source, options); return {fn: fn, dependencies: fn.dependencies}
c303f40444becc57113d04560705be4f88832b5b
routes/poem.js
routes/poem.js
var _ = require('underscore'); var PoemsRepository = require('../lib/repositories/poems_repository.js'); var poemsRepo = new PoemsRepository(); exports.list = function(req, res) { poemsRepo.all(function(err, poems) { res.render('poem/list', { poems: poems }); }); }; exports.edit = function(req, res) { poemsRepo.read(req.params.id, function(err, poem) { res.render('poem/edit', { poem: poem }); }); }; exports.createform = function(req, res) { res.render('poem/new'); }; exports.create = function(req, res) { poemsRepo.create({ name: req.body.name }, function(err, poem) { res.redirect('/poem/' + poem.id); }); };
var _ = require('underscore'), fs = require('fs'), path = require('path'), PoemsRepository = require('../lib/repositories/poems_repository.js'); var dbConfig; if(fs.existsSync(path.join(__dirname, "../db/config.json"))) { dbConfig = require("../db/config.json"); } else { console.log("The database config file was not found!"); process.exit(1); } var poemsRepo = new PoemsRepository(dbConfig); exports.list = function(req, res) { poemsRepo.all(function(err, poems) { res.render('poem/list', { poems: poems }); }); }; exports.edit = function(req, res) { poemsRepo.read(req.params.id, function(err, poem) { res.render('poem/edit', { poem: poem }); }); }; exports.createform = function(req, res) { res.render('poem/new'); }; exports.create = function(req, res) { poemsRepo.create({ name: req.body.name }, function(err, poem) { res.redirect('/poem/' + poem.id); }); };
Read database config from file. Exit process if file not found.
Read database config from file. Exit process if file not found.
JavaScript
mit
jimguys/poemlab,jimguys/poemlab
--- +++ @@ -1,7 +1,17 @@ -var _ = require('underscore'); +var _ = require('underscore'), + fs = require('fs'), + path = require('path'), + PoemsRepository = require('../lib/repositories/poems_repository.js'); -var PoemsRepository = require('../lib/repositories/poems_repository.js'); -var poemsRepo = new PoemsRepository(); +var dbConfig; +if(fs.existsSync(path.join(__dirname, "../db/config.json"))) { + dbConfig = require("../db/config.json"); +} else { + console.log("The database config file was not found!"); + process.exit(1); +} + +var poemsRepo = new PoemsRepository(dbConfig); exports.list = function(req, res) { poemsRepo.all(function(err, poems) {
0d54232f21a916b040b87b3c96c0687568d0e9cc
src/js/app.js
src/js/app.js
var fullscreen = require('./fullscreen')(document.getElementById('fs')); var slides = require('./slides')(document.getElementById('fs')).then(function() { var carousel = require('./carousel'); var slideRotationInterval = window.setInterval(carousel, (2 * 1000)); }); var analytics = require('./analytics'); document.getElementById('full-screen-toggle').onclick = fullscreen; var dashboardSlug = window.location.pathname.split('/').pop(); analytics.setup();
var fullscreen = require('./fullscreen')(document.getElementById('fs')); var slides = require('./slides')(document.getElementById('fs')).then(function() { var carousel = require('./carousel'); var slideRotationInterval = window.setInterval(carousel, (5 * 1000)); }); var analytics = require('./analytics'); document.getElementById('full-screen-toggle').onclick = fullscreen; var dashboardSlug = window.location.pathname.split('/').pop(); analytics.setup();
Increase slide display interval to 10s
Increase slide display interval to 10s
JavaScript
mit
alphagov/performanceplatform-big-screen-view,alphagov/performanceplatform-big-screen-view,alphagov/performanceplatform-big-screen-view
--- +++ @@ -1,7 +1,7 @@ var fullscreen = require('./fullscreen')(document.getElementById('fs')); var slides = require('./slides')(document.getElementById('fs')).then(function() { var carousel = require('./carousel'); - var slideRotationInterval = window.setInterval(carousel, (2 * 1000)); + var slideRotationInterval = window.setInterval(carousel, (5 * 1000)); }); var analytics = require('./analytics');
02fc6dab5673a5581620994cebd53115de756be8
src/layout.js
src/layout.js
import * as dagre from "dagre" export default function() { let width = 1, height = 1; function layout(dag) { const g = new dagre.graphlib.Graph(), info = {}; g.setGraph(info); dag.nodes().forEach(n => g.setNode(n.id, n)); dag.links().forEach(l => g.setEdge(l.source.id, l.target.id, l)); dagre.layout(g); // Rescale dag.links().forEach(({source, target, points}) => { // XXX This seems to be a bug in dagre points[0].y = source.y; points[points.length - 1].y = target.y; points.forEach(p => { p.x *= width / info.width; p.y *= height / info.height; }); }); dag.nodes().forEach(node => { node.x *= width / info.width; node.y *= height / info.height; }); return dag; } layout.size = function(x) { return arguments.length ? ([width, height] = x, layout) : [width, height]; } return layout; }
import * as dagre from "dagre" export default function() { let width = 1, height = 1; function layout(dag) { const g = new dagre.graphlib.Graph(), info = {}; g.setGraph(info); dag.nodes().forEach(n => g.setNode(n.id, n)); dag.links().forEach(l => g.setEdge(l.source.id, l.target.id, l)); dagre.layout(g); // Rescale dag.links().forEach(link => { const { source, target, points } = link; // XXX These are because of perceived bugs in dagre if (points) { points[0].y = source.y; points[points.length - 1].y = target.y; points.forEach(p => { p.x *= width / info.width; p.y *= height / info.height; }); } else { link.points = [{x: source.x, y: source.y}, {x: target.x, y: target.y}]; } }); dag.nodes().forEach(node => { node.x *= width / info.width; node.y *= height / info.height; }); return dag; } layout.size = function(x) { return arguments.length ? ([width, height] = x, layout) : [width, height]; } return layout; }
Fix another bug in dagre
Fix another bug in dagre
JavaScript
mit
erikbrinkman/d3-dag,erikbrinkman/d3-dag
--- +++ @@ -13,14 +13,19 @@ dagre.layout(g); // Rescale - dag.links().forEach(({source, target, points}) => { - // XXX This seems to be a bug in dagre - points[0].y = source.y; - points[points.length - 1].y = target.y; - points.forEach(p => { - p.x *= width / info.width; - p.y *= height / info.height; - }); + dag.links().forEach(link => { + const { source, target, points } = link; + // XXX These are because of perceived bugs in dagre + if (points) { + points[0].y = source.y; + points[points.length - 1].y = target.y; + points.forEach(p => { + p.x *= width / info.width; + p.y *= height / info.height; + }); + } else { + link.points = [{x: source.x, y: source.y}, {x: target.x, y: target.y}]; + } }); dag.nodes().forEach(node => { node.x *= width / info.width;
9a78202e64fc4230885b4dba43061e7ea9106ab4
test/lint-verify-fail.js
test/lint-verify-fail.js
"use strict"; const test = require("ava"); const childProcess = require("child_process"); const fs = require("fs"); const path = require("path"); const ruleFiles = fs .readdirSync(".") .filter(name => !name.startsWith(".") && name.endsWith(".js")); test("test-lint/ causes errors without eslint-config-prettier", t => { const result = childProcess.spawnSync( "npm", ["run", "test:lint-verify-fail", "--silent"], { encoding: "utf8" } ); const output = JSON.parse(result.stdout); t.is( output.length, ruleFiles.length, "every test-lint/ file must cause an error" ); output.forEach(data => { const name = path.basename(data.filePath).replace(/\.js$/, ""); const ruleIds = data.messages.map(message => message.ruleId); t.true(ruleIds.length > 0); // Every test-lint/ file must only cause errors related to its purpose. if (name === "index") { t.true(ruleIds.every(ruleId => ruleId.indexOf("/") === -1)); } else { t.true(ruleIds.every(ruleId => ruleId.startsWith(`${name}/`))); } }); });
"use strict"; const test = require("ava"); const childProcess = require("child_process"); const fs = require("fs"); const path = require("path"); const ruleFiles = fs .readdirSync(".") .filter(name => !name.startsWith(".") && name.endsWith(".js")); test("test-lint/ causes errors without eslint-config-prettier", t => { const result = childProcess.spawnSync( "npm", ["run", "test:lint-verify-fail", "--silent"], { encoding: "utf8" } ); const output = JSON.parse(result.stdout); t.is( output.length, ruleFiles.length, "every test-lint/ file must cause an error" ); output.forEach(data => { const name = path.basename(data.filePath).replace(/\.js$/, ""); const ruleIds = data.messages.map(message => message.ruleId); t.true(name && ruleIds.length > 0); // Every test-lint/ file must only cause errors related to its purpose. if (name === "index") { t.true(ruleIds.every(ruleId => ruleId.indexOf("/") === -1)); } else { t.true(ruleIds.every(ruleId => ruleId.startsWith(`${name}/`))); } }); });
Make failing test-lint/ tests easier to understand
Make failing test-lint/ tests easier to understand
JavaScript
mit
lydell/eslint-config-prettier
--- +++ @@ -27,7 +27,7 @@ const name = path.basename(data.filePath).replace(/\.js$/, ""); const ruleIds = data.messages.map(message => message.ruleId); - t.true(ruleIds.length > 0); + t.true(name && ruleIds.length > 0); // Every test-lint/ file must only cause errors related to its purpose. if (name === "index") {
ab63aa700a31af82e47c8d4958fa5ab6b3bc4474
src/NonASCIIStringSnapshotSerializer.js
src/NonASCIIStringSnapshotSerializer.js
/** * Copyright 2004-present Facebook. All Rights Reserved. * * @emails oncall+ads_integration_management * @flow strict-local * @format */ 'use strict'; const MAX_ASCII_CHARACTER = 127; /** * Serializes strings with non-ASCII characters to their Unicode escape * sequences (eg. \u2022), to avoid hitting this lint rule: * "Source code should only include printable US-ASCII bytes" */ const NonASCIIStringSnapshotSerializer = { test(val: mixed): boolean { if (typeof val !== 'string') { return false; } for (let i = 0; i < val.length; i++) { if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) { return true; } } return false; }, print: (val: string): string => { return ( '"' + val .split('') .map(char => { const code = char.charCodeAt(0); return code > MAX_ASCII_CHARACTER ? '\\u' + code.toString(16).padStart(4, '0') : char; }) .join('') // Keep the same behaviour as Jest's regular string snapshot // serialization, which escapes double quotes. .replace(/"/g, '\\"') + '"' ); }, }; module.exports = NonASCIIStringSnapshotSerializer;
/** * Copyright 2004-present Facebook. All Rights Reserved. * * @emails oncall+ads_integration_management * @flow strict-local * @format */ 'use strict'; const MAX_ASCII_CHARACTER = 127; /** * Serializes strings with non-ASCII characters to their Unicode escape * sequences (eg. \u2022), to avoid hitting this lint rule: * "Source code should only include printable US-ASCII bytes" */ const NonASCIIStringSnapshotSerializer = { test(val: mixed): boolean { if (typeof val !== 'string') { return false; } for (let i = 0; i < val.length; i++) { if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) { return true; } } return false; }, print: (val: string): string => { return ( '"' + val .split('') .map((char) => { const code = char.charCodeAt(0); return code > MAX_ASCII_CHARACTER ? '\\u' + code.toString(16).padStart(4, '0') : char; }) .join('') // Keep the same behaviour as Jest's regular string snapshot // serialization, which escapes double quotes. .replace(/"/g, '\\"') + '"' ); }, }; module.exports = NonASCIIStringSnapshotSerializer;
Format JavaScript files with Prettier: scripts/draft-js/__github__/src
Format JavaScript files with Prettier: scripts/draft-js/__github__/src Differential Revision: D32201648 fbshipit-source-id: f94342845cbe6454bb7ae4f02814e788fb25de9f
JavaScript
mit
facebook/draft-js
--- +++ @@ -33,7 +33,7 @@ '"' + val .split('') - .map(char => { + .map((char) => { const code = char.charCodeAt(0); return code > MAX_ASCII_CHARACTER ? '\\u' + code.toString(16).padStart(4, '0')
259a882114def098b30101aefdcc67366b067aab
src/config.js
src/config.js
module.exports = function(data) { /** * Read in config file and tidy up data * Prefer application to require minimum config as possible */ var config = require('../config.' + environment + '.js'); if (!config.server) config.server = { port: 3000 } if (!config.app) config.app = {} if (!config.cookie) config.cookie = {} config.cookie.key = 'connect.sid'; if (!config.app.useOptimised) { config.app.useOptimised = ('development' == environment) ? false : true; } if (!config.project) config.project = { name: "PinItTo.me" , title: "Welcome!" , _layoutFile: 'layouts/main' , pageName: 'Index' } if (!config.captcha) { config.captcha = { type: 'captcha' } } if (!config.transports || (0 == config.transports.length)) config.transports = config.transports || ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'] config.app.version = data.version config.app.environment = environment config.project.errors = {} config.project.captcha = '' if (!config.app.limits) { config.app.limits = { card: { wait: 0.5 } } } return config }
module.exports = function(data) { /** * Read in config file and tidy up data * Prefer application to require minimum config as possible */ var config = require('../config.' + environment + '.js'); if (!config.server) config.server = { port: 3000 } if (!config.app) config.app = {} if (!config.cookie) config.cookie = {} if (!config.cookie.secret) { config.cookie.secret = 'do-not-tell' console.log('No cookie secret set'.red) } config.cookie.key = 'connect.sid'; if (!config.app.useOptimised) { config.app.useOptimised = ('development' == environment) ? false : true; } if (!config.project) config.project = { name: "PinItTo.me" , title: "Welcome!" , _layoutFile: 'layouts/main' , pageName: 'Index' } if (!config.captcha) { config.captcha = { type: 'captcha' } } if (!config.transports || (0 == config.transports.length)) config.transports = config.transports || ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'] config.app.version = data.version config.app.environment = environment config.project.errors = {} config.project.captcha = '' if (!config.app.limits) { config.app.limits = { card: { wait: 0.5 } } } return config }
Set default cookie secret value
Set default cookie secret value
JavaScript
apache-2.0
pinittome/pinitto.me,pinittome/pinitto.me,pinittome/pinitto.me
--- +++ @@ -12,6 +12,11 @@ if (!config.app) config.app = {} if (!config.cookie) config.cookie = {} + + if (!config.cookie.secret) { + config.cookie.secret = 'do-not-tell' + console.log('No cookie secret set'.red) + } config.cookie.key = 'connect.sid';
26ba50793f316564c6ce0f00e131ccc8b668989a
src/router.js
src/router.js
var controllers = require('./controllers'); var mid = require('./middleware'); var router = function(app) { app.get('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage); app.get('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signupPage); app.get('/logout', mid.requiresSecure, mid.requiresLogin, controllers.Account.logout); app.get('/maker', mid.requiresLogin, controllers.Domo.makerPage); app.get('/', mid.requiresLogout, controllers.Account.loginPage); app.post('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.login); app.post('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signup); app.post('/maker', mid.requiresLogin, controllers.Domo.make); }; module.exports = router;
var controllers = require('./controllers'); var mid = require('./middleware'); var router = function(app) { app.get('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage); app.get('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signupPage); app.get('/logout', mid.requiresSecure, mid.requiresLogin, controllers.Account.logout); app.get('/maker', mid.requiresLogin, controllers.Domo.makerPage); app.get('/', mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage); app.post('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.login); app.post('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signup); app.post('/maker', mid.requiresLogin, controllers.Domo.make); }; module.exports = router;
Add secure requirement to root page.
Add secure requirement to root page.
JavaScript
apache-2.0
cognettings/nefarious-octo-prune,cognettings/nefarious-octo-prune
--- +++ @@ -6,7 +6,7 @@ app.get('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signupPage); app.get('/logout', mid.requiresSecure, mid.requiresLogin, controllers.Account.logout); app.get('/maker', mid.requiresLogin, controllers.Domo.makerPage); - app.get('/', mid.requiresLogout, controllers.Account.loginPage); + app.get('/', mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage); app.post('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.login); app.post('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signup); app.post('/maker', mid.requiresLogin, controllers.Domo.make);
e729d8327a402d403130f005dbb1d54b07a93434
frontend/detail_pane/DetailPaneSection.js
frontend/detail_pane/DetailPaneSection.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; var React = require('react'); class DetailPaneSection extends React.Component { render(): React.Element { var { children, hint, } = this.props; return ( <div style={styles.section}> <strong>{this.props.title}</strong> {hint ? ' ' + hint : null} {children} </div> ); } } var styles = { section: { marginBottom: 10, flexShrink: 0, }, }; module.exports = DetailPaneSection;
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; var React = require('react'); class DetailPaneSection extends React.Component { render(): React.Element { var { children, hint, } = this.props; return ( <div style={styles.section}> <strong>{this.props.title}</strong> {hint ? ' ' + hint : null} {children} </div> ); } } var styles = { section: { marginBottom: 10, flexShrink: 0, }, }; module.exports = DetailPaneSection;
Remove extra blank line for consistency
Remove extra blank line for consistency
JavaScript
bsd-3-clause
jhen0409/react-devtools,woowe/react-dev-tools,aolesky/react-devtools,aadsm/react-devtools,hedgerwang/react-devtools,jhen0409/react-devtools,aadsm/react-devtools,keyanzhang/react-devtools,hedgerwang/react-devtools,keyanzhang/react-devtools,woowe/react-dev-tools,aadsm/react-devtools,hedgerwang/react-devtools,aolesky/react-devtools,aarondancer/react-devtools,aolesky/react-devtools,woowe/react-dev-tools,jhen0409/react-devtools,aarondancer/react-devtools,aarondancer/react-devtools
--- +++ @@ -13,7 +13,6 @@ var React = require('react'); class DetailPaneSection extends React.Component { - render(): React.Element { var { children,
d0e488c8c8da1ed827c5c51382c99c2b25f6819a
addon/utils/init-measure-label.js
addon/utils/init-measure-label.js
import MapLabel from './map-label'; import featureCenter from './feature-center'; import getMeasurement from './get-measurement'; export default function initMeasureLabel(result, map) { if (!result) { return; } if (result.mode === 'measure') { let center = featureCenter(result.feature); let measurement = getMeasurement(result.type, result.feature); result.label = new MapLabel(center, { defaultLabel: `${measurement.value} ${measurement.unit}` }); if (map) { result.label.setMap(map); } } }
import MapLabel from './map-label'; import featureCenter from './feature-center'; import getMeasurement from './get-measurement'; export default function initMeasureLabel(result, map) { if (!result) { return; } if (result.mode === 'measure') { let center = featureCenter(result.feature); let measurement = getMeasurement(result.type, result.feature); result.label = new MapLabel(center); result.label.label = `${measurement.value} ${measurement.unit}`; if (map) { result.label.setMap(map); } } }
Fix measurement label not showing on first load
Fix measurement label not showing on first load After importing the label didn't show up because `defaultLabel` option was removed
JavaScript
mit
knownasilya/google-maps-markup,knownasilya/google-maps-markup
--- +++ @@ -10,9 +10,8 @@ if (result.mode === 'measure') { let center = featureCenter(result.feature); let measurement = getMeasurement(result.type, result.feature); - result.label = new MapLabel(center, { - defaultLabel: `${measurement.value} ${measurement.unit}` - }); + result.label = new MapLabel(center); + result.label.label = `${measurement.value} ${measurement.unit}`; if (map) { result.label.setMap(map);
b88680fdb87dfd4975dbd568a7ac253315354935
express-res-links.js
express-res-links.js
import {stringify as stringifyLinks} from 'http-header-link' export default function (req, res, next) { res.links = function links (linkObj, lang = false) { let val = this.get('Link') || '' lang = lang || this.get('Content-Language') || linkObj.defaultLang const newLinks = stringifyLinks(linkObj, lang) if (val) { val = val.trim() if (newLinks) { val += ', ' } } val += newLinks this.set('Link', val) } next() }
import {stringify as stringifyLinks} from 'http-header-link' export default function (req, res, next) { res.links = function links (linkObj, lang = false) { if (typeof linkObj !== 'object') { throw new Error('res.links expects linkObj to be an object') } let val = this.get('Link') || '' lang = lang || this.get('Content-Language') || linkObj.defaultLang const newLinks = stringifyLinks(linkObj, lang) if (val) { val = val.trim() if (newLinks) { val += ', ' } } val += newLinks this.set('Link', val) } next() }
Enforce arg0 being an object
Enforce arg0 being an object
JavaScript
mit
ileri/express-res-links
--- +++ @@ -2,6 +2,10 @@ export default function (req, res, next) { res.links = function links (linkObj, lang = false) { + if (typeof linkObj !== 'object') { + throw new Error('res.links expects linkObj to be an object') + } + let val = this.get('Link') || '' lang = lang || this.get('Content-Language') || linkObj.defaultLang
05e26d001bc0c577472c7284dccafd0d3526408a
ui.apps/src/main/webpack/bundles/components.js
ui.apps/src/main/webpack/bundles/components.js
// https://webpack.js.org/guides/dependency-management/#require-context const cache = {}; function importAll(r) { r.keys().forEach((key) => { return cache[key] = r(key); }); } // Include all files named "index.js" in a "webpack.modules/" folder. importAll(require.context('./../../content/jcr_root/', true, /\/webpack\.module\/index\.js$/));
/** * Uncomment the following line to include Babel's polyfill. * Note that this increases the size of the bundled JavaScript file. * So be smart about when and where to include the polyfill. */ // import 'babel-polyfill'; // https://webpack.js.org/guides/dependency-management/#require-context const cache = {}; function importAll(r) { r.keys().forEach((key) => { return cache[key] = r(key); }); } // Include all files named "index.js" in a "webpack.modules/" folder. importAll(require.context('./../../content/jcr_root/', true, /\/webpack\.module\/index\.js$/));
Add note about Babel Polyfill
Add note about Babel Polyfill
JavaScript
mit
infielddigital/aem-webpack-example,infielddigital/aem-webpack-example
--- +++ @@ -1,10 +1,17 @@ +/** + * Uncomment the following line to include Babel's polyfill. + * Note that this increases the size of the bundled JavaScript file. + * So be smart about when and where to include the polyfill. + */ +// import 'babel-polyfill'; + // https://webpack.js.org/guides/dependency-management/#require-context const cache = {}; function importAll(r) { - r.keys().forEach((key) => { - return cache[key] = r(key); - }); + r.keys().forEach((key) => { + return cache[key] = r(key); + }); } // Include all files named "index.js" in a "webpack.modules/" folder.
3f8e0dd1bb6261f7991790d78f3c20b9df9a2ace
tasks/jscs.js
tasks/jscs.js
"use strict"; var Vow = require( "vow" ); module.exports = function( grunt ) { var filter = Array.prototype.filter, JSCS = require( "./lib/jscs" ).init( grunt ); grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() { var done = this.async(), options = this.options({ config: null }), jscs = new JSCS( options ), checks = this.filesSrc.map(function( path ) { return jscs.check( path ); }); Vow.allResolved( checks ).spread(function() { // Filter unsuccessful promises var results = filter.call( arguments, function( promise ) { return promise.isFulfilled(); // Make array of errors }).map(function( promise ) { return promise.valueOf()[ 0 ]; }); jscs.setErrors( results ).report().notify(); done( options.force || !jscs.count() ); }); }); };
"use strict"; var Vow = require( "vow" ); module.exports = function( grunt ) { var filter = Array.prototype.filter, JSCS = require( "./lib/jscs" ).init( grunt ); grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() { var done = this.async(), options = this.options({ // null is a default value, but its equivalent to `true`, // with this way it's easy to distinguish specified value config: null }), jscs = new JSCS( options ), checks = this.filesSrc.map(function( path ) { return jscs.check( path ); }); Vow.allResolved( checks ).spread(function() { // Filter unsuccessful promises var results = filter.call( arguments, function( promise ) { return promise.isFulfilled(); // Make array of errors }).map(function( promise ) { return promise.valueOf()[ 0 ]; }); jscs.setErrors( results ).report().notify(); done( options.force || !jscs.count() ); }); }); };
Add comment for null as default value
Add comment for null as default value
JavaScript
mit
jscs-dev/grunt-jscs,BridgeAR/grunt-jscs
--- +++ @@ -10,6 +10,9 @@ grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() { var done = this.async(), options = this.options({ + + // null is a default value, but its equivalent to `true`, + // with this way it's easy to distinguish specified value config: null }),
552ba28555855f44ad37c274db40986c8ee41e45
redux/src/main/renderer/components/Editor.js
redux/src/main/renderer/components/Editor.js
import React, {Component} from 'react' import {keyStringDetector} from '../registories/registory' export default class Editor extends Component { constructor(props) { super(props); this.state = {text: ''}; } getRestTextLength() { return 140 - this.state.text.length; } onTextareaChanged(event) { this.setState({text: event.target.value}); } onTextareaKeyDown(event) { if (keyStringDetector.detect(event) === 'Return') { event.preventDefault(); this.onTweetSubmitted(); } } onTweetSubmitted() { const {onTweetSubmitted} = this.props; onTweetSubmitted(this.state.text); } //TODO: 140字を超えたらviewを変更して伝える render() { return ( <div className="editor"> <textarea name="name" rows="2" cols="40" className="editor-textarea" onChange={this.onTextareaChanged.bind(this)} onKeyDown={this.onTextareaKeyDown.bind(this)} placeholder="What's happening?" value={this.state.text}> </textarea> <div className="editor-counter"> {this.getRestTextLength()} </div> </div> ); } }
import React, {Component} from 'react' import {keyStringDetector} from '../registories/registory' export default class Editor extends Component { constructor(props) { super(props); this.state = this.initialState(); } initialState() { return {text: ''}; } getRestTextLength() { return 140 - this.state.text.length; } onTextareaChanged(event) { this.setState({text: event.target.value}); } onTextareaKeyDown(event) { if (keyStringDetector.detect(event) === 'Return') { event.preventDefault(); this.onTweetSubmitted(); } } onTweetSubmitted() { const {onTweetSubmitted} = this.props; onTweetSubmitted(this.state.text); this.setState(this.initialState()); //TODO: tweetが成功したらテキストを初期化する } //TODO: 140字を超えたらviewを変更して伝える render() { return ( <div className="editor"> <textarea name="name" rows="2" cols="40" className="editor-textarea" onChange={this.onTextareaChanged.bind(this)} onKeyDown={this.onTextareaKeyDown.bind(this)} placeholder="What's happening?" value={this.state.text}> </textarea> <div className="editor-counter"> {this.getRestTextLength()} </div> </div> ); } }
Clear textarea after posting tweet
Clear textarea after posting tweet
JavaScript
mit
wozaki/twitter-js-apps,wozaki/twitter-js-apps
--- +++ @@ -5,7 +5,11 @@ constructor(props) { super(props); - this.state = {text: ''}; + this.state = this.initialState(); + } + + initialState() { + return {text: ''}; } getRestTextLength() { @@ -25,7 +29,9 @@ onTweetSubmitted() { const {onTweetSubmitted} = this.props; + onTweetSubmitted(this.state.text); + this.setState(this.initialState()); //TODO: tweetが成功したらテキストを初期化する } //TODO: 140字を超えたらviewを変更して伝える
d2eb3ebfb3e82d1fc86b867fed795b97a692c5cd
app/assets/javascripts/application/specialist_guide_pagination.js
app/assets/javascripts/application/specialist_guide_pagination.js
$(function() { var container = $(".specialistguide .govspeak"); var navigation = $(".specialistguide #document_sections"); container.splitIntoPages("h2"); pages = container.find(".page"); pages.hide(); var showDefaultPage = function() { pages.first().show(); } var showPage = function(hash) { var heading = $(hash); if (heading.is(":visible")) { return; } pages.hide(); heading.parents(".page").show(); $('html, body').animate({scrollTop:heading.offset().top}, 0); } navigation.find(">li").each(function(el){ var li = $(this), pageNav = li.find('>ol'), chapterSelector = '#' + li.find('>a').attr('href').split('#')[1], inPageNavigation = $("<div class='in-page-navigation'><h3>On this page</h3></div>"); if (pageNav.length > 0) { inPageNavigation.append(pageNav); $(chapterSelector).after(inPageNavigation); } }); $(window).hashchange(function() { if ((location.hash == "") || (location.hash == "#undefined")) { showDefaultPage(); } else { showPage(location.hash); } }) $(window).hashchange(); })
$(function() { var container = $(".specialistguide .govspeak"); var navigation = $(".specialistguide #document_sections"); container.splitIntoPages("h2"); pages = container.find(".page"); pages.hide(); var showPage = function() { var heading = $(location.hash); if (heading.length == 0) { pages.first().show(); return; } if (heading.is(":visible")) { return; } pages.hide(); heading.parents(".page").show(); $('html, body').animate({scrollTop:heading.offset().top}, 0); } navigation.find(">li").each(function(el){ var li = $(this), pageNav = li.find('>ol'), chapterSelector = '#' + li.find('>a').attr('href').split('#')[1], inPageNavigation = $("<div class='in-page-navigation'><h3>On this page</h3></div>"); if (pageNav.length > 0) { inPageNavigation.append(pageNav); $(chapterSelector).after(inPageNavigation); } }); $(window).hashchange(showPage) $(window).hashchange(); })
Simplify and strengthen specialist guide hide/display page ccode.
Simplify and strengthen specialist guide hide/display page ccode. If the page for the hash can't be found, the first page is shown, preventing js errors if people hack in different hashes (or click on old links)
JavaScript
mit
hotvulcan/whitehall,ggoral/whitehall,ggoral/whitehall,robinwhittleton/whitehall,alphagov/whitehall,hotvulcan/whitehall,alphagov/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall,askl56/whitehall,YOTOV-LIMITED/whitehall,robinwhittleton/whitehall,askl56/whitehall,robinwhittleton/whitehall,askl56/whitehall,hotvulcan/whitehall,askl56/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall,YOTOV-LIMITED/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall,alphagov/whitehall,alphagov/whitehall
--- +++ @@ -6,12 +6,13 @@ pages = container.find(".page"); pages.hide(); - var showDefaultPage = function() { - pages.first().show(); - } + var showPage = function() { + var heading = $(location.hash); - var showPage = function(hash) { - var heading = $(hash); + if (heading.length == 0) { + pages.first().show(); + return; + } if (heading.is(":visible")) { return; @@ -34,13 +35,6 @@ } }); - $(window).hashchange(function() { - if ((location.hash == "") || (location.hash == "#undefined")) { - showDefaultPage(); - } else { - showPage(location.hash); - } - }) - + $(window).hashchange(showPage) $(window).hashchange(); })
813fede79c31161c54edea2fd706de79ba9c9769
src/api/properties/array.js
src/api/properties/array.js
const { parse, stringify } = window.JSON; export default { coerce (val) { return Array.isArray(val) ? val : [val]; }, default () { return []; }, deserialize (val) { return parse(val); }, serialize (val) { return stringify(val); } };
export default { coerce: val => Array.isArray(val) ? val : [val], default: () => [], deserialize: JSON.parse, serialize: JSON.stringify };
Make code a bit more concise.
Make code a bit more concise.
JavaScript
mit
skatejs/skatejs,chrisdarroch/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs
--- +++ @@ -1,16 +1,6 @@ -const { parse, stringify } = window.JSON; - export default { - coerce (val) { - return Array.isArray(val) ? val : [val]; - }, - default () { - return []; - }, - deserialize (val) { - return parse(val); - }, - serialize (val) { - return stringify(val); - } + coerce: val => Array.isArray(val) ? val : [val], + default: () => [], + deserialize: JSON.parse, + serialize: JSON.stringify };
8bf0cb0069d886b8afe6dc52a31b806496568253
public/theme/portalshit/script.js
public/theme/portalshit/script.js
(function() { var target = $('.archives li').slice(7); target.each(function() { $(this).css("display", "none"); }) $('#show_more_archive_list').click(function() { target.each(function() { $(this).slideDown(); }) $(this).hide(); $('#show_less_archive_list').show(); }) $('#show_less_archive_list').click(function() { target.each(function() { $(this).slideUp(); }) $(this).hide(); $('#show_more_archive_list').show(); }) var init = function(node) { } document.body.addEventListener('AutoPagerize_DOMNodeInserted',function(evt){ var node = evt.target; var requestURL = evt.newValue; var parentNode = evt.relatedNode; init(node); }, false); init(document); })(); window.onload = function() { // fit image for iPad if (navigator.userAgent.match(/iPad/)) { $('.article img').each(function() { var newWidth = document.body.offsetWidth - 60; var imageRatio = this.naturalHeight / this.naturalWidth; if (this.naturalWidth > newWidth) { this.width = newWidth; this.height = newWidth * imageRatio; } }); } };
(function() { var target = $('.archives li').slice(7); target.each(function() { $(this).css("display", "none"); }) $('#show_more_archive_list').click(function() { target.each(function() { $(this).slideDown(); }) $(this).hide(); $('#show_less_archive_list').show(); }) $('#show_less_archive_list').click(function() { target.each(function() { $(this).slideUp(); }) $(this).hide(); $('#show_more_archive_list').show(); }) var init = function(node) { // fit image for iPhone /* if (navigator.userAgent.match(/iPad/)) { */ /* } */ } document.body.addEventListener('AutoPagerize_DOMNodeInserted',function(evt){ var node = evt.target; var requestURL = evt.newValue; var parentNode = evt.relatedNode; init(node); }, false); init(document); })(); window.onload = function() { $('.article img').each(function() { var newWidth = document.body.offsetWidth - 60; var imageRatio = this.naturalHeight / this.naturalWidth; if (this.naturalWidth > newWidth) { this.width = newWidth; this.height = newWidth * imageRatio; } }); };
Revert "Resize only when UA matches iPad"
Revert "Resize only when UA matches iPad" This reverts commit d5260394049c993a4f4ddcea3cbe694212c36f38.
JavaScript
mit
morygonzalez/portalshit.net,morygonzalez/portalshit.net,morygonzalez/portalshit.net,morygonzalez/portalshit.net
--- +++ @@ -23,6 +23,9 @@ }) var init = function(node) { + // fit image for iPhone + /* if (navigator.userAgent.match(/iPad/)) { */ + /* } */ } document.body.addEventListener('AutoPagerize_DOMNodeInserted',function(evt){ @@ -36,16 +39,13 @@ })(); window.onload = function() { - // fit image for iPad - if (navigator.userAgent.match(/iPad/)) { - $('.article img').each(function() { - var newWidth = document.body.offsetWidth - 60; - var imageRatio = this.naturalHeight / this.naturalWidth; + $('.article img').each(function() { + var newWidth = document.body.offsetWidth - 60; + var imageRatio = this.naturalHeight / this.naturalWidth; - if (this.naturalWidth > newWidth) { - this.width = newWidth; - this.height = newWidth * imageRatio; - } - }); - } + if (this.naturalWidth > newWidth) { + this.width = newWidth; + this.height = newWidth * imageRatio; + } + }); };
d8dac75e6bbbdecfb3ca6f37326dfc35de28da8c
lib/insert.js
lib/insert.js
'use strict' module.exports = function insertInit (showErrors, showStdout) { var callback if (showErrors && showStdout) { callback = function (e, result) { if (e) { console.error(e) return } console.log(JSON.stringify(result.ops[0])) } } else if (showErrors && !showStdout) { callback = function (e) { if (e) { console.error(e) } } } else if (!showErrors && showStdout) { callback = function (e, result) { console.log(JSON.stringify(result.ops[0])) } } return function insert (collection, log) { collection.insertOne(log, { forceServerObjectId: true }, callback) } }
'use strict' module.exports = function insertInit (showErrors, showStdout) { var callback if (showErrors && showStdout) { callback = function (e, result) { if (e) { console.error(e) return } process.stdout.write(JSON.stringify(result.ops[0]) + '\n') } } else if (showErrors && !showStdout) { callback = function (e) { if (e) { console.error(e) } } } else if (!showErrors && showStdout) { callback = function (e, result) { process.stdout.write(JSON.stringify(result.ops[0]) + '\n') } } return function insert (collection, log) { collection.insertOne(log, { forceServerObjectId: true }, callback) } }
Replace console.log to process.stdout to write without formatting
Replace console.log to process.stdout to write without formatting
JavaScript
mit
ViktorKonsta/pino-mongodb
--- +++ @@ -9,7 +9,7 @@ console.error(e) return } - console.log(JSON.stringify(result.ops[0])) + process.stdout.write(JSON.stringify(result.ops[0]) + '\n') } } else if (showErrors && !showStdout) { callback = function (e) { @@ -19,7 +19,7 @@ } } else if (!showErrors && showStdout) { callback = function (e, result) { - console.log(JSON.stringify(result.ops[0])) + process.stdout.write(JSON.stringify(result.ops[0]) + '\n') } }
a2c6b35869dd5b9b9bd918f076756bad55d9901c
app/js/arethusa.relation/directives/nested_menu.js
app/js/arethusa.relation/directives/nested_menu.js
"use strict"; angular.module('arethusa.relation').directive('nestedMenu', [ '$compile', 'relation', function($compile, relation) { return { restrict: 'A', scope: { relObj: '=', labelObj: '=', label: '=', property: '=', ancestors: '=' }, link: function(scope, element, attrs) { var html = '\ <ul\ nested-menu-collection\ current="relObj"\ property="property"\ ancestors="ancestors"\ all="labelObj.nested">\ </ul>\ '; if (scope.labelObj.nested) { element.append($compile(html)(scope)); } scope.selectLabel = function() { scope.relObj[scope.property] = scope.label; relation.buildLabel(scope.relObj); }; element.bind('click', function(event) { scope.$apply(function() { if (event.eventPhase === 2) { // at target, three would be bubbling! scope.selectLabel(); if (scope.ancestors) { relation.resetAncestors(scope.relObj); } } if (scope.ancestors) { relation.addAncestor(scope.relObj, scope.label); } }); }); }, template: '{{ label }}' }; } ]);
"use strict"; angular.module('arethusa.relation').directive('nestedMenu', [ '$compile', 'relation', function($compile, relation) { return { restrict: 'A', scope: { relObj: '=', labelObj: '=', label: '=', property: '=', ancestors: '=' }, link: function(scope, element, attrs) { var html = '\ <ul\ nested-menu-collection\ current="relObj"\ property="property"\ ancestors="ancestors"\ all="labelObj.nested">\ </ul>\ '; if (scope.labelObj.nested) { element.append($compile(html)(scope)); element.addClass('nested'); } scope.selectLabel = function() { scope.relObj[scope.property] = scope.label; relation.buildLabel(scope.relObj); }; element.bind('click', function(event) { scope.$apply(function() { if (event.eventPhase === 2) { // at target, three would be bubbling! scope.selectLabel(); if (scope.ancestors) { relation.resetAncestors(scope.relObj); } } if (scope.ancestors) { relation.addAncestor(scope.relObj, scope.label); } }); }); }, template: '{{ label }}' }; } ]);
Add a nested class for nested menus
Add a nested class for nested menus
JavaScript
mit
Masoumeh/arethusa,PonteIneptique/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa,Masoumeh/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa
--- +++ @@ -26,6 +26,7 @@ if (scope.labelObj.nested) { element.append($compile(html)(scope)); + element.addClass('nested'); } scope.selectLabel = function() {
645cd395a670abc82b4ca2312899ded66e80d2eb
app/mixins/handles-validation-errors-for-inputs.js
app/mixins/handles-validation-errors-for-inputs.js
import Ember from 'ember'; export default Ember.Mixin.create({ errors: [], showError: false, syncErrors: function () { if (this.get('isDestroyed')) return; this.set('errors', this.get('parentModel.errors.' + this.get('name'))); }, observeErrors: function () { if (!this.get('parentModel')) return; this.get('parentModel').addObserver('errors.' + this.get('name'), this, this.syncErrors); }.on('didInsertElement'), // Propagate showError changes to parentModel errorVisibilityForModel: function () { var parentModel = this.get('parentModel'); if (this.get('showError')) { parentModel.trigger('shouldShowValidationError', this.get('name')); } else { parentModel.trigger('shouldDismissValidationError', this.get('name')); } }.observes('showError', 'name') });
import Ember from 'ember'; export default Ember.Mixin.create({ errors: [], showError: false, syncErrors: function () { if (this.get('isDestroyed')) return; this.set('errors', this.get('parentModel.errors.' + this.get('name'))); }, observeErrors: function () { if (!this.get('parentModel')) return; this.get('parentModel').addObserver('errors.' + this.get('name'), this, this.syncErrors); }.on('didInsertElement'), // Propagate showError changes to parentModel errorVisibilityForModel: function () { var parentModel = this.get('parentModel'); if (!parentModel) return; if (this.get('showError')) { parentModel.trigger('shouldShowValidationError', this.get('name')); } else { parentModel.trigger('shouldDismissValidationError', this.get('name')); } }.observes('showError', 'name') });
Return created PaymentMethod when user's 401's in /your-account/billing
Return created PaymentMethod when user's 401's in /your-account/billing
JavaScript
mit
dollarshaveclub/ember-uni-form,dollarshaveclub/ember-uni-form
--- +++ @@ -18,6 +18,8 @@ // Propagate showError changes to parentModel errorVisibilityForModel: function () { var parentModel = this.get('parentModel'); + if (!parentModel) return; + if (this.get('showError')) { parentModel.trigger('shouldShowValidationError', this.get('name')); } else {
2c7ae72aba286d62526643326e71a942965cee60
app/js/filters/dotToDash.js
app/js/filters/dotToDash.js
'use strict'; angular.module('gisto.filter.dotToDash', []).filter('dotToDash', function () { return function (input) { return input.replace('.','-'); }; });
'use strict'; angular.module('gisto.filter.dotToDash', []).filter('dotToDash', function () { return function (input) { var output = input; if(input.charAt(0) === '.') { output = input.substr(1); } return output.replace('.','-'); }; });
FIX (dotfiles in gist): fix links of dotfiles
FIX (dotfiles in gist): fix links of dotfiles - fix links of dotfiles not handled correctly by "dotToDash" custom filter
JavaScript
mit
Gisto/Gisto,Gisto/Gisto,Gisto/Gisto,shmool/Gisto,shmool/Gisto,shmool/Gisto,Gisto/Gisto
--- +++ @@ -2,6 +2,10 @@ angular.module('gisto.filter.dotToDash', []).filter('dotToDash', function () { return function (input) { - return input.replace('.','-'); + var output = input; + if(input.charAt(0) === '.') { + output = input.substr(1); + } + return output.replace('.','-'); }; });
40db9627f80e15aadc231fc3c4ad73fd4afff028
scripts/command-line-utilities.js
scripts/command-line-utilities.js
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ /* eslint-disable no-console, global-require */ import path from 'path'; const exec = ({ command, isExecuted = true, message, dir = '.', rootPath, verbose = true }, callback) => { if (isExecuted) { if (message) { console.log(message); } const child = require('child_process').exec(command, { cwd: path.resolve(rootPath, dir), maxBuffer: 1024 * 500 }, (err) => { callback(err); }); if (verbose === true) { child.stdout.on('data', (data) => process.stdout.write(data.toString())); } } }; export { exec as default };
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ /* eslint-disable no-console, global-require */ import path from 'path'; const exec = ({ command, message, dir = '.', rootPath, verbose = true }, callback) => { if (message) { console.log(message); } const child = require('child_process').exec(command, { cwd: path.resolve(rootPath, dir), maxBuffer: 1024 * 500 }, (err) => { callback(err); }); if (verbose === true) { child.stdout.on('data', (data) => process.stdout.write(data.toString())); } }; export { exec as default };
Remove isExecuted from CLI utils
Remove isExecuted from CLI utils
JavaScript
bsd-3-clause
salesforce/design-system-react,salesforce/design-system-react,salesforce/design-system-react
--- +++ @@ -7,26 +7,23 @@ const exec = ({ command, - isExecuted = true, message, dir = '.', rootPath, verbose = true }, callback) => { - if (isExecuted) { - if (message) { - console.log(message); - } - const child = require('child_process').exec(command, { - cwd: path.resolve(rootPath, dir), - maxBuffer: 1024 * 500 - }, (err) => { - callback(err); - }); + if (message) { + console.log(message); + } + const child = require('child_process').exec(command, { + cwd: path.resolve(rootPath, dir), + maxBuffer: 1024 * 500 + }, (err) => { + callback(err); + }); - if (verbose === true) { - child.stdout.on('data', (data) => process.stdout.write(data.toString())); - } + if (verbose === true) { + child.stdout.on('data', (data) => process.stdout.write(data.toString())); } };
431c9354ae176f0ab2020776145e85bef2dfcd58
app/assets/javascripts/refresh.js
app/assets/javascripts/refresh.js
function refresh () { $(".refresh-link").on("click", function(event) { event.preventDefault(); var $target = $(event.target); var url = $target.attr("href"); var id = url.match(/(\d+)(?!.*\d)/)[0].toString(); var dateTimeIn24Hours = new Date(); var $dateSpan = $(".data" + id); var $timeRemainingSpan = $(".time-remaining" + id); var longest = parseInt($("#longest" + id).text(), 10); var current = parseInt($("#current" + id).text(), 10); $.ajax({ url: url, type: "get" }).done(function(response) { countdown(); }); }); }
function refresh () { $(".refresh-link").on("click", function(event) { event.preventDefault(); var $target = $(event.target); var url = $target.attr("href"); var id = url.match(/(\d+)(?!.*\d)/)[0].toString(); var dateTimeIn24Hours = new Date(); var $dateSpan = $(".data" + id); var $timeRemainingSpan = $(".time-remaining" + id); var longest = parseInt($("#longest" + id).text(), 10); var current = parseInt($("#current" + id).text(), 10); $.ajax({ url: url, type: "get" }).done(function(response) { if ($timeRemainingSpan.text() === "Chain broken:") { $timeRemainingSpan.html("Time remaining: "); $dateSpan.attr("data-countdown", formatCurrentDateTime(dateTimeIn24Hours)); } else { $dateSpan.data("countdown", formatCurrentDateTime(dateTimeIn24Hours)); } incrementStreak(current, longest, id); countdown(); }); }); }
Add conditional to check if chain is currently broken or active
Add conditional to check if chain is currently broken or active
JavaScript
mit
costolo/chain,costolo/chain,costolo/chain
--- +++ @@ -14,6 +14,13 @@ url: url, type: "get" }).done(function(response) { + if ($timeRemainingSpan.text() === "Chain broken:") { + $timeRemainingSpan.html("Time remaining: "); + $dateSpan.attr("data-countdown", formatCurrentDateTime(dateTimeIn24Hours)); + } else { + $dateSpan.data("countdown", formatCurrentDateTime(dateTimeIn24Hours)); + } + incrementStreak(current, longest, id); countdown(); }); });
f711b8d6d6154d8bec444c7ba4d0a2f1ac6387ed
cronjobs.js
cronjobs.js
#!/bin/env node module.exports = function() { var scope = this; this.CronJob = require('cron').CronJob; this.NewReleases = require(__dirname + '/newreleases'); this.User = require(__dirname + '/db/user'); this.jobs = []; this.init = function() { // TODO: select distinct crontime and timezone from database users scope.jobs.push( new scope.CronJob( { cronTime: '10 * * * * *', onTick: scope.runCheck, start: true, timeZone: "Europe/Amsterdam" }) ); }; this.runCheck = function() { console.log(this.cronTime.source); console.log(this.cronTime.zone); scope.User.find({active:true, crontime: this.cronTime.source, timezone: this.cronTime.zone}, function(err, users) { if(err) { console.log('Error getting users from the database: '+ err); } users.forEach(function(user) { var releases = new scope.NewReleases(); releases.checkNewReleases(user); }); }); }; };
#!/bin/env node module.exports = function() { var scope = this; this.CronJob = require('cron').CronJob; this.NewReleases = require(__dirname + '/newreleases'); this.User = require(__dirname + '/db/user'); this.jobs = []; this.init = function() { // TODO: select distinct crontime and timezone from database users scope.jobs.push( new scope.CronJob( { cronTime: '* 00 11 * * *', onTick: scope.runCheck, start: true, timeZone: "Europe/Amsterdam" }) ); }; this.runCheck = function() { console.log(this.cronTime.source); console.log(this.cronTime.zone); scope.User.find({active:true, crontime: this.cronTime.source, timezone: this.cronTime.zone}, function(err, users) { if(err) { console.log('Error getting users from the database: '+ err); } users.forEach(function(user) { var releases = new scope.NewReleases(); releases.checkNewReleases(user); }); }); }; };
Set default to once a day for now
Set default to once a day for now
JavaScript
mit
HalleyInteractive/new-release-notifier,HalleyInteractive/new-release-notifier
--- +++ @@ -15,7 +15,7 @@ scope.jobs.push( new scope.CronJob( { - cronTime: '10 * * * * *', + cronTime: '* 00 11 * * *', onTick: scope.runCheck, start: true, timeZone: "Europe/Amsterdam"
1c9dd302192c8842ffd760e8e1689b602b4350c4
examples/simple/webpack.config.js
examples/simple/webpack.config.js
var path = require( 'path' ); var webpack = require( 'webpack' ); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index.jsx' ], output: { path: path.join( __dirname, 'dist' ), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.jsx?$/, loaders: [ 'babel' ], exclude: /node_modules/, include: __dirname } ] } };
var path = require( 'path' ); var webpack = require( 'webpack' ); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index.jsx' ], output: { path: path.join( __dirname, 'dist' ), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.jsx?$/, loaders: [ 'babel' ], exclude: /node_modules/, include: __dirname } ] }, resolve: { extensions: [ '', '.js', '.jsx' ], modulesDirectories: [ 'node_modules' ] } };
Add .jsx to resolver for webpack.
Add .jsx to resolver for webpack.
JavaScript
mit
coderkevin/redux-trigger
--- +++ @@ -24,5 +24,9 @@ exclude: /node_modules/, include: __dirname } ] + }, + resolve: { + extensions: [ '', '.js', '.jsx' ], + modulesDirectories: [ 'node_modules' ] } };
cd9c75960c99ece71cadd691eb0297850e623a47
spec/javascripts/behaviors/autosize_spec.js
spec/javascripts/behaviors/autosize_spec.js
/* eslint-disable space-before-function-paren, no-var, comma-dangle, no-return-assign, max-len */ import '~/behaviors/autosize'; (function() { describe('Autosize behavior', function() { var load; beforeEach(function() { return setFixtures('<textarea class="js-autosize" style="resize: vertical"></textarea>'); }); it('does not overwrite the resize property', function() { load(); return expect($('textarea')).toHaveCss({ resize: 'vertical' }); }); return load = function() { return $(document).trigger('load'); }; }); }).call(window);
import '~/behaviors/autosize'; function load() { $(document).trigger('load'); } describe('Autosize behavior', () => { beforeEach(() => { setFixtures('<textarea class="js-autosize" style="resize: vertical"></textarea>'); }); it('does not overwrite the resize property', () => { load(); expect($('textarea')).toHaveCss({ resize: 'vertical', }); }); });
Remove iife and eslint disable
Remove iife and eslint disable
JavaScript
mit
mmkassem/gitlabhq,stoplightio/gitlabhq,jirutka/gitlabhq,dreampet/gitlab,jirutka/gitlabhq,mmkassem/gitlabhq,iiet/iiet-git,mmkassem/gitlabhq,axilleas/gitlabhq,dreampet/gitlab,jirutka/gitlabhq,iiet/iiet-git,dreampet/gitlab,axilleas/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,iiet/iiet-git,axilleas/gitlabhq,dreampet/gitlab,axilleas/gitlabhq,stoplightio/gitlabhq,stoplightio/gitlabhq,jirutka/gitlabhq,iiet/iiet-git
--- +++ @@ -1,21 +1,18 @@ -/* eslint-disable space-before-function-paren, no-var, comma-dangle, no-return-assign, max-len */ - import '~/behaviors/autosize'; -(function() { - describe('Autosize behavior', function() { - var load; - beforeEach(function() { - return setFixtures('<textarea class="js-autosize" style="resize: vertical"></textarea>'); +function load() { + $(document).trigger('load'); +} + +describe('Autosize behavior', () => { + beforeEach(() => { + setFixtures('<textarea class="js-autosize" style="resize: vertical"></textarea>'); + }); + + it('does not overwrite the resize property', () => { + load(); + expect($('textarea')).toHaveCss({ + resize: 'vertical', }); - it('does not overwrite the resize property', function() { - load(); - return expect($('textarea')).toHaveCss({ - resize: 'vertical' - }); - }); - return load = function() { - return $(document).trigger('load'); - }; }); -}).call(window); +});
d468959a91e3f4bd83ac8ca73b8ee698483bb03b
lib/logMiddleware.js
lib/logMiddleware.js
'use strict' const morgan = require('morgan') // This adds a very simple log message for each request. Morgan is a package // from express to do this, and we use tiny so we don't record any user // information to logs in production. // // TODO: Add a different log format for dev & staging that provides more // information for debugging. module.exports = morgan('tiny')
'use strict' const morgan = require('morgan') // This adds a very simple log message for each request. Morgan is a package // from express to do this, and we use tiny so we don't record any user // information to logs in production. // // TODO: Add a different log format for dev & staging that provides more // information for debugging. module.exports = morgan(':date[iso] :method :url :status :res[content-length] - :response-time ms')
Add datetime to log format
Add datetime to log format
JavaScript
mit
firstlookmedia/react-scripts,firstlookmedia/react-scripts
--- +++ @@ -8,4 +8,4 @@ // // TODO: Add a different log format for dev & staging that provides more // information for debugging. -module.exports = morgan('tiny') +module.exports = morgan(':date[iso] :method :url :status :res[content-length] - :response-time ms')
b78b249b6650c7381d234cb0a737dab408979e59
src/main/webapp/components/utils/getFields.js
src/main/webapp/components/utils/getFields.js
import {getField} from "./getField"; /** * Creates a new object whose fields are either equal to obj[field] or defaultValue. * Useful for extracting a subset of fields from an object. * * @param obj the object to query the fields for. * @param fields an array of the target fields, in string form. * @param defaultValue the value to be used if obj[field] === undefined. */ export const getFields = (obj, fields, defaultValue) => { const result = { }; for(const field of fields) result[field] = getField(obj, field, defaultValue); return result; }
import {getField} from "./getField"; /** * Creates a new object whose fields are either equal to obj[field] or defaultValue. * Useful for extracting a subset of fields from an object. * * @param obj the object to query the fields for. * @param fields an array of the target fields, in string form. * @param defaultValue the value to be used if obj[field] === undefined. */ export const getFields = (obj, fields, defaultValue) => { const result = {}; for(const field of fields) result[field] = getField(obj, field, defaultValue); return result; }
Delete Space from empty Object
Delete Space from empty Object
JavaScript
apache-2.0
googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020
--- +++ @@ -9,7 +9,7 @@ * @param defaultValue the value to be used if obj[field] === undefined. */ export const getFields = (obj, fields, defaultValue) => { - const result = { }; + const result = {}; for(const field of fields) result[field] = getField(obj, field, defaultValue); return result; }
990f5face2b6eab527e91e98e6d20227c1673479
app/js/models/user/User.Module.js
app/js/models/user/User.Module.js
var _ = require('underscore'); var Mosaic = require('mosaic-commons'); var App = require('mosaic-core').App; var Api = App.Api; var Teleport = require('mosaic-teleport'); /** This module manages resource statistics. */ module.exports = Api.extend({ /** * Initializes internal fields. */ _initFields : function() { this._user = null; }, /** * Loads information about selected/active entities. */ start : function() { }, /** Closes this module. */ stop : function() { }, _http : function(url, method) { method = method || 'GET'; var client = Teleport.HttpClient.newInstance({ baseUrl : url }); return client.exec({ path : '', method : method }).then(function(json) { try { return _.isObject(json) ? json : JSON.parse(json); } catch (err) { return; } }); }, logout : function() { return this._http(this.app.options.logoutApiUrl).then(function(user) { return user; }); }, getUserInfo : function() { return this._http(this.app.options.userInfoApiUrl).then(function(user) { if (!user || !user.displayName) return; return user; }); }, });
var _ = require('underscore'); var Mosaic = require('mosaic-commons'); var App = require('mosaic-core').App; var Api = App.Api; var Teleport = require('mosaic-teleport'); /** This module manages resource statistics. */ module.exports = Api.extend({ /** * Initializes internal fields. */ _initFields : function() { this._user = null; }, /** * Loads information about selected/active entities. */ start : function() { }, /** Closes this module. */ stop : function() { }, _http : function(url, method) { method = method || 'GET'; var client = Teleport.HttpClient.newInstance({ baseUrl : url }); return client.exec({ path : '', method : method }).then(function(json) { try { return _.isObject(json) ? json : JSON.parse(json); } catch (err) { return; } }); }, logout : function() { var that = this; return this._http(this.app.options.logoutApiUrl).then(function(user) { return that.notify(); }).then(function() { return user; }); }, getUserInfo : function() { return this._http(this.app.options.userInfoApiUrl).then(function(user) { if (!user || !user.displayName) return; return user; }); }, });
Add notifications for changes in the user module
Add notifications for changes in the user module
JavaScript
mit
ubimix/techonmap-v2,ubimix/techonmap-v2,ubimix/techonmap-v2
--- +++ @@ -42,7 +42,10 @@ }, logout : function() { + var that = this; return this._http(this.app.options.logoutApiUrl).then(function(user) { + return that.notify(); + }).then(function() { return user; }); },
a90e96f14501c734d425dbed86ddb0e1b80b75f1
client/app/components/organization/organization.js
client/app/components/organization/organization.js
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import organizationComponent from './organization.component'; import organizationDetail from './organizationDetail/organizationDetail'; require('angular-ui-grid/ui-grid.css'); //require('angular-datatables/dist/plugins/columnfilter/angular-datatables.columnfilter.js'); //require('angular-datatables/dist/plugins/bootstrap/angular-datatables.bootstrap.js'); //require('datatables.net-select'); //require('angular-datatables/dist/plugins/select/angular-datatables.select.min.js'); let organizationModule = angular.module('organization', [ uiRouter, 'navbar', organizationDetail, require('angular-ui-grid') ]) .config(($stateProvider) => { "ngInject"; $stateProvider .state('organization', { url: '/organization', component: 'organization' }); }) .run(['Menu', function(Menu){ Menu.addToMainMenu({ display: "Organization", url: "/organization", requireLogin: true }) }]) .component('organization', organizationComponent) .name; export default organizationModule;
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import organizationComponent from './organization.component'; import organizationDetail from './organizationDetail/organizationDetail'; require('angular-ui-grid/ui-grid.css'); //require('angular-datatables/dist/plugins/columnfilter/angular-datatables.columnfilter.js'); //require('angular-datatables/dist/plugins/bootstrap/angular-datatables.bootstrap.js'); //require('datatables.net-select'); //require('angular-datatables/dist/plugins/select/angular-datatables.select.min.js'); let organizationModule = angular.module('organization', [ uiRouter, 'navbar', organizationDetail, require('angular-ui-grid') ]) .config(($stateProvider) => { "ngInject"; $stateProvider .state('organization', { url: '/organization', component: 'organization' }); }) .run(['Menu', function(Menu){ Menu.addToMainMenu({ display: "Organization", url: "/organization", requireLogin: true, requireDev: true }) }]) .component('organization', organizationComponent) .name; export default organizationModule;
Make org a dev function for now
Make org a dev function for now
JavaScript
agpl-3.0
neteoc/neteoc-ui,neteoc/neteoc-ui,neteoc/neteoc-ui
--- +++ @@ -27,7 +27,11 @@ }) .run(['Menu', function(Menu){ - Menu.addToMainMenu({ display: "Organization", url: "/organization", requireLogin: true }) + Menu.addToMainMenu({ + display: "Organization", + url: "/organization", + requireLogin: true, + requireDev: true }) }]) .component('organization', organizationComponent)
20d9f937eec0d0e751a6d52098c3cb90d63e6cd1
test/index.js
test/index.js
import glob from 'glob'; import cssHook from 'css-modules-require-hook'; cssHook({generateScopedName: '[name]__[local]'}); glob.sync('**/*-test.js', {realpath: true, cwd: __dirname}).forEach(require);
require('css-modules-require-hook')({ generateScopedName: '[name]__[local]' }); require('glob') .sync('**/*-test.js', { realpath: true, cwd: require('path').resolve(process.cwd(), 'test') }) .forEach(require);
Use ES5 for test endpoint so there is no need for babel transform
Use ES5 for test endpoint so there is no need for babel transform
JavaScript
mit
nkbt/react-component-template
--- +++ @@ -1,6 +1,10 @@ -import glob from 'glob'; +require('css-modules-require-hook')({ + generateScopedName: '[name]__[local]' +}); -import cssHook from 'css-modules-require-hook'; -cssHook({generateScopedName: '[name]__[local]'}); - -glob.sync('**/*-test.js', {realpath: true, cwd: __dirname}).forEach(require); +require('glob') + .sync('**/*-test.js', { + realpath: true, + cwd: require('path').resolve(process.cwd(), 'test') + }) + .forEach(require);
756c25f989fd2e0cbbe4f1ead2d8c34557fc15be
app/scripts/services/plan-customers-service.js
app/scripts/services/plan-customers-service.js
'use strict'; (function() { angular.module('ncsaas') .service('planCustomersService', ['baseServiceClass', planCustomersService]); function planCustomersService(baseServiceClass) { /*jshint validthis: true */ var ServiceClass = baseServiceClass.extend({ init:function() { this._super(); this.endpoint = '/plan-customers/'; } }); return new ServiceClass(); } })();
'use strict'; (function() { angular.module('ncsaas') .service('planCustomersService', ['baseServiceClass', planCustomersService]); function planCustomersService(baseServiceClass) { /*jshint validthis: true */ var ServiceClass = baseServiceClass.extend({ init:function() { this._super(); this.endpoint = '/plan-customers/'; } }); return new ServiceClass(); } })();
Add new line to end of file (saas-265)
Add new line to end of file (saas-265)
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
bee278faa8706fe7ebdf36a6cc48801cf0ea86b9
test/index.js
test/index.js
'use strict'; module.exports = function (t, a, d) { var invoked; a(t(function () { a(arguments.length, 0, "Arguments"); invoked = true; }), undefined, "Return"); a(invoked, undefined, "Is not run immediately"); setTimeout(function () { a(invoked, true, "Run in next tick"); d(); }, 10); };
'use strict'; module.exports = function (t, a, d) { var invoked; a(t(function () { a(arguments.length, 0, "Arguments"); invoked = true; }), undefined, "Return"); a(invoked, undefined, "Is not run immediately"); setTimeout(function () { a(invoked, true, "Run in next tick"); invoked = []; t(function () { invoked.push(0); }); t(function () { invoked.push(1); }); t(function () { invoked.push(2); }); setTimeout(function () { a.deep(invoked, [0, 1, 2], "Serial"); d(); }, 10); }, 10); };
Add tests for serial calls
Add tests for serial calls
JavaScript
isc
medikoo/next-tick
--- +++ @@ -2,6 +2,7 @@ module.exports = function (t, a, d) { var invoked; + a(t(function () { a(arguments.length, 0, "Arguments"); invoked = true; @@ -9,6 +10,13 @@ a(invoked, undefined, "Is not run immediately"); setTimeout(function () { a(invoked, true, "Run in next tick"); - d(); + invoked = []; + t(function () { invoked.push(0); }); + t(function () { invoked.push(1); }); + t(function () { invoked.push(2); }); + setTimeout(function () { + a.deep(invoked, [0, 1, 2], "Serial"); + d(); + }, 10); }, 10); };
29f392e54a4de685118228b21c6d1312e58b9d66
test/index.js
test/index.js
var caps = require('../'); var test = require('tape'); test('works', function(t) { var TEST_ARRAY = [ ['kitten', 0.0], ['Kitten', 1 / 6.0], ['KItten', 1 / 3.0], ['KITten', 0.5], ['KITTen', 2 / 3.0], ['KITTEn', 5 / 6.0], ['KITTEN', 1.0], ['kittens ARE COOL', 7 / 16.0] ]; t.plan(TEST_ARRAY.length); TEST_ARRAY.forEach(function(value) { t.equal(caps(value[0]), value[1]); }); });
var caps = require('../'); var test = require('tape'); test('works', function(t) { var TEST_ARRAY = [ ['kitten', 0.0], ['Kitten', 1 / 6.0], ['KItten', 1 / 3.0], ['KITten', 0.5], ['KITTen', 2 / 3.0], ['KITTEn', 5 / 6.0], ['KITTEN', 1.0], ['kittens ARE COOL', 7 / 16.0], ['kitteñ', 0.0], ['kitteÑ', 1 / 6.0], ['kittÉÑ', 1 / 3.0] ]; t.plan(TEST_ARRAY.length); TEST_ARRAY.forEach(function(value) { t.equal(caps(value[0]), value[1]); }); });
Add tests for accented characters
Add tests for accented characters
JavaScript
mit
nwitch/caps-rate
--- +++ @@ -10,7 +10,10 @@ ['KITTen', 2 / 3.0], ['KITTEn', 5 / 6.0], ['KITTEN', 1.0], - ['kittens ARE COOL', 7 / 16.0] + ['kittens ARE COOL', 7 / 16.0], + ['kitteñ', 0.0], + ['kitteÑ', 1 / 6.0], + ['kittÉÑ', 1 / 3.0] ]; t.plan(TEST_ARRAY.length);
5ce9c69881ea46aa6b2aa98d6d61e14fe4949f95
script.js
script.js
var html = document.getElementById("html"); var render = document.getElementById("render"); var toggle = document.getElementById("toggle"); var error = document.getElementById("error"); var code = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "javascript" }); function update() { try { var element = new Function( "with(xmgen.svg) { with (xmgen.html) { return " + code.getValue() + "}}" )(); error.innerText = ""; if (toggle.classList.contains("down")) { html.innerText = element.toString(2); CodeMirror.colorize([html], "xml"); } else { render.innerHTML = element.toString(); } } catch (e) { error.innerText = e.toString(); } } code.on("change", update); toggle.addEventListener("click", function() { if (toggle.classList.contains("down")) { toggle.classList.remove("down"); html.innerHTML = ""; } else { toggle.classList.add("down"); render.innerHTML = ""; } update(); }); update();
var html = document.getElementById("html"); var render = document.getElementById("render"); var toggle = document.getElementById("toggle"); var error = document.getElementById("error"); var code = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "javascript" }); function update() { try { var element = new Function( "with(xmgen.svg) { with (xmgen.html) { return " + code.getValue() + "}}" )(); error.textContent = ""; if (toggle.classList.contains("down")) { html.textContent = element.toString(2); CodeMirror.colorize([html], "xml"); } else { render.innerHTML = element.toString(); } } catch (e) { error.textContent = e.toString(); } } code.on("change", update); toggle.addEventListener("click", function() { if (toggle.classList.contains("down")) { toggle.classList.remove("down"); html.innerHTML = ""; } else { toggle.classList.add("down"); render.innerHTML = ""; } update(); }); update();
Use textContent instead of innerText
Use textContent instead of innerText
JavaScript
mit
nucular/xmgen,nucular/xmgen
--- +++ @@ -15,15 +15,15 @@ + "}}" )(); - error.innerText = ""; + error.textContent = ""; if (toggle.classList.contains("down")) { - html.innerText = element.toString(2); + html.textContent = element.toString(2); CodeMirror.colorize([html], "xml"); } else { render.innerHTML = element.toString(); } } catch (e) { - error.innerText = e.toString(); + error.textContent = e.toString(); } }
760268958b0cf37feb87e09876ee8da0333dc00a
lib/runner.js
lib/runner.js
/*global phantom*/ 'use strict'; var system = require('system'); var webpage = require('webpage'); var page = webpage.create(); var errd = false; var timeout = null; var signal = '[E_PHANTOMIC] '; var url = 'http://localhost:' + system.env.PHANTOMIC_PORT; var debug = system.env.PHANTOMIC_DEBUG; var lastLog = Date.now(); var done = false; if (debug) { system.stderr.write('PHANTOMIC_DEBUG'); url += '?debug'; } page.onConsoleMessage = function (msg) { if (msg.indexOf(signal) === 0) { errd = true; msg = msg.substring(signal.length); } if (msg === '[X_PHANTOMIC]') { if (!done && Date.now() - lastLog > 100) { done = true; phantom.exit(errd ? 1 : 0); } } else { lastLog = Date.now(); console.log(msg); } }; page.onError = function (msg, trace) { errd = true; console.log(msg); if (trace) { trace.forEach(function (t) { console.log(' at ' + url + '/js/bundle:' + t.line); }); } }; page.open(url);
/*global phantom*/ 'use strict'; var system = require('system'); var webpage = require('webpage'); var page = webpage.create(); var errd = false; var timeout = null; var signal = '[E_PHANTOMIC] '; var url = 'http://localhost:' + system.env.PHANTOMIC_PORT; var debug = system.env.PHANTOMIC_DEBUG; var lastLog = Date.now(); var done = false; if (debug) { system.stderr.write('PHANTOMIC_DEBUG'); url += '?debug'; } page.onConsoleMessage = function (msg) { if (msg.indexOf(signal) === 0) { errd = true; msg = msg.substring(signal.length); } if (msg === '[X_PHANTOMIC]') { if (!done && Date.now() - lastLog > 100) { done = true; var code = errd ? 1 : 0; if (debug) { phantom.debugExit(code); } else { phantom.exit(code); } } } else { lastLog = Date.now(); console.log(msg); } }; page.onError = function (msg, trace) { errd = true; console.log(msg); if (trace) { trace.forEach(function (t) { console.log(' at ' + url + '/js/bundle:' + t.line); }); } }; page.open(url);
Use phantom.debugExit(code) to exit in debug mode
Use phantom.debugExit(code) to exit in debug mode
JavaScript
mit
mantoni/phantomic,mantoni/phantomic,mantoni/phantomic
--- +++ @@ -26,7 +26,12 @@ if (msg === '[X_PHANTOMIC]') { if (!done && Date.now() - lastLog > 100) { done = true; - phantom.exit(errd ? 1 : 0); + var code = errd ? 1 : 0; + if (debug) { + phantom.debugExit(code); + } else { + phantom.exit(code); + } } } else { lastLog = Date.now();
7098ecba8c91c0851fbd070a1798bd2562c4f264
test/index.js
test/index.js
import test from 'ava'; import removeTrailingSeparator from '..'; test('strip trailing separator:', t => { t.is(removeTrailingSeparator('foo/'), 'foo'); t.is(removeTrailingSeparator('foo\\'), 'foo'); }); test('don\'t strip when it\'s the only char in the string', async t => { t.is(removeTrailingSeparator('/'), '/'); t.is(removeTrailingSeparator('\\'), '\\'); }); test('strip only trailing separator:', t => { t.is(removeTrailingSeparator('/test/foo/bar/'), '/test/foo/bar'); t.is(removeTrailingSeparator('\\test\\foo\\bar\\'), '\\test\\foo\\bar'); }); test('strip multiple trailing separators', t => { t.is(removeTrailingSeparator('/test//'), '/test'); t.is(removeTrailingSeparator('\\test\\\\'), '\\test'); }); test('leave 1st separator in a string of only separators', t => { t.is(removeTrailingSeparator('//'), '/'); t.is(removeTrailingSeparator('////'), '/'); t.is(removeTrailingSeparator('\\\\'), '\\'); t.is(removeTrailingSeparator('\\\\\\\\'), '\\'); }); test('return back empty string', t => { t.is(removeTrailingSeparator(''), ''); });
import test from 'ava'; import removeTrailingSeparator from '..'; test('strip trailing separator:', t => { t.is(removeTrailingSeparator('foo/'), 'foo'); t.is(removeTrailingSeparator('foo\\'), 'foo'); }); test('don\'t strip when it\'s the only char in the string', t => { t.is(removeTrailingSeparator('/'), '/'); t.is(removeTrailingSeparator('\\'), '\\'); }); test('strip only trailing separator:', t => { t.is(removeTrailingSeparator('/test/foo/bar/'), '/test/foo/bar'); t.is(removeTrailingSeparator('\\test\\foo\\bar\\'), '\\test\\foo\\bar'); }); test('strip multiple trailing separators', t => { t.is(removeTrailingSeparator('/test//'), '/test'); t.is(removeTrailingSeparator('\\test\\\\'), '\\test'); }); test('leave 1st separator in a string of only separators', t => { t.is(removeTrailingSeparator('//'), '/'); t.is(removeTrailingSeparator('////'), '/'); t.is(removeTrailingSeparator('\\\\'), '\\'); t.is(removeTrailingSeparator('\\\\\\\\'), '\\'); }); test('return back empty string', t => { t.is(removeTrailingSeparator(''), ''); });
Use normal function for normal test
Use normal function for normal test
JavaScript
isc
darsain/remove-trailing-separator
--- +++ @@ -6,7 +6,7 @@ t.is(removeTrailingSeparator('foo\\'), 'foo'); }); -test('don\'t strip when it\'s the only char in the string', async t => { +test('don\'t strip when it\'s the only char in the string', t => { t.is(removeTrailingSeparator('/'), '/'); t.is(removeTrailingSeparator('\\'), '\\'); });
c6ab3077925eb574062b1b9815bed6c954ab3cb6
lib/server.js
lib/server.js
const express = require('express') const fs = require('fs') const http = require('http') const https = require('https') const path = require('path') function startHttpServer(app, port) { const httpServer = http.Server(app) httpServer.listen(port, () => console.log(`Listening on HTTP port *:${port}`)) } function startHttpsServer(app, port, sslKey, sslCert) { const privateKey = fs.readFileSync(sslKey, 'utf8') const certificate = fs.readFileSync(sslCert, 'utf8') const httpsServer = https.Server({key: privateKey, cert: certificate}, app) httpsServer.listen(port, () => console.log(`Listening on HTTPS port *:${port}`)) } function bindRoutes(app, rootFolder) { const sendFileOptions = {root: path.resolve(rootFolder)} app.use((req, res, next) => { if (req.url.endsWith('gz')) { res.sendFile(req.url, sendFileOptions) } else { res.sendFile(`${req.url}/index.json`, sendFileOptions) } }) } function init(options) { const app = express() bindRoutes(app, options.root) startHttpServer(app, options.port) if (options.https) { startHttpsServer(app, options.https.port, options.https.sslKey, options.https.sslCert) } } module.exports = init
const express = require('express') const fs = require('fs') const http = require('http') const https = require('https') const path = require('path') function startHttpServer(app, port) { const httpServer = http.Server(app) httpServer.listen(port, () => console.log(`Listening on HTTP port *:${port}`)) } function startHttpsServer(app, port, sslKey, sslCert) { const privateKey = fs.readFileSync(sslKey, 'utf8') const certificate = fs.readFileSync(sslCert, 'utf8') const httpsServer = https.Server({key: privateKey, cert: certificate}, app) httpsServer.listen(port, () => console.log(`Listening on HTTPS port *:${port}`)) } function jsonError(res) { return function (err) { if (err) { res.status(err.status).json({}) } } } function bindRoutes(app, rootFolder) { const sendFileOptions = {root: path.resolve(rootFolder)} app.use((req, res, next) => { if (req.url.endsWith('gz')) { res.sendFile(req.url, sendFileOptions, jsonError(res)) } else { res.sendFile(`${req.url}/index.json`, sendFileOptions, jsonError(res)) } }) } function init(options) { const app = express() bindRoutes(app, options.root) startHttpServer(app, options.port) if (options.https) { startHttpsServer(app, options.https.port, options.https.sslKey, options.https.sslCert) } } module.exports = init
Send 404 errors as JSON to keep NPM happy
Send 404 errors as JSON to keep NPM happy
JavaScript
mit
heikkipora/registry-sync,heikkipora/registry-sync,heikkipora/registry-sync
--- +++ @@ -16,13 +16,21 @@ httpsServer.listen(port, () => console.log(`Listening on HTTPS port *:${port}`)) } +function jsonError(res) { + return function (err) { + if (err) { + res.status(err.status).json({}) + } + } +} + function bindRoutes(app, rootFolder) { const sendFileOptions = {root: path.resolve(rootFolder)} app.use((req, res, next) => { if (req.url.endsWith('gz')) { - res.sendFile(req.url, sendFileOptions) + res.sendFile(req.url, sendFileOptions, jsonError(res)) } else { - res.sendFile(`${req.url}/index.json`, sendFileOptions) + res.sendFile(`${req.url}/index.json`, sendFileOptions, jsonError(res)) } }) }
f19500f18b8f577703ce1fe0318f86308335c62e
src/components/FlightTracker/FlightsForm.js
src/components/FlightTracker/FlightsForm.js
import React from 'react' export function FlightsForm({ homeFloor, value, onChange }) { function onFlightsChanged(event) { const flights = parseFloat(event.target.value) onChange(flights) } function addFlights(flights) { onChange(value + flights) } function onAddDefaultFlights() { addFlights(homeFloor) } function addFlight() { addFlights(1) } function subtractFlight() { addFlights(-1) } return ( <div> <fieldset className="input-group"> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={subtractFlight} type="button">-</button> </span> <input type="number" className="form-control" value={value} onChange={onFlightsChanged} /> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={addFlight} type="button">+</button> </span> </fieldset> <button className="btn btn-block btn-primary" onClick={onAddDefaultFlights}> Add {homeFloor} flights </button> <p>{value * 13} ft</p> </div> ) } FlightsForm.propTypes = { homeFloor: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func.isRequired, } FlightsForm.defaultProps = { homeFloor: 1, value: 0, onChange() {}, }
import React from 'react' export function FlightsForm({ homeFloor, value, onChange }) { function onFlightsChanged(event) { const flights = parseFloat(event.target.value) onChange(flights) } function addFlights(flights) { onChange(value + flights) } function onAddDefaultFlights() { addFlights(homeFloor) } function addFlight() { addFlights(1) } function subtractFlight() { addFlights(-1) } return ( <div> <div className="input-group"> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={subtractFlight} type="button">-</button> </span> <input type="number" className="form-control" value={value} onChange={onFlightsChanged} /> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={addFlight} type="button">+</button> </span> </div> <button className="btn btn-block btn-primary" onClick={onAddDefaultFlights}> Add {homeFloor} flights </button> <p>{value * 13} ft</p> </div> ) } FlightsForm.propTypes = { homeFloor: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func.isRequired, } FlightsForm.defaultProps = { homeFloor: 1, value: 0, onChange() {}, }
Fix styling on flights form
Fix styling on flights form
JavaScript
mit
elstgav/step-up,elstgav/stair-climber,elstgav/stair-climber
--- +++ @@ -24,7 +24,7 @@ return ( <div> - <fieldset className="input-group"> + <div className="input-group"> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={subtractFlight} type="button">-</button> </span> @@ -32,7 +32,7 @@ <span className="input-group-btn"> <button className="btn btn-secondary" onClick={addFlight} type="button">+</button> </span> - </fieldset> + </div> <button className="btn btn-block btn-primary" onClick={onAddDefaultFlights}> Add {homeFloor} flights </button>
42b4ff08ac63d894afdf75eee999bb763a2c5b96
src/dataset/pastedataset.js
src/dataset/pastedataset.js
'use strict'; /** * @ngdoc directive * @name vlui.directive:pasteDataset * @description * # pasteDataset */ angular.module('vlui') .directive('pasteDataset', function (Dataset, Alerts, Logger, Config, _, Papa) { return { templateUrl: 'dataset/pastedataset.html', restrict: 'E', replace: true, scope: false, // use scope from datasetSelector link: function postLink(scope/*, element, attrs*/) { scope.datasetName = ''; scope.data = ''; // need to give this a unique name because we share the namespace scope.addPasted = function() { var data; var result = Papa.parse(scope.data, { dynamicTyping: true, header: true }); if (result.errors.length === 0) { data = result.data; } else { _.each(result.errors, function(err) { Alerts.add(err.message, 2000); }); return; } var dataset = { id: Date.now(), // time as id name: scope.datasetName, values: data, group: 'pasted' }; Dataset.dataset = Dataset.add(angular.copy(dataset)); scope.datasetChanged(); scope.datasetName = ''; scope.data = ''; scope.doneAdd(); }; } }; });
'use strict'; /** * @ngdoc directive * @name vlui.directive:pasteDataset * @description * # pasteDataset */ angular.module('vlui') .directive('pasteDataset', function (Dataset, Alerts, Logger, Config, _, dl) { return { templateUrl: 'dataset/pastedataset.html', restrict: 'E', replace: true, scope: false, // use scope from datasetSelector link: function postLink(scope/*, element, attrs*/) { scope.datasetName = ''; scope.data = ''; // need to give this a unique name because we share the namespace scope.addPasted = function() { var data = dl.read(response.data, {type: 'csv'}); var dataset = { id: Date.now(), // time as id name: scope.datasetName, values: data, group: 'pasted' }; Dataset.dataset = Dataset.add(angular.copy(dataset)); scope.datasetChanged(); scope.datasetName = ''; scope.data = ''; scope.doneAdd(); }; } }; });
Use details parser for reading pasted data
Use details parser for reading pasted data
JavaScript
bsd-3-clause
uwdata/vega-lite-ui,vega/vega-lite-ui,uwdata/vega-lite-ui,vega/vega-lite-ui,vega/vega-lite-ui,uwdata/vega-lite-ui
--- +++ @@ -7,7 +7,7 @@ * # pasteDataset */ angular.module('vlui') - .directive('pasteDataset', function (Dataset, Alerts, Logger, Config, _, Papa) { + .directive('pasteDataset', function (Dataset, Alerts, Logger, Config, _, dl) { return { templateUrl: 'dataset/pastedataset.html', restrict: 'E', @@ -19,21 +19,7 @@ // need to give this a unique name because we share the namespace scope.addPasted = function() { - var data; - - var result = Papa.parse(scope.data, { - dynamicTyping: true, - header: true - }); - - if (result.errors.length === 0) { - data = result.data; - } else { - _.each(result.errors, function(err) { - Alerts.add(err.message, 2000); - }); - return; - } + var data = dl.read(response.data, {type: 'csv'}); var dataset = { id: Date.now(), // time as id
7fe66bd01126d5f670ea02d988b217e706b46a2b
test/token.js
test/token.js
let config = require("./config"); let Token = require("../lib/token"); (async function() { let token = new Token(config.token); let value = await token.value; console.log(value); })();
let config = require("./config"); let Token = require("../lib/token"); (async function() { let token = new Token(config.fmeToken); let value = await token.value; console.log(value); })();
Fix up node name of config
Fix up node name of config
JavaScript
apache-2.0
Tomella/fsdf-elvis,Tomella/fsdf-elvis,Tomella/fsdf-elvis
--- +++ @@ -3,7 +3,7 @@ (async function() { - let token = new Token(config.token); + let token = new Token(config.fmeToken); let value = await token.value; console.log(value);
16bc4ac36243d04e1dbc3e7675137cb016ed9c5e
server.js
server.js
var express = require('express'); var redis = require('ioredis'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/endpoints'); var users = require('./routes/users'); var api = express(); // var redis = new Redis('/tmp/redis.sock'); api.get('/', function(req, res){ res.send('Hello World'); }); api.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); api.set('port', process.env.PORT || 3000); var server = api.listen(api.get('port'), function() { console.log('Listening on port %d', server.address().port); });
var express = require('express'); var redis = require('ioredis'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var endpoints = require('./routes/endpoints'); var users = require('./routes/users'); var api = express(); // var redis = new Redis('/tmp/redis.sock'); // view engine setup api.set('views', path.join(__dirname, 'views')); api.set('view engine', 'jade'); api.use(bodyParser.json()); api.use(bodyParser.urlencoded()); api.use(cookieParser()); api.get('/', function(req, res){ res.send('Hello World'); }); api.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); api.set('port', process.env.PORT || 3000); api.set('env', 'development'); var server = api.listen(api.get('port'), function() { console.log('Listening on port %d', server.address().port); }); api.use(express.static(path.join(__dirname, 'public'))); api.use('/', endpoints); api.use('/users', users); /// error handlers /// catch 404 and forward to error handler api.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // development error handler // will print stacktrace if (api.get('env') === 'development') { api.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user api.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); });
Add error handling, endpoints, and view engine w/ views
Add error handling, endpoints, and view engine w/ views
JavaScript
mit
nathansmyth/node-stack,nathansmyth/node-stack
--- +++ @@ -1,14 +1,23 @@ var express = require('express'); var redis = require('ioredis'); +var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); -var routes = require('./routes/endpoints'); +var endpoints = require('./routes/endpoints'); var users = require('./routes/users'); var api = express(); // var redis = new Redis('/tmp/redis.sock'); + +// view engine setup +api.set('views', path.join(__dirname, 'views')); +api.set('view engine', 'jade'); + +api.use(bodyParser.json()); +api.use(bodyParser.urlencoded()); +api.use(cookieParser()); api.get('/', function(req, res){ res.send('Hello World'); @@ -19,7 +28,44 @@ }); api.set('port', process.env.PORT || 3000); +api.set('env', 'development'); var server = api.listen(api.get('port'), function() { console.log('Listening on port %d', server.address().port); }); + +api.use(express.static(path.join(__dirname, 'public'))); + +api.use('/', endpoints); +api.use('/users', users); + +/// error handlers + +/// catch 404 and forward to error handler +api.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// development error handler +// will print stacktrace +if (api.get('env') === 'development') { + api.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +api.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +});
f7bba22e5b5b3ee2fc1b14402f5c265a8a087170
server.js
server.js
'use strict'; // Dependencies var express = require('express'); var http = require('http'); var bodyparser = require('body-parser'); // Config var app = express(); app.use(bodyparser.json()); app.use(express.static(__dirname + (process.env.STATIC_DIR || '/build'))); // Routing require('./expressRoutes')(app); // Init var server = app.listen(process.env.PORT || 3000, function() { console.log('Lookin legit on port: %d', server.address().port); });
'use strict'; // Dependencies var express = require('express'); var http = require('http'); var bodyparser = require('body-parser'); // Config var app = express(); app.use(bodyparser.json()); app.use(express.static(__dirname + (process.env.STATIC_DIR || '/build'))); // Routing require('./expressRoutes')(app); // Init var port = process.env.PORT || 3000; var server = app.listen(port, function() { console.log('Lookin legit on port: %d', server.address().port); }); exports.port = port;
Add port as an export, for testing
Add port as an export, for testing
JavaScript
mit
Localhost3000/along-the-way
--- +++ @@ -14,6 +14,9 @@ require('./expressRoutes')(app); // Init -var server = app.listen(process.env.PORT || 3000, function() { +var port = process.env.PORT || 3000; +var server = app.listen(port, function() { console.log('Lookin legit on port: %d', server.address().port); }); + +exports.port = port;
25ca4515d828802927aec301c7721fe4fe294e0b
Melchior/JS/Socket.js
Melchior/JS/Socket.js
var Sockets = {} Sockets.Socket = function Socket (signal) { if(!('WebSocket' in window)) throw new Error("Websockets not supported in this browser") this.connection = io.connect('http://localhost:3001') this.signal = signal this.connection.onopen = function () { //hmmm... } this.connection.onclose = function () { //hmmm... } this.connection.onerror = function(e) { console.error(e) } this.send = function (value) { //stringify? this.connection.send(value) } this.connection.on('data', function(value) { this.signal.push(value) }) } Sockets.createSocketedSignal = function() { var signal = new Signal(), socket = new Sockets.Socket(signal) return signal }
var Sockets = {} Sockets.Socket = function Socket (signal) { if(!('WebSocket' in window)) throw new Error("Websockets not supported in this browser") this.connection = io ? io.connect('http://localhost:3001') : new WebSocket("ws://localhost:3001") this.signal = signal this.send = this.connection.emit ? function (value) { this.connection.emit('data', value) } : function (value) { //stringify? this.connection.send(value) } if(this.connection.on) this.connection.on('data', function(value) { this.signal.push(value) }) else this.connection.onmessage = function(value) { this.signal.push(value) } } Sockets.createSocketedSignal = function() { var signal = new Signal(), socket = new Sockets.Socket(signal) return signal }
Make it less tightly coupled with socket.io
Make it less tightly coupled with socket.io
JavaScript
mit
kjgorman/melchior,kjgorman/melchior,kjgorman/melchior,kjgorman/melchior,kjgorman/melchior,kjgorman/melchior
--- +++ @@ -3,29 +3,24 @@ Sockets.Socket = function Socket (signal) { if(!('WebSocket' in window)) throw new Error("Websockets not supported in this browser") - this.connection = io.connect('http://localhost:3001') + this.connection = io ? io.connect('http://localhost:3001') : new WebSocket("ws://localhost:3001") this.signal = signal - this.connection.onopen = function () { - //hmmm... - } - - this.connection.onclose = function () { - //hmmm... - } - - this.connection.onerror = function(e) { - console.error(e) - } - - this.send = function (value) { + this.send = this.connection.emit ? function (value) { + this.connection.emit('data', value) + } : function (value) { //stringify? this.connection.send(value) } + if(this.connection.on) this.connection.on('data', function(value) { this.signal.push(value) }) + else this.connection.onmessage = function(value) { + this.signal.push(value) + } + } Sockets.createSocketedSignal = function() {
636201763e023889587448dcf6e60d46ea8cd52b
src/apps/omis/apps/list/router.js
src/apps/omis/apps/list/router.js
const router = require('express').Router() const { ENTITIES } = require('../../../search/constants') const QUERY_FIELDS = require('../../constants') const { getCollection, exportCollection } = require('../../../../modules/search/middleware/collection') const { setDefaultQuery } = require('../../../middleware') const { getRequestBody } = require('../../../../middleware/collection') const { renderList } = require('./controllers') const { setRequestBody } = require('./middleware') const { transformOrderToListItem } = require('../../transformers') const DEFAULT_QUERY = { sortby: 'created_on:desc', } router.get('/', setDefaultQuery(DEFAULT_QUERY), setRequestBody, getCollection('order', ENTITIES, transformOrderToListItem), renderList, ) router.get('/export', setDefaultQuery(DEFAULT_QUERY), getRequestBody(QUERY_FIELDS), exportCollection('order'), ) module.exports = router
const router = require('express').Router() const { ENTITIES } = require('../../../search/constants') const { QUERY_FIELDS } = require('../../constants') const { getCollection, exportCollection } = require('../../../../modules/search/middleware/collection') const { setDefaultQuery } = require('../../../middleware') const { getRequestBody } = require('../../../../middleware/collection') const { renderList } = require('./controllers') const { setRequestBody } = require('./middleware') const { transformOrderToListItem } = require('../../transformers') const DEFAULT_QUERY = { sortby: 'created_on:desc', } router.get('/', setDefaultQuery(DEFAULT_QUERY), setRequestBody, getCollection('order', ENTITIES, transformOrderToListItem), renderList, ) router.get('/export', setDefaultQuery(DEFAULT_QUERY), getRequestBody(QUERY_FIELDS), exportCollection('order'), ) module.exports = router
Update QUERY_FIELDS const to only deconstruct the query fields object
Update QUERY_FIELDS const to only deconstruct the query fields object
JavaScript
mit
uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend
--- +++ @@ -2,7 +2,7 @@ const { ENTITIES } = require('../../../search/constants') -const QUERY_FIELDS = require('../../constants') +const { QUERY_FIELDS } = require('../../constants') const { getCollection, exportCollection } = require('../../../../modules/search/middleware/collection') const { setDefaultQuery } = require('../../../middleware')
17b3022d261f64d8ca427a8999a3008f0038bcbc
public/app/js/cbus-server-get-podcast-info.js
public/app/js/cbus-server-get-podcast-info.js
if (!cbus.hasOwnProperty("server")) { cbus.server = {} } (function() { const request = require("request"); const x2j = require("xml2js"); const path = require("path"); cbus.server.getPodcastInfo = function(podcastUrl, callback) { var podcastData = {}; request({ url: podcastUrl, headers: REQUEST_HEADERS }, function(err, result, body) { x2j.parseString(body, function(err, result) { if (err) { console.log("error parsing xml", err); callback(null) } else { var channel = result.rss.channel[0]; // console.log(channel); // title if (existsRecursive(channel, ["title", 0])) { podcastData.title = channel.title[0]; } // publisher if (existsRecursive(channel, ["itunes:author", 0])) { podcastData.publisher = channel["itunes:author"][0]; } // description if (channel.description && channel.description[0]) { podcastData.description = channel.description[0]; } // image if (existsRecursive(channel, ["image", 0, "url", 0])) { podcastData.image = channel["image"][0]["url"][0]; } else if (existsRecursive(channel, ["itunes:image", 0])) { podcastData.image = channel["itunes:image"][0].$.href; } callback(podcastData); } }); }); } }());
if (!cbus.hasOwnProperty("server")) { cbus.server = {} } (function() { const request = require("request"); const x2j = require("xml2js"); const path = require("path"); cbus.server.getPodcastInfo = function(podcastUrl, callback) { var podcastData = {}; request({ url: podcastUrl, headers: REQUEST_HEADERS }, function(err, result, body) { x2j.parseString(body, function(err, result) { if (err) { console.log("error parsing xml", err); callback(null) } else { var channel = result.rss.channel[0]; // console.log(channel); // title if (existsRecursive(channel, ["title", 0])) { podcastData.title = channel.title[0].trim(); } // publisher if (existsRecursive(channel, ["itunes:author", 0])) { podcastData.publisher = channel["itunes:author"][0]; } // description if (channel.description && channel.description[0]) { podcastData.description = channel.description[0]; } // image if (existsRecursive(channel, ["image", 0, "url", 0])) { podcastData.image = channel["image"][0]["url"][0]; } else if (existsRecursive(channel, ["itunes:image", 0])) { podcastData.image = channel["itunes:image"][0].$.href; } callback(podcastData); } }); }); } }());
Trim whitespace from podcast titles
Trim whitespace from podcast titles
JavaScript
apache-2.0
z-------------/cumulonimbus,z-------------/cumulonimbus,z-------------/cumulonimbus
--- +++ @@ -22,7 +22,7 @@ // title if (existsRecursive(channel, ["title", 0])) { - podcastData.title = channel.title[0]; + podcastData.title = channel.title[0].trim(); } // publisher if (existsRecursive(channel, ["itunes:author", 0])) {
14382c87363ebc85f58b0da4b5689f8d0f0140bd
src/util/valid-auth-type.js
src/util/valid-auth-type.js
/*global module */ module.exports = function validAuthType(type) { 'use strict'; var authTypes = ['AWS_IAM', 'NONE', 'CUSTOM']; return (authTypes.indexOf(type) >= 0); };
/*global module */ module.exports = function validAuthType(type) { 'use strict'; var authTypes = ['AWS_IAM', 'NONE', 'CUSTOM', 'COGNITO_USER_POOLS']; return (authTypes.indexOf(type) >= 0); };
Allow cognito user pool authorization
Allow cognito user pool authorization
JavaScript
mit
dhackner/claudia,dhackner/claudia
--- +++ @@ -1,6 +1,6 @@ /*global module */ module.exports = function validAuthType(type) { 'use strict'; - var authTypes = ['AWS_IAM', 'NONE', 'CUSTOM']; + var authTypes = ['AWS_IAM', 'NONE', 'CUSTOM', 'COGNITO_USER_POOLS']; return (authTypes.indexOf(type) >= 0); };
314fdb4ec7a97d488ba231847a7dbfac78045fd2
lib/plugin/router/handler/permissionHandler.js
lib/plugin/router/handler/permissionHandler.js
"use strict"; const Handler = require('./handler'); class PermissionHandler extends Handler { constructor(data={}) { super(data); ['permissions'].map(val => this[val] = data[val] ? data[val] : (this[val] ? this[val] : this.constructor[val])); } async allowAccess(context) { if (!this.Account) { // Cache the location to the Account plugin, because this portion of code // will be run many, many times! this.Account = context.engine.pluginRegistry.get('Account'); } for (let permission of this.permissions) { if (await this.Account.accountHasPermission(context.account, permission)) { return true; } } // Give the user an Access Denied code. context.httpResponse = 403; return false; } } PermissionHandler.permissions = []; module.exports = PermissionHandler;
"use strict"; const Handler = require('./handler'); class PermissionHandler extends Handler { constructor(data={}) { super(data); ['permissions'].map(val => this[val] = data[val] ? data[val] : (this[val] ? this[val] : this.constructor[val])); } async allowAccess(context) { if (!this.Account) { // Cache the location to the Account plugin, because this portion of code // will be run many, many times! this.Account = context.engine.pluginRegistry.get('Account'); } for (let permission of (this.permissions || [])) { if (await this.Account.accountHasPermission(context.account, permission)) { return true; } } // Give the user an Access Denied code. context.httpResponse = 403; return false; } } PermissionHandler.permissions = []; module.exports = PermissionHandler;
Make PermissionHandler more robust to missing permission directive
Make PermissionHandler more robust to missing permission directive
JavaScript
mit
coreyp1/defiant,coreyp1/defiant
--- +++ @@ -14,7 +14,7 @@ // will be run many, many times! this.Account = context.engine.pluginRegistry.get('Account'); } - for (let permission of this.permissions) { + for (let permission of (this.permissions || [])) { if (await this.Account.accountHasPermission(context.account, permission)) { return true; }
6f19117980bf8943f0c36d310e9b74466e82dc11
src/modules/search/middleware/collection.js
src/modules/search/middleware/collection.js
const { search, exportSearch } = require('../services') const { transformApiResponseToSearchCollection } = require('../transformers') function getCollection (searchEntity, entityDetails, ...itemTransformers) { return async function (req, res, next) { try { res.locals.results = await search({ searchEntity, requestBody: req.body, token: req.session.token, page: req.query.page, isAggregation: false, }).then(transformApiResponseToSearchCollection({ query: req.query }, entityDetails, ...itemTransformers)) next() } catch (error) { next(error) } } } function exportCollection (searchEntity) { return async function (req, res, next) { try { exportSearch({ searchEntity, requestBody: req.body, token: req.session.token, }).then(apiReq => { return apiReq.pipe(res) }).catch(error => { return next(error) }) } catch (error) { next(error) } } } module.exports = { exportCollection, getCollection, }
const { search, exportSearch } = require('../services') const { transformApiResponseToSearchCollection } = require('../transformers') function getCollection (searchEntity, entityDetails, ...itemTransformers) { return async function (req, res, next) { try { res.locals.results = await search({ searchEntity, requestBody: req.body, token: req.session.token, page: req.query.page, isAggregation: false, }).then(transformApiResponseToSearchCollection({ query: req.query }, entityDetails, ...itemTransformers)) next() } catch (error) { next(error) } } } function exportCollection (searchEntity) { return async function (req, res, next) { return exportSearch({ searchEntity, requestBody: req.body, token: req.session.token, }).then(apiReq => { return apiReq.pipe(res) }).catch(error => { return next(error) }) } } module.exports = { exportCollection, getCollection, }
Remove redundant exception handling in exportCollection
Remove redundant exception handling in exportCollection
JavaScript
mit
uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend
--- +++ @@ -21,19 +21,15 @@ function exportCollection (searchEntity) { return async function (req, res, next) { - try { - exportSearch({ - searchEntity, - requestBody: req.body, - token: req.session.token, - }).then(apiReq => { - return apiReq.pipe(res) - }).catch(error => { - return next(error) - }) - } catch (error) { - next(error) - } + return exportSearch({ + searchEntity, + requestBody: req.body, + token: req.session.token, + }).then(apiReq => { + return apiReq.pipe(res) + }).catch(error => { + return next(error) + }) } }
6eae6d6034c9b3ceb6e564498d9fc0bfeb4bbc9b
src/Object.js
src/Object.js
/** * @require {core.ext.Object} * @require {core.ext.String} * @require {core.ext.Function} */ core.Class("lowland.Object", { include : [core.property.MGeneric, lowland.base.UserData, lowland.base.Events], construct : function() { lowland.base.UserData.call(this); lowland.base.Events.call(this); } });
/** * @require {core.ext.Object} * @require {core.ext.String} * @require {core.ext.Function} */ core.Class("lowland.Object", { include : [core.property.MGeneric, lowland.base.UserData, lowland.base.Events], construct : function() { lowland.base.UserData.call(this); lowland.base.Events.call(this); }, members : { error : function() { console.error(this.constructor || this, arguments); }, warn : function() { console.warn(this.constructor || this, arguments); } } });
Add warn and error to generic object
Add warn and error to generic object
JavaScript
mit
fastner/lowland,fastner/lowland
--- +++ @@ -9,5 +9,15 @@ construct : function() { lowland.base.UserData.call(this); lowland.base.Events.call(this); + }, + + members : { + error : function() { + console.error(this.constructor || this, arguments); + }, + + warn : function() { + console.warn(this.constructor || this, arguments); + } } });
806b668ac7fce02ede78aad9528024a771d0631b
tool/src/main/webapp/static/lib/Text.js
tool/src/main/webapp/static/lib/Text.js
// Simple file for handling text. var Text = (function() { var emailRegex = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/ig; var emailReplacement = '<a class="email" href="mailto:$&">$&</a>'; var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig var urlReplacement = '<a class="url" href="$&">$&</a>'; var lineRegex = /\n/g; var lineReplacement = '<br>'; return { /** * Escape text so we can output it in a HTML page. * It attempts to escape HTML characters and marks up emails and links. * It currently has a bug in that a &amp; in URL will get escaped twice. * @param source The source text. * @returns The escape/marked up version. */ "toHtml": function(source) { var dest = source.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/, "&quot;"); dest = dest.replace(urlRegex, urlReplacement); dest = dest.replace(emailRegex, emailReplacement); dest = dest.replace(lineRegex, lineReplacement); return dest; } }; })();
// Simple file for handling text. var Text = (function() { var emailRegex = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/ig; var emailReplacement = '<a class="email" href="mailto:$&">$&</a>'; var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig var urlReplacement = '<a class="url" href="$&" target="_blank">$&</a>'; var lineRegex = /\n/g; var lineReplacement = '<br>'; return { /** * Escape text so we can output it in a HTML page. * It attempts to escape HTML characters and marks up emails and links. * It currently has a bug in that a &amp; in URL will get escaped twice. * @param source The source text. * @returns The escape/marked up version. */ "toHtml": function(source) { var dest = source.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/, "&quot;"); dest = dest.replace(urlRegex, urlReplacement); dest = dest.replace(emailRegex, emailReplacement); dest = dest.replace(lineRegex, lineReplacement); return dest; } }; })();
Make links open up in new windows.
Make links open up in new windows.
JavaScript
apache-2.0
ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup
--- +++ @@ -4,7 +4,7 @@ var emailRegex = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/ig; var emailReplacement = '<a class="email" href="mailto:$&">$&</a>'; var urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig - var urlReplacement = '<a class="url" href="$&">$&</a>'; + var urlReplacement = '<a class="url" href="$&" target="_blank">$&</a>'; var lineRegex = /\n/g; var lineReplacement = '<br>';
5fd9fe62dcd6e442344d202bc7d9c4fa0fea0a18
src/network.js
src/network.js
// https://en.bitcoin.it/wiki/List_of_address_prefixes module.exports = { bitcoin: { bip32: { pub: 0x0488b21e, priv: 0x0488ade4 }, pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80 }, dogecoin: { pubKeyHash: 0x30, scriptHash: 0x20, wif: 0x9e }, litecoin: { scriptHash: 0x30, }, testnet: { bip32: { pub: 0x043587cf, priv: 0x04358394 }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef } }
// https://en.bitcoin.it/wiki/List_of_address_prefixes // Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 module.exports = { bitcoin: { bip32: { pub: 0x0488b21e, priv: 0x0488ade4 }, pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80 }, dogecoin: { bip32: { pub: 0x02facafd, priv: 0x02fac398 }, pubKeyHash: 0x1e, scriptHash: 0x16, wif: 0x9e }, litecoin: { bip32: { pub: 0x019da462, priv: 0x019d9cfe }, pubKeyHash: 0x30, scriptHash: 0x05, wif: 0xb0 }, testnet: { bip32: { pub: 0x043587cf, priv: 0x04358394 }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef } }
Fix address prefixes, add dogecoin/litecoin BIP32 versions
Fix address prefixes, add dogecoin/litecoin BIP32 versions
JavaScript
mit
bitcoinhaber/bitcoinjs-lib,bpdavenport/bitcoinjs-lib,ptcrypto/bitcoinjs-lib,erikvold/bitcoinjs-lib,junderw/bitcoinjs-lib,BitGo/BitGoJS,p2pmining/bitcoinjs-lib,BitGo/bitcoinjs-lib,bitcoinjs/bitcoinjs-lib,visvirial/bitcoinjs-lib,visvirial/bitcoinjs-lib,habibmasuro/bitcoinjs-lib,blocktrail/bitcoinjs-lib,whitj00/opalcoinjs-lib,anders94/bitcoinjs-lib,oklink-dev/bitcoinjs,fanatid/bitcoinjs-lib,eXcomm/bitcoinjs-lib,Sjors/bitcoinjs-lib,bitcoinjs/bitcoinjs-lib,scotcoin/czarcoinjs-lib,UdjinM6/bitcoinjs-lib-dash,CoinBlack/blackcoinjs-lib,CryptArc/bitcoinjs-lib,BitGo/bitcoinjs-lib,lekkas/bitcoinjs-lib,BitGo/BitGoJS,mano10/bitcoinjs-lib,janko33bd/bitcoinjs-lib,BitGo/BitGoJS,BitGo/BitGoJS,javascriptit/bitcoinjs-lib,junderw/bitcoinjs-lib
--- +++ @@ -1,4 +1,5 @@ // https://en.bitcoin.it/wiki/List_of_address_prefixes +// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 module.exports = { bitcoin: { bip32: { @@ -10,12 +11,22 @@ wif: 0x80 }, dogecoin: { - pubKeyHash: 0x30, - scriptHash: 0x20, + bip32: { + pub: 0x02facafd, + priv: 0x02fac398 + }, + pubKeyHash: 0x1e, + scriptHash: 0x16, wif: 0x9e }, litecoin: { - scriptHash: 0x30, + bip32: { + pub: 0x019da462, + priv: 0x019d9cfe + }, + pubKeyHash: 0x30, + scriptHash: 0x05, + wif: 0xb0 }, testnet: { bip32: {
aa8eda993799431082acdaf1c515ee2902817a06
build/modules/renderPage.js
build/modules/renderPage.js
var components = require('./components'); var javascript = require('../tasks/javascript'); var extend = require('extend'); /** * Helper function for rendering a page * Abstracted out here to reduce some duplication in the main server */ var renderPage = function(hbs, data) { return new Promise(function(resolve, reject) { var pageData = { pageTitle: data.title + ' - Land Registry pattern library', assetPath: '/', homepageUrl: '/', content: data.content, scripts: [], propositionName: 'Land Registry pattern library' }; // If any of the demos define pageData we need to pop this up onto the page context extend(pageData, data.pageData); // Grab all our components, sort them into bundles and then output the // necessary script tags to load them components .getComponents() .then(javascript.sort) .then(function(bundles) { Object.keys(bundles).forEach(function(bundle) { pageData.scripts.push('<script async defer src="/javascripts/' + bundle + '.js"></script>') }); }) .then(function() { pageData.scripts = pageData.scripts.join('\n'); }) .then(function() { resolve(hbs.compile(hbs.partials['layout/govuk_template'])(pageData)); }) .catch(function(err) { reject(err); }); }) } module.exports = renderPage;
var components = require('./components'); var javascript = require('../tasks/javascript'); var extend = require('extend'); /** * Helper function for rendering a page * Abstracted out here to reduce some duplication in the main server */ var renderPage = function(hbs, data) { return new Promise(function(resolve, reject) { var pageData = { pageTitle: data.title + ' - Land Registry pattern library', assetPath: '/', homepageUrl: '/', content: data.content, scripts: [], propositionName: 'Land Registry pattern library' }; // If any of the demos define pageData we need to pop this up onto the page context extend(pageData, data.pageData); // Grab all our components, sort them into bundles and then output the // necessary script tags to load them components .getComponents() .then(javascript.sort) .then(function(bundles) { Object.keys(bundles).forEach(function(bundle) { pageData.scripts.push('<script defer src="/javascripts/' + bundle + '.js"></script>') }); }) .then(function() { pageData.scripts = pageData.scripts.join('\n'); }) .then(function() { resolve(hbs.compile(hbs.partials['layout/govuk_template'])(pageData)); }) .catch(function(err) { reject(err); }); }) } module.exports = renderPage;
Remove async again - not compatibile with leafletjs
Remove async again - not compatibile with leafletjs
JavaScript
mit
LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements
--- +++ @@ -28,7 +28,7 @@ .then(javascript.sort) .then(function(bundles) { Object.keys(bundles).forEach(function(bundle) { - pageData.scripts.push('<script async defer src="/javascripts/' + bundle + '.js"></script>') + pageData.scripts.push('<script defer src="/javascripts/' + bundle + '.js"></script>') }); }) .then(function() {
62bcabb8826bea721d9d53c6141ea2393737e90d
app/javascript/app/components/stories/stories-actions.js
app/javascript/app/components/stories/stories-actions.js
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; const fetchStoriesInit = createAction('fetchStoriesInit'); const fetchStoriesReady = createAction('fetchStoriesReady'); const fetchStoriesFail = createAction('fetchStoriesFail'); const fetchStories = createThunkAction('fetchStories', () => dispatch => { dispatch(fetchStoriesInit()); fetch('/api/v1/stories') .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchStoriesReady(data)); }) .catch(error => { console.info(error); dispatch(fetchStoriesFail()); }); }); export default { fetchStories, fetchStoriesInit, fetchStoriesReady, fetchStoriesFail };
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; const fetchStoriesInit = createAction('fetchStoriesInit'); const fetchStoriesReady = createAction('fetchStoriesReady'); const fetchStoriesFail = createAction('fetchStoriesFail'); const TAGS = ['NDC', 'ndcsdg', 'esp', 'climate watch']; const fetchStories = createThunkAction('fetchStories', () => dispatch => { dispatch(fetchStoriesInit()); fetch(`/api/v1/stories?tags=${TAGS}`) .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchStoriesReady(data)); }) .catch(error => { console.info(error); dispatch(fetchStoriesFail()); }); }); export default { fetchStories, fetchStoriesInit, fetchStoriesReady, fetchStoriesFail };
Add filter tags to stories actions on js app
Add filter tags to stories actions on js app
JavaScript
mit
Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch
--- +++ @@ -5,9 +5,11 @@ const fetchStoriesReady = createAction('fetchStoriesReady'); const fetchStoriesFail = createAction('fetchStoriesFail'); +const TAGS = ['NDC', 'ndcsdg', 'esp', 'climate watch']; + const fetchStories = createThunkAction('fetchStories', () => dispatch => { dispatch(fetchStoriesInit()); - fetch('/api/v1/stories') + fetch(`/api/v1/stories?tags=${TAGS}`) .then(response => { if (response.ok) return response.json(); throw Error(response.statusText);
603409dc7896549d58ab36821d581820c298c7ee
assets/js/util/api.js
assets/js/util/api.js
/** * Cache data. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { // Exclude certain errors from tracking based on error code. const excludedErrorCodes = [ 'fetch_error', // Client failed to fetch from WordPress. ]; if ( excludedErrorCodes.indexOf( error.code ) >= 0 ) { return; } await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
/** * Track API errors. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { // Exclude certain errors from tracking based on error code. const excludedErrorCodes = [ 'fetch_error', // Client failed to fetch from WordPress. ]; if ( excludedErrorCodes.indexOf( error.code ) >= 0 ) { return; } await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
Improve track API file header.
Improve track API file header.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -1,5 +1,5 @@ /** - * Cache data. + * Track API errors. * * Site Kit by Google, Copyright 2020 Google LLC *
7eb5153314da93c30f41e5615ea55fb672e5534e
server/app.js
server/app.js
// Server startup script // ===================== // Responsible for configuring the server, // inserting middleware, and starting the // app up. // // Note: this was written on my iPhone, please excuse typos 'use strict' let express = require('express'), exphbs = require('express-handlebars'), app = express(), _ = require('lodash'), config = _.merge(require(__dirname + '/config/app').common, require(__dirname + '/config/app')[process.env.NODE_ENV]); // App configuration // ----------------- // Configure views and other settings app.engine('hbs', exphbs(config.handlebars)); app.set('view engine', 'hbs'); app.set('views', __dirname + '/views'); // Middleware // ---------- // Insert, configure, update middleware // Routes // ------ // Initialize user facing routes require('./controllers')(app); // Start server // ------------ // Start the server let server = app.listen(process.env.PORT, () => { console.log('Started app on localhost:' + server.address().port); });
// Server startup script // ===================== // Responsible for configuring the server, // inserting middleware, and starting the // app up. // // Note: this was written on my iPhone, please excuse typos 'use strict' let express = require('express'), exphbs = require('express-handlebars'), app = express(), _ = require('lodash'), config = _.merge(require(__dirname + '/config/app').common, require(__dirname + '/config/app')[process.env.NODE_ENV]); // App configuration // ----------------- // Configure views and other settings app.engine('hbs', exphbs(config.handlebars)); app.set('view engine', 'hbs'); app.set('views', __dirname + '/views'); // Middleware // ---------- // Insert, configure, update middleware if (_.includes(['development', 'test'], process.env.NODE_ENV)) { // DEVELOPMENT/TEST MIDDLEWARE app.use(express.static(__dirname + '/public')); } // Routes // ------ // Initialize user facing routes require('./controllers')(app); // Start server // ------------ // Start the server let server = app.listen(process.env.PORT, () => { console.log('Started app on localhost:' + server.address().port); });
Add static server middleware that is active in non-production environments only.
Add static server middleware that is active in non-production environments only.
JavaScript
mit
billpatrianakos/coverage-web,billpatrianakos/coverage-web,billpatrianakos/coverage-web
--- +++ @@ -26,6 +26,10 @@ // Middleware // ---------- // Insert, configure, update middleware +if (_.includes(['development', 'test'], process.env.NODE_ENV)) { + // DEVELOPMENT/TEST MIDDLEWARE + app.use(express.static(__dirname + '/public')); +} // Routes
37b2967fc7523e849273d4b739184cdfc3778761
src/commands/rover/PingCommand.js
src/commands/rover/PingCommand.js
const Command = require('../Command') module.exports = class PingCommand extends Command { constructor (client) { super(client, { name: 'ping', properName: 'Ping', description: 'Ping the bot to see API latency' }) } async fn (msg) { msg.channel.send('Pinging...').then(message => { message.edit(`:ping_pong: Pong! Took **${message.createdTimestamp - msg.createdTimestamp}ms**`) }) } }
const Command = require('../Command') module.exports = class PingCommand extends Command { constructor (client) { super(client, { name: 'ping', properName: 'Ping', description: 'Ping the bot to see API latency', userPermissions: [] }) } async fn (msg) { msg.channel.send('Pinging...').then(message => { message.edit(`:ping_pong: Pong! Took **${message.createdTimestamp - msg.createdTimestamp}ms**`) }) } }
Allow ping command to be used by anyone
Allow ping command to be used by anyone
JavaScript
apache-2.0
evaera/RoVer
--- +++ @@ -6,7 +6,8 @@ super(client, { name: 'ping', properName: 'Ping', - description: 'Ping the bot to see API latency' + description: 'Ping the bot to see API latency', + userPermissions: [] }) } async fn (msg) {
4c5679e121aa1a5c32fd18c40619df0c01c93ff5
app/config/sockjs_server.js
app/config/sockjs_server.js
(function() { 'use strict'; define(['sockjs'], function (sockjs) { var sockjs_opts = { sockjs_url: 'http://cdn.sockjs.org/sockjs-0.3.min.js' }; return sockjs.createServer(sockjs_opts); }); }());
(function() { 'use strict'; define(['sockjs'], function (sockjs) { return sockjs.createServer(); }); }());
Remove unused SockJS server-side config options
Remove unused SockJS server-side config options
JavaScript
mit
ndhoule/underscoreboard,ndhoule/underscoreboard
--- +++ @@ -2,10 +2,6 @@ 'use strict'; define(['sockjs'], function (sockjs) { - var sockjs_opts = { - sockjs_url: 'http://cdn.sockjs.org/sockjs-0.3.min.js' - }; - - return sockjs.createServer(sockjs_opts); + return sockjs.createServer(); }); }());
55dbc0efa497718406293b8d1d0165464c212413
client/src/teams/reducer.js
client/src/teams/reducer.js
import { ADD_TEAM_SUCCESS } from './actionCreators' let initialState = [ { id: 2, name: 'gym', colour: "#49078d", balance: 105463 }, { id: 1, name: 'fred', colour: "#23fe4d", balance: 105463 }, { id: 3, name: 'suup', colour: "#1fffe4", balance: 105463 } ] export default (state=initialState, action) => { switch (action.type) { case ADD_TEAM_SUCCESS: return Object.keys(action.response.teams).map(key => action.response.teams[key]) default: return state } }
import { ADD_TEAM_SUCCESS } from './actionCreators' const teams_in = (hash) => Object.keys(hash).map(key => hash[key]) export default (state=[], action) => { switch (action.type) { case ADD_TEAM_SUCCESS: return teams_in(action.response.teams) default: return state } }
Delete the hard-coded fake teams
Delete the hard-coded fake teams
JavaScript
mit
xpsurgery/shopping-cart,xpsurgery/shopping-cart,xpsurgery/shopping-cart
--- +++ @@ -1,15 +1,11 @@ import { ADD_TEAM_SUCCESS } from './actionCreators' -let initialState = [ - { id: 2, name: 'gym', colour: "#49078d", balance: 105463 }, - { id: 1, name: 'fred', colour: "#23fe4d", balance: 105463 }, - { id: 3, name: 'suup', colour: "#1fffe4", balance: 105463 } -] +const teams_in = (hash) => Object.keys(hash).map(key => hash[key]) -export default (state=initialState, action) => { +export default (state=[], action) => { switch (action.type) { case ADD_TEAM_SUCCESS: - return Object.keys(action.response.teams).map(key => action.response.teams[key]) + return teams_in(action.response.teams) default: return state
03ae44a0ef4d4c96f2578c317967bf38778f27b0
src/tracker.js
src/tracker.js
'use strict'; var trackStar = (function(){ function TrackStar() { var integrations = {}; if(!(this instanceof TrackStar)){ return new TrackStar(); } this.getIntegrations = function() { return integrations; }; this.integrate = function(integrationsObj) { if (Object.prototype.toString.call(integrationsObj) !== '[object Object]') { throw new Error('trackStar requires an Object of integrations'); } for(var key in integrationsObj){ var val = integrationsObj[key]; if (integrations.hasOwnProperty(key)) { integrations[key] = integrations[key].concat(val); } else { integrations[key] = [].concat(val); } } return this; }; // Start testing API this.wipeClean = TrackStar; // End testing API return this; } function sendFunction (context, functionName, opts) { var integrations = context.getIntegrations(); for (var key in integrations){ _integrationsMasterList[key][functionName](opts); }; } TrackStar.prototype.trackPageView = function() { sendFunction(this, 'trackPageView'); }; TrackStar.prototype.trackConversion = function(){ sendFunction(this, 'trackConversion'); }; TrackStar.prototype.trackAction = function(opts){ sendFunction(this, 'trackAction', opts); }; return window.trackStar = TrackStar(); }());
'use strict'; var trackStar = (function(){ function TrackStar() { var integrations = {}; if(!(this instanceof TrackStar)){ return new TrackStar(); } this.getIntegrations = function() { return integrations; }; this.integrate = function(integrationsObj) { if (Object.prototype.toString.call(integrationsObj) !== '[object Object]') { throw new Error('trackStar requires an Object of integrations'); } for(var key in integrationsObj){ if (integrationsObj.hasOwnProperty[key]){ var val = integrationsObj[key]; if (integrations.hasOwnProperty(key)) { integrations[key] = integrations[key].concat(val); } else { integrations[key] = [].concat(val); } } } return this; }; // Start testing API this.wipeClean = TrackStar; // End testing API return this; } function sendFunction (context, functionName, opts) { var integrations = context.getIntegrations(); for (var key in integrations){ if(integrations.hasOwnProperty(key)){ _integrationsMasterList[key][functionName](opts); } } } TrackStar.prototype.trackPageView = function() { sendFunction(this, 'trackPageView'); }; TrackStar.prototype.trackConversion = function(){ sendFunction(this, 'trackConversion'); }; TrackStar.prototype.trackAction = function(opts){ sendFunction(this, 'trackAction', opts); }; return window.trackStar = TrackStar(); }());
Make sure we're not grabbing any prototype props
Make sure we're not grabbing any prototype props Probably unnecessary, but let's be safe
JavaScript
apache-2.0
dustincoates/trackstar
--- +++ @@ -18,11 +18,13 @@ } for(var key in integrationsObj){ - var val = integrationsObj[key]; - if (integrations.hasOwnProperty(key)) { - integrations[key] = integrations[key].concat(val); - } else { - integrations[key] = [].concat(val); + if (integrationsObj.hasOwnProperty[key]){ + var val = integrationsObj[key]; + if (integrations.hasOwnProperty(key)) { + integrations[key] = integrations[key].concat(val); + } else { + integrations[key] = [].concat(val); + } } } @@ -42,8 +44,10 @@ var integrations = context.getIntegrations(); for (var key in integrations){ - _integrationsMasterList[key][functionName](opts); - }; + if(integrations.hasOwnProperty(key)){ + _integrationsMasterList[key][functionName](opts); + } + } } TrackStar.prototype.trackPageView = function() {
20fbc6c4ccda450b31c39c739f5c438c994a67ed
src/wrapper.js
src/wrapper.js
/** Copyright (c) 2013 Jan Nicklas Released under MIT license */ /* global define: false, jQuery: true */ /* jshint sub:true */ // RequireJS amd factory // http://stackoverflow.com/questions/10918063/how-to-make-a-jquery-plugin-loadable-with-requirejs#answer-11890239 (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Run without AMD factory(jQuery); } }(function ($) { 'use strict'; // @@ code @@ // }));
/** Copyright (c) 2013 Jan Nicklas Released under MIT license */ /* global define: false, jQuery: true */ /* jshint sub:true */ // RequireJS amd factory // http://stackoverflow.com/questions/10918063/how-to-make-a-jquery-plugin-loadable-with-requirejs#answer-11890239 (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Run without AMD factory(jQuery); } }(function ($) { 'use strict'; // @@ include ariaMenu.js @@ // }));
Add the name of the included script
Add the name of the included script
JavaScript
mit
jantimon/ariaMenu,jantimon/ariaMenu
--- +++ @@ -16,5 +16,5 @@ } }(function ($) { 'use strict'; - // @@ code @@ // + // @@ include ariaMenu.js @@ // }));
ce99af2e737a2afc6ffcb6a2c5e6869953b21757
app/javascript/modules/EmailParliament/index.js
app/javascript/modules/EmailParliament/index.js
import React, { useState } from 'react'; import classnames from 'classnames'; import { search } from './api'; import SearchByPostcode from './SearchByPostcode'; import EmailComposer from './EmailComposer'; import ComponentWrapper from '../../components/ComponentWrapper'; import { redirect } from '../../util/redirector'; export const init = options => { if (!options.config || !options.config.active) return; if (options.el) { render( <EmailParliament config={options.config} onSend={options.onSend} />, options.el ); } }; const EmailParliament = props => { const [target, setTarget] = useState(null); const searchClassname = classnames({ 'hidden-irrelevant': target !== null, }); return ( <div className="EmailParliament"> <ComponentWrapper locale={props.config.locale}> <SearchByPostcode className={searchClassname} onChange={setTarget} /> <EmailComposer title={props.config.title} postcode={''} target={target} subject={props.config.subject} template={props.config.template} onSend={props.onSend || redirect} /> </ComponentWrapper> </div> ); }; export default EmailParliament;
import React, { useState } from 'react'; import { render } from 'react-dom'; import classnames from 'classnames'; import { search } from './api'; import SearchByPostcode from './SearchByPostcode'; import EmailComposer from './EmailComposer'; import ComponentWrapper from '../../components/ComponentWrapper'; import { redirect } from '../../util/redirector'; export const init = options => { if (!options.config || !options.config.active) return; if (options.el) { render( <EmailParliament config={options.config} onSend={options.onSend} />, options.el ); } }; const EmailParliament = props => { const [target, setTarget] = useState(null); const searchClassname = classnames({ 'hidden-irrelevant': target !== null, }); return ( <div className="EmailParliament"> <ComponentWrapper locale={props.config.locale}> <SearchByPostcode className={searchClassname} onChange={setTarget} /> <EmailComposer title={props.config.title} postcode={''} target={target} subject={props.config.subject} template={props.config.template} onSend={props.onSend || redirect} /> </ComponentWrapper> </div> ); }; export default EmailParliament;
Fix `render is undefined` in EmailParliament
Fix `render is undefined` in EmailParliament
JavaScript
mit
SumOfUs/Champaign,SumOfUs/Champaign,SumOfUs/Champaign,SumOfUs/Champaign,SumOfUs/Champaign
--- +++ @@ -1,4 +1,5 @@ import React, { useState } from 'react'; +import { render } from 'react-dom'; import classnames from 'classnames'; import { search } from './api'; import SearchByPostcode from './SearchByPostcode';
407921321c4746588b60c441f69820368ed8bee3
app/assets/scripts/components/community-card.js
app/assets/scripts/components/community-card.js
'use strict'; import React from 'react'; var CommunityCard = React.createClass({ displayName: 'CommunityCard', propTypes: { title: React.PropTypes.string, linkTitle: React.PropTypes.string, url: React.PropTypes.string, imageNode: React.PropTypes.node, children: React.PropTypes.object }, render: function () { return ( <article className='card card--horizontal card--horizontal--align-middle'> <div className='card__contents'> <figure className='card__media'> <div className='card__thumbnail'> {this.props.imageNode} </div> </figure> <div className="card__copy"> <header className='card__header'> <h1 className='card__title'><a title={this.props.linkTitle} href={this.props.url}>{this.props.title}</a></h1> </header> <div className='card__body'> {this.props.children} <a title={this.props.linkTitle} href={this.props.url}>Learn More</a> </div> </div> </div> </article> ); } }); module.exports = CommunityCard;
'use strict'; import React from 'react'; import c from 'classnames'; var CommunityCard = React.createClass({ displayName: 'CommunityCard', propTypes: { title: React.PropTypes.string, linkTitle: React.PropTypes.string, url: React.PropTypes.string, imageNode: React.PropTypes.node, horizontal: React.PropTypes.bool, children: React.PropTypes.object }, getDefaultProps: function () { return { horizontal: false }; }, render: function () { return ( <article className={c('card', {'card--horizontal card--horizontal--align-middle': this.props.horizontal})}> <div className='card__contents'> <figure className='card__media'> <div className='card__thumbnail'> {this.props.imageNode} </div> </figure> <div className="card__copy"> <header className='card__header'> <h1 className='card__title'><a title={this.props.linkTitle} href={this.props.url}>{this.props.title}</a></h1> </header> <div className='card__body'> {this.props.children} <a title={this.props.linkTitle} href={this.props.url}>Learn More</a> </div> </div> </div> </article> ); } }); module.exports = CommunityCard;
Make community card horizontal by default
Make community card horizontal by default
JavaScript
bsd-3-clause
openaq/openaq.org,openaq/openaq.github.io,openaq/openaq.github.io,openaq/openaq.org,openaq/openaq.github.io,openaq/openaq.org
--- +++ @@ -1,5 +1,6 @@ 'use strict'; import React from 'react'; +import c from 'classnames'; var CommunityCard = React.createClass({ displayName: 'CommunityCard', @@ -9,12 +10,19 @@ linkTitle: React.PropTypes.string, url: React.PropTypes.string, imageNode: React.PropTypes.node, + horizontal: React.PropTypes.bool, children: React.PropTypes.object + }, + + getDefaultProps: function () { + return { + horizontal: false + }; }, render: function () { return ( - <article className='card card--horizontal card--horizontal--align-middle'> + <article className={c('card', {'card--horizontal card--horizontal--align-middle': this.props.horizontal})}> <div className='card__contents'> <figure className='card__media'> <div className='card__thumbnail'>
9e4c6ea66332e0f9cf6472dad44bf8dc1dc31443
site/build.js
site/build.js
import Metalsmith from 'metalsmith'; import common from '@rollup/plugin-commonjs'; import inPlace from '@metalsmith/in-place'; import layouts from '@metalsmith/layouts'; import markdown from '@metalsmith/markdown'; import {dirname, resolve} from 'node:path'; import {env} from 'node:process'; import {fileURLToPath} from 'node:url'; import {nodeResolve} from '@rollup/plugin-node-resolve'; import {rollup} from 'rollup'; import {terser} from 'rollup-plugin-terser'; const baseDir = dirname(fileURLToPath(import.meta.url)); const builder = Metalsmith(baseDir) .source('./src') .destination('./build') .clean(true) .metadata({ version: env.OL_VERSION || 'dev', }) .use(inPlace()) .use(markdown()) .use(layouts()); builder.build(async (err) => { if (err) { throw err; } await bundleMain(); }); async function bundleMain() { const inputOptions = { plugins: [ common(), nodeResolve({ moduleDirectories: [ resolve(baseDir, '../src'), resolve(baseDir, '../node_modules'), ], }), terser(), ], input: resolve(baseDir, './build/main.js'), }; const outputOptions = { dir: resolve(baseDir, './build'), format: 'iife', }; const bundle = await rollup(inputOptions); await bundle.write(outputOptions); bundle.close(); }
import Metalsmith from 'metalsmith'; import common from '@rollup/plugin-commonjs'; import inPlace from '@metalsmith/in-place'; import layouts from '@metalsmith/layouts'; import markdown from '@metalsmith/markdown'; import {dirname, resolve} from 'node:path'; import {env} from 'node:process'; import {fileURLToPath} from 'node:url'; import {nodeResolve} from '@rollup/plugin-node-resolve'; import {rollup} from 'rollup'; import {terser} from 'rollup-plugin-terser'; const baseDir = dirname(fileURLToPath(import.meta.url)); const builder = Metalsmith(baseDir) .source('./src') .destination('./build') .clean(true) .metadata({ version: env.OL_VERSION || 'dev', }) .use(inPlace()) .use(markdown()) .use(layouts()); builder.build(async (err) => { if (err) { throw err; } await bundleMain(); }); async function bundleMain() { const inputOptions = { plugins: [ common(), nodeResolve({ modulePaths: [ resolve(baseDir, '../src'), resolve(baseDir, '../node_modules'), ], }), terser(), ], input: resolve(baseDir, './build/main.js'), }; const outputOptions = { dir: resolve(baseDir, './build'), format: 'iife', }; const bundle = await rollup(inputOptions); await bundle.write(outputOptions); bundle.close(); }
Use modulePaths instead of moduleDirectories
Use modulePaths instead of moduleDirectories
JavaScript
bsd-2-clause
stweil/openlayers,openlayers/openlayers,stweil/openlayers,openlayers/openlayers,ahocevar/openlayers,stweil/openlayers,openlayers/openlayers,ahocevar/openlayers,ahocevar/openlayers
--- +++ @@ -35,7 +35,7 @@ plugins: [ common(), nodeResolve({ - moduleDirectories: [ + modulePaths: [ resolve(baseDir, '../src'), resolve(baseDir, '../node_modules'), ],
a12d5f8834dd451a6d70a3a1b9f8a60753246ce6
src/pages/Application/ApplicationDropdown.js
src/pages/Application/ApplicationDropdown.js
import React from 'react'; import { changeApplicationFieldValue } from '../../actions/application'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; const ApplicationTextField = ({changeApplicationFieldValue, field, applicationForm, disabled, isLoading, styles, options}) => ( <select value={applicationForm[field] || ""} onChange={ (e) => changeApplicationFieldValue(field,e.target.value) } disabled={(disabled || false) || isLoading} className="dropdown" > { Object.keys(options).map((t,i) => <option key={i} value={t}>{t}</option>) } {/* <option value="grapefruit">Grapefruit</option> <option value="lime">Lime</option> <option value="coconut">Coconut</option> <option value="mango">Mango</option> */} </select> ); function mapStateToProps (state) { return { applicationForm: state.application.applicationForm, isLoading: state.application.isLoading }; } const mapDispatchToProps = (dispatch) => { return bindActionCreators({changeApplicationFieldValue}, dispatch) }; export default connect(mapStateToProps, mapDispatchToProps)(ApplicationTextField);
import React from 'react'; import { changeApplicationFieldValue } from '../../actions/application'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; const ApplicationDropdown = ({changeApplicationFieldValue, field, applicationForm, disabled, isLoading, styles, options}) => ( <select value={applicationForm[field] || ""} onChange={ (e) => changeApplicationFieldValue(field,e.target.value) } disabled={(disabled || false) || isLoading} className="dropdown" > { Object.keys(options).map((t,i) => <option key={i} value={t}>{t}</option>) } {/* <option value="grapefruit">Grapefruit</option> <option value="lime">Lime</option> <option value="coconut">Coconut</option> <option value="mango">Mango</option> */} </select> ); function mapStateToProps (state) { return { applicationForm: state.application.applicationForm, isLoading: state.application.isLoading }; } const mapDispatchToProps = (dispatch) => { return bindActionCreators({changeApplicationFieldValue}, dispatch) }; export default connect(mapStateToProps, mapDispatchToProps)(ApplicationDropdown);
Update dropdown with properr var name
Update dropdown with properr var name
JavaScript
agpl-3.0
BoilerMake/frontend,BoilerMake/frontend
--- +++ @@ -3,7 +3,7 @@ import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; -const ApplicationTextField = ({changeApplicationFieldValue, field, applicationForm, disabled, isLoading, styles, options}) => ( +const ApplicationDropdown = ({changeApplicationFieldValue, field, applicationForm, disabled, isLoading, styles, options}) => ( <select value={applicationForm[field] || ""} onChange={ @@ -31,4 +31,4 @@ return bindActionCreators({changeApplicationFieldValue}, dispatch) }; -export default connect(mapStateToProps, mapDispatchToProps)(ApplicationTextField); +export default connect(mapStateToProps, mapDispatchToProps)(ApplicationDropdown);
0c3cf9273f3bef100484b50bbdb1968cddc06717
src/katagroup.js
src/katagroup.js
import Kata from './kata.js'; export default class KataGroup { static withKatas(groupName, rawKataItems) { var group = new KataGroup(); group.name = groupName; group.createKatas(rawKataItems); group.sortByName(); return group; } createKatas(rawKataItems) { this.katas = rawKataItems.map(item => Kata.fromRawItem(item)); } sortByName() { this.katas.sort((kata1, kata2) => toInt(kata1.id) < toInt(kata2.id) ? -1 : 1); } get highestId() { if (this.katas.length === 0) { return 0; } return this.katas[this.katas.length - 1].id; } } const toInt = (string) => Number.parseInt(string, 10);
import Kata from './kata.js'; export default class KataGroup { static withKatas(groupName, rawKataItems) { var group = new KataGroup(); group.name = groupName; group.createKatas(rawKataItems); group.sortByName(); return group; } createKatas(rawKataItems) { this.katas = rawKataItems.map(item => Kata.fromRawItem(item)); } sortByName() { this.katas.sort((kata1, kata2) => kata1.id < kata2.id ? -1 : 1); } get highestId() { if (this.katas.length === 0) { return 0; } return this.katas[this.katas.length - 1].id; } }
Remove unnecessary conversion, that is done now at kata creation time.
Remove unnecessary conversion, that is done now at kata creation time.
JavaScript
mit
tddbin/es6katas.org
--- +++ @@ -15,7 +15,7 @@ } sortByName() { - this.katas.sort((kata1, kata2) => toInt(kata1.id) < toInt(kata2.id) ? -1 : 1); + this.katas.sort((kata1, kata2) => kata1.id < kata2.id ? -1 : 1); } get highestId() { @@ -25,5 +25,3 @@ return this.katas[this.katas.length - 1].id; } } - -const toInt = (string) => Number.parseInt(string, 10);
0a643864d51d550234a6391b761512467cf44e73
src/modules/navigation/reducer.js
src/modules/navigation/reducer.js
import { isArray } from 'lodash'; import { AppNavigator } from 'DailyScrum/src/Scenes'; export default (state, action) => { const { type } = action; if (type === 'Navigation/NAVIGATE' && isRouteSameAsLastRouteFromNavigationStateSelector(state, action)) { console.warn( 'You pressed the navigation button two times, pushing two times to the same route.\n\n' + 'The last dispatch was canceled. \n\n' + 'If the call was intended, you can add an exception in redux routing.', action ); return state || {}; } const newState = AppNavigator.router.getStateForAction(action, state); return newState || state; }; const isRouteSameAsLastRouteFromNavigationStateSelector = (state, action) => { const lastRoute = routeFromNavigationStateSelector(state); if (!lastRoute) { return false; } // FUTURE add exceptions here (params in lastRoute.params, action.params) return lastRoute.routeName === action.routeName; }; export const routeFromNavigationStateSelector = state => { const currentRootRoute = state.routes[state.index]; let route; if (isArray(currentRootRoute.routes)) { route = currentRootRoute.routes[currentRootRoute.index]; } else { route = currentRootRoute; } return route; };
import { isArray, isEqual } from 'lodash'; import { AppNavigator } from 'DailyScrum/src/Scenes'; export default (state, action) => { const { type } = action; if (type === 'Navigation/NAVIGATE' && isRouteSameAsLastRouteFromNavigationStateSelector(state, action)) { console.warn( 'You pressed the navigation button two times, pushing two times to the same route.\n\n' + 'The last dispatch was canceled. \n\n' + 'If the call was intended, you can add an exception in redux routing.', action ); return state || {}; } const newState = AppNavigator.router.getStateForAction(action, state); return newState || state; }; const isRouteSameAsLastRouteFromNavigationStateSelector = (state, action) => { const lastRoute = routeFromNavigationStateSelector(state); if (!lastRoute) { return false; } // FUTURE add exceptions here (params in lastRoute.params, action.params) if (lastRoute.routeName !== action.routeName) { return false; } return isEqual(lastRoute.params, action.params); }; export const routeFromNavigationStateSelector = state => { const currentRootRoute = state.routes[state.index]; let route; if (isArray(currentRootRoute.routes)) { route = currentRootRoute.routes[currentRootRoute.index]; } else { route = currentRootRoute; } return route; };
Fix navigating twice with params
Fix navigating twice with params
JavaScript
mit
Minishlink/DailyScrum,Minishlink/DailyScrum,Minishlink/DailyScrum,Minishlink/DailyScrum,Minishlink/DailyScrum
--- +++ @@ -1,4 +1,4 @@ -import { isArray } from 'lodash'; +import { isArray, isEqual } from 'lodash'; import { AppNavigator } from 'DailyScrum/src/Scenes'; export default (state, action) => { @@ -25,8 +25,11 @@ } // FUTURE add exceptions here (params in lastRoute.params, action.params) + if (lastRoute.routeName !== action.routeName) { + return false; + } - return lastRoute.routeName === action.routeName; + return isEqual(lastRoute.params, action.params); }; export const routeFromNavigationStateSelector = state => {
0a95b27d95b6310072080a41e1edcb5af75b32d1
server/routes/UserRoutes.js
server/routes/UserRoutes.js
import express from 'express'; import UserController from '../controllers/UserController'; const userRouter = express.Router(); userRouter.post('/api/user/signup', UserController.createUser()); userRouter.post('/api/user/signin', [ UserController.validateRequest(), UserController.authenticateUser() ]); userRouter.use('/api', [ UserController.getClientAuthToken(), UserController.authorizeUser() ]); userRouter.get('/api/user/groups', UserController.getUserGroups()); export default userRouter;
import express from 'express'; import UserController from '../controllers/UserController'; const userRouter = express.Router(); userRouter.post('/api/user/signup', UserController.createUser()); userRouter.post('/api/user/signin', [ UserController.validateRequest(), UserController.authenticateUser() ]); userRouter.use('/api', [ UserController.getClientAuthToken(), UserController.authorizeUser() ]); userRouter.put('/api/user', UserController.updateUser()); userRouter.delete('/api/user', UserController.deleteUser()); userRouter.get('/api/user/groups', UserController.getUserGroups()); export default userRouter;
Add endpoints to update and delete user
[feat]: Add endpoints to update and delete user
JavaScript
mit
tomipaul/PostIt,tomipaul/PostIt
--- +++ @@ -11,6 +11,8 @@ UserController.getClientAuthToken(), UserController.authorizeUser() ]); +userRouter.put('/api/user', UserController.updateUser()); +userRouter.delete('/api/user', UserController.deleteUser()); userRouter.get('/api/user/groups', UserController.getUserGroups()); export default userRouter;
b306f5568b17eaae2b1289ebfb6ea47c7676c9a4
js/responsive.js
js/responsive.js
$(document).ready(function (){ var width = $(window).width(), costumizedWith = width - 30, image = $('.artis-img'); headline = $('.headline-img'); ads = $('.ads'); image.css('width', costumizedWith); headline.css('width', costumizedWith); ads.css('width', costumizedWith); });
$(document).ready(function (){ var width = $(window).width(), costumizedWith = width - 30, image = $('.artis-img'), headline = $('.headline-img'), ads = $('.ads'); image.css('width', costumizedWith); headline.css('width', costumizedWith); ads.css('width', costumizedWith); });
Use , rather than ;
Use , rather than ;
JavaScript
mit
tauduluan/php,tauduluan/php,tauduluan/php
--- +++ @@ -1,8 +1,8 @@ $(document).ready(function (){ var width = $(window).width(), costumizedWith = width - 30, - image = $('.artis-img'); - headline = $('.headline-img'); + image = $('.artis-img'), + headline = $('.headline-img'), ads = $('.ads'); image.css('width', costumizedWith); headline.css('width', costumizedWith);
c7fff6c1a91a69a54b9096d3698433abbcf2dd8e
source/main/utils/getNumberOfEpochsConsolidated.js
source/main/utils/getNumberOfEpochsConsolidated.js
// @flow import fs from 'fs'; import path from 'path'; import { appFolderPath } from '../config'; import { getNumberOfEpochsConsolidatedChannel } from '../ipc/getNumberOfEpochsConsolidated.ipc'; import type { GetNumberOfEpochsConsolidatedChannelResponse } from '../../common/ipc/api'; export const getNumberOfEpochsConsolidated = () => { getNumberOfEpochsConsolidatedChannel .onRequest((): Promise<GetNumberOfEpochsConsolidatedChannelResponse> => { const epochsPath = path.join(appFolderPath, 'DB-1.0', 'epochs'); let latestConsolidatedEpoch = 0; if (fs.existsSync(epochsPath)) { const epochfiles = fs .readdirSync(epochsPath) .filter(file => file.indexOf('.epoch') > -1) .map(file => parseInt(file.split('.').shift(), 10)); if (epochfiles.length) latestConsolidatedEpoch = Math.max(...epochfiles); } return Promise.resolve(latestConsolidatedEpoch); }); };
// @flow import fs from 'fs'; import path from 'path'; import { appFolderPath } from '../config'; import { getNumberOfEpochsConsolidatedChannel } from '../ipc/getNumberOfEpochsConsolidated.ipc'; import type { GetNumberOfEpochsConsolidatedChannelResponse } from '../../common/ipc/api'; import { environment } from '../environment'; const { isLinux } = environment; export const getNumberOfEpochsConsolidated = () => { getNumberOfEpochsConsolidatedChannel .onRequest((): Promise<GetNumberOfEpochsConsolidatedChannelResponse> => { const epochsPath = isLinux ? path.join(appFolderPath, 'DB', 'epochs') : path.join(appFolderPath, 'DB-1.0', 'epochs'); let latestConsolidatedEpoch = 0; if (fs.existsSync(epochsPath)) { const epochfiles = fs .readdirSync(epochsPath) .filter(file => file.indexOf('.epoch') > -1) .map(file => parseInt(file.split('.').shift(), 10)); if (epochfiles.length) latestConsolidatedEpoch = Math.max(...epochfiles); } return Promise.resolve(latestConsolidatedEpoch); }); };
Correct path for EPOCH files in Linux
[DDW-557] Correct path for EPOCH files in Linux
JavaScript
apache-2.0
input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus
--- +++ @@ -4,11 +4,16 @@ import { appFolderPath } from '../config'; import { getNumberOfEpochsConsolidatedChannel } from '../ipc/getNumberOfEpochsConsolidated.ipc'; import type { GetNumberOfEpochsConsolidatedChannelResponse } from '../../common/ipc/api'; +import { environment } from '../environment'; + +const { isLinux } = environment; export const getNumberOfEpochsConsolidated = () => { getNumberOfEpochsConsolidatedChannel .onRequest((): Promise<GetNumberOfEpochsConsolidatedChannelResponse> => { - const epochsPath = path.join(appFolderPath, 'DB-1.0', 'epochs'); + const epochsPath = isLinux + ? path.join(appFolderPath, 'DB', 'epochs') + : path.join(appFolderPath, 'DB-1.0', 'epochs'); let latestConsolidatedEpoch = 0; if (fs.existsSync(epochsPath)) { const epochfiles = fs
26e8c6f32ca4dda553ca2394a155cb7174b1bf05
generate.js
generate.js
'use strict'; var fs = require('fs'); var Download = require('download'); var CSV = require('comma-separated-values'); var arrayUniq = require('array-uniq'); new Download({extract: true}) .get('http://www.mapcode.com/kader/isotables.zip') .run(function (err, files) { var data = files[0].contents.toString(); var items = new CSV(data, {header: true}).parse(); var ret = []; items.forEach(function (el) { if (el.Territory !== '') { ret.push(el.Territory); } if (el['Local code'] !== '') { ret.push(el['Local code']); } if (el['Full code'] !== '') { ret.push(el['Full code']); } }); var out = '\'use strict\';\nmodule.exports = function () {\n\treturn /(?:(' + arrayUniq(ret).sort().join('|') + ') )?[A-Z0-9]{2,}\.[A-Z0-9]{2,}/g;\n};'; fs.writeFileSync('index.js', out); });
'use strict'; var fs = require('fs'); var Download = require('download'); var CSV = require('comma-separated-values'); var arrayUniq = require('array-uniq'); new Download({extract: true}) .get('http://www.mapcode.com/kader/isotables.zip') .run(function (err, files) { var data = files[0].contents.toString(); var items = new CSV(data, {header: true}).parse(); var ret = []; items.forEach(function (el) { if (el.Territory !== '') { ret.push(el.Territory); } if (el['Local code'] !== '') { ret.push(el['Local code']); } if (el['Full code'] !== '') { ret.push(el['Full code']); } }); var out = '\'use strict\';\nmodule.exports = function () {\n\treturn /(?:(' + arrayUniq(ret).sort().join('|') + ') )?[A-Z0-9]{2,5}\.[A-Z0-9]{2,4}/g;\n};'; fs.writeFileSync('index.js', out); });
Set max length on mapcode pieces
Set max length on mapcode pieces Fixes #1.
JavaScript
mit
sindresorhus/mapcode-regex
--- +++ @@ -25,7 +25,7 @@ } }); - var out = '\'use strict\';\nmodule.exports = function () {\n\treturn /(?:(' + arrayUniq(ret).sort().join('|') + ') )?[A-Z0-9]{2,}\.[A-Z0-9]{2,}/g;\n};'; + var out = '\'use strict\';\nmodule.exports = function () {\n\treturn /(?:(' + arrayUniq(ret).sort().join('|') + ') )?[A-Z0-9]{2,5}\.[A-Z0-9]{2,4}/g;\n};'; fs.writeFileSync('index.js', out); });
21696a17dc4596908764c291b251916f2735177b
src/Crayon.js
src/Crayon.js
define([ 'jquery', // src/jquery.js, 'defaults' ], function ($, defaults) { function Crayon(element, options) { console.error('construct'); this.element = element; this.options = $.extend({}, defaults, options); this.init(); } // Define plugin Crayon.prototype = { elems: null, init: function () { console.error('init'); this.elems = this.query(); this.load(this.elems); }, query: function () { return $(this.options.selector, this.element); }, load: function (elems) { var me = this; elems.each(function (i, pre) { var atts = $(pre).attr(me.options.attrSelector); var parsedAtts = me.options.attrParser(atts); pre.crayon = { atts: parsedAtts }; console.log('atts', parsedAtts); var output = me.parse(me.options.getValue(pre), parsedAtts); if (output && output.length) { me.options.setValue(pre, output); } console.log('output', output); }); }, parse: function (value, atts) { // TODO Load language, cache // TODO Apply regex to code // TODO Return output console.log('value', value); return value; } }; return Crayon; });
define([ 'jquery', // src/jquery.js, 'defaults' ], function ($, defaults) { function Crayon(element, options) { console.error('construct'); this.element = element; this.options = $.extend({}, defaults, options); this.init(); } // Define plugin Crayon.prototype = { nodes: null, init: function () { console.error('init'); this.nodes = this.query(); this.load(this.nodes); }, query: function () { return $(this.options.selector, this.element); }, load: function (nodes) { var me = this; nodes.each(function (i, node) { var atts = $(node).attr(me.options.attrSelector); var parsedAtts = me.options.attrParser(atts); node.crayon = { atts: parsedAtts }; console.log('atts', parsedAtts); var output = me.parse(me.options.getValue(node), parsedAtts); if (output && output.length) { me.options.setValue(node, output); } console.log('output', output); }); }, parse: function (value, atts) { // TODO Load language, cache // TODO Apply regex to code // TODO Return output console.log('value', value); return value; } }; return Crayon; });
Rename of pre and elems to generic nodes
Rename of pre and elems to generic nodes
JavaScript
mit
aramk/crayon.js,aramk/crayon.js
--- +++ @@ -13,30 +13,30 @@ // Define plugin Crayon.prototype = { - elems: null, + nodes: null, init: function () { console.error('init'); - this.elems = this.query(); - this.load(this.elems); + this.nodes = this.query(); + this.load(this.nodes); }, query: function () { return $(this.options.selector, this.element); }, - load: function (elems) { + load: function (nodes) { var me = this; - elems.each(function (i, pre) { - var atts = $(pre).attr(me.options.attrSelector); + nodes.each(function (i, node) { + var atts = $(node).attr(me.options.attrSelector); var parsedAtts = me.options.attrParser(atts); - pre.crayon = { + node.crayon = { atts: parsedAtts }; console.log('atts', parsedAtts); - var output = me.parse(me.options.getValue(pre), parsedAtts); + var output = me.parse(me.options.getValue(node), parsedAtts); if (output && output.length) { - me.options.setValue(pre, output); + me.options.setValue(node, output); } console.log('output', output); });
21659890301ececebda2ed6b70c782a2eb8cff11
test/integration/server/test_crash_worker.js
test/integration/server/test_crash_worker.js
'use strict'; var path = require('path'); var expect = require('thehelp-test').expect; var supertest = require('supertest'); var util = require('./util'); describe('top-level crash in worker', function() { var agent, child; before(function(done) { agent = supertest.agent('http://localhost:3000'); child = util.startProcess(path.join(__dirname, '../../scenarios/crash_worker.js')); setTimeout(done, 1000); }); it('logs out top-level exception, calls last-ditch, graceful shutdown', function(done) { this.timeout(10000); child.on('close', function() { expect(child).to.have.property('result'); expect(child.result).to.match(/LastDitch: crash/); expect(child.result).to.match(/Worker #1 top-level domain error/); expect(child.result).to.match(/Worker #2 top-level domain error/); expect(child.result).to.match(/died after less than spin timeout/); expect(child.result).to.match(/No workers currently running!/); expect(child.result).to.match(/All workers gone./); done(); }); setTimeout(function() { child.kill(); }, 2000); }); });
'use strict'; var path = require('path'); var expect = require('thehelp-test').expect; var supertest = require('supertest'); var util = require('./util'); describe('top-level crash in worker', function() { var agent, child; before(function(done) { agent = supertest.agent('http://localhost:3000'); child = util.startProcess(path.join(__dirname, '../../scenarios/crash_worker.js')); setTimeout(done, 1000); }); it('logs out top-level exception, calls last-ditch, graceful shutdown', function(done) { this.timeout(10000); child.on('close', function() { expect(child).to.have.property('result'); expect(child.result).to.match(/LastDitch: crash/); expect(child.result).to.match(/Worker #1 top-level domain error/); expect(child.result).to.match(/Worker #2 top-level domain error/); expect(child.result).to.match(/died after less than spin timeout/); expect(child.result).to.match(/No workers currently running!/); expect(child.result).to.match(/All workers gone./); done(); }); setTimeout(function() { child.kill(); }, 4000); }); });
Increase timeout in crash/worker test for travis
Increase timeout in crash/worker test for travis
JavaScript
mit
thehelp/cluster
--- +++ @@ -37,7 +37,7 @@ setTimeout(function() { child.kill(); - }, 2000); + }, 4000); }); });