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
49078f5d1c8bfd2510ba39414279dd1756dff22e
js/templates.js
js/templates.js
var Templates = {}; Templates.ItemListingTemplate = _.template('\ <div class="item media">\ <img class="pull-left" src="<%= imageUrl %>" />\ <div class="media-body">\ <h3 class="media-heading"><%= name %></h3>\ <div class="item-location"><strong>Location:</strong> <%= location %></div>\ <div class="item-price"><%= price %></div>\ <div class="item-buyers"><%= buyers.length %></div>\ </div>\ </div>');
var Templates = {}; Templates.ItemListingTemplate = _.template('\ <div class="item media">\ <img class="pull-left" src="<%= imageUrl %>" />\ <div class="media-body">\ <h3 class="media-heading"><%= name %></h3>\ <div class="item-location"><span class="glyphicon glyphicon-globe"></span> <%= location %></div>\ <div class="item-price"><span class="glyphicon glyphicon-usd"></span><%= price %></div>\ <div class="item-buyers"><%= buyers.length %></div>\ </div>\ </div>');
Add icons to item template.
Add icons to item template.
JavaScript
mit
burnflare/CrowdBuy,burnflare/CrowdBuy
--- +++ @@ -5,8 +5,8 @@ <img class="pull-left" src="<%= imageUrl %>" />\ <div class="media-body">\ <h3 class="media-heading"><%= name %></h3>\ - <div class="item-location"><strong>Location:</strong> <%= location %></div>\ - <div class="item-price"><%= price %></div>\ + <div class="item-location"><span class="glyphicon glyphicon-globe"></span> <%= location %></div>\ + <div class="item-price"><span class="glyphicon glyphicon-usd"></span><%= price %></div>\ <div class="item-buyers"><%= buyers.length %></div>\ </div>\ </div>');
9d9d48d9df942fe3697726351791e3ccd02cce40
lib/dependency-theme-import.js
lib/dependency-theme-import.js
var ThemingContext = require('./ThemingContext'); var lessParser = require('./less-parser'); var logger = require('raptor-logging').logger(module); module.exports = function create(config) { return { properties: { path: 'string' }, // we don't actually produce JavaScript or CSS contentType: 'none', init: function(optimizerContext, callback) { if (!lessParser.exists()) { return callback(new Error('Unable to handle themed Less dependency for path "' + this.path + '". The "less" module was not found. This module should be installed as a top-level application module.')); } this.resolvedPath = this.requireResolvePath(this.path); callback(); }, onAddToPageBundle: function(bundle, optimizerContext) { var themingContext = ThemingContext.getThemingContext(optimizerContext); themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { logger.debug('Added theme import: ' + this.resolvedPath); } }, onAddToAsyncPageBundle: function(bundle, optimizerContext) { var themingContext = ThemingContext.getThemingContext(optimizerContext); themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { logger.debug('Added theme import: ' + this.resolvedPath); } }, read: function(optimizerContext, callback) { return null; }, calculateKey: function() { // use the absolute path to the imported resource as the key return this.resolvedPath; } }; };
var ThemingContext = require('./ThemingContext'); var lessParser = require('./less-parser'); var logger = require('raptor-logging').logger(module); module.exports = function create(config) { return { properties: { path: 'string' }, // we don't actually produce JavaScript or CSS contentType: 'none', init: function(optimizerContext, callback) { if (!lessParser.exists()) { return callback(new Error('Unable to handle themed Less dependency for path "' + this.path + '". The "less" module was not found. This module should be installed as a top-level application module.')); } this.path = this.requireResolvePath(this.path); callback(); }, onAddToPageBundle: function(bundle, optimizerContext) { var themingContext = ThemingContext.getThemingContext(optimizerContext); themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { logger.debug('Added theme import: ' + this.path); } }, onAddToAsyncPageBundle: function(bundle, optimizerContext) { var themingContext = ThemingContext.getThemingContext(optimizerContext); themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { logger.debug('Added theme import: ' + this.path); } }, read: function(optimizerContext, callback) { return null; }, calculateKey: function() { // use the absolute path to the imported resource as the key return this.path; } }; };
Store resolved path in path property (don't use separate resolvedPath property)
Store resolved path in path property (don't use separate resolvedPath property)
JavaScript
apache-2.0
lasso-js/lasso-theming
--- +++ @@ -17,7 +17,7 @@ return callback(new Error('Unable to handle themed Less dependency for path "' + this.path + '". The "less" module was not found. This module should be installed as a top-level application module.')); } - this.resolvedPath = this.requireResolvePath(this.path); + this.path = this.requireResolvePath(this.path); callback(); }, @@ -26,7 +26,7 @@ themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { - logger.debug('Added theme import: ' + this.resolvedPath); + logger.debug('Added theme import: ' + this.path); } }, @@ -35,7 +35,7 @@ themingContext.addThemeImport(this); if (logger.isDebugEnabled()) { - logger.debug('Added theme import: ' + this.resolvedPath); + logger.debug('Added theme import: ' + this.path); } }, @@ -45,7 +45,7 @@ calculateKey: function() { // use the absolute path to the imported resource as the key - return this.resolvedPath; + return this.path; } }; };
9b123e9cca657c4167d91526a768e90654b514bd
src/main.js
src/main.js
/* @flow */ import React from 'react'; import ReactDOM from 'react-dom'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import { useRouterHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import makeRoutes from './routes'; import Root from './containers/Root'; import configureStore from './redux/configureStore'; // Configure history for react-router const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }); // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the key "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState, browserHistory); const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }); // Now that we have the Redux store, we can create our routes. We provide // the store to the route definitions so that routes have access to it for // hooks such as `onEnter`. const routes = makeRoutes(store); // Now that redux and react-router have been configured, we can render the // React application to the DOM! ReactDOM.render( <Root history={history} routes={routes} store={store} />, document.getElementById('root') );
/* @flow */ import React from 'react'; import ReactDOM from 'react-dom'; import makeRoutes from './routes'; import Root from './containers/Root'; import configureStore from './redux/configureStore'; // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the key "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState, null); // Now that we have the Redux store, we can create our routes. We provide // the store to the route definitions so that routes have access to it for // hooks such as `onEnter`. const routes = makeRoutes(store); // Now that redux and react-router have been configured, we can render the // React application to the DOM! ReactDOM.render( <Root history={null} routes={routes} store={store} />, document.getElementById('root') );
Remove browser history for now
Remove browser history for now ...since it was playing up on github pages
JavaScript
mit
felixSchl/try-neodoc,felixSchl/try-neodoc
--- +++ @@ -1,27 +1,16 @@ /* @flow */ import React from 'react'; import ReactDOM from 'react-dom'; -import createBrowserHistory from 'history/lib/createBrowserHistory'; -import { useRouterHistory } from 'react-router'; -import { syncHistoryWithStore } from 'react-router-redux'; import makeRoutes from './routes'; import Root from './containers/Root'; import configureStore from './redux/configureStore'; - -// Configure history for react-router -const browserHistory = useRouterHistory(createBrowserHistory)({ - basename: __BASENAME__ -}); // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the key "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.__INITIAL_STATE__; -const store = configureStore(initialState, browserHistory); -const history = syncHistoryWithStore(browserHistory, store, { - selectLocationState: (state) => state.router -}); +const store = configureStore(initialState, null); // Now that we have the Redux store, we can create our routes. We provide // the store to the route definitions so that routes have access to it for @@ -31,6 +20,6 @@ // Now that redux and react-router have been configured, we can render the // React application to the DOM! ReactDOM.render( - <Root history={history} routes={routes} store={store} />, + <Root history={null} routes={routes} store={store} />, document.getElementById('root') );
d1e99478d6fc5b296b511e389da0352372262fa4
lib/configuration.js
lib/configuration.js
'use babel'; export default { "prerelease": { "title": "Level of prerelease", "description": "Set the level maximum to check for the libraries versions", "type": "string", "default": "stable", "enum": ["stable", "rc", "beta", "alpha", "dev"] }, "info": { "title": "Display information", "description": "Display information of the package that have a not enough restrictive version", "type": "boolean", "default": true }, "checkInstalled": { "title": "Check installed package version", "description": "The installed package will be inspected to verify that the version satisfy the package.json dependency", "type": "boolean", "default": true }, "npmrc": { "title": "Path to NPM config file", "type": "string", "default": ".npmrc" }, "npmUrl": { "title": "NPM Package information base url", "type": "string", "default": "https://www.npmjs.com/package" } };
'use babel'; export default { "prerelease": { "title": "Level of prerelease", "description": "Set the level maximum to check for the libraries versions", "type": "string", "default": "stable", "enum": ["stable", "rc", "beta", "alpha", "dev"] }, "info": { "title": "Display information", "description": "Display information of the package that have a not enough restrictive version", "type": "boolean", "default": true }, "checkInstalled": { "title": "Check installed package version", "description": "The installed package will be inspected to verify that the version satisfy the package.json dependency", "type": "boolean", "default": false }, "npmrc": { "title": "Path to NPM config file", "type": "string", "default": ".npmrc" }, "npmUrl": { "title": "NPM Package information base url", "type": "string", "default": "https://www.npmjs.com/package" } };
Set the default value of the checkInstalled option to false
Set the default value of the checkInstalled option to false
JavaScript
mit
kilian-ito/atom-npm-outdated
--- +++ @@ -18,7 +18,7 @@ "title": "Check installed package version", "description": "The installed package will be inspected to verify that the version satisfy the package.json dependency", "type": "boolean", - "default": true + "default": false }, "npmrc": { "title": "Path to NPM config file",
4b87a36448f78a70138dcd8110074ac518fb9dbe
lib/policies/jwt/extractors.js
lib/policies/jwt/extractors.js
const passportJWT = require('passport-jwt'); module.exports = { 'header': passportJWT.ExtractJwt.fromHeader, 'body': passportJWT.ExtractJwt.fromBodyField, 'query': passportJWT.ExtractJwt.fromUrlQueryParameter, 'authScheme': passportJWT.ExtractJwt.fromAuthHeaderWithScheme, 'authBearer': passportJWT.ExtractJwt.fromAuthHeaderAsBearerToken };
const passportJWT = require('passport-jwt'); module.exports = { 'header': passportJWT.ExtractJwt.fromHeader, 'query': passportJWT.ExtractJwt.fromUrlQueryParameter, 'authScheme': passportJWT.ExtractJwt.fromAuthHeaderWithScheme, 'authBearer': passportJWT.ExtractJwt.fromAuthHeaderAsBearerToken };
Remove body as an extractor
Remove body as an extractor
JavaScript
apache-2.0
ExpressGateway/express-gateway
--- +++ @@ -2,7 +2,6 @@ module.exports = { 'header': passportJWT.ExtractJwt.fromHeader, - 'body': passportJWT.ExtractJwt.fromBodyField, 'query': passportJWT.ExtractJwt.fromUrlQueryParameter, 'authScheme': passportJWT.ExtractJwt.fromAuthHeaderWithScheme, 'authBearer': passportJWT.ExtractJwt.fromAuthHeaderAsBearerToken
317c217910049983a56ea8c03c216356fb747040
lib/loggly/config.js
lib/loggly/config.js
/* * config.js: Configuration information for your Loggly account. * This information is only used for require('loggly')./\.+/ methods * * (C) 2010 Nodejitsu Inc. * MIT LICENSE * */ // // function createConfig (defaults) // Creates a new instance of the configuration // object based on default values // exports.createConfig = function (defaults) { return new Config(defaults); }; // // Config (defaults) // Constructor for the Config object // var Config = exports.Config = function (defaults) { if (!defaults.subdomain) { throw new Error('Subdomain is required to create an instance of Config'); } this.subdomain = defaults.subdomain; this.json = defaults.json || null; this.auth = defaults.auth || null; }; Config.prototype = { get subdomain () { return this._subdomain; }, set subdomain (value) { this._subdomain = value; }, get logglyUrl () { return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api'; }, get inputUrl () { return 'https://logs.loggly.com/inputs/'; } };
/* * config.js: Configuration information for your Loggly account. * This information is only used for require('loggly')./\.+/ methods * * (C) 2010 Nodejitsu Inc. * MIT LICENSE * */ // // function createConfig (defaults) // Creates a new instance of the configuration // object based on default values // exports.createConfig = function (defaults) { return new Config(defaults); }; // // Config (defaults) // Constructor for the Config object // var Config = exports.Config = function (defaults) { if (!defaults.subdomain) { throw new Error('Subdomain is required to create an instance of Config'); } this.subdomain = defaults.subdomain; this.json = defaults.json || null; this.auth = defaults.auth || null; this.inputUrl = defaults.inputUrl || 'https://logs.loggly.com/inputs/'; }; Config.prototype = { get subdomain () { return this._subdomain; }, set subdomain (value) { this._subdomain = value; }, get logglyUrl () { return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api'; }, get inputUrl () { return this._inputUrl; }, set inputUrl (value) { this._inputUrl = value; } };
Add support for alternate URLs for input logging (aka ec2)
Add support for alternate URLs for input logging (aka ec2)
JavaScript
mit
mavrick/node-loggly,nodejitsu/node-loggly,dtudury/node-loggly,mafintosh/node-loggly,rosskukulinski/node-loggly,freeall/node-loggly
--- +++ @@ -28,6 +28,7 @@ this.subdomain = defaults.subdomain; this.json = defaults.json || null; this.auth = defaults.auth || null; + this.inputUrl = defaults.inputUrl || 'https://logs.loggly.com/inputs/'; }; Config.prototype = { @@ -44,6 +45,10 @@ }, get inputUrl () { - return 'https://logs.loggly.com/inputs/'; + return this._inputUrl; + }, + + set inputUrl (value) { + this._inputUrl = value; } };
68e60dc5b22ab3aa668ea1a841037eac10ea5987
lib/models/errors.js
lib/models/errors.js
ErrorModel = function (appId) { var self = this; this.appId = appId; this.errors = {}; this.startTime = Date.now(); } _.extend(ErrorModel.prototype, KadiraModel.prototype); ErrorModel.prototype.buildPayload = function() { var metrics = _.values(this.errors); this.startTime = Date.now(); this.errors = {}; return {errors: metrics}; }; ErrorModel.prototype.trackError = function(ex, source) { var name = ex.name + ': ' + ex.message; if(this.errors[name]) { this.errors[name].count++; } else { this.errors[name] = this._formatError(ex, source); } }; ErrorModel.prototype._formatError = function(ex, source) { var name = ex.name + ': ' + ex.message; var now = Date.now(); return { appId : this.appId, name : name, source : source, startTime : now, type : 'server', stack : [{at: now, events: [], stack: ex.stack}], count: 1, } };
ErrorModel = function (appId) { var self = this; this.appId = appId; this.errors = {}; this.startTime = Date.now(); } _.extend(ErrorModel.prototype, KadiraModel.prototype); ErrorModel.prototype.buildPayload = function() { var metrics = _.values(this.errors); this.startTime = Date.now(); this.errors = {}; return {errors: metrics}; }; ErrorModel.prototype.trackError = function(ex, source) { if(this.errors[ex.message]) { this.errors[ex.message].count++; } else { this.errors[ex.message] = this._formatError(ex, source); } }; ErrorModel.prototype._formatError = function(ex, source) { var now = Date.now(); return { appId : this.appId, name : ex.message, source : source, startTime : now, type : 'server', stack : [{at: now, events: [], stack: ex.stack}], count: 1, } };
Use e.message as error name
Use e.message as error name
JavaScript
mit
chatr/kadira,meteorhacks/kadira
--- +++ @@ -16,20 +16,18 @@ }; ErrorModel.prototype.trackError = function(ex, source) { - var name = ex.name + ': ' + ex.message; - if(this.errors[name]) { - this.errors[name].count++; + if(this.errors[ex.message]) { + this.errors[ex.message].count++; } else { - this.errors[name] = this._formatError(ex, source); + this.errors[ex.message] = this._formatError(ex, source); } }; ErrorModel.prototype._formatError = function(ex, source) { - var name = ex.name + ': ' + ex.message; var now = Date.now(); return { appId : this.appId, - name : name, + name : ex.message, source : source, startTime : now, type : 'server',
906cd1da17461c8a71ecefb68462db7628224fd2
lib/ping-sys.js
lib/ping-sys.js
/** * LICENSE MIT * (C) Daniel Zelisko * http://github.com/danielzzz/node-ping * * a simple wrapper for ping * Now with support of not only english Windows. * */ //system library var sys = require('util'), cp = require('child_process'), os = require('os'); // Promise implementation var ping = require('./ping-promise'); /** * Callback after probing given host * @callback probeCallback * @param {boolean} isAlive - Whether target is alive or not * @param {Object} error - Null if no error occurs */ /** * Class::Ping construtor * * @param {string} addr - Hostname or ip addres * @param {probeCallback} cb - Callback * @param {PingConfig} config - Configuration for command ping */ function probe(addr, cb, config) { // Do not reassign function parameter var _config = config || {}; return ping.probe(addr, _config).then(function (res) { cb(res.alive, null); }).catch(function (err) { cb(null, err); }).done(); } exports.probe = probe;
'use strict'; /** * LICENSE MIT * (C) Daniel Zelisko * http://github.com/danielzzz/node-ping * * a simple wrapper for ping * Now with support of not only english Windows. * */ // Promise implementation var ping = require('./ping-promise'); // TODO: // 1. Port round trip time to this callback // 2. However, it may breaks backward compatability // 3. Need discussion /** * Callback after probing given host * @callback probeCallback * @param {boolean} isAlive - Whether target is alive or not * @param {Object} error - Null if no error occurs */ /** * Class::Ping construtor * * @param {string} addr - Hostname or ip addres * @param {probeCallback} cb - Callback * @param {PingConfig} config - Configuration for command ping */ function probe(addr, cb, config) { // Do not reassign function parameter var _config = config || {}; return ping.probe(addr, _config).then(function (res) { cb(res.alive, null); }).catch(function (err) { cb(null, err); }).done(); } exports.probe = probe;
Add TODO comment and fix warning from eslint
Add TODO comment and fix warning from eslint
JavaScript
mit
danielzzz/node-ping
--- +++ @@ -1,3 +1,5 @@ +'use strict'; + /** * LICENSE MIT * (C) Daniel Zelisko @@ -8,14 +10,13 @@ * */ -//system library -var sys = require('util'), - cp = require('child_process'), - os = require('os'); - // Promise implementation var ping = require('./ping-promise'); +// TODO: +// 1. Port round trip time to this callback +// 2. However, it may breaks backward compatability +// 3. Need discussion /** * Callback after probing given host * @callback probeCallback
902e3846be5c6c87cfec171a9ae513b7a72d72a0
list-and-run.js
list-and-run.js
'use strict'; const addLineNumbers = require('add-line-numbers'); const spawnSync = require('child_process').spawnSync; const fs = require('fs'); const path = '/tmp/te'; module.exports = function listAndRun() { var text = []; const listing = fs.readFileSync(path, 'utf8'); if (listing.length > 0) { text.push(addLineNumbers(listing) + '\n'); const child = spawnSync('node', [path], {timeout: 100, maxBuffer: 100}); text.push(`stdout: ${child.output[1]}`); text.push(`stderr: ${child.output[2]}`); } else { text.push("Code listing is empty\n"); } console.log(text.join('')); };
'use strict'; const addLineNumbers = require('add-line-numbers'); const spawnSync = require('child_process').spawnSync; const fs = require('fs'); const path = '/tmp/te'; module.exports = function listAndRun() { let readFileAsync = function(filename, encoding) { return new Promise(function(resolve, reject) { fs.readFile(filename, encoding, (data, err) => { if (err) { reject(err); } resolve(data); }); }); }; readFileAsync(path, 'utf8') .then(listing => { var text = []; if (listing.length > 0) { text.push(addLineNumbers(listing) + '\n'); const child = spawnSync('node', [path], {timeout: 100, maxBuffer: 100}); text.push(`stdout: ${child.output[1]}`); text.push(`stderr: ${child.output[2]}`); } else { text.push("Code listing is empty\n"); } console.log(text.join('')); }) .catch(err => { throw err; }) };
Change file IO in listAndRun to be asynchronous
Change file IO in listAndRun to be asynchronous
JavaScript
mit
gudnm/te
--- +++ @@ -5,20 +5,34 @@ const path = '/tmp/te'; module.exports = function listAndRun() { - var text = []; - const listing = fs.readFileSync(path, 'utf8'); + let readFileAsync = function(filename, encoding) { + return new Promise(function(resolve, reject) { + fs.readFile(filename, encoding, (data, err) => { + if (err) { + reject(err); + } + resolve(data); + }); + }); + }; + + readFileAsync(path, 'utf8') + .then(listing => { + var text = []; - if (listing.length > 0) { - text.push(addLineNumbers(listing) + '\n'); + if (listing.length > 0) { + text.push(addLineNumbers(listing) + '\n'); + const child = spawnSync('node', [path], {timeout: 100, maxBuffer: 100}); + text.push(`stdout: ${child.output[1]}`); + text.push(`stderr: ${child.output[2]}`); + } else { + text.push("Code listing is empty\n"); + } - const child = spawnSync('node', [path], {timeout: 100, maxBuffer: 100}); - text.push(`stdout: ${child.output[1]}`); - text.push(`stderr: ${child.output[2]}`); - - } else { - text.push("Code listing is empty\n"); - } - - console.log(text.join('')); + console.log(text.join('')); + }) + .catch(err => { + throw err; + }) };
6e2386f38b8296f00a36de7f2041a6c3c43abe9f
app/main.js
app/main.js
var counter; function setup() { var canvas = createCanvas(400, 400); canvas.parent('play'); counter = new Counter(); counter.new(); } function draw() { background(233, 0, 0); counter.draw(); } function keyTyped() { if (key === ' ') { counter.new(); } } function Counter () { this.objects = []; this.number = 0; this.new = function () { this.objects = []; this.number = random(1, 10); while(this.objects.length < this.number - 1) { var newObject = createVector(random(45,355), random(45,355)); if (this.objects.every(function(item){ return p5.Vector.sub(item, newObject).mag() > 85; })) { this.objects.push(newObject); } } } this.draw = function() { for(var i = 0; i < this.objects.length; i++) { var object = this.objects[i]; ellipse(object.x, object.y, 80); } } }
var counter; function setup() { var canvas = createCanvas(400, 400); canvas.parent('play'); counter = new Counter(); counter.new(); } function draw() { background(233, 0, 0); counter.draw(); } function keyTyped() { if (key === ' ') { counter.new(); } } function touchStarted() { if (touches.length > 0) { var touch = touches[0]; if ( touch.x >= 0 && touch.x < 400 && touch.y >= 0 && touch.y < 400 ) { counter.new(); } } } function Counter () { this.objects = []; this.number = 0; this.new = function () { this.objects = []; this.number = random(1, 10); while(this.objects.length < this.number - 1) { var newObject = createVector(random(45,355), random(45,355)); if (this.objects.every(function(item){ return p5.Vector.sub(item, newObject).mag() > 85; })) { this.objects.push(newObject); } } } this.draw = function() { for(var i = 0; i < this.objects.length; i++) { var object = this.objects[i]; ellipse(object.x, object.y, 80); } } }
Add touch support for the redraw of the circles
Add touch support for the redraw of the circles
JavaScript
mit
nemesv/playfive,nemesv/playfive
--- +++ @@ -15,6 +15,19 @@ function keyTyped() { if (key === ' ') { counter.new(); + } +} + +function touchStarted() { + if (touches.length > 0) { + var touch = touches[0]; + if ( + touch.x >= 0 && touch.x < 400 && + touch.y >= 0 && touch.y < 400 + ) + { + counter.new(); + } } }
bcd5517032a7e46a98f90f496967a2ce22bd3b89
webpack/modules/babelPreset.js
webpack/modules/babelPreset.js
const { isProd, isDev } = require('../env'); module.exports = (config) => { const options = { babelrc: false, compact: true, cacheDirectory: `${__dirname}/.babelCache`, presets: [ ['env', { loose: true, modules: false, exclude: ['transform-regenerator'], }], require.resolve('babel-preset-react'), ], plugins: [ // class { handleClick = () => { } } 'transform-class-properties', // { ...todo, completed: true } ['transform-object-rest-spread', { useBuiltIns: true, }], ], }; if (isProd) { options.plugins = [ 'transform-imports', 'transform-react-constant-elements', ['transform-react-remove-prop-types', { mode: 'wrap', }], ...options.plugins, ]; } if (isDev) { options.plugins = [ ...options.plugins, 'react-hot-loader/babel', ]; } return options; };
const { isProd, isDev } = require('../env'); module.exports = (config) => { const options = { babelrc: false, compact: true, cacheDirectory: `${__dirname}/.babelCache`, presets: [ ['env', { loose: true, modules: false, useBuiltIns: false, exclude: ['transform-regenerator'], targets: { browsers: [ 'last 4 versions', '> 1%', 'Firefox ESR', 'safari >= 7', 'ie >= 10', ], }, }], require.resolve('babel-preset-react'), ], plugins: [ // class { handleClick = () => { } } 'transform-class-properties', // { ...todo, completed: true } ['transform-object-rest-spread', { useBuiltIns: true, }], ], }; if (isProd) { options.plugins = [ 'transform-imports', 'transform-react-constant-elements', ['transform-react-remove-prop-types', { mode: 'wrap', }], ...options.plugins, ]; } if (isDev) { options.plugins = [ ...options.plugins, 'react-hot-loader/babel', ]; } return options; };
Add targets option to babel configuration
Add targets option to babel configuration
JavaScript
mit
AlexMasterov/webpack-kit,AlexMasterov/webpack-kit
--- +++ @@ -10,7 +10,17 @@ ['env', { loose: true, modules: false, + useBuiltIns: false, exclude: ['transform-regenerator'], + targets: { + browsers: [ + 'last 4 versions', + '> 1%', + 'Firefox ESR', + 'safari >= 7', + 'ie >= 10', + ], + }, }], require.resolve('babel-preset-react'), ],
aa4808300be58b9508178b2b7ede4212eb86ac13
lib/store-init.js
lib/store-init.js
var SimpleStore = require('fh-wfm-simple-store'), config = require('./config.js'); /** * Creates and initializes a store to be used by the app modules. * @param {String} dataSetId String used as an identifier for the store * @param {Object|null} seedData Object to be saved in the store initially * @param {Object} mediator Object used for listening to a topic. */ function initStore(dataSetId, seedData, mediator) { var dataStore = new SimpleStore(dataSetId); /** * Check if existing data exists. If no existing data is found, initialize with the given seed data. Otherwise, * continue to listen to topic. * * TODO: Check for existing data may be removed in production as applications are likely to start with no * initial data. Instead, initialize store with: dataStore.init(); */ dataStore.list().then(function(storeData) { if (!storeData || storeData.length === 0) { //Check if seed data is given, otherwise initialize store with no initial data. if (seedData) { dataStore.init(seedData).then(function() { dataStore.listen(config.get('dataTopicPrefix'), mediator); }); } else { dataStore.init().then(function() { dataStore.listen(config.get('dataTopicPrefix'), mediator); }); } } else { dataStore.listen(config.get('dataTopicPrefix'), mediator); } }); } module.exports = { init: initStore };
var SimpleStore = require('fh-wfm-simple-store'), config = require('./config.js'); /** * Creates and initializes a store to be used by the app modules. * @param {String} dataSetId String used as an identifier for the store * @param {Object|null} seedData Object to be saved in the store initially * @param {Object} mediator Object used for listening to a topic. */ function initStore(dataSetId, seedData, mediator) { var dataStore = new SimpleStore(dataSetId); /** * Check if existing data exists. If no existing data is found, initialize with the given seed data. Otherwise, * continue to listen to topic. * * TODO: Check for existing data may be removed in production as applications are likely to start with no * initial data. Instead, initialize store with: dataStore.init(); */ dataStore.list().then(function(storeData) { if (!storeData || storeData.length === 0) { //Check if seed data is given, otherwise initialize store with no initial data. //array store needs to be initialized with an empty array if there is no seed data given. if (!seedData && process.env.WFM_USE_MEMORY_STORE === "true") { seedData = []; } dataStore.init(seedData).then(function() { dataStore.listen(config.get('dataTopicPrefix'), mediator); }); } else { dataStore.listen(config.get('dataTopicPrefix'), mediator); } }); } module.exports = { init: initStore };
Initialize array store with an empty array
Initialize array store with an empty array
JavaScript
mit
feedhenry-raincatcher/raincatcher-demo-cloud
--- +++ @@ -21,15 +21,14 @@ dataStore.list().then(function(storeData) { if (!storeData || storeData.length === 0) { //Check if seed data is given, otherwise initialize store with no initial data. - if (seedData) { - dataStore.init(seedData).then(function() { - dataStore.listen(config.get('dataTopicPrefix'), mediator); - }); - } else { - dataStore.init().then(function() { - dataStore.listen(config.get('dataTopicPrefix'), mediator); - }); + //array store needs to be initialized with an empty array if there is no seed data given. + if (!seedData && process.env.WFM_USE_MEMORY_STORE === "true") { + seedData = []; } + + dataStore.init(seedData).then(function() { + dataStore.listen(config.get('dataTopicPrefix'), mediator); + }); } else { dataStore.listen(config.get('dataTopicPrefix'), mediator); }
3ccbabddc220088addfe6b059a4468ba96c2a09c
www/js/fonts.js
www/js/fonts.js
var urls = [ 'http://s.npr.org/templates/css/fonts/GothamSSm.css', 'http://s.npr.org/templates/css/fonts/Gotham.css' ]; if (window.location.protocol == "https:") { urls = [ 'https://secure.npr.org/templates/css/fonts/GothamSSm.css', 'https://secure.npr.org/templates/css/fonts/Gotham.css' ]; } WebFont.load({ custom: { families: [ 'Gotham SSm:n4,n7', 'Gotham:n4,n7' ], urls: urls }, timeout: 10000 });
var urls = [ 'http://s.npr.org/templates/css/fonts/GothamSSm.css', 'http://s.npr.org/templates/css/fonts/Gotham.css', 'http://s.npr.org/templates/css/fonts/Knockout.css' ]; if (window.location.protocol == "https:") { urls = [ 'https://secure.npr.org/templates/css/fonts/GothamSSm.css', 'https://secure.npr.org/templates/css/fonts/Gotham.css', 'https://secure.npr.org/templates/css/fonts/Knockout.css' ]; } WebFont.load({ custom: { families: [ 'Gotham SSm:n4,n7', 'Gotham:n4,n7', 'Knockout 31 4r:n4' ], urls: urls }, timeout: 10000 });
Add Knockout to font loader
Add Knockout to font loader
JavaScript
mit
nprapps/austin,nprapps/austin,nprapps/austin,nprapps/austin
--- +++ @@ -1,12 +1,14 @@ var urls = [ 'http://s.npr.org/templates/css/fonts/GothamSSm.css', - 'http://s.npr.org/templates/css/fonts/Gotham.css' + 'http://s.npr.org/templates/css/fonts/Gotham.css', + 'http://s.npr.org/templates/css/fonts/Knockout.css' ]; if (window.location.protocol == "https:") { urls = [ 'https://secure.npr.org/templates/css/fonts/GothamSSm.css', - 'https://secure.npr.org/templates/css/fonts/Gotham.css' + 'https://secure.npr.org/templates/css/fonts/Gotham.css', + 'https://secure.npr.org/templates/css/fonts/Knockout.css' ]; } @@ -14,7 +16,8 @@ custom: { families: [ 'Gotham SSm:n4,n7', - 'Gotham:n4,n7' + 'Gotham:n4,n7', + 'Knockout 31 4r:n4' ], urls: urls },
5a2a56e4b6a678ae96fe4b377c0d7922e0963118
test/libs/utils/metadata.spec.js
test/libs/utils/metadata.spec.js
'use strict'; // Load chai const chai = require('chai'); const expect = chai.expect; // Load our module const utils = require('../../../app/libs/utils'); describe('Function "metadata"', () => { it('should export a function', () => { expect(utils.metadata).to.be.a('function'); }); });
'use strict'; // Load requirements const path = require('path'); // Load chai const chai = require('chai'); const expect = chai.expect; chai.use(require('chai-as-promised')); // Load our module const utils = require('../../../app/libs/utils'); describe('Function "metadata"', () => { it('should export a function', () => { expect(utils.metadata).to.be.a('function'); }); it('should return a promise', () => { let metadataResult = utils.metadata(); return expect(metadataResult).to.be.a('promise') .and.to.eventually.be.rejected; }); it('should resolve with an object', (done) => { let file = path.resolve('./test/data/task/metadata/Castle.S01E01.mp4'); utils.metadata(file).then((result) => { expect(result).to.be.an('object'); return done(); }).catch((err) => { return done(err); }); }); it('should reject without a valid file argument', (done) => { utils.metadata().then((result) => { return done(false); }).catch((err) => { expect(err).to.match(/No file provided/ig); return done(); }); }); it('should reject when given a non-existent file path', (done) => { let file = path.resolve('./not-a-real-file.mp4'); utils.metadata(file).then((result) => { return done(false); }).catch((err) => { expect(err).to.match(/does not exist/ig); return done(); }); }); it('should reject when given an invalid input file', (done) => { let file = path.resolve('./test/data/task/listing/invalid file.ext'); utils.metadata(file).then((result) => { return done(false); }).catch((err) => { expect(err).to.match(/ffprobe exited with code 1/ig); return done(); }); }); });
Add test coverage to utils metadata
Add test coverage to utils metadata
JavaScript
apache-2.0
transmutejs/core
--- +++ @@ -1,8 +1,12 @@ 'use strict'; + +// Load requirements +const path = require('path'); // Load chai const chai = require('chai'); const expect = chai.expect; +chai.use(require('chai-as-promised')); // Load our module const utils = require('../../../app/libs/utils'); @@ -13,4 +17,58 @@ expect(utils.metadata).to.be.a('function'); }); + it('should return a promise', () => { + + let metadataResult = utils.metadata(); + + return expect(metadataResult).to.be.a('promise') + .and.to.eventually.be.rejected; + }); + + it('should resolve with an object', (done) => { + + let file = path.resolve('./test/data/task/metadata/Castle.S01E01.mp4'); + + utils.metadata(file).then((result) => { + expect(result).to.be.an('object'); + return done(); + }).catch((err) => { + return done(err); + }); + }); + + it('should reject without a valid file argument', (done) => { + + utils.metadata().then((result) => { + return done(false); + }).catch((err) => { + expect(err).to.match(/No file provided/ig); + return done(); + }); + }); + + it('should reject when given a non-existent file path', (done) => { + + let file = path.resolve('./not-a-real-file.mp4'); + + utils.metadata(file).then((result) => { + return done(false); + }).catch((err) => { + expect(err).to.match(/does not exist/ig); + return done(); + }); + }); + + it('should reject when given an invalid input file', (done) => { + + let file = path.resolve('./test/data/task/listing/invalid file.ext'); + + utils.metadata(file).then((result) => { + return done(false); + }).catch((err) => { + expect(err).to.match(/ffprobe exited with code 1/ig); + return done(); + }); + }); + });
e58037f834b0b34c01456d9e01fa493955e3665b
.template-lintrc.js
.template-lintrc.js
/* eslint-env node */ 'use strict'; module.exports = { extends: 'recommended', rules: { 'html-comments': false } };
/* eslint-env node */ 'use strict'; module.exports = { extends: 'recommended', rules: { 'no-html-comments': false } };
Fix deprecated template lint runle
Fix deprecated template lint runle
JavaScript
mit
jelhan/ember-bootstrap,kaliber5/ember-bootstrap,jelhan/ember-bootstrap,kaliber5/ember-bootstrap
--- +++ @@ -4,6 +4,6 @@ module.exports = { extends: 'recommended', rules: { - 'html-comments': false + 'no-html-comments': false } };
fb815f7573e040d032b894069e10fb4e0a61dd42
.eslintrc.js
.eslintrc.js
module.exports = { 'env': { 'browser': true, 'es6': true, 'node': true, }, 'extends': [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:import/errors', 'plugin:import/warnings', ], 'installedESLint': true, 'parserOptions': { 'ecmaVersion': 7, 'ecmaFeatures': { 'experimentalObjectRestSpread': true, 'jsx': true, }, 'sourceType': 'module', }, 'plugins': [ 'import', 'react', ], 'parser': 'babel-eslint', 'rules': { 'comma-dangle': ['error', 'always-multiline'], 'indent': ['warn', 2], 'linebreak-style': ['error', 'unix'], 'no-console': ['warn', {'allow': ['warn', 'error']}], 'no-var': 'error', 'no-unused-vars': ['warn', {'args': 'none'}], 'semi': ['error', 'never'], 'sort-vars': 'warn', 'unicode-bom': 'error', 'react/prop-types': 'off', }, }
module.exports = { 'env': { 'browser': true, 'es6': true, 'node': true, }, 'extends': [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:import/errors', 'plugin:import/warnings', ], 'installedESLint': true, 'parserOptions': { 'ecmaVersion': 7, 'ecmaFeatures': { 'experimentalObjectRestSpread': true, 'jsx': true, }, 'sourceType': 'module', }, 'plugins': [ 'import', 'react', ], 'parser': 'babel-eslint', 'rules': { 'comma-dangle': ['error', 'always-multiline'], 'indent': ['warn', 2], 'linebreak-style': ['error', 'unix'], 'no-console': ['warn', {'allow': ['warn', 'error']}], 'no-var': 'error', 'no-unused-vars': ['warn', {'args': 'none'}], 'semi': ['error', 'never'], 'sort-vars': 'warn', 'unicode-bom': 'error', 'react/prop-types': 'off', }, 'settings': { 'import/resolver': { 'node': { 'extensions': ['.js', '.jsx', '.es', '.coffee', '.cjsx'], 'paths': [__dirname], }, }, 'import/core-modules': [ 'electron', 'react', 'react-redux', 'redux-observers', 'reselect', 'react-bootstrap', 'react-fontawesome', 'path-extra', 'fs-extra', 'lodash', 'cson', ], }, }
Update eslint for es6 import
Update eslint for es6 import
JavaScript
mit
poooi/plugin-battle-detail
--- +++ @@ -37,4 +37,25 @@ 'react/prop-types': 'off', }, + 'settings': { + 'import/resolver': { + 'node': { + 'extensions': ['.js', '.jsx', '.es', '.coffee', '.cjsx'], + 'paths': [__dirname], + }, + }, + 'import/core-modules': [ + 'electron', + 'react', + 'react-redux', + 'redux-observers', + 'reselect', + 'react-bootstrap', + 'react-fontawesome', + 'path-extra', + 'fs-extra', + 'lodash', + 'cson', + ], + }, }
3497efd63d2c0af9ffa99c67a4b33cf60988da1b
providers/nmea0183-signalk.js
providers/nmea0183-signalk.js
/* * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Transform = require('stream').Transform; function ToSignalK(options) { Transform.call(this, { objectMode: true }); this.parser = new(require('nmea0183-signalk').Parser)(options); var that = this; this.parser.on('delta', function(delta) { that.push(delta); }); } require('util').inherits(ToSignalK, Transform); ToSignalK.prototype._transform = function(chunk, encoding, done) { this.parser.write(chunk + '\n'); done() } module.exports = ToSignalK;
/* * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Transform = require('stream').Transform; function ToSignalK(options) { Transform.call(this, { objectMode: true }); this.parser = new(require('nmea0183-signalk').Parser)(options); var that = this; this.parser.on('delta', function(delta) { that.push(delta); }); } require('util').inherits(ToSignalK, Transform); ToSignalK.prototype._transform = function(chunk, encoding, done) { try { this.parser.write(chunk + '\n'); } catch (ex) { console.error(ex); } done(); } module.exports = ToSignalK;
Add try-catch as safeguard against potentionally misbehaving parser
Add try-catch as safeguard against potentionally misbehaving parser
JavaScript
apache-2.0
lsoltero/signalk-server-node,SignalK/signalk-server-node,SignalK/signalk-server-node,sbender9/signalk-server-node,jaittola/signalk-server-node,webmasterkai/signalk-server-node,sbender9/signalk-server-node,jaittola/signalk-server-node,SignalK/signalk-server-node,mauroc/signalk-oauth-node,sbender9/signalk-server-node,mauroc/signalk-oauth-node,lsoltero/signalk-server-node,jaittola/signalk-server-node,webmasterkai/signalk-server-node,mauroc/signalk-oauth-node,SignalK/signalk-server-node,webmasterkai/signalk-server-node
--- +++ @@ -31,8 +31,12 @@ require('util').inherits(ToSignalK, Transform); ToSignalK.prototype._transform = function(chunk, encoding, done) { - this.parser.write(chunk + '\n'); - done() + try { + this.parser.write(chunk + '\n'); + } catch (ex) { + console.error(ex); + } + done(); }
370f817c0f879093557c98091c3bdc7207ebad25
server/startup.js
server/startup.js
Meteor.startup(function () { Meteor.call("lightstreamerConnect") Restivus.configure({ useAuth: true, prettyJson: true }); Restivus.addCollection(isslocation, { excludedEndpoints: ['put', 'post', 'delete', 'deleteAll'] }); });
Meteor.startup(function () { Meteor.call("lightstreamerConnect") Restivus.configure({ useAuth: false, prettyJson: true }); Restivus.addRoute('isslocation/latest', {authRequired: false}, { get: function(){ var positionx = isslocation.findOne({type: 'positionx'},{sort: {time : -1}}); var positiony = isslocation.findOne({type: 'positiony'},{sort: {time : -1}}); var positionz = isslocation.findOne({type: 'positionz'},{sort: {time : -1}}); var telemetry = { telemetry: positionx.position, positiony: positiony.position, positionz: positionz.position }; if (positionx && positiony && positionz){ return {status: 'success', data: telemetry}; }else{ return {statusCode: 404, body: {status: 'fail', message: 'Record not found.'}} }; } }); });
Add latest data API endpoint
Add latest data API endpoint
JavaScript
mit
slashrocket/stationstream,slashrocket/stationstream
--- +++ @@ -1,10 +1,24 @@ Meteor.startup(function () { Meteor.call("lightstreamerConnect") Restivus.configure({ - useAuth: true, + useAuth: false, prettyJson: true }); - Restivus.addCollection(isslocation, { - excludedEndpoints: ['put', 'post', 'delete', 'deleteAll'] + Restivus.addRoute('isslocation/latest', {authRequired: false}, { + get: function(){ + var positionx = isslocation.findOne({type: 'positionx'},{sort: {time : -1}}); + var positiony = isslocation.findOne({type: 'positiony'},{sort: {time : -1}}); + var positionz = isslocation.findOne({type: 'positionz'},{sort: {time : -1}}); + var telemetry = { + telemetry: positionx.position, + positiony: positiony.position, + positionz: positionz.position + }; + if (positionx && positiony && positionz){ + return {status: 'success', data: telemetry}; + }else{ + return {statusCode: 404, body: {status: 'fail', message: 'Record not found.'}} + }; + } }); });
d9ece655ddd7df695ef2a2087971f691e77ec84a
routes/index.js
routes/index.js
//get index require('./../config'); async=require('async'); var bitcoin=require('bitcoin').bitcoin; var knex=require('knex').knex; //var bookshelf=require('bookshelf').bookshelf; exports.index = function(req, res){ testnet: async.parallel({ testnet: function(callback){ bitcoin.getInfo(function(e, info){ if(e){ return console.log(e);} if(info.testnet){ callback(null, 'bitcoin RPC is testnet'); }else{ callback(null, 'nope.. you must be crazy'); } }); }, name: function(callback){ var c=knex('config').select().then(function(r){ callback(null, r[0].site_name); }); } }, function(err, r){ res.render('index', { title: r.name, testnet: r.testnet }); }); };
//get index require('./../config'); var Promise = require("bluebird"); var bitcoin=require('bitcoin').bitcoin; var knex=require('knex').knex; Promise.promisifyAll(require('bitcoin').Client.prototype); //var bookshelf=require('bookshelf').bookshelf; exports.index = function(req, res){ var info = bitcoin.getInfoAsync(); var config = knex('config').select(); Promise.all([info, config]).spread(function(info, config) { res.render('index', { title: config[0].site_name, testnet: info.testnet ? 'bitcoin RPC is testnet' : 'nope.. you must be crazy' }); }).catch(function(e){ console.log(e); }); };
Change to using promisify instead of async for better code and easy error handling
Change to using promisify instead of async for better code and easy error handling
JavaScript
bsd-2-clause
Earlz/d4btc
--- +++ @@ -1,31 +1,21 @@ //get index require('./../config'); -async=require('async'); +var Promise = require("bluebird"); + var bitcoin=require('bitcoin').bitcoin; var knex=require('knex').knex; - +Promise.promisifyAll(require('bitcoin').Client.prototype); //var bookshelf=require('bookshelf').bookshelf; exports.index = function(req, res){ - testnet: async.parallel({ - testnet: function(callback){ - bitcoin.getInfo(function(e, info){ - if(e){ return console.log(e);} - if(info.testnet){ - callback(null, 'bitcoin RPC is testnet'); - }else{ - callback(null, 'nope.. you must be crazy'); - } + var info = bitcoin.getInfoAsync(); + var config = knex('config').select(); + Promise.all([info, config]).spread(function(info, config) { + res.render('index', { + title: config[0].site_name, + testnet: info.testnet ? 'bitcoin RPC is testnet' : 'nope.. you must be crazy' }); - }, - name: function(callback){ - var c=knex('config').select().then(function(r){ - callback(null, r[0].site_name); - }); - } - }, - function(err, r){ - res.render('index', { title: r.name, testnet: r.testnet }); - }); - + }).catch(function(e){ + console.log(e); + }); };
c22cd7328d458b2d307095bf44b5557bbccf881f
routes/users.js
routes/users.js
var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.send('respond with a resource'); }); module.exports = router;
var express = require('express'); var withConnection = require('../lib/withConnection'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.send('respond with a resource'); }); router.post('/authenticate', function(req, res, next) { var user; var data = { email: req.body.email, password: req.body.password }; var sql = 'SELECT * FROM users WHERE email = $1 LIMIT 1;'; withConnection(function(client) { client.query(sql, [data.email]) .on('row', function(row) { user = row; }) .on('end', function() { client.end(); return res.json(user); }); }); }); module.exports = router;
Add authenticate endpoint (but not actually authenticating yet)
Add authenticate endpoint (but not actually authenticating yet)
JavaScript
mit
getfretless/tracker-serverjs,getfretless/tracker-serverjs
--- +++ @@ -1,4 +1,5 @@ var express = require('express'); +var withConnection = require('../lib/withConnection'); var router = express.Router(); /* GET users listing. */ @@ -6,4 +7,20 @@ res.send('respond with a resource'); }); +router.post('/authenticate', function(req, res, next) { + var user; + var data = { email: req.body.email, password: req.body.password }; + var sql = 'SELECT * FROM users WHERE email = $1 LIMIT 1;'; + withConnection(function(client) { + client.query(sql, [data.email]) + .on('row', function(row) { + user = row; + }) + .on('end', function() { + client.end(); + return res.json(user); + }); + }); +}); + module.exports = router;
9ecea827bb974b789e7a171b1682059de2cf572b
lib/joiless.js
lib/joiless.js
var isFunction = require('lodash.isfunction'); var joi = require('joi'); var pc = require('pascal-case'); /* Public */ function attach(schema) { var attachments = {}; schema && schema._inner && schema._inner.children && schema._inner.children.forEach(function (child) { attachments[pc(child.key)] = { get: function () { return child.schema; } }; }); return Object.defineProperties(schema, attachments); } function spec(type, params) { var after, spec; if (arguments.length === 1) { params = type; type = params.type; delete params.type; } if (isFunction(params.after)) { after = params.after; delete params.after; } spec = joi[type](); Object.keys(params).forEach(function (key) { spec = Array.isArray(params[key]) ? spec[key].apply(spec, params[key]) : spec[key](params[key]); }); if (after) { after(spec); } return spec; } /* Exports */ module.exports.attach = attach; module.exports.spec = spec;
var isFunction = require('lodash.isfunction'); var joi = require('joi'); var pc = require('pascal-case'); /* Public */ function attach(schema) { var attachments = {}; schema && schema._inner && schema._inner.children && schema._inner.children.forEach(function (child) { attachments[pc(child.key)] = { get: function () { return child.schema; } }; }); return Object.defineProperties(schema, attachments); } function spec(type, params) { var after, spec; if (!params) { params = type || {}; type = params.type; delete params.type; } if (isFunction(params.after)) { after = params.after; delete params.after; } spec = joi[type](); Object.keys(params).forEach(function (key) { spec = Array.isArray(params[key]) ? spec[key].apply(spec, params[key]) : spec[key](params[key]); }); if (after) { after(spec); } return spec; } /* Exports */ module.exports.attach = attach; module.exports.spec = spec;
Fix an issue with parameter validation
Fix an issue with parameter validation
JavaScript
mit
zackehh/joiless
--- +++ @@ -24,8 +24,8 @@ function spec(type, params) { var after, spec; - if (arguments.length === 1) { - params = type; + if (!params) { + params = type || {}; type = params.type; delete params.type; }
a1c28dd59d5f156a58629be110bb823d978e3db4
frontend/src/Lists/ListsView.js
frontend/src/Lists/ListsView.js
import React, { Component } from "react"; import styled from "styled-components"; import { Row, RowContent, ColumnContainer } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <ColumnContainer> <Row> <RowContent> Du är: {user.nick} </RowContent> </Row> <MainContainer> <ListContainer width={(lists.length - 2) * 20}> {lists.map((list, i) => <List key={list.id} list={list} user={user} inactive={i < lists.length - 1} />)} </ListContainer> {user.isAdmin && <CreateList />} <Notes /> </MainContainer> </ColumnContainer> ); } } const ListContainer = Row.extend` margin-left: -${props => props.width}em; `; const MainContainer = styled(Row)` padding-top: 2em; `; export default ListsView;
import React, { Component } from "react"; import styled from "styled-components"; import { Row, RowContent, ColumnContainer } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <ColumnContainer> <Row> <RowContent> Du är: {user.nick} </RowContent> </Row> <MainContainer> <ListContainer numberOfLists={lists.length} > {lists.map((list, i) => <List key={list.id} list={list} user={user} inactive={i < lists.length - 1} />)} </ListContainer> {user.isAdmin && <CreateList />} <Notes /> </MainContainer> </ColumnContainer> ); } } const ListContainer = Row.extend` margin-left: -${props => (props.numberOfLists - 2) * 20}em; align-self: ${props => (props.numberOfLists > 1) ? 'flex-end' : 'center'}; margin-bottom: 2em; `; const MainContainer = Row.extend` padding-top: 2em; @media (min-width: 900px) { flex-direction: row; } @media (max-width: 900px) { flex-direction: column; align-items: center; } `; export default ListsView;
Make Lists view mobile friendly
Make Lists view mobile friendly
JavaScript
mit
Tejpbit/talarlista,Tejpbit/talarlista,Tejpbit/talarlista
--- +++ @@ -26,7 +26,7 @@ </Row> <MainContainer> - <ListContainer width={(lists.length - 2) * 20}> + <ListContainer numberOfLists={lists.length} > {lists.map((list, i) => <List key={list.id} list={list} user={user} inactive={i < lists.length - 1} />)} </ListContainer> {user.isAdmin && <CreateList />} @@ -38,11 +38,21 @@ } const ListContainer = Row.extend` - margin-left: -${props => props.width}em; + margin-left: -${props => (props.numberOfLists - 2) * 20}em; + align-self: ${props => (props.numberOfLists > 1) ? 'flex-end' : 'center'}; + margin-bottom: 2em; `; -const MainContainer = styled(Row)` +const MainContainer = Row.extend` padding-top: 2em; + + @media (min-width: 900px) { + flex-direction: row; + } + @media (max-width: 900px) { + flex-direction: column; + align-items: center; + } `; export default ListsView;
5408e47e50289815efbd9ea491e83f9452136f4b
examples/benchmark1-NGX.js
examples/benchmark1-NGX.js
/* * Copyright (C) DreamLab Onet.pl Sp. z o. o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var uriparser = require('../bin/uriparser'), url = "http://10.177.51.76:1337//example/dir/hi", matches; for (var i = 0; i < 2000000; i++) { matches = uriparser.parse(url, uriparser.kAll, uriparser.eNgxParser); }
/* * Copyright (C) DreamLab Onet.pl Sp. z o. o. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var uriparser = require('../bin/uriparser'), url = "http://10.177.51.76:1337//example/dir/hi", matches; for (var i = 0; i < 2000000; i++) { matches = uriparser.parse(url, uriparser.Uri.PROTOCOL, uriparser.Engines.NGINX); }
Update example for NGINX parser
Update example for NGINX parser
JavaScript
mit
DreamLab/node-uriparser,DreamLab/node-uriparser,DreamLab/node-uriparser,DreamLab/node-uriparser
--- +++ @@ -23,6 +23,6 @@ var uriparser = require('../bin/uriparser'), url = "http://10.177.51.76:1337//example/dir/hi", matches; for (var i = 0; i < 2000000; i++) { - matches = uriparser.parse(url, uriparser.kAll, uriparser.eNgxParser); + matches = uriparser.parse(url, uriparser.Uri.PROTOCOL, uriparser.Engines.NGINX); }
c2562990cb077bdf7f2dbb9f5fedb9fd446a05e5
scripts/ayuda.js
scripts/ayuda.js
document.getElementById("ayuda").setAttribute("aria-current", "page"); var aside = document.getElementById("complementario"); var form = document.createElement("FORM"); var p = document.createElement("P"); var label = document.createElement("LABEL"); label.setAttribute("for", "repo"); t = document.createTextNode("cuenta/repositorio de GitHub"); label.appendChild(t); var input = document.createElement("INPUT"); input.setAttribute("type", "text"); input.setAttribute("id", "repo"); input.setAttribute("name", "repo"); label.appendChild(input); var submit = document.createElement("BUTTON"); submit.setAttribute("id", "submit"); var t = document.createTextNode("Consultar descargas de última versión"); submit.appendChild(t); p.appendChild(label); form.appendChild(p); aside.appendChild(form); aside.appendChild(submit); $(document).ready(function () { $("#submit").click(function () { $.getJSON("https://api.github.com/repos/releases/latest", function(json) { var name = json.name; }); }); });
document.getElementById("ayuda").setAttribute("aria-current", "page"); var aside = document.getElementById("complementario"); var form = document.createElement("FORM"); var p = document.createElement("P"); var label = document.createElement("LABEL"); label.setAttribute("for", "repo"); t = document.createTextNode("cuenta/repositorio de GitHub"); label.appendChild(t); var input = document.createElement("INPUT"); input.setAttribute("type", "text"); input.setAttribute("id", "repo"); input.setAttribute("name", "repo"); label.appendChild(input); var submit = document.createElement("BUTTON"); submit.setAttribute("id", "submit"); submit.setAttribute("type", "button"); var t = document.createTextNode("Consultar descargas de última versión"); submit.appendChild(t); p.appendChild(label); form.appendChild(p); form.appendChild(submit); $(document).ready(function () { $("#submit").click(function () { $.getJSON("https://api.github.com/repos/releases/latest", function(json) { var name = json.name; }); }); });
Add type attribute set to button
Add type attribute set to button
JavaScript
mit
nvdaes/nvdaes.github.io,nvdaes/nvdaes.github.io
--- +++ @@ -15,12 +15,12 @@ label.appendChild(input); var submit = document.createElement("BUTTON"); submit.setAttribute("id", "submit"); +submit.setAttribute("type", "button"); var t = document.createTextNode("Consultar descargas de última versión"); submit.appendChild(t); p.appendChild(label); form.appendChild(p); -aside.appendChild(form); -aside.appendChild(submit); +form.appendChild(submit); $(document).ready(function () { $("#submit").click(function () {
d33efd6901b5a54c10da2630bb5fda11ae3391bf
src/validators/record_type_txt.js
src/validators/record_type_txt.js
'use strict'; const Hoek = require('hoek'); const Joi = require('joi'); const recordBase = require('./record_base'); module.exports = Hoek.clone(recordBase).keys({ record_type: Joi.string().valid('TXT').required(), text_content: Joi.string().required() });
'use strict'; const Hoek = require('hoek'); const Joi = require('joi'); const recordBase = require('./record_base'); module.exports = Hoek.clone(recordBase).keys({ record_type: Joi.string().valid('TXT').required(), // Allowed in TXT records are ASCII letters, plus a selected set of // symbols, which translates to this gobbledygook you see in the regex // below. The \[\\\]\ sequence just whitelists the characters [\], but // since they all need escaping in regex, it becomes a bit strange. text_content: Joi.string().required().regex(/^[A-Za-z0-9 !"#\$%&'()*+,-.\/:;<=>?@\[\\\]\^_`{\|}~-]+$/) });
Whitelist for characters in TXT records
Whitelist for characters in TXT records
JavaScript
isc
mikl/edzif-validator
--- +++ @@ -6,5 +6,9 @@ module.exports = Hoek.clone(recordBase).keys({ record_type: Joi.string().valid('TXT').required(), - text_content: Joi.string().required() + // Allowed in TXT records are ASCII letters, plus a selected set of + // symbols, which translates to this gobbledygook you see in the regex + // below. The \[\\\]\ sequence just whitelists the characters [\], but + // since they all need escaping in regex, it becomes a bit strange. + text_content: Joi.string().required().regex(/^[A-Za-z0-9 !"#\$%&'()*+,-.\/:;<=>?@\[\\\]\^_`{\|}~-]+$/) });
c7d9c51fc1728c01eadf48be2ed559da0b133076
client-vendor/after-body/jquery.event.clickConfirmed/jquery.event.clickConfirmed.js
client-vendor/after-body/jquery.event.clickConfirmed/jquery.event.clickConfirmed.js
/* * Author: CM */ (function($) { $.event.special.clickConfirmed = { bindType: "click", delegateType: "click", settings: { message: 'Please Confirm' }, handle: function(event) { var $this = $(this); var activateButton = function() { $this.addClass('confirmClick'); $this.attr('title', $.event.special.clickConfirmed.settings.message).tooltip({trigger: 'manual'}).tooltip('show'); $this.data('timeoutId', setTimeout(function() { deactivateButton(); }, 5000)); setTimeout(function() { $(document).one('click.clickConfirmed', function(e) { if (!$this.length || e.target !== $this[0] && !$.contains($this[0], e.target)) { deactivateButton(); } }); }, 0); }; var deactivateButton = function() { $this.removeClass('confirmClick'); $this.removeAttr('title').tooltip('hide'); clearTimeout($this.data('timeoutId')); $(document).off('click.clickConfirmed'); }; if ($this.hasClass('confirmClick')) { deactivateButton(); return event.handleObj.handler.call(this, event); } activateButton(); return false; } }; })(jQuery);
/* * Author: CM */ (function($) { $.event.special.clickConfirmed = { bindType: "click", delegateType: "click", settings: { message: 'Please Confirm' }, handle: function(event) { var $this = $(this); var deactivateTimeout = null; var activateButton = function() { $this.addClass('confirmClick'); $this.attr('title', $.event.special.clickConfirmed.settings.message).tooltip({trigger: 'manual'}).tooltip('show'); deactivateTimeout = setTimeout(function() { deactivateButton(); }, 5000); setTimeout(function() { $(document).one('click.clickConfirmed', function(e) { if (!$this.length || e.target !== $this[0] && !$.contains($this[0], e.target)) { deactivateButton(); } }); }, 0); }; var deactivateButton = function() { $this.removeClass('confirmClick'); $this.removeAttr('title').tooltip('hide'); clearTimeout(deactivateTimeout); $(document).off('click.clickConfirmed'); }; if ($this.hasClass('confirmClick')) { deactivateButton(); return event.handleObj.handler.call(this, event); } activateButton(); return false; } }; })(jQuery);
Store timeoutId in local variable
Store timeoutId in local variable
JavaScript
mit
alexispeter/CM,christopheschwyzer/CM,cargomedia/CM,cargomedia/CM,christopheschwyzer/CM,fvovan/CM,cargomedia/CM,njam/CM,fvovan/CM,fauvel/CM,christopheschwyzer/CM,njam/CM,fvovan/CM,vogdb/cm,fauvel/CM,mariansollmann/CM,vogdb/cm,alexispeter/CM,njam/CM,zazabe/cm,cargomedia/CM,christopheschwyzer/CM,vogdb/cm,vogdb/cm,njam/CM,zazabe/cm,njam/CM,tomaszdurka/CM,alexispeter/CM,mariansollmann/CM,tomaszdurka/CM,tomaszdurka/CM,tomaszdurka/CM,fauvel/CM,fauvel/CM,tomaszdurka/CM,fauvel/CM,fvovan/CM,vogdb/cm,mariansollmann/CM,mariansollmann/CM,zazabe/cm,alexispeter/CM,zazabe/cm
--- +++ @@ -12,13 +12,14 @@ handle: function(event) { var $this = $(this); + var deactivateTimeout = null; var activateButton = function() { $this.addClass('confirmClick'); $this.attr('title', $.event.special.clickConfirmed.settings.message).tooltip({trigger: 'manual'}).tooltip('show'); - $this.data('timeoutId', setTimeout(function() { + deactivateTimeout = setTimeout(function() { deactivateButton(); - }, 5000)); + }, 5000); setTimeout(function() { $(document).one('click.clickConfirmed', function(e) { if (!$this.length || e.target !== $this[0] && !$.contains($this[0], e.target)) { @@ -31,7 +32,7 @@ var deactivateButton = function() { $this.removeClass('confirmClick'); $this.removeAttr('title').tooltip('hide'); - clearTimeout($this.data('timeoutId')); + clearTimeout(deactivateTimeout); $(document).off('click.clickConfirmed'); };
a581d98fce6f891d0f78e1ab3dcff70b851d9d55
server/router.js
server/router.js
const express = require('express'); const router = express.Router(); const authController = require('./authController'); const locationsController = require('./locationsController'); const locationTypeController = require('./locationTypeController'); const happyHoursController = require('./happyHoursController'); router.post('/v1/auth', authController.getAuth); router.post( '/v1/auth/test', authController.checkAuth, authController.testCheckAuth ); router.post( '/v1/locations', authController.checkAuth, locationsController.addLocation ); router.get('/v1/locations', locationsController.getLocations); router.delete( '/v1/locations/:id', authController.checkAuth, locationsController.deleteLocation ); router.get( '/v1/locations/:id/happyhours', happyHoursController.getHappyHoursByLocation ); router.post( '/v1/happyhours', authController.checkAuth, happyHoursController.addHappyHours ); router.put( '/v1/happyhours/:id', authController.checkAuth, happyHoursController.updateHappyHours ); router.delete( '/v1/happyhours/:id', authController.checkAuth, happyHoursController.deleteHappyHours ); router.get('/v1/locationtypes', locationTypeController.getLocationTypes); module.exports = router;
const express = require('express'); const router = express.Router(); const authController = require('./authController'); const locationsController = require('./locationsController'); const locationTypeController = require('./locationTypeController'); const happyHoursController = require('./happyHoursController'); router.post('/v1/auth', authController.getAuth); router.post( '/v1/auth/test', authController.checkAuth, authController.testCheckAuth ); router.post( '/v1/locations', authController.checkAuth, locationsController.addLocation ); router.get('/v1/locations', locationsController.getLocations); router.get('/v1/locations/:id', locationsController.getLocationById); router.delete( '/v1/locations/:id', authController.checkAuth, locationsController.deleteLocation ); router.get( '/v1/locations/:id/happyhours', happyHoursController.getHappyHoursByLocation ); router.post( '/v1/happyhours', authController.checkAuth, happyHoursController.addHappyHours ); router.put( '/v1/happyhours/:id', authController.checkAuth, happyHoursController.updateHappyHours ); router.delete( '/v1/happyhours/:id', authController.checkAuth, happyHoursController.deleteHappyHours ); router.get('/v1/locationtypes', locationTypeController.getLocationTypes); module.exports = router;
Add GET location by ID route.
Add GET location by ID route.
JavaScript
mit
the-oem/happy-hour-power,the-oem/happy-hour-power
--- +++ @@ -20,6 +20,7 @@ locationsController.addLocation ); router.get('/v1/locations', locationsController.getLocations); +router.get('/v1/locations/:id', locationsController.getLocationById); router.delete( '/v1/locations/:id', authController.checkAuth,
cb927bcf825de717db3a331ab5357c1e95cdbbec
src/Versioning.js
src/Versioning.js
let path = require('path'); let Manifest = require('./Manifest'); let objectValues = require('lodash').values; class Versioning { /** * Create a new Versioning instance. * * @param {object} manifest */ constructor(manifest) { this.manifest = manifest; this.files = []; } /** * Record versioned files. */ record() { if (! this.manifest.exists()) return; this.reset(); this.files = objectValues(this.manifest.read()); return this; } /** * Reset all recorded files. */ reset() { this.files = []; return this; } /** * Replace all old hashed files with the new versions. * * @param {string} baseDir */ prune(baseDir) { let updated = new Versioning(this.manifest).record(); if (! updated) return; this.files.filter(file => ! updated.files.includes(file)) .forEach(file => this.manifest.remove(path.join(baseDir, file))); this.files = updated.files; return this; } } module.exports = Versioning;
let path = require('path'); let Manifest = require('./Manifest'); let objectValues = require('lodash').values; class Versioning { /** * Create a new Versioning instance. * * @param {object} manifest */ constructor(manifest) { this.manifest = manifest; this.files = []; } /** * Record versioned files. */ record() { if (! this.manifest.exists()) return this; this.reset(); this.files = objectValues(this.manifest.read()); return this; } /** * Reset all recorded files. */ reset() { this.files = []; return this; } /** * Replace all old hashed files with the new versions. * * @param {string} baseDir */ prune(baseDir) { let updated = new Versioning(this.manifest).record(); if (! updated) return; this.files.filter(file => ! updated.files.includes(file)) .forEach(file => this.manifest.remove(path.join(baseDir, file))); this.files = updated.files; return this; } } module.exports = Versioning;
Fix record function returning this
Fix record function returning this
JavaScript
mit
JeffreyWay/laravel-mix
--- +++ @@ -19,7 +19,7 @@ * Record versioned files. */ record() { - if (! this.manifest.exists()) return; + if (! this.manifest.exists()) return this; this.reset();
b8d08b990108cf42f22e2a196007d99ea34282e4
tests/integration/components/attributes-test.js
tests/integration/components/attributes-test.js
import { moduleForComponent, test } from 'ember-qunit'; import Component from '@ember/component'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('attributes', 'Integration | Component | attributes', { integration: true, beforeEach() { this.register('component:x-foo', Component.extend()); } }); test('it works!', function(assert) { this.render(hbs`{{x-foo (attributes data-foo="bar")}}`); assert.equal(this._element.querySelectorAll('[data-foo="bar"]').length, 1); });
import { moduleForComponent, test } from 'ember-qunit'; import Component from '@ember/component'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('attributes', 'Integration | Component | attributes', { integration: true, }); test('it works when component has no existing attribute bindings', function(assert) { this.register('component:x-foo', Component.extend()); this.render(hbs`{{x-foo (attributes data-foo="bar")}} {{x-foo}}`); assert.equal(this._element.querySelectorAll('[data-foo="bar"]').length, 1); }); test('it works when component has existing attribute bindings', function(assert) { this.register('component:x-foo', Component.extend({ attributeBindings: ['dataDerp:data-derp'] })); this.render(hbs`{{x-foo (attributes data-foo="bar") dataDerp="lol"}} {{x-foo dataDerp="hehe"}}`); assert.equal(this._element.querySelectorAll('[data-foo="bar"]').length, 1); assert.equal(this._element.querySelectorAll('[data-derp]').length, 2); });
Add basic sanity test for both scenarios.
Add basic sanity test for both scenarios.
JavaScript
mit
mmun/ember-component-attributes,mmun/ember-component-attributes
--- +++ @@ -4,15 +4,21 @@ moduleForComponent('attributes', 'Integration | Component | attributes', { integration: true, - - beforeEach() { - this.register('component:x-foo', Component.extend()); - } }); -test('it works!', function(assert) { +test('it works when component has no existing attribute bindings', function(assert) { + this.register('component:x-foo', Component.extend()); - this.render(hbs`{{x-foo (attributes data-foo="bar")}}`); + this.render(hbs`{{x-foo (attributes data-foo="bar")}} {{x-foo}}`); assert.equal(this._element.querySelectorAll('[data-foo="bar"]').length, 1); }); + +test('it works when component has existing attribute bindings', function(assert) { + this.register('component:x-foo', Component.extend({ attributeBindings: ['dataDerp:data-derp'] })); + + this.render(hbs`{{x-foo (attributes data-foo="bar") dataDerp="lol"}} {{x-foo dataDerp="hehe"}}`); + + assert.equal(this._element.querySelectorAll('[data-foo="bar"]').length, 1); + assert.equal(this._element.querySelectorAll('[data-derp]').length, 2); +});
efdd8855715caf469a9423c2dddc90523e6104c6
src/ol/source/VectorEventType.js
src/ol/source/VectorEventType.js
/** * @module ol/source/VectorEventType */ /** * @enum {string} */ export default { /** * Triggered when a feature is added to the source. * @event module:ol/source/Vector.VectorSourceEvent#addfeature * @api */ ADDFEATURE: 'addfeature', /** * Triggered when a feature is updated. * @event module:ol/source/Vector.VectorSourceEvent#changefeature * @api */ CHANGEFEATURE: 'changefeature', /** * Triggered when the clear method is called on the source. * @event module:ol/source/Vector.VectorSourceEvent#clear * @api */ CLEAR: 'clear', /** * Triggered when a feature is removed from the source. * See {@link module:ol/source/Vector#clear source.clear()} for exceptions. * @event module:ol/source/Vector.VectorSourceEvent#removefeature * @api */ REMOVEFEATURE: 'removefeature', /** * Triggered when features starts loading. * @event module:ol/source/Vector.VectorSourceEvent#featureloadstart * @api */ FEATURESLOADSTART: 'featuresloadstart', /** * Triggered when features finishes loading. * @event module:ol/source/Vector.VectorSourceEvent#featureloadend * @api */ FEATURESLOADEND: 'featuresloadend', /** * Triggered if feature loading results in an error. * @event module:ol/source/Vector.VectorSourceEvent#featureloaderror * @api */ FEATURESLOADERROR: 'featuresloaderror', };
/** * @module ol/source/VectorEventType */ /** * @enum {string} */ export default { /** * Triggered when a feature is added to the source. * @event module:ol/source/Vector.VectorSourceEvent#addfeature * @api */ ADDFEATURE: 'addfeature', /** * Triggered when a feature is updated. * @event module:ol/source/Vector.VectorSourceEvent#changefeature * @api */ CHANGEFEATURE: 'changefeature', /** * Triggered when the clear method is called on the source. * @event module:ol/source/Vector.VectorSourceEvent#clear * @api */ CLEAR: 'clear', /** * Triggered when a feature is removed from the source. * See {@link module:ol/source/Vector#clear source.clear()} for exceptions. * @event module:ol/source/Vector.VectorSourceEvent#removefeature * @api */ REMOVEFEATURE: 'removefeature', /** * Triggered when features starts loading. * @event module:ol/source/Vector.VectorSourceEvent#featuresloadstart * @api */ FEATURESLOADSTART: 'featuresloadstart', /** * Triggered when features finishes loading. * @event module:ol/source/Vector.VectorSourceEvent#featuresloadend * @api */ FEATURESLOADEND: 'featuresloadend', /** * Triggered if feature loading results in an error. * @event module:ol/source/Vector.VectorSourceEvent#featuresloaderror * @api */ FEATURESLOADERROR: 'featuresloaderror', };
Correct documented event names for VectorSourceEvent
Correct documented event names for VectorSourceEvent
JavaScript
bsd-2-clause
ahocevar/ol3,oterral/ol3,ahocevar/openlayers,stweil/openlayers,adube/ol3,adube/ol3,stweil/openlayers,ahocevar/openlayers,bjornharrtell/ol3,ahocevar/openlayers,stweil/ol3,ahocevar/ol3,oterral/ol3,adube/ol3,stweil/ol3,openlayers/openlayers,ahocevar/ol3,openlayers/openlayers,stweil/ol3,oterral/ol3,openlayers/openlayers,bjornharrtell/ol3,stweil/openlayers,bjornharrtell/ol3,stweil/ol3,ahocevar/ol3
--- +++ @@ -37,21 +37,21 @@ /** * Triggered when features starts loading. - * @event module:ol/source/Vector.VectorSourceEvent#featureloadstart + * @event module:ol/source/Vector.VectorSourceEvent#featuresloadstart * @api */ FEATURESLOADSTART: 'featuresloadstart', /** * Triggered when features finishes loading. - * @event module:ol/source/Vector.VectorSourceEvent#featureloadend + * @event module:ol/source/Vector.VectorSourceEvent#featuresloadend * @api */ FEATURESLOADEND: 'featuresloadend', /** * Triggered if feature loading results in an error. - * @event module:ol/source/Vector.VectorSourceEvent#featureloaderror + * @event module:ol/source/Vector.VectorSourceEvent#featuresloaderror * @api */ FEATURESLOADERROR: 'featuresloaderror',
64b61935b843fd6245495699bfee732ab228a50c
prolific.executable/header.js
prolific.executable/header.js
const { Staccato } = require('staccato') module.exports = async function (input) { const staccato = new Staccato(input) let accumulator = Buffer.alloc(0) for (;;) { const buffer = await staccato.readable.read() if (buffer == null) { return null } accumulator = Buffer.concat([ accumulator, buffer ]) if (~accumulator.indexOf(0xa)) { staccato.stream.destroy() return JSON.parse(accumulator.toString('utf8')) } } }
const { Staccato } = require('staccato') module.exports = async function (input) { const staccato = new Staccato(input) let accumulator = Buffer.alloc(0) for (;;) { const buffer = await staccato.readable.read() if (buffer == null) { return null } accumulator = Buffer.concat([ accumulator, buffer ]) if (~accumulator.indexOf(0xa)) { staccato.unlisten() return JSON.parse(accumulator.toString('utf8')) } } }
Replace socket destroy with Staccato unlisten.
Replace socket destroy with Staccato unlisten.
JavaScript
mit
bigeasy/prolific,bigeasy/prolific
--- +++ @@ -10,7 +10,7 @@ } accumulator = Buffer.concat([ accumulator, buffer ]) if (~accumulator.indexOf(0xa)) { - staccato.stream.destroy() + staccato.unlisten() return JSON.parse(accumulator.toString('utf8')) } }
c80e93c106619ce86eae908e32f1382f666f5c48
rollup.config.js
rollup.config.js
// @flow import babel from "rollup-plugin-babel"; import commonjs from "rollup-plugin-commonjs"; import fs from "fs"; import pascalCase from "pascal-case"; import resolve from "rollup-plugin-node-resolve"; import pkg from "./package.json"; const plugins = { babel: babel({ exclude: "node_modules/**", runtimeHelpers: true }), commonjs: commonjs(), resolve: resolve() }; const dirs = { input: "src", output: "dist", compat: "compat" }; const getCjsAndEsConfig = fileName => ({ input: `${dirs.input}/${fileName}`, output: [ {file: `${dirs.output}/${fileName}`, format: "es"}, {file: `${dirs.compat}/cjs/${fileName}`, format: "cjs"} ], plugins: [plugins.babel] }); const sources = fs.readdirSync("src"); const getUnscopedName = pkg => pkg.name.split("/")[1]; export default [ { input: `${dirs.input}/index.js`, output: { file: `${dirs.compat}/umd/index.js`, format: "umd" }, name: pascalCase(getUnscopedName(pkg)), plugins: [plugins.babel, plugins.resolve, plugins.commonjs] }, ...sources.map(getCjsAndEsConfig) ];
// @flow import babel from "rollup-plugin-babel"; import commonjs from "rollup-plugin-commonjs"; import fs from "fs"; import pascalCase from "pascal-case"; import resolve from "rollup-plugin-node-resolve"; import uglify from "rollup-plugin-uglify"; import {minify} from "uglify-es"; import pkg from "./package.json"; const plugins = { babel: babel({ exclude: "node_modules/**", runtimeHelpers: true }), commonjs: commonjs(), resolve: resolve(), uglify: uglify({}, minify) }; const dirs = { input: "src", output: "dist", compat: "compat" }; const getCjsAndEsConfig = fileName => ({ input: `${dirs.input}/${fileName}`, output: [ {file: `${dirs.output}/${fileName}`, format: "es"}, {file: `${dirs.compat}/cjs/${fileName}`, format: "cjs"} ], plugins: [plugins.babel, plugins.uglify], sourcemap: true }); const sources = fs.readdirSync("src"); const getUnscopedName = pkg => pkg.name.split("/")[1]; export default [ { input: `${dirs.input}/index.js`, output: { file: `${dirs.compat}/umd/index.js`, format: "umd" }, name: pascalCase(getUnscopedName(pkg)), plugins: [plugins.babel, plugins.resolve, plugins.commonjs, plugins.uglify], sourcemap: true }, ...sources.map(getCjsAndEsConfig) ];
Set up uglify plugin and sourcemaps
build(rollup): Set up uglify plugin and sourcemaps
JavaScript
mit
jumpn/utils-composite,jumpn/utils-composite
--- +++ @@ -5,6 +5,8 @@ import fs from "fs"; import pascalCase from "pascal-case"; import resolve from "rollup-plugin-node-resolve"; +import uglify from "rollup-plugin-uglify"; +import {minify} from "uglify-es"; import pkg from "./package.json"; @@ -14,7 +16,8 @@ runtimeHelpers: true }), commonjs: commonjs(), - resolve: resolve() + resolve: resolve(), + uglify: uglify({}, minify) }; const dirs = { @@ -29,7 +32,8 @@ {file: `${dirs.output}/${fileName}`, format: "es"}, {file: `${dirs.compat}/cjs/${fileName}`, format: "cjs"} ], - plugins: [plugins.babel] + plugins: [plugins.babel, plugins.uglify], + sourcemap: true }); const sources = fs.readdirSync("src"); @@ -44,7 +48,8 @@ format: "umd" }, name: pascalCase(getUnscopedName(pkg)), - plugins: [plugins.babel, plugins.resolve, plugins.commonjs] + plugins: [plugins.babel, plugins.resolve, plugins.commonjs, plugins.uglify], + sourcemap: true }, ...sources.map(getCjsAndEsConfig) ];
7480df0fd6a00c11045cf0c1523610e611606cfa
test/fixtures/hard/indentation.js
test/fixtures/hard/indentation.js
import styled from 'styled-components' // None of the below should throw indentation errors const Comp = () => { const Button = styled.button` color: blue; ` return Button } const Comp2 = () => { const InnerComp = () => { const Button = styled.button` color: blue; ` return Button } return InnerComp() } const Button = styled.button`color: blue;`
import styled, { keyframes } from 'styled-components' // None of the below should throw indentation errors const Comp = () => { const Button = styled.button` color: blue; ` return Button } const Comp2 = () => { const InnerComp = () => { const Button = styled.button` color: blue; ` return Button } return InnerComp() } const Button = styled.button`color: blue;` const animations = { spinnerCircle: keyframes` 0% { opacity: 0; } 100% { opacity: 1; } ` }
Move wrongly linted animation to hard tests
Move wrongly linted animation to hard tests
JavaScript
mit
styled-components/stylelint-processor-styled-components
--- +++ @@ -1,4 +1,4 @@ -import styled from 'styled-components' +import styled, { keyframes } from 'styled-components' // None of the below should throw indentation errors const Comp = () => { @@ -22,3 +22,15 @@ } const Button = styled.button`color: blue;` + +const animations = { + spinnerCircle: keyframes` + 0% { + opacity: 0; + } + + 100% { + opacity: 1; + } + ` +}
867f920794bbfff30901a187ad39296893df5b59
generators/travis/index.js
generators/travis/index.js
'use strict'; var generators = require('yeoman-generator'); var extend = require('deep-extend'); module.exports = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments); this.option('coveralls', { required: false, defaults: false, desc: 'Use React syntax' }); this.option('testRunner', { required: true, defaults: 'gulp', desc: 'Test runner' }); }, writing: { travisyml: function () { this.fs.copyTpl( this.templatePath('travis.yml'), this.destinationPath('.travis.yml'), { coveralls: this.options.coveralls, testRunner: this.options.testRunner, } ); }, package: function () { var pkg = this.fs.readJSON(this.destinationPath('package.json'), {}); if (this.options.testRunner === 'karma') { extend(pkg, { devDependencies: { scripts: { "test-travis": "karma start --browsers Firefox --single-run", } } }); } else if (this.options.testRunner === 'gulp') { extend(pkg, { devDependencies: { scripts: { "test-travis": "gulp test-travis", } } }); } this.fs.writeJSON(this.destinationPath('package.json'), pkg); } } });
'use strict'; var generators = require('yeoman-generator'); var extend = require('deep-extend'); module.exports = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments); this.option('coveralls', { required: false, defaults: false, desc: 'Use React syntax' }); this.option('testRunner', { required: true, defaults: 'gulp', desc: 'Test runner' }); }, writing: { travisyml: function () { this.fs.copyTpl( this.templatePath('travis.yml'), this.destinationPath('.travis.yml'), { coveralls: this.options.coveralls, testRunner: this.options.testRunner, } ); }, packageJson: function () { var pkg = this.fs.readJSON(this.destinationPath('package.json'), {}); if (this.options.testRunner === 'karma') { extend(pkg, { scripts: { "test-travis": "karma start --single-run", } }); } else if (this.options.testRunner === 'gulp') { extend(pkg, { scripts: { "test-travis": "gulp test-travis", } }); } this.fs.writeJSON(this.destinationPath('package.json'), pkg); } } });
Fix script addition to package.son
Fix script addition to package.son
JavaScript
mit
dmarchena/generator-node-test
--- +++ @@ -31,24 +31,19 @@ ); }, - package: function () { + packageJson: function () { var pkg = this.fs.readJSON(this.destinationPath('package.json'), {}); if (this.options.testRunner === 'karma') { extend(pkg, { - devDependencies: { - scripts: { - "test-travis": "karma start --browsers Firefox --single-run", - } + scripts: { + "test-travis": "karma start --single-run", } }); - } - else if (this.options.testRunner === 'gulp') { + } else if (this.options.testRunner === 'gulp') { extend(pkg, { - devDependencies: { - scripts: { - "test-travis": "gulp test-travis", - } + scripts: { + "test-travis": "gulp test-travis", } }); }
82c98e5bc76ab1235c070e7253acb616e91f4dd7
pwm.js
pwm.js
/* pwm Password Manager Copyright Owen Maule 2015 o@owen-m.com https://github.com/owenmaule/pwm License: GNU Affero General Public License v3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/agpl.html>. */ $( function() { console.log( "pwm Password Manager (c) Copyright Owen Maule 2015 <o@owen-m.com> http://owen-m.com/" ); console.log( "Latest version: https://github.com/owenmaule/pwm Licence: GNU Affero General Public License" ); } );
/* pwm Password Manager Copyright Owen Maule 2015 o@owen-m.com https://github.com/owenmaule/pwm License: GNU Affero General Public License v3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/agpl.html>. */ $( function() { console.log( "pwm Password Manager (c) Copyright Owen Maule 2015 <o@owen-m.com> http://owen-m.com/" ); console.log( "Latest version: https://github.com/owenmaule/pwm Licence: GNU Affero General Public License" ); if( debugToConsole ) { // Transfer debug alerts to console $( "#alert .alert-debug" ).each( function() { console.log( 'debug: ' + $( this ).html() ); $( this ).hide(); } ); } } );
Copy debug alerts to browser console if flag set
Copy debug alerts to browser console if flag set
JavaScript
agpl-3.0
owenmaule/pwm,owenmaule/pwm
--- +++ @@ -23,4 +23,11 @@ $( function() { console.log( "pwm Password Manager (c) Copyright Owen Maule 2015 <o@owen-m.com> http://owen-m.com/" ); console.log( "Latest version: https://github.com/owenmaule/pwm Licence: GNU Affero General Public License" ); + if( debugToConsole ) + { // Transfer debug alerts to console + $( "#alert .alert-debug" ).each( function() { + console.log( 'debug: ' + $( this ).html() ); + $( this ).hide(); + } ); + } } );
657eb96720524a1ee4656f7bf3889cba05ef2f62
lib/assets/seeders/skeleton.js
lib/assets/seeders/skeleton.js
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkInsert('Person', [{ name: 'John Doe', isBetaMember: false }]); */ }, down: function (queryInterface, Sequelize) { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('Person', null, {}); */ } };
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkInsert('Person', [{ name: 'John Doe', isBetaMember: false }], {}); */ }, down: function (queryInterface, Sequelize) { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('Person', null, {}); */ } };
Add options object to seed template
[Changed] Add options object to seed template
JavaScript
mit
xpepermint/cli,martinLE/cli,Americas/cli,Americas/cli,Americas/cli,martinLE/cli,cogpie/cli,sequelize/cli,sequelize/cli,martinLE/cli,brad-decker/cli,sequelize/cli,brad-decker/cli,brad-decker/cli,timrourke/cli
--- +++ @@ -10,7 +10,7 @@ return queryInterface.bulkInsert('Person', [{ name: 'John Doe', isBetaMember: false - }]); + }], {}); */ },
09e4dca1919431a57d7c767cdc35826c9b58f59a
addon/components/rl-dropdown-toggle.js
addon/components/rl-dropdown-toggle.js
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['rl-dropdown-toggle'], tagName: 'button', attributeBindings: ['type'], type: 'button', targetObject: function () { return this.get('parentView'); }.property('parentView'), action: 'toggleDropdown', click: function () { this.sendAction(); } });
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['rl-dropdown-toggle'], tagName: 'button', attributeBindings: ['type'], type: function () { return this.get('tagName') === 'button' ? 'button' : null; }.property('tagName'), targetObject: function () { return this.get('parentView'); }.property('parentView'), action: 'toggleDropdown', click: function () { this.sendAction(); } });
Add type=button only for button tagged dropdown toggles (not for eg. a tags)
Add type=button only for button tagged dropdown toggles (not for eg. a tags)
JavaScript
mit
RSSchermer/ember-rl-dropdown,RSSchermer/ember-rl-dropdown
--- +++ @@ -7,7 +7,9 @@ attributeBindings: ['type'], - type: 'button', + type: function () { + return this.get('tagName') === 'button' ? 'button' : null; + }.property('tagName'), targetObject: function () { return this.get('parentView');
2c54da703ecbab8c03498b08230ac803bf099249
src/files/scripts/disqus.js
src/files/scripts/disqus.js
var disqus_shortname = 'jtwebman'; (function () { 'use strict'; var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); }());
var disqus_shortname = 'jtwebman'; (function () { 'use strict'; var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; dsq.setAttribute('data-cfasync', 'false'); (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); }());
Add cloudflare Rocket Fix Try 1
Add cloudflare Rocket Fix Try 1
JavaScript
mit
jtwebman/jtwebman
--- +++ @@ -6,5 +6,6 @@ dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; + dsq.setAttribute('data-cfasync', 'false'); (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); }());
406d0c78c8112f464f05951c2182833c6ae566c9
src/data/post.js
src/data/post.js
'use strict'; import { importEntities, validateEntities } from './base'; import { schema } from '../schema/post'; export function importData (entries, space, contentType, data) { validateEntities(data.posts || [], 'post', schema()); return importEntities(...arguments, 'post', mapData); } function mapData (post) { return { sys: { id: post.slug }, fields: { title: { 'en-US': post.title }, slug: { 'en-US': post.slug }, body: { 'en-US': post.body }, publishedAt: { 'en-US': post.publishedAt }, metaTitle: { 'en-US': post.metaTitle }, metaDescription: { 'en-US': post.metaDescription }, author: { 'en-US': getAuthor(post) }, tags: { 'en-US': getTags(post) } } }; } function getTags (post) { return post.tags.map((tagSlug) => { return { sys: { type: 'Link', linkType: 'Entry', id: tagSlug } }; }); } function getAuthor (post) { return { sys: { type: 'Link', linkType: 'Entry', id: post.author } }; }
'use strict'; import { importEntities, validateEntities } from './base'; import { schema } from '../schema/post'; export function importData (entries, space, contentType, data) { validateEntities(data.posts || [], 'post', schema()); return importEntities(...arguments, 'post', mapData); } function mapData (post) { return { sys: { id: post.slug }, fields: { title: { 'en-US': post.title }, slug: { 'en-US': post.slug }, body: { 'en-US': post.body }, publishedAt: { 'en-US': post.publishedAt }, metaTitle: { 'en-US': post.metaTitle }, metaDescription: { 'en-US': post.metaDescription }, author: { 'en-US': getAuthor(post) }, tags: { 'en-US': getTags(post) } } }; } function getTags (post) { return (post.tags || []).map((tagSlug) => { return { sys: { type: 'Link', linkType: 'Entry', id: tagSlug } }; }); } function getAuthor (post) { return { sys: { type: 'Link', linkType: 'Entry', id: post.author } }; }
Fix handling of undefined tags
Fix handling of undefined tags
JavaScript
mit
sdepold/contentful-blog-importer
--- +++ @@ -25,7 +25,7 @@ } function getTags (post) { - return post.tags.map((tagSlug) => { + return (post.tags || []).map((tagSlug) => { return { sys: { type: 'Link', linkType: 'Entry', id: tagSlug } }; }); }
20390640e1ba92f6bd52ce14b9e06f0dd241badc
apis/reports.es6.js
apis/reports.es6.js
import BaseAPI from './base.es6.js'; import Report from '../models/report.es6.js'; export default class Reports extends BaseAPI { model = Report; move = this.notImplemented('move'); copy = this.notImplemented('copy'); get = this.notImplemented('get'); put = this.notImplemented('put'); patch = this.notImplemented('patch'); del = this.notImplemented('del'); path() { return 'api/report'; } post(data) { return super.post({ ...data, reason: 'other', api_type: 'json', }); } }
import BaseAPI from './base.es6.js'; import Report from '../models/report.es6.js'; export default class Reports extends BaseAPI { model = Report; move = this.notImplemented('move'); copy = this.notImplemented('copy'); get = this.notImplemented('get'); put = this.notImplemented('put'); patch = this.notImplemented('patch'); del = this.notImplemented('del'); path() { return 'api/report'; } post(data) { return super.post({ ...data, reason: 'other', api_type: 'json', }); }
Make Reports return a promise as expected
Make Reports return a promise as expected
JavaScript
mit
reddit/node-api-client,reddit/snoode
--- +++ @@ -21,5 +21,4 @@ reason: 'other', api_type: 'json', }); - } }
02b45d28bfec3ab4573762aeb6813ded9e9e0286
lib/post_install.js
lib/post_install.js
// adapted based on rackt/history (MIT) // Node 0.12+ var execSync = require('child_process').execSync; var stat = require('fs').stat; function exec(command) { execSync(command, { stdio: [0, 1, 2] }); } stat('dist-modules', function(error, stat) { if (error || !stat.isDirectory()) { exec('npm i babel'); exec('npm run dist-modules'); } });
// adapted based on rackt/history (MIT) // Node 0.12+ var execSync = require('child_process').execSync; var stat = require('fs').stat; function exec(command) { execSync(command, { stdio: [0, 1, 2] }); } stat('dist-modules', function(error, stat) { if (error || !stat.isDirectory()) { exec('npm i babel@5.x'); exec('npm run dist-modules'); } });
Install Babel 5 on postinstall
Install Babel 5 on postinstall Babel 6 will fail.
JavaScript
mit
austinsc/react-gooey,austinsc/react-gooey
--- +++ @@ -11,7 +11,7 @@ stat('dist-modules', function(error, stat) { if (error || !stat.isDirectory()) { - exec('npm i babel'); + exec('npm i babel@5.x'); exec('npm run dist-modules'); } });
ec77870dcd8bc0286dded116a04b44ee0f910f39
app/controllers/application.js
app/controllers/application.js
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), actions: { login () { var lockOptions = { allowedConnections: [ 'Username-Password-Authentication', ], autoclose: true, allowLogin: true, allowSignUp: false, rememberLastLogin: true, theme: { logo: 'https://s3-us-west-1.amazonaws.com/barberscore/static/images/bhs_logo.png', primaryColor: '#337ab7' }, languageDictionary: { title: "Barberscore" }, auth: { redirect: false, params: { scope: 'openid profile', } } }; this.get('session').authenticate('authenticator:auth0-lock', lockOptions); }, logout () { this.get('session').invalidate(); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), actions: { login () { var lockOptions = { allowedConnections: [ 'Default', ], autoclose: true, allowLogin: true, allowSignUp: false, rememberLastLogin: true, theme: { logo: 'https://s3-us-west-1.amazonaws.com/barberscore/static/images/bhs_logo.png', primaryColor: '#337ab7' }, languageDictionary: { title: "Barberscore" }, auth: { redirect: false, params: { scope: 'openid profile', } } }; this.get('session').authenticate('authenticator:auth0-lock', lockOptions); }, logout () { this.get('session').invalidate(); } } });
Change configuration on production Auth0
Change configuration on production Auth0
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
--- +++ @@ -6,7 +6,7 @@ login () { var lockOptions = { allowedConnections: [ - 'Username-Password-Authentication', + 'Default', ], autoclose: true, allowLogin: true,
18913df91f33250f01da3a178f8816cca7d13db4
src/js/helpers/JSONPUtil.js
src/js/helpers/JSONPUtil.js
import Q from "q"; const JSONPUtil = { /** * Request JSONP data * * @todo: write test to verify this util is working properly * * @param {string} url * @returns {Q.promise} promise */ request(url) { var deferred = Q.defer(); var callback = `jsonp_${Date.now().toString(16)}`; var script = document.createElement("script"); // Add jsonp callback window[callback] = function handleJSONPResponce(data) { if (data != null) { return deferred.resolve(data); } deferred.reject(new Error("Empty response")); }; // Add clean up method script.cleanUp = function () { if (this.parentNode) { this.parentNode.removeChild(script); } }; // Add handler script.onerror = function handleScriptError(error) { script.cleanUp(); deferred.reject(error); }; script.onload = function handleScriptLoad() { script.cleanUp(); }; // Load data script.src = `${url}${ /[?&]/.test(url) ? "&" : "?" }jsonp=${callback}`; document.head.appendChild(script); return deferred.promise; } }; export default JSONPUtil;
const JSONPUtil = { /** * Request JSONP data * * @todo: write test to verify this util is working properly * * @param {string} url * @returns {Promise} promise */ request(url) { return new Promise(function (resolve, reject) { var callback = `jsonp_${Date.now().toString(16)}`; var script = document.createElement("script"); // Add jsonp callback window[callback] = function handleJSONPResponce(data) { if (data != null) { return resolve(data); } reject(new Error("Empty response")); }; // Add clean up method script.cleanUp = function () { if (this.parentNode) { this.parentNode.removeChild(script); } }; // Add handler script.onerror = function handleScriptError(error) { script.cleanUp(); reject(error); }; script.onload = function handleScriptLoad() { script.cleanUp(); }; // Load data script.src = `${url}${ /[?&]/.test(url) ? "&" : "?" }jsonp=${callback}`; document.head.appendChild(script); }); } }; export default JSONPUtil;
Use es6 promises instead of Q
Use es6 promises instead of Q
JavaScript
apache-2.0
cribalik/marathon-ui,cribalik/marathon-ui,mesosphere/marathon-ui,mesosphere/marathon-ui
--- +++ @@ -1,5 +1,3 @@ -import Q from "q"; - const JSONPUtil = { /** * Request JSONP data @@ -7,37 +5,37 @@ * @todo: write test to verify this util is working properly * * @param {string} url - * @returns {Q.promise} promise + * @returns {Promise} promise */ request(url) { - var deferred = Q.defer(); - var callback = `jsonp_${Date.now().toString(16)}`; - var script = document.createElement("script"); - // Add jsonp callback - window[callback] = function handleJSONPResponce(data) { - if (data != null) { - return deferred.resolve(data); - } - deferred.reject(new Error("Empty response")); - }; - // Add clean up method - script.cleanUp = function () { - if (this.parentNode) { - this.parentNode.removeChild(script); - } - }; - // Add handler - script.onerror = function handleScriptError(error) { - script.cleanUp(); - deferred.reject(error); - }; - script.onload = function handleScriptLoad() { - script.cleanUp(); - }; - // Load data - script.src = `${url}${ /[?&]/.test(url) ? "&" : "?" }jsonp=${callback}`; - document.head.appendChild(script); - return deferred.promise; + return new Promise(function (resolve, reject) { + var callback = `jsonp_${Date.now().toString(16)}`; + var script = document.createElement("script"); + // Add jsonp callback + window[callback] = function handleJSONPResponce(data) { + if (data != null) { + return resolve(data); + } + reject(new Error("Empty response")); + }; + // Add clean up method + script.cleanUp = function () { + if (this.parentNode) { + this.parentNode.removeChild(script); + } + }; + // Add handler + script.onerror = function handleScriptError(error) { + script.cleanUp(); + reject(error); + }; + script.onload = function handleScriptLoad() { + script.cleanUp(); + }; + // Load data + script.src = `${url}${ /[?&]/.test(url) ? "&" : "?" }jsonp=${callback}`; + document.head.appendChild(script); + }); } };
89fdc37d358e0a2c15d6b75d7a40d9dd8f19e977
tools/deploy.js
tools/deploy.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import GitRepo from 'git-repository'; import task from './lib/task'; // TODO: Update deployment URL const remote = { name: 'github', url: 'git@github.com:nelseric/fhack.git', branch: 'gh-pages', }; /** * Deploy the contents of the `/build` folder to GitHub Pages. */ export default task(async function deploy() { // Initialize a new Git repository inside the `/build` folder // if it doesn't exist yet const repo = await GitRepo.open('build', { init: true }); await repo.setRemote(remote.name, remote.url); // Fetch the remote repository if it exists if ((await repo.hasRef(remote.url, remote.branch))) { await repo.fetch(remote.name); await repo.reset(`${remote.name}/${remote.branch}`, { hard: true }); await repo.clean({ force: true }); } // Build the project in RELEASE mode which // generates optimized and minimized bundles process.argv.push('release'); await require('./build')(); // Push the contents of the build folder to the remote server via Git await repo.add('--all .'); await repo.commit('Update ' + new Date().toISOString()); await repo.push(remote.name, 'master:' + remote.branch); });
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import GitRepo from 'git-repository'; import task from './lib/task'; // TODO: Update deployment URL const remote = { name: 'github', url: 'git@github.com:nelseric/nelseric.github.io.git', branch: 'master', }; /** * Deploy the contents of the `/build` folder to GitHub Pages. */ export default task(async function deploy() { // Initialize a new Git repository inside the `/build` folder // if it doesn't exist yet const repo = await GitRepo.open('build', { init: true }); await repo.setRemote(remote.name, remote.url); // Fetch the remote repository if it exists if ((await repo.hasRef(remote.url, remote.branch))) { await repo.fetch(remote.name); await repo.reset(`${remote.name}/${remote.branch}`, { hard: true }); await repo.clean({ force: true }); } // Build the project in RELEASE mode which // generates optimized and minimized bundles process.argv.push('release'); await require('./build')(); // Push the contents of the build folder to the remote server via Git await repo.add('--all .'); await repo.commit('Update ' + new Date().toISOString()); await repo.push(remote.name, 'master:' + remote.branch); });
Deploy to my account gh page
Deploy to my account gh page
JavaScript
mit
nelseric/fhack-yo
--- +++ @@ -10,8 +10,8 @@ // TODO: Update deployment URL const remote = { name: 'github', - url: 'git@github.com:nelseric/fhack.git', - branch: 'gh-pages', + url: 'git@github.com:nelseric/nelseric.github.io.git', + branch: 'master', }; /**
83cdb77f02cc4c98d7882468580abb001441d6e6
src/modules/rooms/routes.js
src/modules/rooms/routes.js
(function (angular) { 'use strict'; angular.module('birdyard.rooms') .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/rooms/c/everything', { controller: 'roomsController', templateUrl: 'modules/rooms/views/rooms.html' }); $routeProvider.when('/rooms/c/:category', { controller: 'roomsController', templateUrl: 'modules/rooms/views/rooms.html' }); $routeProvider.when('/rooms/new', { controller: 'newroomController', templateUrl: 'modules/rooms/views/newroom.html' }) $routeProvider.when('/', { redirectTo: '/rooms/c/everything' }); }]); })(angular);
(function (angular) { 'use strict'; angular.module('birdyard.rooms') .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/rooms/c/everything', { controller: 'roomsController', templateUrl: 'modules/rooms/views/rooms.html' }); $routeProvider.when('/rooms/c/:category', { controller: 'roomsController', templateUrl: 'modules/rooms/views/rooms.html' }); $routeProvider.whenAuthenticated('/rooms/new', { controller: 'newroomController', templateUrl: 'modules/rooms/views/newroom.html', resolve: { user: ['$Auth', function ($Auth) { var $auth = $Auth; return $auth.$waitForAuth(); }] } }) $routeProvider.when('/', { redirectTo: '/rooms/c/everything' }); }]); })(angular);
Make "new room" page an authenticated route
Make "new room" page an authenticated route
JavaScript
mit
birdyard/birdyard,birdyard/birdyard,bebopchat/bebop,robotnoises/bebop,bebopchat/bebop,robotnoises/bebop
--- +++ @@ -16,9 +16,15 @@ templateUrl: 'modules/rooms/views/rooms.html' }); - $routeProvider.when('/rooms/new', { + $routeProvider.whenAuthenticated('/rooms/new', { controller: 'newroomController', - templateUrl: 'modules/rooms/views/newroom.html' + templateUrl: 'modules/rooms/views/newroom.html', + resolve: { + user: ['$Auth', function ($Auth) { + var $auth = $Auth; + return $auth.$waitForAuth(); + }] + } }) $routeProvider.when('/', {
99d6b09e651738e29e1f373093f3653043b65573
src/node_main.js
src/node_main.js
var sys = require('sys'), fs = require('fs'), path = require('path'), optparse = require('optparse'); function Options(argv){ var switches = [ [ '--encoding', 'Specify encoding (default: utf8)'], ['-h', '--help', 'Shows help sections'] ]; var parser = new optparse.OptionParser(switches); parser.on('help', function() { sys.puts('Help'); }); this.args = parser.parse(argv); } var opts = new Options(process.argv.slice(2)); var intp = new BiwaScheme.Interpreter(function(e){ sys.puts(Object.inspect(e)); process.exit(1); }); if(opts.args.size() >= 1){ var src = fs.readFileSync(opts.args[0], 'utf8'); intp.evaluate(src); } else{ // TODO repl //sys.print("biwas > "); }
var sys = require('sys'), fs = require('fs'), path = require('path'), optparse = require('optparse'); function Options(argv){ var switches = [ [ '--encoding', 'Specify encoding (default: utf8)'], ['-h', '--help', 'Shows help sections'] ]; var parser = new optparse.OptionParser(switches); parser.on('help', function() { sys.puts('Help'); }); this.args = parser.parse(argv); } var opts = new Options(process.argv.slice(2)); var intp = new BiwaScheme.Interpreter(function(e){ sys.puts(e.stack); process.exit(1); }); if(opts.args.size() >= 1){ var src = fs.readFileSync(opts.args[0], 'utf8'); intp.evaluate(src); } else{ // TODO repl //sys.print("biwas > "); }
Print stacktrace when Biwa crashes in node.js.
Print stacktrace when Biwa crashes in node.js.
JavaScript
mit
biwascheme/biwascheme.github.io,yhara/biwascheme,biwascheme/biwascheme.github.io,biwascheme/biwascheme,biwascheme/biwascheme,biwascheme/biwascheme,yhara/biwascheme
--- +++ @@ -21,7 +21,7 @@ var opts = new Options(process.argv.slice(2)); var intp = new BiwaScheme.Interpreter(function(e){ - sys.puts(Object.inspect(e)); + sys.puts(e.stack); process.exit(1); });
0eefb282ca8a8eddacca6c55c77d1abd51cdb2b2
spec/api-deprecations-spec.js
spec/api-deprecations-spec.js
const assert = require('assert') const deprecations = require('electron').deprecations describe('deprecations', function () { beforeEach(function () { deprecations.setHandler(null) process.throwDeprecation = true }) it('allows a deprecation handler function to be specified', function () { var messages = [] deprecations.setHandler(function (message) { messages.push(message) }) require('electron').deprecate.log('this is deprecated') assert.deepEqual(messages, ['this is deprecated']) }) it('throws an exception if no deprecation handler is specified', function () { assert.throws(function () { require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme') }, 'registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead.') }) })
const assert = require('assert') const deprecations = require('electron').deprecations describe('deprecations', function () { beforeEach(function () { deprecations.setHandler(null) process.throwDeprecation = true }) it('allows a deprecation handler function to be specified', function () { var messages = [] deprecations.setHandler(function (message) { messages.push(message) }) require('electron').deprecate.log('this is deprecated') assert.deepEqual(messages, ['this is deprecated']) }) it('throws an exception if no deprecation handler is specified', function () { assert.throws(function () { require('electron').deprecate.log('this is deprecated') }, /this is deprecated/) }) })
Test no handler via call to deprecate.log
Test no handler via call to deprecate.log
JavaScript
mit
kcrt/electron,the-ress/electron,brave/electron,thomsonreuters/electron,miniak/electron,renaesop/electron,tonyganch/electron,brave/muon,brave/electron,gerhardberger/electron,voidbridge/electron,MaxWhere/electron,rajatsingla28/electron,noikiy/electron,jhen0409/electron,gabriel/electron,thompsonemerson/electron,rreimann/electron,brave/muon,voidbridge/electron,tonyganch/electron,tonyganch/electron,renaesop/electron,noikiy/electron,aliib/electron,Gerhut/electron,minggo/electron,shiftkey/electron,aichingm/electron,MaxWhere/electron,shiftkey/electron,seanchas116/electron,aichingm/electron,shiftkey/electron,miniak/electron,kokdemo/electron,brave/muon,posix4e/electron,tinydew4/electron,brave/electron,the-ress/electron,brenca/electron,MaxWhere/electron,seanchas116/electron,jhen0409/electron,aliib/electron,biblerule/UMCTelnetHub,tonyganch/electron,twolfson/electron,deed02392/electron,brave/electron,miniak/electron,tinydew4/electron,rreimann/electron,preco21/electron,minggo/electron,preco21/electron,electron/electron,aliib/electron,leethomas/electron,electron/electron,rreimann/electron,rajatsingla28/electron,biblerule/UMCTelnetHub,dongjoon-hyun/electron,kokdemo/electron,thompsonemerson/electron,joaomoreno/atom-shell,leethomas/electron,the-ress/electron,aichingm/electron,aliib/electron,brenca/electron,kcrt/electron,brenca/electron,miniak/electron,stevekinney/electron,thompsonemerson/electron,minggo/electron,biblerule/UMCTelnetHub,bbondy/electron,rajatsingla28/electron,brenca/electron,bpasero/electron,Gerhut/electron,renaesop/electron,dongjoon-hyun/electron,voidbridge/electron,brave/muon,twolfson/electron,gabriel/electron,posix4e/electron,rreimann/electron,rreimann/electron,noikiy/electron,wan-qy/electron,shiftkey/electron,gabriel/electron,stevekinney/electron,bbondy/electron,gerhardberger/electron,aliib/electron,bpasero/electron,dongjoon-hyun/electron,minggo/electron,MaxWhere/electron,thomsonreuters/electron,Floato/electron,aliib/electron,tinydew4/electron,renaesop/electron,brave/electron,deed02392/electron,leethomas/electron,miniak/electron,seanchas116/electron,thomsonreuters/electron,posix4e/electron,the-ress/electron,thomsonreuters/electron,the-ress/electron,gabriel/electron,tinydew4/electron,tinydew4/electron,joaomoreno/atom-shell,brave/electron,wan-qy/electron,deed02392/electron,aichingm/electron,kokdemo/electron,kokdemo/electron,posix4e/electron,twolfson/electron,thomsonreuters/electron,kcrt/electron,brenca/electron,deed02392/electron,Gerhut/electron,shiftkey/electron,shiftkey/electron,seanchas116/electron,noikiy/electron,kokdemo/electron,bbondy/electron,preco21/electron,tinydew4/electron,brave/muon,Gerhut/electron,gerhardberger/electron,bpasero/electron,the-ress/electron,noikiy/electron,dongjoon-hyun/electron,rajatsingla28/electron,minggo/electron,renaesop/electron,gabriel/electron,stevekinney/electron,tonyganch/electron,bpasero/electron,gerhardberger/electron,jhen0409/electron,stevekinney/electron,wan-qy/electron,biblerule/UMCTelnetHub,bpasero/electron,jhen0409/electron,leethomas/electron,bbondy/electron,rajatsingla28/electron,noikiy/electron,the-ress/electron,electron/electron,electron/electron,biblerule/UMCTelnetHub,twolfson/electron,leethomas/electron,deed02392/electron,deed02392/electron,MaxWhere/electron,minggo/electron,joaomoreno/atom-shell,rreimann/electron,electron/electron,gerhardberger/electron,twolfson/electron,voidbridge/electron,electron/electron,Gerhut/electron,thompsonemerson/electron,bpasero/electron,Floato/electron,MaxWhere/electron,gerhardberger/electron,bpasero/electron,bbondy/electron,thompsonemerson/electron,posix4e/electron,dongjoon-hyun/electron,biblerule/UMCTelnetHub,kcrt/electron,preco21/electron,Floato/electron,joaomoreno/atom-shell,gabriel/electron,joaomoreno/atom-shell,twolfson/electron,wan-qy/electron,posix4e/electron,jhen0409/electron,aichingm/electron,dongjoon-hyun/electron,kcrt/electron,voidbridge/electron,Gerhut/electron,gerhardberger/electron,miniak/electron,aichingm/electron,stevekinney/electron,rajatsingla28/electron,brenca/electron,leethomas/electron,kokdemo/electron,preco21/electron,jhen0409/electron,electron/electron,thomsonreuters/electron,Floato/electron,Floato/electron,wan-qy/electron,kcrt/electron,voidbridge/electron,Floato/electron,tonyganch/electron,bbondy/electron,seanchas116/electron,thompsonemerson/electron,renaesop/electron,wan-qy/electron,joaomoreno/atom-shell,preco21/electron,seanchas116/electron,stevekinney/electron,brave/muon
--- +++ @@ -21,7 +21,7 @@ it('throws an exception if no deprecation handler is specified', function () { assert.throws(function () { - require('electron').webFrame.registerUrlSchemeAsPrivileged('some-scheme') - }, 'registerUrlSchemeAsPrivileged is deprecated. Use registerURLSchemeAsPrivileged instead.') + require('electron').deprecate.log('this is deprecated') + }, /this is deprecated/) }) })
f6465abae47d69e2941e9640930a9e6d13035679
spec/unpoly/framework_spec.js
spec/unpoly/framework_spec.js
const u = up.util const $ = jQuery describe('up.framework', function() { describe('JavaScript functions', function() { describe('up.framework.isSupported', function() { it('returns true on a supported browser', function() { expect(up.framework.isSupported()).toBe(true) }) it('returns false if window.Promise is missing', function() { // Cannot use spyOnProperty() for window.Promise, as window does not return a property descriptor. let oldPromise = window.Promise try { window.Promise = undefined expect(up.framework.isSupported()).toBe(false) } finally { window.Promise = oldPromise } }) it('returns false if the document is missing a DOCTYPE, triggering quirks mode', function() { // Cannot use spyOnProperty() for document.compatMode, as document does not return a property descriptor. let oldCompatMode = document.compatMode try { // Quirks mode is "BackCompat". Standards mode is "CSS1Compat". Object.defineProperty(document, 'compatMode', { value: 'BackCompat' }) expect(up.framework.isSupported()).toBe(false) } finally { document.compatMode = oldCompatMode } }) }) }) })
const u = up.util const $ = jQuery describe('up.framework', function() { describe('JavaScript functions', function() { describe('up.framework.isSupported', function() { it('returns true on a supported browser', function() { expect(up.framework.isSupported()).toBe(true) }) it('returns false if window.Promise is missing', function() { // Cannot use spyOnProperty() for window.Promise, as window does not return a property descriptor. let oldPromise = window.Promise try { window.Promise = undefined expect(up.framework.isSupported()).toBe(false) } finally { window.Promise = oldPromise } }) it('returns false if the document is missing a DOCTYPE, triggering quirks mode', function() { // Cannot use spyOnProperty() for document.compatMode, as document does not return a property descriptor. let oldCompatMode = document.compatMode expect(oldCompatMode).toEqual('CSS1Compat') try { // Quirks mode is "BackCompat". Standards mode is "CSS1Compat". Object.defineProperty(document, 'compatMode', { value: 'BackCompat', configurable: true }) expect(up.framework.isSupported()).toBe(false) } finally { Object.defineProperty(document, 'compatMode', { value: oldCompatMode, configurable: true }) // Make sure we cleaned up correctly expect(document.compatMode).toEqual(oldCompatMode) } }) }) }) })
Fix spec leaving browser in mocked quirks mode
Fix spec leaving browser in mocked quirks mode
JavaScript
mit
unpoly/unpoly,unpoly/unpoly,unpoly/unpoly
--- +++ @@ -25,12 +25,15 @@ it('returns false if the document is missing a DOCTYPE, triggering quirks mode', function() { // Cannot use spyOnProperty() for document.compatMode, as document does not return a property descriptor. let oldCompatMode = document.compatMode + expect(oldCompatMode).toEqual('CSS1Compat') try { // Quirks mode is "BackCompat". Standards mode is "CSS1Compat". - Object.defineProperty(document, 'compatMode', { value: 'BackCompat' }) + Object.defineProperty(document, 'compatMode', { value: 'BackCompat', configurable: true }) expect(up.framework.isSupported()).toBe(false) } finally { - document.compatMode = oldCompatMode + Object.defineProperty(document, 'compatMode', { value: oldCompatMode, configurable: true }) + // Make sure we cleaned up correctly + expect(document.compatMode).toEqual(oldCompatMode) } })
72d6339df3fce22422bec835bddbc9e3efb47cb4
simpleshelfmobile/_attachments/code/views/PageView.js
simpleshelfmobile/_attachments/code/views/PageView.js
/** * Page view constructor * Handles all jQuery Mobile setup for any sub-classed page. */ define([ "backbone" ], function(Backbone) { var PageView = Backbone.View.extend({ tagName: "div", isInDOM: false, _name: null, getName: function() { return this._name; }, postRender: function() { this.isInDOM = true; return this; }, render: function() { if (this.isInDOM) { console.warn(this.getName() + " already in DOM."); } else { if (this.model) { this.$el.html(this.template(this.model.attributes)); } else { this.$el.html(this.template()); } // Set jQuery Mobile attributes here. this.$el.attr("data-role", "page"); // Append to body. $("body").append(this.$el); } return this; } }); return PageView; });
/** * Page view constructor * Handles all jQuery Mobile setup for any sub-classed page. */ define([ "backbone" ], function(Backbone) { var PageView = Backbone.View.extend({ tagName: "div", isInDOM: false, _name: null, getName: function() { return this._name; }, postRender: function() { this.isInDOM = true; return this; }, render: function() { if (this.isInDOM) { console.warn(this.getName() + " already in DOM."); } else { if (this.model) { this.$el.html(this.template(this.model.toJSON())); } else { this.$el.html(this.template()); } // Set jQuery Mobile attributes here. this.$el.attr("data-role", "page"); // Append to body. $("body").append(this.$el); } return this; } }); return PageView; });
Switch to toJSON to pull data from models
Switch to toJSON to pull data from models Allows for simpler customization of data.
JavaScript
agpl-3.0
tephyr/simpleshelf,tephyr/simpleshelf,tephyr/simpleshelf,tephyr/simpleshelf
--- +++ @@ -24,7 +24,7 @@ console.warn(this.getName() + " already in DOM."); } else { if (this.model) { - this.$el.html(this.template(this.model.attributes)); + this.$el.html(this.template(this.model.toJSON())); } else { this.$el.html(this.template()); }
fc41731cd9c82b44d7cb9c6dce0bd33596bba2c7
src/bootstrap/package-json.js
src/bootstrap/package-json.js
import { join } from 'path' import json from '../util/json' const saguiScripts = { 'start': 'npm run develop', 'test': 'sagui test', 'test-watch': 'sagui test --watch', 'develop': 'sagui develop', 'build': 'sagui build', 'dist': 'NODE_ENV=production sagui dist' } export default function (projectPath) { const packagePath = join(projectPath, 'package.json') const packageJSON = json.read(packagePath) json.write(packagePath, { ...packageJSON, scripts: { ...saguiScripts, ...withoutDefaults(packageJSON.scripts) } }) } /** * Remove default configurations generated by NPM that can be overwriten * We don't want to overwrite any user configured scripts */ function withoutDefaults (scripts) { const defaultScripts = { 'test': 'echo \"Error: no test specified\" && exit 1' } return Object.keys(scripts) .filter((key) => !scripts[key] !== '' && scripts[key] !== defaultScripts[key]) .reduce((filtered, key) => { return { ...filtered, [key]: scripts[key] } }, {}) }
import { join } from 'path' import json from '../util/json' const saguiScripts = { 'start': 'npm run develop', 'test': 'NODE_ENV=test sagui test', 'test-watch': 'NODE_ENV=test sagui test --watch', 'develop': 'sagui develop', 'build': 'sagui build', 'dist': 'NODE_ENV=production sagui dist' } export default function (projectPath) { const packagePath = join(projectPath, 'package.json') const packageJSON = json.read(packagePath) json.write(packagePath, { ...packageJSON, scripts: { ...saguiScripts, ...withoutDefaults(packageJSON.scripts) } }) } /** * Remove default configurations generated by NPM that can be overwriten * We don't want to overwrite any user configured scripts */ function withoutDefaults (scripts) { const defaultScripts = { 'test': 'echo \"Error: no test specified\" && exit 1' } return Object.keys(scripts) .filter((key) => !scripts[key] !== '' && scripts[key] !== defaultScripts[key]) .reduce((filtered, key) => { return { ...filtered, [key]: scripts[key] } }, {}) }
Add NODE_ENV on test scripts
Add NODE_ENV on test scripts
JavaScript
mit
saguijs/sagui,saguijs/sagui
--- +++ @@ -3,8 +3,8 @@ const saguiScripts = { 'start': 'npm run develop', - 'test': 'sagui test', - 'test-watch': 'sagui test --watch', + 'test': 'NODE_ENV=test sagui test', + 'test-watch': 'NODE_ENV=test sagui test --watch', 'develop': 'sagui develop', 'build': 'sagui build', 'dist': 'NODE_ENV=production sagui dist'
7b2b8101d99f60c6b60bd04c1a290e40b6357254
noita/javascript.js
noita/javascript.js
--- --- $(document).foundation(); {% for javascript in site.noita.javascripts %} {% include javascript %} {% endfor %}
--- --- {% for javascript in site.noita.javascripts %} {% include javascript %} {% endfor %} $(document).foundation();
Move foundation start to the end
Move foundation start to the end
JavaScript
mit
remy-actual/remy-actual.github.io,rootandflow/old.rootandflow.com,thehammar/thehammar.github.io,remy-actual/remy-actual.github.io,rootandflow/old.rootandflow.com,inlandsplash/inlandsplash.github.io,rootandflow/rootandflow.github.io,inlandsplash/inlandsplash.github.io,mariagwyn/jekyll-noita,inlandsplash/inlandsplash.github.io,penibelst/jekyll-noita,mariagwyn/jekyll-noita,rootandflow/rootandflow.github.io,thehammar/thehammar.github.io,carlseibert/carlseibert.github.io,manimejia/manimejia.github.io,thehammar/thehammar.github.io,manimejia/manimejia.github.io,rootandflow/rootandflow.github.io,carlseibert/carlseibert.github.io,manimejia/manimejia.github.io,inlandsplash/staging.inlandsplash.org,rootandflow/old.rootandflow.com,inlandsplash/staging.inlandsplash.org
--- +++ @@ -1,8 +1,8 @@ --- --- - -$(document).foundation(); {% for javascript in site.noita.javascripts %} {% include javascript %} {% endfor %} + +$(document).foundation();
6dee47bf20ddcbcee0e757725f300ae3ca8f91db
src/quailBuild.js
src/quailBuild.js
#!/usr/bin/env node --harmony 'use strict'; const path = require('path'); const configUtil = require('./config'); const cwd = process.cwd(); const quailCore = require(path.join(cwd, 'node_modules', '@quailjs/quail-core')); module.exports = function quailBuild () { // Get a list of assessments. configUtil.getLocalConfig(function (data) { quailCore.build(data); }); };
#!/usr/bin/env node --harmony 'use strict'; const path = require('path'); const configUtil = require('./config'); const cwd = process.cwd(); module.exports = function quailBuild () { const quailCore = require( path.join(cwd, 'node_modules', '@quailjs/quail-core') ); // Get a list of assessments. configUtil.getLocalConfig(function (data) { quailCore.build(data); }); };
Move the quail-core require into the build method
Move the quail-core require into the build method
JavaScript
mit
quailjs/quail-cli
--- +++ @@ -5,9 +5,11 @@ const path = require('path'); const configUtil = require('./config'); const cwd = process.cwd(); -const quailCore = require(path.join(cwd, 'node_modules', '@quailjs/quail-core')); module.exports = function quailBuild () { + const quailCore = require( + path.join(cwd, 'node_modules', '@quailjs/quail-core') + ); // Get a list of assessments. configUtil.getLocalConfig(function (data) { quailCore.build(data);
5ed795207a690f729c4fa04c5894adc17f2f7bc7
src/containers/App.js
src/containers/App.js
// This file bootstraps the app with the boilerplate necessary // to support hot reloading in Redux import React, {PropTypes} from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import FuelSavingsApp from '../components/FuelSavingsApp'; import * as FuelSavingsActions from '../actions/fuelSavingsActions'; import DevTools from './DevTools'; class App extends React.Component { render() { const { fuelSavingsAppState, actions } = this.props; return ( <div> <FuelSavingsApp fuelSavingsAppState={fuelSavingsAppState} actions={actions} /> </div> ); } } App.propTypes = { actions: PropTypes.object.isRequired, fuelSavingsAppState: PropTypes.object.isRequired }; function mapStateToProps(state) { return { fuelSavingsAppState: state.fuelSavingsAppState }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(FuelSavingsActions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(App);
// This file bootstraps the app with the boilerplate necessary // to support hot reloading in Redux import React, {PropTypes} from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import FuelSavingsApp from '../components/FuelSavingsApp'; import * as FuelSavingsActions from '../actions/fuelSavingsActions'; class App extends React.Component { render() { const { fuelSavingsAppState, actions } = this.props; return ( <div> <FuelSavingsApp fuelSavingsAppState={fuelSavingsAppState} actions={actions} /> </div> ); } } App.propTypes = { actions: PropTypes.object.isRequired, fuelSavingsAppState: PropTypes.object.isRequired }; function mapStateToProps(state) { return { fuelSavingsAppState: state.fuelSavingsAppState }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(FuelSavingsActions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(App);
Fix no need to always import DevTools component.
Fix no need to always import DevTools component.
JavaScript
mit
barrystaes/react-trebuchet,barrystaes/react-trebuchet
--- +++ @@ -5,7 +5,6 @@ import { connect } from 'react-redux'; import FuelSavingsApp from '../components/FuelSavingsApp'; import * as FuelSavingsActions from '../actions/fuelSavingsActions'; -import DevTools from './DevTools'; class App extends React.Component { render() {
d9bbd11b08973865e288102114de7523d5f78768
packages/truffle/lib/init.js
packages/truffle/lib/init.js
var copy = require("./copy"); var path = require("path"); var temp = require("temp").track(); var Config = require("./config"); var Init = function(destination, callback) { var example_directory = path.resolve(path.join(__dirname, "..", "example")); copy(example_directory, destination, callback); } Init.sandbox = function(callback) { var self = this; temp.mkdir("truffle-sandbox-", function(err, dirPath) { if (err) return callback(err); Init(dirPath, function(err) { if (err) return callback(err); var config = Config.load(path.join(dirPath, "truffle.js")); callback(null, config); }); }); }; module.exports = Init;
var copy = require("./copy"); var path = require("path"); var temp = require("temp").track(); var Config = require("./config"); var Init = function(destination, callback) { var example_directory = path.resolve(path.join(__dirname, "..", "example")); copy(example_directory, destination, callback); } Init.sandbox = function(extended_config, callback) { var self = this; extended_config = extended_config || {} temp.mkdir("truffle-sandbox-", function(err, dirPath) { if (err) return callback(err); Init(dirPath, function(err) { if (err) return callback(err); var config = Config.load(path.join(dirPath, "truffle.js"), extended_config); callback(null, config); }); }); }; module.exports = Init;
Make Init.sandbox() take an input configuration.
Make Init.sandbox() take an input configuration.
JavaScript
mit
ConsenSys/truffle
--- +++ @@ -8,15 +8,17 @@ copy(example_directory, destination, callback); } -Init.sandbox = function(callback) { +Init.sandbox = function(extended_config, callback) { var self = this; + extended_config = extended_config || {} + temp.mkdir("truffle-sandbox-", function(err, dirPath) { if (err) return callback(err); Init(dirPath, function(err) { if (err) return callback(err); - var config = Config.load(path.join(dirPath, "truffle.js")); + var config = Config.load(path.join(dirPath, "truffle.js"), extended_config); callback(null, config); }); });
d13199ba65acdbf7f6e2bca4f37c71958cbf349c
test/runner-core.js
test/runner-core.js
var EventEmitter = require('events').EventEmitter; var nodeunit = require('nodeunit'); var assert = require('nodeunit/lib/assert'); assert.equal = function equal(actual, expected, message) { if (actual != expected) { if (actual && actual.nodeType) { actual = actual.toString(); } if (expected && expected.nodeType) { expected = expected.toString(); } assert.fail(actual, expected, message, '==', assert.equal); } }; assert.domSame = function(actual, expected, message) { if(expected != actual) { assert.equal(expected.nodeType, actual.nodeType); assert.equal(expected.nodeValue, actual.nodeValue); } }; module.exports = function runModules(toRun) { var emitter = new EventEmitter(); process.nextTick(function () { nodeunit.runModules(toRun, { moduleStart: function (name) { emitter.emit('moduleStart', name); }, moduleDone: function (name, assertions) { emitter.emit('moduleDone', name, assertions); }, testStart: function (name) { emitter.emit('testStart', name); }, testReady: function (name) { emitter.emit('testReady', name); }, testDone: function (test, assertions) { emitter.emit('testDone', test, assertions); }, log: function (assertion) { emitter.emit('log', assertion); }, done: function (assertions) { emitter.emit('done', assertions); } }); }); return emitter; };
var EventEmitter = require('events').EventEmitter; var nodeunit = require('nodeunit'); module.exports = function runModules(toRun) { var emitter = new EventEmitter(); process.nextTick(function () { nodeunit.runModules(toRun, { moduleStart: function (name) { emitter.emit('moduleStart', name); }, moduleDone: function (name, assertions) { emitter.emit('moduleDone', name, assertions); }, testStart: function (name) { emitter.emit('testStart', name); }, testReady: function (name) { emitter.emit('testReady', name); }, testDone: function (test, assertions) { emitter.emit('testDone', test, assertions); }, log: function (assertion) { emitter.emit('log', assertion); }, done: function (assertions) { emitter.emit('done', assertions); } }); }); return emitter; };
Remove monkey patches of the unit tester
Remove monkey patches of the unit tester
JavaScript
mit
nicolashenry/jsdom,Sebmaster/jsdom,zaucy/jsdom,danieljoppi/jsdom,kesla/jsdom,tmpvar/jsdom,evdevgit/jsdom,kesla/jsdom,mbostock/jsdom,medikoo/jsdom,aduyng/jsdom,szarouski/jsdom,susaing/jsdom,beni55/jsdom,Ye-Yong-Chi/jsdom,sirbrillig/jsdom,Zirro/jsdom,Sebmaster/jsdom,evdevgit/jsdom,AVGP/jsdom,lcstore/jsdom,zaucy/jsdom,mzgol/jsdom,darobin/jsdom,Ye-Yong-Chi/jsdom,robertknight/jsdom,szarouski/jsdom,Ye-Yong-Chi/jsdom,kevinold/jsdom,kittens/jsdom,crealogix/jsdom,darobin/jsdom,AVGP/jsdom,sirbrillig/jsdom,AshCoolman/jsdom,crealogix/jsdom,evanlucas/jsdom,medikoo/jsdom,mbostock/jsdom,kittens/jsdom,evdevgit/jsdom,susaing/jsdom,Zirro/jsdom,jeffcarp/jsdom,snuggs/jsdom,janusnic/jsdom,jeffcarp/jsdom,fiftin/jsdom,beni55/jsdom,kevinold/jsdom,aduyng/jsdom,selam/jsdom,tmpvar/jsdom,kesla/jsdom,Joris-van-der-Wel/jsdom,aduyng/jsdom,darobin/jsdom,selam/jsdom,janusnic/jsdom,medikoo/jsdom,selam/jsdom,sebmck/jsdom,danieljoppi/jsdom,szarouski/jsdom,vestineo/jsdom,Sebmaster/jsdom,kevinold/jsdom,danieljoppi/jsdom,cpojer/jsdom,sebmck/jsdom,mzgol/jsdom,fiftin/jsdom,nicolashenry/jsdom,cpojer/jsdom,Joris-van-der-Wel/jsdom,vestineo/jsdom,janusnic/jsdom,AshCoolman/jsdom,evanlucas/jsdom,Joris-van-der-Wel/jsdom,lcstore/jsdom,mbostock/jsdom,snuggs/jsdom,evanlucas/jsdom,fiftin/jsdom,susaing/jsdom,kittens/jsdom,nicolashenry/jsdom,jeffcarp/jsdom,beni55/jsdom,sebmck/jsdom,zaucy/jsdom,lcstore/jsdom,sirbrillig/jsdom,cpojer/jsdom,robertknight/jsdom,robertknight/jsdom,mzgol/jsdom,AshCoolman/jsdom,vestineo/jsdom
--- +++ @@ -1,28 +1,5 @@ var EventEmitter = require('events').EventEmitter; var nodeunit = require('nodeunit'); - -var assert = require('nodeunit/lib/assert'); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) { - if (actual && actual.nodeType) { - actual = actual.toString(); - } - - if (expected && expected.nodeType) { - expected = expected.toString(); - } - - assert.fail(actual, expected, message, '==', assert.equal); - } -}; - -assert.domSame = function(actual, expected, message) { - if(expected != actual) { - assert.equal(expected.nodeType, actual.nodeType); - assert.equal(expected.nodeValue, actual.nodeValue); - } -}; module.exports = function runModules(toRun) { var emitter = new EventEmitter();
db407b1d236f05921ada01645f025921e9ec7614
adapters/generic.js
adapters/generic.js
/** * Basic engine support. */ require('../lib/setModuleDefaults'); var config = require('config'); var engineConfig = config.engines ? config.engines : undefined; /** * Return a function that creates a plugin: */ module.exports = function(language){ return { attach: function (/* options */){ /** * If there is a specified engine for this language then use it, * otherwise just use the provided name: */ var module = (engineConfig && engineConfig[language]) ? engineConfig[language].module : language; this.engine = require(module); /** * Add key methods: */ this.__express = this.engine.__express || undefined; this.renderFile = this.engine.renderFile || undefined; } , name: 'adapter-' + language }; };
/** * Basic engine support. */ require('../lib/setModuleDefaults'); var config = require('config'); var engineConfig = config.engines || {}; /** * Return a function that creates a plugin: */ module.exports = function(language){ return { attach: function (/* options */){ var languageConfig = engineConfig[language] || {}; /** * If there is a specified engine for this language then use it, * otherwise just use the provided name: */ this.engine = require(languageConfig.module || language); /** * Add key methods: */ this.__express = this.engine.__express || undefined; this.renderFile = this.engine.renderFile || undefined; } , name: 'adapter-' + language }; };
Allow module value in config to be optional.
Allow module value in config to be optional.
JavaScript
mit
markbirbeck/adapter-template
--- +++ @@ -5,7 +5,7 @@ require('../lib/setModuleDefaults'); var config = require('config'); -var engineConfig = config.engines ? config.engines : undefined; +var engineConfig = config.engines || {}; /** * Return a function that creates a plugin: @@ -14,17 +14,14 @@ module.exports = function(language){ return { attach: function (/* options */){ + var languageConfig = engineConfig[language] || {}; /** * If there is a specified engine for this language then use it, * otherwise just use the provided name: */ - var module = (engineConfig && engineConfig[language]) - ? engineConfig[language].module - : language; - - this.engine = require(module); + this.engine = require(languageConfig.module || language); /** * Add key methods:
f1007ef66ef5ffcacbc5a2b0fbbb4725bc99099b
test/test-suites.js
test/test-suites.js
window.VaadinDatePickerSuites = [ 'basic.html', 'dropdown.html', 'overlay.html', 'month-calendar.html', 'scroller.html', 'form-input.html', 'custom-input.html', 'keyboard-navigation.html', 'keyboard-input.html', 'late-upgrade.html', 'wai-aria.html' ];
const isPolymer2 = document.querySelector('script[src*="wct-browser-legacy"]') === null; window.VaadinDatePickerSuites = [ 'basic.html', 'dropdown.html', 'overlay.html', 'month-calendar.html', 'scroller.html', 'form-input.html', 'custom-input.html', 'keyboard-navigation.html', 'keyboard-input.html', 'wai-aria.html' ]; if (isPolymer2) { window.VaadinDatePickerSuites.push('late-upgrade.html'); }
Exclude tests usinig importHref from Polymer 3
Exclude tests usinig importHref from Polymer 3
JavaScript
apache-2.0
vaadin/vaadin-date-picker,vaadin/vaadin-date-picker
--- +++ @@ -1,3 +1,5 @@ +const isPolymer2 = document.querySelector('script[src*="wct-browser-legacy"]') === null; + window.VaadinDatePickerSuites = [ 'basic.html', 'dropdown.html', @@ -8,6 +10,9 @@ 'custom-input.html', 'keyboard-navigation.html', 'keyboard-input.html', - 'late-upgrade.html', 'wai-aria.html' ]; + +if (isPolymer2) { + window.VaadinDatePickerSuites.push('late-upgrade.html'); +}
4c9e3a410418c864ea94b509d494893bd18393bb
test/testOffline.js
test/testOffline.js
var assert = require('assert'); var fs = require('fs'); var path = require('path'); var temp = require('temp').track(); var offline = require('../lib/offline'); describe('Offline', function() { it('should create offline-worker.js in the destination directory', function() { var dir = temp.mkdirSync('tmp'); return offline({ rootDir: dir, }).then(function() { fs.accessSync(path.join(dir, 'offline-worker.js')); }); }); });
var assert = require('assert'); var fs = require('fs'); var path = require('path'); var temp = require('temp').track(); var offline = require('../lib/offline'); describe('Offline', function() { it('should create offline-worker.js in the destination directory', function() { var dir = temp.mkdirSync('tmp'); return offline({ rootDir: dir, }).then(function() { assert.doesNotThrow(fs.accessSync.bind(fs, path.join(dir, 'offline-worker.js'))); }); }); it('should not fail if the destination directory already contains a offline-worker.js file', function() { var dir = temp.mkdirSync('tmp'); fs.writeFileSync(path.join(dir, 'offline-worker.js'), 'something'); return offline({ rootDir: dir, }).then(function() { var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8'); assert.notEqual(content, 'something'); }); }); });
Test that 'offline' overwrites an already existing offline-worker.js
Test that 'offline' overwrites an already existing offline-worker.js
JavaScript
apache-2.0
mykmelez/oghliner,mozilla/oghliner,mykmelez/oghliner,mozilla/oghliner,marco-c/oghliner,marco-c/oghliner
--- +++ @@ -11,7 +11,20 @@ return offline({ rootDir: dir, }).then(function() { - fs.accessSync(path.join(dir, 'offline-worker.js')); + assert.doesNotThrow(fs.accessSync.bind(fs, path.join(dir, 'offline-worker.js'))); + }); + }); + + it('should not fail if the destination directory already contains a offline-worker.js file', function() { + var dir = temp.mkdirSync('tmp'); + + fs.writeFileSync(path.join(dir, 'offline-worker.js'), 'something'); + + return offline({ + rootDir: dir, + }).then(function() { + var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8'); + assert.notEqual(content, 'something'); }); }); });
452636534735fb807f00d73c1608f97bf40b7025
parse/public/js/MapsService.js
parse/public/js/MapsService.js
angular.module('atlasApp').service('MapsService', function( $scope, $http, LocationProvider, BusInfoProvider ) { return { /** * Initializes the Google Maps canvas */ this.initMap = function () { console.log('Initializing'); var mapOptions = { zoom: 15, center: $scope.mapCenter, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true, }; var mapCanvas = document.getElementById('map-canvas'); $scope.map = new google.maps.Map( mapCanvas, mapOptions ); $scope.locationProvider = new LocationProvider($scope.map); // Instantiating the Bus Info Provider with a map. $scope.busInfoProvider = new BusInfoProvider($scope.map); }; this.plotMarker = function(lat, lng, name) { var position = new google.maps.LatLng(lat, lng); $scope.marker = new google.maps.Marker({ position: position, map: $scope.map, title: name }); $scope.map.setCenter(position); }; /** * Resizes the view to fit within the bounds of the screen. */ this.resizeView = function() { var newHeight = $(window).height() - $('div.navbar').height() - 90 - $('#toolbar').height(); $('#map-canvas').css({height: newHeight}); }; this.clearMap = function() {}; }; });
angular.module('atlasApp').service('MapsService', function( $scope, $http, LocationProvider, BusInfoProvider ) { return { /** * Initializes the Google Maps canvas */ initMap: function () { console.log('Initializing'); var mapOptions = { zoom: 15, center: $scope.mapCenter, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true, }; var mapCanvas = document.getElementById('map-canvas'); $scope.map = new google.maps.Map( mapCanvas, mapOptions ); $scope.locationProvider = new LocationProvider($scope.map); // Instantiating the Bus Info Provider with a map. $scope.busInfoProvider = new BusInfoProvider($scope.map); }; plotMarker: function(lat, lng, name) { var position = new google.maps.LatLng(lat, lng); $scope.marker = new google.maps.Marker({ position: position, map: $scope.map, title: name }); $scope.map.setCenter(position); }; /** * Resizes the view to fit within the bounds of the screen. */ resizeView: function() { var newHeight = $(window).height() - $('div.navbar').height() - 90 - $('#toolbar').height(); $('#map-canvas').css({height: newHeight}); }; clearMap: function() {}; }; });
Fix object notation in service
Fix object notation in service
JavaScript
mit
rice-apps/atlas,rice-apps/atlas,rice-apps/atlas
--- +++ @@ -8,7 +8,7 @@ /** * Initializes the Google Maps canvas */ - this.initMap = function () { + initMap: function () { console.log('Initializing'); var mapOptions = { zoom: 15, @@ -31,7 +31,7 @@ }; - this.plotMarker = function(lat, lng, name) { + plotMarker: function(lat, lng, name) { var position = new google.maps.LatLng(lat, lng); $scope.marker = new google.maps.Marker({ @@ -45,7 +45,7 @@ /** * Resizes the view to fit within the bounds of the screen. */ - this.resizeView = function() { + resizeView: function() { var newHeight = $(window).height() - $('div.navbar').height() @@ -55,7 +55,7 @@ }; - this.clearMap = function() {}; + clearMap: function() {}; }; });
b53cc39e264405e073e842e72cb06a7d0e5726c9
app/initializers/raven-setup.js
app/initializers/raven-setup.js
/* global Raven */ import config from '../config/environment'; import Ember from 'ember'; export function initialize() { // Disable for development if (Ember.get('config.sentry.development') === true) { return; } if (!config.sentry) { throw new Error('`sentry` should be configured when not in development mode.'); } Raven.config(config.sentry.dsn, { release: config.APP.version, whitelistUrls: config.sentry.whitelistUrls }).install(); } export default { name: 'sentry-setup', initialize: initialize };
/* global Raven */ import config from '../config/environment'; import Ember from 'ember'; export function initialize() { // Disable for development if (Ember.get(config, 'sentry.development') === true) { return; } if (!config.sentry) { throw new Error('`sentry` should be configured when not in development mode.'); } Raven.config(config.sentry.dsn, { release: config.APP.version, whitelistUrls: config.sentry.whitelistUrls }).install(); } export default { name: 'sentry-setup', initialize: initialize };
Fix a broken Ember.get call
Fix a broken Ember.get call
JavaScript
mit
pifantastic/ember-cli-sentry,dschmidt/ember-cli-sentry,damiencaselli/ember-cli-sentry,damiencaselli/ember-cli-sentry,pifantastic/ember-cli-sentry,dschmidt/ember-cli-sentry
--- +++ @@ -5,7 +5,8 @@ export function initialize() { // Disable for development - if (Ember.get('config.sentry.development') === true) { + + if (Ember.get(config, 'sentry.development') === true) { return; }
3c0b367aab0d2574a42897f908a57f66a41398be
app/models/user.server.model.js
app/models/user.server.model.js
/** * Created by vinichenkosa on 05.03.15. */ var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ firstName: String, lastName: String, email: String, username: String, password: String }); mongoose.model('User', UserSchema);
/** * Created by vinichenkosa on 05.03.15. */ var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ firstName: String, lastName: String, email: { type: String, index: true }, username: { type: String, trim: true, unique: true }, password: String, created: { type: Date, default: Date.now() }, website: { type: String, get: function (url) { if (url && url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) { url = "http://" + url; } return url; } } }); //virtual fields UserSchema.virtual('fullName').get(function () { return this.firstName + ' ' + this.lastName; }); UserSchema.set('toJSON', {getters: true, virtuals: true}); mongoose.model('User', UserSchema);
Add get and set modifiers Add virtual fields
Add get and set modifiers Add virtual fields
JavaScript
mit
winechess/MEAN
--- +++ @@ -7,9 +7,37 @@ var UserSchema = new Schema({ firstName: String, lastName: String, - email: String, - username: String, - password: String + email: { + type: String, + index: true + }, + username: { + type: String, + trim: true, + unique: true + }, + password: String, + created: { + type: Date, + default: Date.now() + }, + website: { + type: String, + get: function (url) { + + if (url && url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) { + url = "http://" + url; + } + return url; + } + } + +}); +//virtual fields +UserSchema.virtual('fullName').get(function () { + return this.firstName + ' ' + this.lastName; }); +UserSchema.set('toJSON', {getters: true, virtuals: true}); + mongoose.model('User', UserSchema);
49370f227a106c43129c23a6a30a91b5a82e9ad6
src/server/gqlUpdateSchema.js
src/server/gqlUpdateSchema.js
import fs from 'fs-extra'; import path from 'path'; import { mainStory, chalk } from 'storyboard'; import Promise from 'bluebird'; import * as gqlServer from './gqlServer'; const outputPath = path.join(__dirname, '../common/'); gqlServer.init(); Promise.resolve() .then(() => { mainStory.info('gqlUpdate', 'Introspecting...'); return gqlServer.runIntrospect(); }) .then(result => { let filePath = path.join(outputPath, 'gqlSchema.json'); mainStory.info('gqlUpdate', `Writing ${chalk.cyan(filePath)}...`); fs.writeFileSync(filePath, JSON.stringify(result, null, 2)); filePath = path.join(outputPath, 'gqlSchema.graphql'); mainStory.info('gqlUpdate', `Writing ${chalk.cyan(filePath)}...`); fs.writeFileSync(filePath, gqlServer.getSchemaShorthand()); mainStory.info('gqlUpdate', 'Done!'); });
import fs from 'fs-extra'; import path from 'path'; import { addListener, mainStory, chalk } from 'storyboard'; import consoleListener from 'storyboard/lib/listeners/console'; import Promise from 'bluebird'; import * as gqlServer from './gqlServer'; addListener(consoleListener); const outputPath = path.join(__dirname, '../common/'); gqlServer.init(); Promise.resolve() .then(() => { mainStory.info('gqlUpdate', 'Introspecting...'); return gqlServer.runIntrospect(); }) .then(result => { let filePath = path.join(outputPath, 'gqlSchema.json'); mainStory.info('gqlUpdate', `Writing ${chalk.cyan(filePath)}...`); fs.writeFileSync(filePath, JSON.stringify(result, null, 2)); filePath = path.join(outputPath, 'gqlSchema.graphql'); mainStory.info('gqlUpdate', `Writing ${chalk.cyan(filePath)}...`); fs.writeFileSync(filePath, gqlServer.getSchemaShorthand()); mainStory.info('gqlUpdate', 'Done!'); });
Fix update-schema JSON for Storyboard 2
Fix update-schema JSON for Storyboard 2
JavaScript
mit
guigrpa/mady,guigrpa/mady,guigrpa/mady
--- +++ @@ -1,8 +1,11 @@ import fs from 'fs-extra'; import path from 'path'; -import { mainStory, chalk } from 'storyboard'; +import { addListener, mainStory, chalk } from 'storyboard'; +import consoleListener from 'storyboard/lib/listeners/console'; import Promise from 'bluebird'; import * as gqlServer from './gqlServer'; + +addListener(consoleListener); const outputPath = path.join(__dirname, '../common/'); gqlServer.init();
0d1e37a9f5b3581bea862fa2b54c554fc45d8091
src/js/api/UserAPI.js
src/js/api/UserAPI.js
import { fetchUser, fetchThreads, fetchRecommendation, fetchUserArray, fetchProfile, fetchStats, postLikeUser, deleteLikeUser, fetchMatching, fetchSimilarity } from '../utils/APIUtils'; export function getUser(login, url = `users/${login}`) { return fetchUser(url); } export function getProfile(login, url = `users/${login}/profile`) { return fetchProfile(url); } export function getStats(login, url = `users/${login}/stats`) { return fetchStats(url); } export function getThreads(login, url = `users/${login}/threads`){ return fetchThreads(url); } export function getRecommendation(threadId, url = `threads/${threadId}/recommendation`){ return fetchRecommendation(url); } export function setLikeUser(from, to, url = `users/${from}/likes/${to}`){ return postLikeUser(url); } export function unsetLikeUser(from, to, url = `users/${from}/likes/${to}`){ return deleteLikeUser(url); export function getMatching(userId1, userId2, url = `users/${userId1}/matching/${userId2}`){ return fetchMatching(url); } export function getSimilarity(userId1, userId2, url = `users/${userId1}/similarity/${userId2}`){ return fetchSimilarity(url); }
import { fetchUser, fetchThreads, fetchRecommendation, fetchUserArray, fetchProfile, fetchStats, postLikeUser, deleteLikeUser, fetchMatching, fetchSimilarity } from '../utils/APIUtils'; export function getUser(login, url = `users/${login}`) { return fetchUser(url); } export function getProfile(login, url = `users/${login}/profile`) { return fetchProfile(url); } export function getStats(login, url = `users/${login}/stats`) { return fetchStats(url); } export function getThreads(login, url = `users/${login}/threads`){ return fetchThreads(url); } export function getRecommendation(threadId, url = `threads/${threadId}/recommendation`){ return fetchRecommendation(url); } export function setLikeUser(from, to, url = `users/${from}/likes/${to}`){ return postLikeUser(url); } export function unsetLikeUser(from, to, url = `users/${from}/likes/${to}`) { return deleteLikeUser(url); } export function getMatching(userId1, userId2, url = `users/${userId1}/matching/${userId2}`){ return fetchMatching(url); } export function getSimilarity(userId1, userId2, url = `users/${userId1}/similarity/${userId2}`){ return fetchSimilarity(url); }
Fix error in conflicted merge
QS-907: Fix error in conflicted merge
JavaScript
agpl-3.0
nekuno/client,nekuno/client
--- +++ @@ -24,9 +24,10 @@ return postLikeUser(url); } -export function unsetLikeUser(from, to, url = `users/${from}/likes/${to}`){ +export function unsetLikeUser(from, to, url = `users/${from}/likes/${to}`) { return deleteLikeUser(url); - +} + export function getMatching(userId1, userId2, url = `users/${userId1}/matching/${userId2}`){ return fetchMatching(url); }
95d0ef56ecf2aa03d11b957a75bf7fadbb60bc21
src/routes/ui.js
src/routes/ui.js
'use strict' const path = require('path') const sass = require('rosid-handler-sass') const js = require('rosid-handler-js') const preload = require('../preload') const html = require('../ui/index') const index = async () => { return html() } const styles = async () => { const filePath = path.resolve(__dirname, '../ui/styles/index.scss') const opts = { optimize: true } return sass(filePath, opts) } const scripts = async () => { const filePath = path.resolve(__dirname, '../ui/scripts/index.js') const babel = { presets: [ [ '@babel/preset-env', { targets: { browsers: [ 'last 2 Safari versions', 'last 2 Chrome versions', 'last 2 Opera versions', 'last 2 Firefox versions' ] } } ] ], babelrc: false } const opts = { optimize: false, browserify: {}, babel } return js(filePath, opts) } module.exports = { index: process.env.NODE_ENV === 'development' ? index : preload(index), styles: process.env.NODE_ENV === 'development' ? styles : preload(styles), scripts: process.env.NODE_ENV === 'development' ? scripts : preload(scripts) }
'use strict' const { resolve } = require('path') const sass = require('rosid-handler-sass') const js = require('rosid-handler-js') const preload = require('../preload') const html = require('../ui/index') const optimize = process.env.NODE_ENV !== 'development' const index = async () => { return html() } const styles = async () => { const filePath = resolve(__dirname, '../ui/styles/index.scss') return sass(filePath, { optimize }) } const scripts = async () => { console.log(process.env.NODE_ENV !== 'development') const filePath = resolve(__dirname, '../ui/scripts/index.js') const babel = { presets: [ [ '@babel/preset-env', { targets: { browsers: [ 'last 2 Safari versions', 'last 2 Chrome versions', 'last 2 Opera versions', 'last 2 Firefox versions' ] } } ] ], babelrc: false } return js(filePath, { optimize, babel }) } module.exports = { index: optimize === true ? preload(index) : index, styles: optimize === true ? preload(styles) : styles, scripts: optimize === true ? preload(scripts) : scripts }
Optimize SASS and JS output
Optimize SASS and JS output
JavaScript
mit
electerious/Ackee
--- +++ @@ -1,11 +1,13 @@ 'use strict' -const path = require('path') +const { resolve } = require('path') const sass = require('rosid-handler-sass') const js = require('rosid-handler-js') const preload = require('../preload') const html = require('../ui/index') + +const optimize = process.env.NODE_ENV !== 'development' const index = async () => { @@ -15,16 +17,18 @@ const styles = async () => { - const filePath = path.resolve(__dirname, '../ui/styles/index.scss') - const opts = { optimize: true } + const filePath = resolve(__dirname, '../ui/styles/index.scss') - return sass(filePath, opts) + return sass(filePath, { + optimize + }) } const scripts = async () => { - const filePath = path.resolve(__dirname, '../ui/scripts/index.js') + console.log(process.env.NODE_ENV !== 'development') + const filePath = resolve(__dirname, '../ui/scripts/index.js') const babel = { presets: [ @@ -44,18 +48,15 @@ babelrc: false } - const opts = { - optimize: false, - browserify: {}, + return js(filePath, { + optimize, babel - } - - return js(filePath, opts) + }) } module.exports = { - index: process.env.NODE_ENV === 'development' ? index : preload(index), - styles: process.env.NODE_ENV === 'development' ? styles : preload(styles), - scripts: process.env.NODE_ENV === 'development' ? scripts : preload(scripts) + index: optimize === true ? preload(index) : index, + styles: optimize === true ? preload(styles) : styles, + scripts: optimize === true ? preload(scripts) : scripts }
b3e6b257a2e19d1e10cae8307a9bd673d707a104
src/lib/background.js
src/lib/background.js
/* * Copyright (c) 2014 mono * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ chrome.extension.onConnect.addListener(function(port) { port.onMessage.addListener(function(m) { switch (m.message) { case 'openInTab': chrome.tabs.create({url: m.url, selected: false}); break; } }); });
/* * Copyright (c) 2014 mono * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ chrome.extension.onConnect.addListener(function(port) { port.onMessage.addListener(function(m) { switch (m.message) { case 'openInTab': chrome.tabs.create({url: m.url, active: false}); break; } }); });
Use active flag instead of selected flag
Use active flag instead of selected flag
JavaScript
mit
mono0x/ldr-open-in-background-tab,mono0x/ldr-open-in-background-tab
--- +++ @@ -24,7 +24,7 @@ port.onMessage.addListener(function(m) { switch (m.message) { case 'openInTab': - chrome.tabs.create({url: m.url, selected: false}); + chrome.tabs.create({url: m.url, active: false}); break; } });
1fbf7513c94fa3f7466ecba2256a276455b7ab0b
src/plugins/system.js
src/plugins/system.js
export default function systemPlugin () { return (mp) => { function onMessage (text) { mp.emit('systemMessage', text) } mp.on('connected', () => { mp.ws.on('plugMessage', onMessage) }) } }
export default function systemPlugin () { return (mp) => { function onMessage (text) { mp.emit('systemMessage', text) } function onMaintenanceAlert (minutesLeft) { mp.emit('maintenanceAlert', minutesLeft) } function onMaintenance () { mp.emit('maintenance') } mp.on('connected', () => { mp.ws.on('plugMessage', onMessage) mp.ws.on('plugMaintenanceAlert', onMaintenanceAlert) mp.ws.on('plugMaintenance', onMaintenance) }) } }
Implement `maintenance` and `maintenanceAlert` events.
Implement `maintenance` and `maintenanceAlert` events.
JavaScript
mit
goto-bus-stop/miniplug
--- +++ @@ -4,8 +4,18 @@ mp.emit('systemMessage', text) } + function onMaintenanceAlert (minutesLeft) { + mp.emit('maintenanceAlert', minutesLeft) + } + + function onMaintenance () { + mp.emit('maintenance') + } + mp.on('connected', () => { mp.ws.on('plugMessage', onMessage) + mp.ws.on('plugMaintenanceAlert', onMaintenanceAlert) + mp.ws.on('plugMaintenance', onMaintenance) }) } }
d86ced6ac75cb6e71b6018d3761177cdf5bd892e
app/scripts/directives/block.js
app/scripts/directives/block.js
'use strict'; angular.module('confRegistrationWebApp') .directive('block', function () { return { templateUrl: 'views/blockDirective.html', restrict: 'E', controller: function ($scope, AnswerCache, RegistrationCache, uuid) { var currentRegistration = RegistrationCache.getCurrentRightNow($scope.conference.id); for (var i = 0;i < currentRegistration.answers.length; i++) { if (angular.isDefined(currentRegistration.answers[i]) && currentRegistration.answers[i].blockId === $scope.block.id) { $scope.answer = currentRegistration.answers[i]; break; } } if (!angular.isDefined($scope.answer)) { $scope.answer = { id : uuid(), registrationId : currentRegistration.id, blockId : $scope.block.id, value : {} }; currentRegistration.answers.push($scope.answer); } AnswerCache.syncBlock($scope, 'answer'); } }; });
'use strict'; angular.module('confRegistrationWebApp') .directive('block', function () { return { templateUrl: 'views/blockDirective.html', restrict: 'E', controller: function ($scope, AnswerCache, RegistrationCache, uuid) { var currentRegistration = RegistrationCache.getCurrentRightNow($scope.conference.id); var answerForThisBlock = _.where(currentRegistration.answers, { 'blockId': $scope.block.id }); if (answerForThisBlock.length > 0) { $scope.answer = answerForThisBlock[0]; } if (!angular.isDefined($scope.answer)) { $scope.answer = { id : uuid(), registrationId : currentRegistration.id, blockId : $scope.block.id, value : {} }; currentRegistration.answers.push($scope.answer); } AnswerCache.syncBlock($scope, 'answer'); } }; });
Tidy up for loop code
Tidy up for loop code
JavaScript
mit
CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web
--- +++ @@ -7,12 +7,9 @@ restrict: 'E', controller: function ($scope, AnswerCache, RegistrationCache, uuid) { var currentRegistration = RegistrationCache.getCurrentRightNow($scope.conference.id); - for (var i = 0;i < currentRegistration.answers.length; i++) { - if (angular.isDefined(currentRegistration.answers[i]) && - currentRegistration.answers[i].blockId === $scope.block.id) { - $scope.answer = currentRegistration.answers[i]; - break; - } + var answerForThisBlock = _.where(currentRegistration.answers, { 'blockId': $scope.block.id }); + if (answerForThisBlock.length > 0) { + $scope.answer = answerForThisBlock[0]; } if (!angular.isDefined($scope.answer)) { $scope.answer = {
f1a86242849a9e75fd555dfdc95322d563b26646
src/utils/parseUrl.js
src/utils/parseUrl.js
/** * Exports `parseUrl` for, well, parsing URLs! */ import urlParse from 'url-parse'; const schemeMatcher = /^([a-zA-Z]*\:)?\/\//; const hasScheme = url => { if (typeof url !== 'string') { return false; } return schemeMatcher.test(url); }; const parseUrl = (url = '', baseUrl) => { if (!hasScheme(url)) { if (!hasScheme(baseUrl)) { throw new Error('Must provide scheme in url or baseUrl to parse.'); } } if (!hasScheme(url)) { if (url[0] !== '/') { throw new Error('Only absolute URLs are currently supported.'); } } const urlObj = urlParse(url, baseUrl); return { protocol: urlObj.protocol, host: urlObj.host, hostname: urlObj.hostname, port: urlObj.port, pathname: urlObj.pathname, hash: urlObj.hash, search: urlObj.query, origin: urlObj.host ? (urlObj.protocol + '//' + urlObj.host) : '', href: urlObj.href }; }; export default parseUrl;
/** * Exports `parseUrl` for, well, parsing URLs! */ import urlParse from 'url-parse'; const schemeMatcher = /^([a-zA-Z]*\:)?\/\//; const hasScheme = url => { if (typeof url !== 'string') { return false; } return schemeMatcher.test(url); }; const parseUrl = (url = '', baseUrl) => { if (!hasScheme(url)) { if (!hasScheme(baseUrl)) { throw new Error( `Must provide scheme in url or baseUrl to parse. \`url\` provided: ${url}. \`baseUrl\` provided: ${baseUrl}.` ); } } if (!hasScheme(url)) { if (url[0] !== '/') { throw new Error( `Only absolute URLs are currently supported. \`url\` provided: ${url}` ); } } const urlObj = urlParse(url, baseUrl); return { protocol: urlObj.protocol, host: urlObj.host, hostname: urlObj.hostname, port: urlObj.port, pathname: urlObj.pathname, hash: urlObj.hash, search: urlObj.query, origin: urlObj.host ? (urlObj.protocol + '//' + urlObj.host) : '', href: urlObj.href }; }; export default parseUrl;
Add url and baseUrl to error messages
Add url and baseUrl to error messages Add the url and baseUrl to the error messages inside `parseUrl`. This should help debug where these errors originated.
JavaScript
mit
zapier/redux-router-kit
--- +++ @@ -14,16 +14,19 @@ }; const parseUrl = (url = '', baseUrl) => { - if (!hasScheme(url)) { if (!hasScheme(baseUrl)) { - throw new Error('Must provide scheme in url or baseUrl to parse.'); + throw new Error( + `Must provide scheme in url or baseUrl to parse. \`url\` provided: ${url}. \`baseUrl\` provided: ${baseUrl}.` + ); } } if (!hasScheme(url)) { if (url[0] !== '/') { - throw new Error('Only absolute URLs are currently supported.'); + throw new Error( + `Only absolute URLs are currently supported. \`url\` provided: ${url}` + ); } }
75e10d72e55daf37d47e269b6b1cc5b774b69e22
stories/index.js
stories/index.js
import { MemoryRouter } from 'react-router'; if (typeof MemoryRouter !== 'undefined') { require('./V4/index'); } else { require('./V3/index'); }
require('./V4/index'); // replace with V3 to test with react-router v.3
Remove any kind of logic that tries to load the right version of react-router and simply does not work.
Remove any kind of logic that tries to load the right version of react-router and simply does not work.
JavaScript
mit
gvaldambrini/storybook-router
--- +++ @@ -1,9 +1 @@ -import { MemoryRouter } from 'react-router'; - - -if (typeof MemoryRouter !== 'undefined') { - require('./V4/index'); -} -else { - require('./V3/index'); -} +require('./V4/index'); // replace with V3 to test with react-router v.3
5ffcd271f7bccef678c377558ded06fadb5a234f
app/crash-herald.js
app/crash-herald.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ const appConfig = require('../js/constants/appConfig') const crashReporter = require('electron').crashReporter exports.init = () => { const options = { productName: 'Brave Developers', companyName: 'Brave.com', submitURL: appConfig.crashes.crashSubmitUrl, autoSubmit: true, extra: { node_env: process.env.NODE_ENV } } crashReporter.start(options) }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ const appConfig = require('../js/constants/appConfig') const crashReporter = require('electron').crashReporter const buildConfig = require('../js/constants/buildConfig') exports.init = () => { const options = { productName: 'Brave Developers', companyName: 'Brave.com', submitURL: appConfig.crashes.crashSubmitUrl, autoSubmit: true, extra: { node_env: process.env.NODE_ENV, rev: buildConfig.BROWSER_LAPTOP_REV || 'unknown' } } crashReporter.start(options) }
Send rev hash to crash reports
Send rev hash to crash reports Add rev. hash to the extra parameter send with crash reports. Auditors: 552486fed9a9ff3f07aa28f460daa63ab433892d@alexwykoff
JavaScript
mpl-2.0
diasdavid/browser-laptop,timborden/browser-laptop,luixxiul/browser-laptop,diasdavid/browser-laptop,timborden/browser-laptop,diasdavid/browser-laptop,timborden/browser-laptop,timborden/browser-laptop,luixxiul/browser-laptop,luixxiul/browser-laptop,diasdavid/browser-laptop,luixxiul/browser-laptop
--- +++ @@ -4,6 +4,7 @@ const appConfig = require('../js/constants/appConfig') const crashReporter = require('electron').crashReporter +const buildConfig = require('../js/constants/buildConfig') exports.init = () => { const options = { @@ -12,7 +13,8 @@ submitURL: appConfig.crashes.crashSubmitUrl, autoSubmit: true, extra: { - node_env: process.env.NODE_ENV + node_env: process.env.NODE_ENV, + rev: buildConfig.BROWSER_LAPTOP_REV || 'unknown' } } crashReporter.start(options)
3c46ee20228420ded9a6752e8b5fbf482d1ab9b4
scripts/tweet_release.js
scripts/tweet_release.js
var fetch = require('node-fetch') var execSync = require('child_process').execSync var zapierHookURL = 'https://zapier.com/hooks/catch/3petdc/' var tag = process.env.TRAVIS_TAG || execSync('git describe --abbrev=0 --tags').toString().trim() fetch(zapierHookURL, { method: 'POST', body: JSON.stringify({ tweet: `date-fns ${tag} is published! See changelog: https://github.com/toptal/tracker-front/blob/master/CHANGELOG.md#${tag.replace(/\./g, '')}` }), headers: {'Content-Type': 'application/json'} })
import fetch from 'node-fetch' import {execSync} from 'child_process' const zapierHookURL = `https://zapier.com/hooks/catch/${process.env.ZAPIER_TWEET_RELEASE_HOOK_ID}/` const tag = process.env.TRAVIS_TAG || execSync('git describe --abbrev=0 --tags').toString().trim() const changelogUrl = `https://github.com/toptal/tracker-front/blob/master/CHANGELOG.md#${tag.replace(/\./g, '')}` console.log('~ Posting release tweet') fetch(zapierHookURL, { method: 'POST', body: JSON.stringify({ tweet: `date-fns ${tag} is published! See changelog: ${changelogUrl}.` }), headers: {'Content-Type': 'application/json'} }) .then(() => console.log('+ Done!')) .catch((err) => { console.error(err) process.exit(1) })
Secure the Zapier hook URL, use ES 2015 in the script
Secure the Zapier hook URL, use ES 2015 in the script
JavaScript
mit
js-fns/date-fns,date-fns/date-fns,js-fns/date-fns,date-fns/date-fns,date-fns/date-fns
--- +++ @@ -1,14 +1,24 @@ -var fetch = require('node-fetch') -var execSync = require('child_process').execSync +import fetch from 'node-fetch' +import {execSync} from 'child_process' -var zapierHookURL = 'https://zapier.com/hooks/catch/3petdc/' -var tag = process.env.TRAVIS_TAG +const zapierHookURL + = `https://zapier.com/hooks/catch/${process.env.ZAPIER_TWEET_RELEASE_HOOK_ID}/` +const tag = process.env.TRAVIS_TAG || execSync('git describe --abbrev=0 --tags').toString().trim() +const changelogUrl + = `https://github.com/toptal/tracker-front/blob/master/CHANGELOG.md#${tag.replace(/\./g, '')}` + +console.log('~ Posting release tweet') fetch(zapierHookURL, { method: 'POST', body: JSON.stringify({ - tweet: `date-fns ${tag} is published! See changelog: https://github.com/toptal/tracker-front/blob/master/CHANGELOG.md#${tag.replace(/\./g, '')}` + tweet: `date-fns ${tag} is published! See changelog: ${changelogUrl}.` }), headers: {'Content-Type': 'application/json'} }) + .then(() => console.log('+ Done!')) + .catch((err) => { + console.error(err) + process.exit(1) + })
5061c75c815a0b43f3e5f52c2a6b7068b7aeaeea
lib/configTest.js
lib/configTest.js
//Copyright 2012 Telefonica Investigación y Desarrollo, S.A.U // //This file is part of RUSH. // // RUSH is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // RUSH is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License along with RUSH // . If not, seehttp://www.gnu.org/licenses/. // //For those usages not covered by the GNU Affero General Public License please contact with::dtc_support@tid.es module.exports = require('./configBase.js'); //0..15 for 0 ->pre-production 1->test module.exports.selectedDB = 1; //Include evMonitor module.exports.consumer.evModules.push( { module: './evMonitor' } ); //Reduce bucket timers module.exports.retryBuckets = [5, 10, 15]; module.exports.probeInterval = 5 * 1000; module.exports.sentinels = [{host:'localhost', port:26379}];
//Copyright 2012 Telefonica Investigación y Desarrollo, S.A.U // //This file is part of RUSH. // // RUSH is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // RUSH is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License along with RUSH // . If not, seehttp://www.gnu.org/licenses/. // //For those usages not covered by the GNU Affero General Public License please contact with::dtc_support@tid.es module.exports = require('./configBase.js'); //0..15 for 0 ->pre-production 1->test module.exports.selectedDB = 1; //Include evMonitor module.exports.consumer.evModules.push( { module: './evMonitor' } ); //Reduce bucket timers module.exports.retryBuckets = [5, 10, 15]; module.exports.probeInterval = 5 * 1000; //module.exports.sentinels = [{host:'localhost', port:26379}];
Remove sentinel from config. Travis won't pass if a sentinel is set
Remove sentinel from config. Travis won't pass if a sentinel is set
JavaScript
agpl-3.0
telefonicaid/Rush,telefonicaid/Rush
--- +++ @@ -26,4 +26,4 @@ module.exports.probeInterval = 5 * 1000; -module.exports.sentinels = [{host:'localhost', port:26379}]; +//module.exports.sentinels = [{host:'localhost', port:26379}];
05b9f0d821d0fda89b49cddd3823a74ccd8a17d8
lib/httpStatus.js
lib/httpStatus.js
/*jshint node:true */ "use strict"; var data = { created: { code: 201, body: "Created" }, noContent: { code: 204, body: "" }, notFound: { code: 404, body: "Not found" }, methodNotAllowed: { code: 405, body: "Method not allowed" }, notImplemented: { code: 501, body: "Not implemented"} }; function HTTPStatus(code, message) { var err = new Error(message); err.code = code; return err; } HTTPStatus.names = Object.keys(data); HTTPStatus.names.forEach(function(key) { HTTPStatus[key] = HTTPStatus.bind(null, data[key].code, data[key].body); }); module.exports = HTTPStatus;
/*jshint node:true */ "use strict"; var data = { created: { code: 201, body: "Created" }, noContent: { code: 204, body: "" }, badRequest: { code: 400, body: "Bad request" }, notFound: { code: 404, body: "Not found" }, methodNotAllowed: { code: 405, body: "Method not allowed" }, notImplemented: { code: 501, body: "Not implemented"} }; function HTTPStatus(code, message) { var err = new Error(message); err.code = code; return err; } HTTPStatus.names = Object.keys(data); HTTPStatus.names.forEach(function(key) { HTTPStatus[key] = HTTPStatus.bind(null, data[key].code, data[key].body); }); module.exports = HTTPStatus;
Add 400 bad request status helper
Add 400 bad request status helper
JavaScript
mit
njoyard/yarm
--- +++ @@ -4,6 +4,7 @@ var data = { created: { code: 201, body: "Created" }, noContent: { code: 204, body: "" }, + badRequest: { code: 400, body: "Bad request" }, notFound: { code: 404, body: "Not found" }, methodNotAllowed: { code: 405, body: "Method not allowed" }, notImplemented: { code: 501, body: "Not implemented"}
75eee88ec94c6174761ddb6f121b1becb7b1b395
app/js/factories.js
app/js/factories.js
'use strict'; angular.module('ahoyApp.factories', []) .factory("smartBanner", function() { var argument = ""; if (document.location.hash.indexOf("#/link/") != -1) { argument = document.location.hash.substring("#/link/".length);; } return { appId: "973996885", appArgument: argument } });
'use strict'; angular.module('ahoyApp.factories', []) .factory("smartBanner", function() { var argument = ""; if (document.location.hash.indexOf("#/link/") != -1) { argument = "ahoyconference://link/"+document.location.hash.substring("#/link/".length);; } return { appId: "973996885", appArgument: argument } });
Use full URL as smartbanner argument.
Use full URL as smartbanner argument.
JavaScript
mit
ahoyconference/ahoy-ui,ahoyconference/ahoy-ui
--- +++ @@ -4,7 +4,7 @@ .factory("smartBanner", function() { var argument = ""; if (document.location.hash.indexOf("#/link/") != -1) { - argument = document.location.hash.substring("#/link/".length);; + argument = "ahoyconference://link/"+document.location.hash.substring("#/link/".length);; } return { appId: "973996885",
8012441a16ecb34c7933a7edf7d3fd88470bdd19
test/transform.js
test/transform.js
var test = require('tap').test; var fs = require('fs'); var path = require('path'); var through = require('through'); var convert = require('convert-source-map'); var transform = require('..'); test('transform adds sourcemap comment', function (t) { t.plan(1); var data = ''; var file = path.join(__dirname, '../example/foo.coffee') fs.createReadStream(file) .pipe(transform(file)) .pipe(through(write, end)); function write (buf) { data += buf } function end () { var sourceMap = convert.fromSource(data).toObject(); t.deepEqual( sourceMap, { version: 3, file: file, sourceRoot: '', sources: [ file ], names: [], mappings: 'AAAA,CAAQ,EAAR,IAAO,GAAK', sourcesContent: [ 'console.log(require \'./bar.js\')\n' ] }, 'adds sourcemap comment including original source' ); } });
var test = require('tap').test; var fs = require('fs'); var path = require('path'); var through = require('through'); var convert = require('convert-source-map'); var transform = require('..'); test('transform adds sourcemap comment', function (t) { t.plan(1); var data = ''; var file = path.join(__dirname, '../example/foo.coffee') fs.createReadStream(file) .pipe(transform(file)) .pipe(through(write, end)); function write (buf) { data += buf } function end () { var sourceMap = convert.fromSource(data).toObject(); t.deepEqual( sourceMap, { version: 3, file: file, sourceRoot: '', sources: [ file ], names: [], mappings: 'AAAA,OAAO,CAAC,GAAR,CAAY,OAAA,CAAQ,UAAR,CAAZ,CAAA,CAAA', sourcesContent: [ 'console.log(require \'./bar.js\')\n' ] }, 'adds sourcemap comment including original source' ); } });
Update source map test to correspond with CoffeeScript 1.7
Update source map test to correspond with CoffeeScript 1.7
JavaScript
mit
jsdf/coffee-reactify,jsdf/coffee-reactify,jnordberg/coffeeify,hafeez-syed/coffeeify
--- +++ @@ -25,7 +25,7 @@ sourceRoot: '', sources: [ file ], names: [], - mappings: 'AAAA,CAAQ,EAAR,IAAO,GAAK', + mappings: 'AAAA,OAAO,CAAC,GAAR,CAAY,OAAA,CAAQ,UAAR,CAAZ,CAAA,CAAA', sourcesContent: [ 'console.log(require \'./bar.js\')\n' ] }, 'adds sourcemap comment including original source' );
6055151b88734de9f3dec4bf0c2f6487caf602b1
jest-puppeteer.config.js
jest-puppeteer.config.js
module.exports = () => ({ browser: process.env.BROWSER || 'chromium', launch: { dumpio: true, headless: process.env.HEADLESS !== 'false', }, server: { command: 'yarn dev:serve', port: 5000, }, }());
module.exports = { browser: process.env.BROWSER || 'chromium', launch: { dumpio: true, headless: process.env.HEADLESS !== 'false', }, server: { command: 'yarn dev:serve', port: 5000, }, };
Revert "test: fix default browser value"
Revert "test: fix default browser value" This reverts commit a8f88984443a15616c9bdfba67ae7e42dd179ddd.
JavaScript
mit
FezVrasta/popper.js,FezVrasta/popper.js,FezVrasta/popper.js,floating-ui/floating-ui,floating-ui/floating-ui,floating-ui/floating-ui,FezVrasta/popper.js
--- +++ @@ -1,12 +1,11 @@ -module.exports = () => - ({ - browser: process.env.BROWSER || 'chromium', - launch: { - dumpio: true, - headless: process.env.HEADLESS !== 'false', - }, - server: { - command: 'yarn dev:serve', - port: 5000, - }, - }()); +module.exports = { + browser: process.env.BROWSER || 'chromium', + launch: { + dumpio: true, + headless: process.env.HEADLESS !== 'false', + }, + server: { + command: 'yarn dev:serve', + port: 5000, + }, +};
400fdea7e619c24ed21257b340cd27de5876801e
client/otp/index.js
client/otp/index.js
var config = require('config'); var debug = require('debug')(config.application() + ':otp'); var Profiler = require('otp-profiler'); var spin = require('spinner'); /** * Create profiler */ var profiler = new Profiler({ host: '/api/otp' }); /** * Expose `journey` */ module.exports = function profile(query, callback) { debug('--> profiling %s', JSON.stringify(query)); var spinner = spin(); profiler.profile(query, function(err, data) { if (err || !data) { spinner.stop(); debug('<-- error profiling', err); callback(err); } else { query.profile = data; profiler.journey(query, function(err, journey) { spinner.stop(); if (err) { debug('<-- error profiling', err); callback(err); } else { debug('<-- profiled %s options', data.options.length); callback(null, { journey: journey, options: data.options }); } }); } }); };
var config = require('config'); var debug = require('debug')(config.application() + ':otp'); var Profiler = require('otp-profiler'); var spin = require('spinner'); /** * Create profiler */ var profiler = new Profiler({ host: '/api/otp' }); /** * Expose `journey` */ module.exports = function profile(query, callback) { debug('--> profiling %s', JSON.stringify(query)); var spinner = spin(); profiler.profile(query, function(err, data) { if (err || !data) { spinner.remove(); debug('<-- error profiling', err); callback(err); } else { query.profile = data; profiler.journey(query, function(err, journey) { spinner.remove(); if (err) { debug('<-- error profiling', err); callback(err); } else { debug('<-- profiled %s options', data.options.length); callback(null, { journey: journey, options: data.options }); } }); } }); };
Add spinning animation back in
Add spinning animation back in
JavaScript
bsd-3-clause
miraculixx/modeify,tismart/modeify,arunnair80/modeify-1,miraculixx/modeify,arunnair80/modeify,miraculixx/modeify,miraculixx/modeify,arunnair80/modeify,amigocloud/modeify,amigocloud/modified-tripplanner,arunnair80/modeify,tismart/modeify,amigocloud/modified-tripplanner,arunnair80/modeify-1,amigocloud/modeify,amigocloud/modeify,tismart/modeify,arunnair80/modeify,amigocloud/modeify,arunnair80/modeify-1,arunnair80/modeify-1,tismart/modeify,amigocloud/modified-tripplanner,amigocloud/modified-tripplanner
--- +++ @@ -21,13 +21,13 @@ var spinner = spin(); profiler.profile(query, function(err, data) { if (err || !data) { - spinner.stop(); + spinner.remove(); debug('<-- error profiling', err); callback(err); } else { query.profile = data; profiler.journey(query, function(err, journey) { - spinner.stop(); + spinner.remove(); if (err) { debug('<-- error profiling', err); callback(err);
16a03f73f99f7e6b0fc9c4ab60dc76579092d3ce
app/components/Docker/index.js
app/components/Docker/index.js
import React, { Component } from 'react' import { Icon } from 'antd' import Images from './Images' import styles from './Docker.scss' class Docker extends Component { render() { return ( <div> <h1><Icon type="hdd" /> Docker</h1> <Images /> </div> ) } } export default Docker
import React, { Component } from 'react' import { Tabs, Icon } from 'antd' import Images from './Images' import styles from './Docker.scss' const TabPane = Tabs.TabPane class Docker extends Component { render() { return ( <div> <h1><Icon type="hdd" /> Docker</h1> <Tabs type="card" animated={false}> <TabPane tab="Images" key="1"> <Images /> </TabPane> <TabPane tab="Containers" key="2">Nothing Here Yet</TabPane> <TabPane tab="Tab 3" key="3">And Nothing Here!</TabPane> </Tabs> </div> ) } } export default Docker
Add tab information to Docker window for various sub-interfaces
Add tab information to Docker window for various sub-interfaces
JavaScript
mit
baublet/lagniappe,baublet/lagniappe
--- +++ @@ -1,9 +1,11 @@ import React, { Component } from 'react' -import { Icon } from 'antd' +import { Tabs, Icon } from 'antd' import Images from './Images' import styles from './Docker.scss' + +const TabPane = Tabs.TabPane class Docker extends Component { @@ -12,7 +14,13 @@ return ( <div> <h1><Icon type="hdd" /> Docker</h1> - <Images /> + <Tabs type="card" animated={false}> + <TabPane tab="Images" key="1"> + <Images /> + </TabPane> + <TabPane tab="Containers" key="2">Nothing Here Yet</TabPane> + <TabPane tab="Tab 3" key="3">And Nothing Here!</TabPane> + </Tabs> </div> ) }
a3d4149b667f00bc44401292b7ed95f705e1b2e2
source/class/test/Mammalian.js
source/class/test/Mammalian.js
/** * This is a generic Interface for Mammalian Animals * * Those class of Animals have different things in * common - compared to other animal classes like * {api.test.Fish}. */ core.Interface('api.test.Mammalian', { properties: { /** * All Mammalians have a fur! */ fur: { type: 'Object', fire: 'changeFur', apply: function(value, old) { } }, /** * All Mammalians have teeth! */ teeth: { type: 'Number', fire: 'looseTeeth', apply: function(value, old) { } }, /** * All Mammalians have bones! */ bones: { type: 'Number', fire: 'breakBones', apply: function(value, old) { } } } });
/** * This is a generic Interface for Mammalian Animals * * Those class of Animals have different things in * common - compared to other animal classes like * {api.test.Fish}. */ core.Interface('api.test.Mammalian', { properties: { /** * All Mammalians have a fur! */ fur: { type: 'Object', fire: 'changeFur' }, /** * All Mammalians have teeth! */ teeth: { type: 'Number', fire: 'looseTeeth' }, /** * All Mammalians have bones! */ bones: { type: 'Number', fire: 'breakBones' } } });
Make no sense to have apply routines in interface as it is not visible from the outside
Make no sense to have apply routines in interface as it is not visible from the outside
JavaScript
mit
zynga/apibrowser,zynga/apibrowser
--- +++ @@ -14,9 +14,7 @@ */ fur: { type: 'Object', - fire: 'changeFur', - apply: function(value, old) { - } + fire: 'changeFur' }, /** @@ -24,9 +22,7 @@ */ teeth: { type: 'Number', - fire: 'looseTeeth', - apply: function(value, old) { - } + fire: 'looseTeeth' }, /** @@ -34,9 +30,7 @@ */ bones: { type: 'Number', - fire: 'breakBones', - apply: function(value, old) { - } + fire: 'breakBones' } }
4b79570b45e609bf224347add37c5be95a432a62
app/libs/utils/color-string.js
app/libs/utils/color-string.js
'use strict'; // Load requirements const clk = require('chalk'), chalk = new clk.constructor({level: 1, enabled: true}); // Formats a string with ANSI styling module.exports = function(str) { // Variables const regex = /\{([a-z,]+)\:([\s\S]*?)\}/gmi; let m; // Check for a non-string if ( typeof str !== 'string' ) { return ''; } // Loop through matches while ( ( m = regex.exec(str) ) !== null ) { // Allow for multiple formatting options let split = m[1].split(','), partial = m[2]; // Wrap the replacement area for ( let i in split ) { if ( chalk[split[i]] !== undefined ) { partial = chalk[split[i]](partial); } } // Make the replacement in the original string str = str.replace(m[0], partial); } // Still matches to be made return ( str.match(regex) !== null ? this.colorString(str) : str.replace(/\{([a-z,]+)\:/gi, '') ); };
'use strict'; // Load requirements const clk = require('chalk'), chalk = new clk.constructor({level: 1, enabled: true}); // Formats a string with ANSI styling module.exports = function(str) { // Variables const regex = /\{([a-z,]+)\:([\s\S]*?)\}/gmi; let m = null, args = Array.prototype.slice.call(arguments, 1); // Check for a non-string if ( typeof str !== 'string' ) { return ''; } // Add basic sprintf-esque support args.forEach((arg) => { str = str.replace('%s', arg); }); // Loop through matches while ( ( m = regex.exec(str) ) !== null ) { // Allow for multiple formatting options let split = m[1].split(','), partial = m[2]; // Wrap the replacement area for ( let i in split ) { if ( chalk[split[i]] !== undefined ) { partial = chalk[split[i]](partial); } } // Make the replacement in the original string str = str.replace(m[0], partial); } // Still matches to be made return ( str.match(regex) !== null ? this.colorString(str, args) : str.replace(/\{([a-z,]+)\:/gi, '') ); };
Update utils color string with basic sprintf support
Update utils color string with basic sprintf support
JavaScript
apache-2.0
transmutejs/core
--- +++ @@ -9,12 +9,17 @@ // Variables const regex = /\{([a-z,]+)\:([\s\S]*?)\}/gmi; - let m; + let m = null, args = Array.prototype.slice.call(arguments, 1); // Check for a non-string if ( typeof str !== 'string' ) { return ''; } + + // Add basic sprintf-esque support + args.forEach((arg) => { + str = str.replace('%s', arg); + }); // Loop through matches while ( ( m = regex.exec(str) ) !== null ) { @@ -35,5 +40,5 @@ } // Still matches to be made - return ( str.match(regex) !== null ? this.colorString(str) : str.replace(/\{([a-z,]+)\:/gi, '') ); + return ( str.match(regex) !== null ? this.colorString(str, args) : str.replace(/\{([a-z,]+)\:/gi, '') ); };
819016b9a70329ff1340ebcbdf149244fe60cd4c
client/app/components/b-portion.js
client/app/components/b-portion.js
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'li', classNames: ['b-portion'], click(e) { const target = Ember.$(e.target); if (target.hasClass('checkbox__text') || target.hasClass('checkbox__control')) { this.togglePaidStatus(this.get('portion')); } return false; }, togglePaidStatus(portion) { portion.toggleProperty('paid'); portion.save(); } });
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'li', classNames: ['b-portion'], click(e) { const target = Ember.$(e.target); if (target.hasClass('checkbox__text') || target.hasClass('checkbox__control')) { this.togglePaidStatus(this.get('portion')); } return false; }, togglePaidStatus(portion) { portion.toggleProperty('paid'); portion.save(); portion.get('order').then((order) => { const cost = portion.get('cost'); const available = order.get('money.available'); order.set('money.available', available + ((portion.get('paid')) ? +cost : -cost) ); order.save(); }); } });
Update order money available when portion status is changed
Update order money available when portion status is changed
JavaScript
mit
yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time
--- +++ @@ -15,5 +15,14 @@ togglePaidStatus(portion) { portion.toggleProperty('paid'); portion.save(); + + portion.get('order').then((order) => { + const cost = portion.get('cost'); + const available = order.get('money.available'); + order.set('money.available', + available + ((portion.get('paid')) ? +cost : -cost) + ); + order.save(); + }); } });
c8d8b9c215426ebef3d42c94498e1ddaa5718a64
public/js/calnav.js
public/js/calnav.js
'use strict'; var calnav = (function() { var nav = $('.nav-cals'); var renderCal = function(cal, level) { var input = document.createElement('input'); input.type = 'checkbox'; input.checked = 'checked'; $(input).on('change', function(e) { var active = $(this).is(":checked"); var l = $(this).parent('label'); l.toggleClass('active', active); // Apply to calendar $('#calendar').fullCalendar((active ? 'add' : 'remove') + 'EventSource', l.data('url')) }) var label = document.createElement('label'); var $label = $(label); $label.append(input).append(cal.name); $label.data('id', cal.id); $label.data('slug', cal.slug); $label.data('url', cal.url); $label.addClass('level--' + level); $label.addClass('active'); nav.append($label); }; var render = function(sources) { var levels = { 1: 1 }; var glob = sources[0]; $.each(sources, function(index, cal) { if (!levels[cal.parent_id]) { levels[cal.id] = 1; } else { levels[cal.id] = levels[levels[cal.parent_id]] + 1; } }) $.each(sources, function(index, cal) { renderCal(cal, levels[cal.parent_id]); }) }; return { render: render }; })();
'use strict'; var calnav = (function() { var nav = $('.nav-cals'); var renderCal = function(cal, level) { var input = document.createElement('input'); input.type = 'checkbox'; input.checked = 'checked'; $(input).on('change', function(e) { var active = $(this).is(":checked"); var l = $(this).parent('label'); l.toggleClass('active', active); // Apply to calendar $('#calendar').fullCalendar((active ? 'add' : 'remove') + 'EventSource', l.data('url')) }) var label = document.createElement('label'); var $label = $(label); $label.append(input).append(cal.name); $label.data('id', cal.id); $label.data('slug', cal.slug); $label.data('url', cal.url); $label.addClass('level--' + level); $label.addClass('active'); nav.append($label); }; var render = function(sources) { }; return { render: render }; })();
Remove calendar nav generated by js
Remove calendar nav generated by js
JavaScript
mit
oSoc15/educal,tthoeye/educal,oSoc14/code9000,oSoc14/code9000,tthoeye/educal,oSoc15/educal
--- +++ @@ -29,22 +29,6 @@ }; var render = function(sources) { - var levels = { - 1: 1 - }; - var glob = sources[0]; - $.each(sources, function(index, cal) { - if (!levels[cal.parent_id]) { - levels[cal.id] = 1; - } else { - levels[cal.id] = levels[levels[cal.parent_id]] + 1; - } - }) - - $.each(sources, function(index, cal) { - renderCal(cal, levels[cal.parent_id]); - }) - }; return {
f7a29ef2c87f4f56ddb17dafa154c8775b1ba1c1
app.js
app.js
var gpio = require('onoff').Gpio; var red = new gpio(16, 'out'); var green = new gpio(12, 'out'); var blue = new gpio(21, 'out'); var button = new gpio(25, 'in', 'both'); var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World!'); }); app.listen(3000, function(){ console.log('App listening on port 3000!'); }) // define the callback function function light(err, state) { console.log('Button pushed'); // check the state of the button // 1 == pressed, 0 == not pressed if(state == 1) { // turn LED on red.writeSync(1); gree.writeSync(1); blue.writeSync(1); } else { // turn LED off red.writeSync(0); gree.writeSync(0); blue.writeSync(0) } } // pass the callback function to the // as the first argument to watch() button.watch(light);
var gpio = require('onoff').Gpio; var red = new gpio(16, 'out'); var green = new gpio(12, 'out'); var blue = new gpio(21, 'out'); var button = new gpio(25, 'in', 'both'); var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hi I changed this!'); }); app.listen(3000, function(){ console.log('App listening on port 3000!'); }) // define the callback function function light(err, state) { console.log('Button pushed'); // check the state of the button // 1 == pressed, 0 == not pressed if(state == 1) { // turn LED on red.writeSync(1); gree.writeSync(1); blue.writeSync(1); } else { // turn LED off red.writeSync(0); gree.writeSync(0); blue.writeSync(0) } } // pass the callback function to the // as the first argument to watch() button.watch(light);
Update hello world text to text git push to remote server
Update hello world text to text git push to remote server
JavaScript
mit
davesroka/rpi-node-led,davesroka/rpi-node-led
--- +++ @@ -7,7 +7,7 @@ var app = express(); app.get('/', function(req, res){ - res.send('Hello World!'); + res.send('Hi I changed this!'); }); app.listen(3000, function(){
7bfe479fbee18bc557cafc26986e01ad947abbda
src/app/index.run.js
src/app/index.run.js
export function runBlock($log, $state, $trace) { 'ngInject'; // Enable logging of state transition $trace.enable('TRANSITION'); // Add any logic for handling errors from state transitions $state.defaultErrorHandler(function() { // console.error('error:', error); }); }
export function runBlock($log, $state, $trace, $transitions) { 'ngInject'; // Enable logging of state transition $trace.enable('TRANSITION'); // Add any logic for handling errors from state transitions $state.defaultErrorHandler(function() { // console.error('error:', error); }); // Test when application is changing to 'app.start' route // to determine if a websocket connected has already been opened // so we can re-route the user back to the 'game' $transitions.onEnter({ to: 'app.start' }, (trans) => { let websocket = trans.injector().get('websocket'); if (websocket.$ws) { let status = websocket.getStatus(); if (status === websocket.STATUS.OPEN) { $state.go('app.game'); } } }); }
Add transition to test for 'app.start' and redirect if websocket is OPEN
Add transition to test for 'app.start' and redirect if websocket is OPEN
JavaScript
unlicense
ejwaibel/squarrels,ejwaibel/squarrels
--- +++ @@ -1,4 +1,4 @@ -export function runBlock($log, $state, $trace) { +export function runBlock($log, $state, $trace, $transitions) { 'ngInject'; // Enable logging of state transition @@ -8,4 +8,19 @@ $state.defaultErrorHandler(function() { // console.error('error:', error); }); + + // Test when application is changing to 'app.start' route + // to determine if a websocket connected has already been opened + // so we can re-route the user back to the 'game' + $transitions.onEnter({ to: 'app.start' }, (trans) => { + let websocket = trans.injector().get('websocket'); + + if (websocket.$ws) { + let status = websocket.getStatus(); + + if (status === websocket.STATUS.OPEN) { + $state.go('app.game'); + } + } + }); }
c35fd81e9ec426c683317ce0687de91b6dda4e38
lib/cb.socket.io/main.js
lib/cb.socket.io/main.js
// Requires var socketio = require('socket.io'); function setup(options, imports, register) { var server = imports.server.http; var io = socketio.listen(server, { // Do not run a flash policy server // (requires root permissions) 'flash policy port': -1, 'destroy upgrade': false }); register(null, { "socket_io": { "io": io } }); } // Exports module.exports = setup;
// Requires var socketio = require('socket.io'); function setup(options, imports, register) { var server = imports.server.http; var io = socketio.listen(server, { // Do not run a flash policy server // (requires root permissions) 'flash policy port': -1, 'destroy upgrade': false, 'log level': 1, }); register(null, { "socket_io": { "io": io } }); } // Exports module.exports = setup;
Switch socket.io's log level to warnings
Switch socket.io's log level to warnings
JavaScript
apache-2.0
CodeboxIDE/codebox,code-box/codebox,lcamilo15/codebox,CodeboxIDE/codebox,smallbal/codebox,blubrackets/codebox,ronoaldo/codebox,fly19890211/codebox,LogeshEswar/codebox,ahmadassaf/Codebox,etopian/codebox,blubrackets/codebox,quietdog/codebox,quietdog/codebox,kustomzone/codebox,nobutakaoshiro/codebox,Ckai1991/codebox,listepo/codebox,rajthilakmca/codebox,indykish/codebox,kustomzone/codebox,smallbal/codebox,rajthilakmca/codebox,LogeshEswar/codebox,listepo/codebox,code-box/codebox,indykish/codebox,ahmadassaf/Codebox,rodrigues-daniel/codebox,nobutakaoshiro/codebox,Ckai1991/codebox,lcamilo15/codebox,rodrigues-daniel/codebox,etopian/codebox,fly19890211/codebox,ronoaldo/codebox
--- +++ @@ -10,7 +10,8 @@ // Do not run a flash policy server // (requires root permissions) 'flash policy port': -1, - 'destroy upgrade': false + 'destroy upgrade': false, + 'log level': 1, }); register(null, {
c79f0fa931512d00a0c76b7d067e3e80088aeb69
app/javascript/components/forms/login/actions.js
app/javascript/components/forms/login/actions.js
import { createThunkAction } from 'utils/redux'; import { FORM_ERROR } from 'final-form'; import { login, register, resetPassword } from 'services/user'; import { getUserProfile } from 'providers/mygfw-provider/actions'; export const loginUser = createThunkAction('logUserIn', data => dispatch => login(data) .then(response => { if (response.status < 400 && response.data) { dispatch(getUserProfile()); } }) .catch(error => { const { errors } = error.response.data; return { [FORM_ERROR]: errors[0].detail }; }) ); export const registerUser = createThunkAction('sendRegisterUser', data => () => register(data) .then(() => {}) .catch(error => { const { errors } = error.response.data; return { [FORM_ERROR]: errors[0].detail }; }) ); export const resetUserPassword = createThunkAction( 'sendResetPassword', ({ data, success }) => () => resetPassword(data) .then(() => { success(); }) .catch(error => { const { errors } = error.response.data; return { [FORM_ERROR]: errors[0].detail }; }) );
import { createThunkAction } from 'utils/redux'; import { FORM_ERROR } from 'final-form'; import { login, register, resetPassword } from 'services/user'; import { getUserProfile } from 'providers/mygfw-provider/actions'; export const loginUser = createThunkAction('logUserIn', data => dispatch => login(data) .then(response => { if (response.status < 400 && response.data) { dispatch(getUserProfile()); } }) .catch(error => { const { errors } = error.response.data; return { [FORM_ERROR]: errors[0].detail }; }) ); export const registerUser = createThunkAction('sendRegisterUser', data => () => register(data) .then(() => {}) .catch(error => { const { errors } = error.response.data; return { [FORM_ERROR]: errors[0].detail }; }) ); export const resetUserPassword = createThunkAction( 'sendResetPassword', data => () => resetPassword(data) .then(() => {}) .catch(error => { const { errors } = error.response.data; return { [FORM_ERROR]: errors[0].detail }; }) );
Fix reset password for MyGFW
Fix reset password for MyGFW
JavaScript
mit
Vizzuality/gfw,Vizzuality/gfw
--- +++ @@ -34,11 +34,9 @@ export const resetUserPassword = createThunkAction( 'sendResetPassword', - ({ data, success }) => () => + data => () => resetPassword(data) - .then(() => { - success(); - }) + .then(() => {}) .catch(error => { const { errors } = error.response.data;
6555da3374369edb9bcd03d006c1504010688268
javascripts/pong.js
javascripts/pong.js
(function() { 'use strict'; var canvas = document.getElementById('game'); var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; canvas.width = WIDTH; canvas.height = HEIGHT; var ctx = canvas.getContext('2d'); var FPS = 1000 / 60; var Paddle = function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; this.xSpeed = 0; this.ySpeed = 0; }; Paddle.prototype.render = function() { ctx.fillStyle = "#FFFFFF"; ctx.fillRect(this.x, this.y, this.width, this.height); } var clear = function() { ctx.clearRect(0, 0, WIDTH, HEIGHT); }; var update = function() { }; var render = function () { ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, WIDTH, HEIGHT); }; var step = function() { update(); render(); requestAnimationFrame(FPS); } requestAnimationFrame(step()); })();
(function() { 'use strict'; var canvas = document.getElementById('game'); var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; canvas.width = WIDTH; canvas.height = HEIGHT; var ctx = canvas.getContext('2d'); var FPS = 1000 / 60; // Define game objects, i.e paddle and ball var Paddle = function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; this.xSpeed = 0; this.ySpeed = 0; }; Paddle.prototype.render = function() { ctx.fillStyle = "#FFFFFF"; ctx.fillRect(this.x, this.y, this.width, this.height); }; var Player = function() { var playerHeight = 100; this.paddle = new Paddle(10, HEIGHT / 2 - (playerHeight / 2), 10, playerHeight); }; Player.prototype.render = function() { this.paddle.render(); }; var Computer = function() { var playerWidth = 10; var playerHeight = 100; this.paddle = new Paddle(WIDTH - 10 - playerWidth, HEIGHT / 2 - (playerHeight / 2), playerWidth, playerHeight); }; Computer.prototype.render = function() { this.paddle.render(); }; // Game logic begins here var player = new Player(); var computer = new Computer(); var clear = function() { ctx.clearRect(0, 0, WIDTH, HEIGHT); }; var update = function() { }; var render = function () { ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, WIDTH, HEIGHT); player.render(); computer.render(); }; var step = function() { update(); render(); requestAnimationFrame(FPS); } requestAnimationFrame(step()); })();
Define and create human player and computer objects. Render them as well!
Define and create human player and computer objects. Render them as well!
JavaScript
mit
msanatan/pong,msanatan/pong,msanatan/pong
--- +++ @@ -8,6 +8,7 @@ var ctx = canvas.getContext('2d'); var FPS = 1000 / 60; + // Define game objects, i.e paddle and ball var Paddle = function(x, y, width, height) { this.x = x; this.y = y; @@ -20,7 +21,30 @@ Paddle.prototype.render = function() { ctx.fillStyle = "#FFFFFF"; ctx.fillRect(this.x, this.y, this.width, this.height); - } + }; + + var Player = function() { + var playerHeight = 100; + this.paddle = new Paddle(10, HEIGHT / 2 - (playerHeight / 2), 10, playerHeight); + }; + + Player.prototype.render = function() { + this.paddle.render(); + }; + + var Computer = function() { + var playerWidth = 10; + var playerHeight = 100; + this.paddle = new Paddle(WIDTH - 10 - playerWidth, HEIGHT / 2 - (playerHeight / 2), playerWidth, playerHeight); + }; + + Computer.prototype.render = function() { + this.paddle.render(); + }; + + // Game logic begins here + var player = new Player(); + var computer = new Computer(); var clear = function() { ctx.clearRect(0, 0, WIDTH, HEIGHT); @@ -33,6 +57,8 @@ var render = function () { ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, WIDTH, HEIGHT); + player.render(); + computer.render(); }; var step = function() {
5b861da127b26493fa721cb65152edb8f06ab8bf
app/notes/notes.js
app/notes/notes.js
angular.module('marvelousnote.notes', [ 'ui.router' ]) .config(function($stateProvider) { $stateProvider .state('notes', { url: '/notes', templateUrl: 'notes/notes.html', controller: 'NotesController' }) .state('notes.form', { url: '/:noteId', templateUrl: 'notes/notes-form.html' }); }) .controller('NotesController', function(){ });
(function() { angular .module('marvelousnote.notes', ['ui.router']) .congig(notesConfig) .controller('NotesController', NotesController); function notesConfig($stateProvider) { $stateProvider .state('notes', { url: '/notes', templateUrl: 'notes/notes.html', controller: 'NotesController' }) .state('notes.form', { url: '/:noteId', templateUrl: 'notes/notes-form.html' }); } function NotesController($scope){ $scope.notes = []; $scope.save = function() { $scope.notes.push($scope.note); $scope.note = { title: '', body: '' }; }; } })();
Move NotesController and config to named functions.
Move NotesController and config to named functions.
JavaScript
mit
patriciachunk/MarvelousNote,patriciachunk/MarvelousNote
--- +++ @@ -1,8 +1,11 @@ -angular.module('marvelousnote.notes', [ - 'ui.router' -]) +(function() { + angular + .module('marvelousnote.notes', ['ui.router']) + .congig(notesConfig) + .controller('NotesController', NotesController); -.config(function($stateProvider) { + +function notesConfig($stateProvider) { $stateProvider .state('notes', { @@ -16,7 +19,13 @@ url: '/:noteId', templateUrl: 'notes/notes-form.html' }); -}) +} -.controller('NotesController', function(){ -}); +function NotesController($scope){ + $scope.notes = []; + $scope.save = function() { + $scope.notes.push($scope.note); + $scope.note = { title: '', body: '' }; + }; +} +})();
f1062cf3977db91ec257b63fd11e825f40df52aa
web/js/socket.js
web/js/socket.js
window.DEVELOPMENT_MODE = 'local-debug'; switch(window.DEVELOPMENT_MODE) { case 'local-debug': window.SOCKET_URI = '0.0.0.0'; break; case 'competition': default: window.SOCKET_URI = "roboRIO-2503-frc.local"; break; } window.SOCKET = new Socket("ws://" + window.SOCKET_URI + ":5800/"); function Socket(url) { this.url = url; this.socket = new WebSocket(url); /* TODO: Implement */ this.socket.onopen = null; this.socket.onmessage = null; this.socket.onerror = null; this.socket.onclose = null; this.send = function(data) { this.socket.send(data); } }
window.DEVELOPMENT_MODE = 'local-debug'; switch(window.DEVELOPMENT_MODE) { case 'local-debug': window.SOCKET_URI = '0.0.0.0'; break; case 'competition': default: window.SOCKET_URI = "roboRIO-2503-frc.local"; break; } function setupSocket(key, uri, messageCallback) { window[key] = new Socket(uri, (function() { setupSocket(key, uri, messageCallback); }), messageCallback); } function Socket(url, setupCallback, messageCallback) { this.url = url; this.socket = new WebSocket(url); this.setupCallback = setupCallback; this.messageCallback = messageCallback; /* TODO: Implement */ this.socket.onopen = function() { console.debug(arguments); }; this.socket.onmessage = function(messageEvent) { this.messageCallback(messageEvent); }; this.socket.onerror = function() { console.debug(arguments); }; this.socket.onclose = function() { setTimeout(function() { this.setupCallback(); }.bind(this), 500); }.bind(this); this.send = function(data) { this.socket.send(data); } } setupSocket('configuration_socket', 'ws://' + window.SOCKET_URI + ':5800/', function(messageEvent) { console.debug(messageEvent.data); });
Fix connection pipeline to be persistent in attempting to connect
Socket: Fix connection pipeline to be persistent in attempting to connect
JavaScript
mit
frc2503/r2016
--- +++ @@ -11,19 +11,42 @@ break; } -window.SOCKET = new Socket("ws://" + window.SOCKET_URI + ":5800/"); +function setupSocket(key, uri, messageCallback) { + window[key] = new Socket(uri, (function() { + setupSocket(key, uri, messageCallback); + }), messageCallback); +} -function Socket(url) { +function Socket(url, setupCallback, messageCallback) { this.url = url; this.socket = new WebSocket(url); + this.setupCallback = setupCallback; + this.messageCallback = messageCallback; /* TODO: Implement */ - this.socket.onopen = null; - this.socket.onmessage = null; - this.socket.onerror = null; - this.socket.onclose = null; + this.socket.onopen = function() { + console.debug(arguments); + }; + + this.socket.onmessage = function(messageEvent) { + this.messageCallback(messageEvent); + }; + + this.socket.onerror = function() { + console.debug(arguments); + }; + + this.socket.onclose = function() { + setTimeout(function() { + this.setupCallback(); + }.bind(this), 500); + }.bind(this); this.send = function(data) { this.socket.send(data); } } + +setupSocket('configuration_socket', 'ws://' + window.SOCKET_URI + ':5800/', function(messageEvent) { + console.debug(messageEvent.data); +});
95b5b40653b50eea009f6f240e0cd60d8110e94f
controllers/news.js
controllers/news.js
klimaChallenge.controller('newsCtrl', function($scope, $http, $sce) { $scope.facebookImages = Array(); $http.get('https://graph.facebook.com/v2.4/klimachallenge/photos/uploaded?fields=link,width,name,images&limit=10&access_token=846767055411205|UKF39DbxTvvEeA9BuKkWsJgiuLE'). success(function(data, status, headers, config) { angular.forEach(data.data, function(image, key) { // Only take images when they are big enough if (image.width >= 720) { if (image.name) { // Shorten image text if longer than 160 chars if (image.name.length > 160) { var newText = image.name.substring(0,140); var i = 140; while (image.name.charAt(i) != " ") { newText = newText + image.name.charAt(i); i++; } image.name = newText; image.showReadMore = true; } } $scope.facebookImages.push(image); } }); }); });
klimaChallenge.controller('newsCtrl', function($scope, $http, $sce) { $scope.facebookImages = Array(); $http.get('https://graph.facebook.com/v2.10/klimachallenge/photos/uploaded?fields=link,width,name,images&limit=10&access_token=846767055411205|UKF39DbxTvvEeA9BuKkWsJgiuLE'). success(function(data, status, headers, config) { angular.forEach(data.data, function(image, key) { // Only take images when they are big enough if (image.width >= 720) { if (image.name) { // Shorten image text if longer than 160 chars if (image.name.length > 160) { var newText = image.name.substring(0,140); var i = 140; while (image.name.charAt(i) != " ") { newText = newText + image.name.charAt(i); i++; } image.name = newText; image.showReadMore = true; } } $scope.facebookImages.push(image); } }); }); });
Upgrade Facebook API to v. 2.10
Upgrade Facebook API to v. 2.10
JavaScript
mit
stromhalm/klimachallenge,stromhalm/klimachallenge,stromhalm/klimachallenge
--- +++ @@ -2,7 +2,7 @@ $scope.facebookImages = Array(); - $http.get('https://graph.facebook.com/v2.4/klimachallenge/photos/uploaded?fields=link,width,name,images&limit=10&access_token=846767055411205|UKF39DbxTvvEeA9BuKkWsJgiuLE'). + $http.get('https://graph.facebook.com/v2.10/klimachallenge/photos/uploaded?fields=link,width,name,images&limit=10&access_token=846767055411205|UKF39DbxTvvEeA9BuKkWsJgiuLE'). success(function(data, status, headers, config) { angular.forEach(data.data, function(image, key) {
03c84159702761c70ebc9a3e2abd56048f04ac56
src/containers/weather_list.js
src/containers/weather_list.js
// Container to render a list of cities and their data // Saturday, February 25, 2017 import React, { Component } from 'react'; import { connect } from 'react-redux'; class WeatherList extends Component { render() { return ( <table className = 'table table-hover'> <thead> <tr> <th>City</th> <th>Temperature</th> <th>Pressure</th> <th>Humidity</th> </tr> </thead> <tbody> </tbody> </table> ); } } function mapStateToProps({ weather }) { return { weather }; // => ES6 syntax identical to { weather: weather} } export default connect(mapStateToProps)(WeatherList);
// Container to render a list of cities and their data // Saturday, February 25, 2017 import React, { Component } from 'react'; import { connect } from 'react-redux'; class WeatherList extends Component { constructor(props) { super(props); } renderForecast() { // this.props.weather => [{ }, { }] console.log('this.props.weather =', this.props.weather); return this.props.weather.map((city, index) => { return ( <tr key= {index}> <td> {city.name} </td> <td> {city.main.temp} </td> <td> {city.main.pressure} </td> <td> {city.main.humidity} </td> </tr> ); }); } render() { // props => returns an object with weather as a property // the value of weather is an array, with each element // representing a city searched by the user // the most recent city searched => this.props.weather[0] // accessing a value for each city's weather property: // => this.props.weather[0]{<value>} // console.log('WeatherList props.weather', this.props.weather); // <tr> => defines a row // <td> => defines a cell return ( <table className = 'table table-hover'> <thead> <tr> <th>City</th> <th>Temperature</th> <th>Pressure</th> <th>Humidity</th> </tr> </thead> <tbody> {this.renderForecast()} </tbody> </table> ); } } function mapStateToProps({ weather }) { return { weather }; // => ES6 syntax identical to { weather: weather} } export default connect(mapStateToProps)(WeatherList);
Create renderForecast() method to render each row of data in the weather table.
Create renderForecast() method to render each row of data in the weather table.
JavaScript
mit
jstowers/ReduxWeatherApp,jstowers/ReduxWeatherApp
--- +++ @@ -6,7 +6,51 @@ class WeatherList extends Component { + constructor(props) { + super(props); + + + } + + renderForecast() { + + // this.props.weather => [{ }, { }] + console.log('this.props.weather =', this.props.weather); + + return this.props.weather.map((city, index) => { + return ( + <tr key= {index}> + <td> + {city.name} + </td> + <td> + {city.main.temp} + </td> + <td> + {city.main.pressure} + </td> + <td> + {city.main.humidity} + </td> + </tr> + ); + }); + } + render() { + + // props => returns an object with weather as a property + // the value of weather is an array, with each element + // representing a city searched by the user + // the most recent city searched => this.props.weather[0] + + // accessing a value for each city's weather property: + // => this.props.weather[0]{<value>} + // console.log('WeatherList props.weather', this.props.weather); + + // <tr> => defines a row + // <td> => defines a cell + return ( <table className = 'table table-hover'> <thead> @@ -18,8 +62,7 @@ </tr> </thead> <tbody> - - + {this.renderForecast()} </tbody> </table> );
8fcdcd00b8a9c97a31c605ec4286984849be0378
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var moment = require('moment'); var fs = require('fs'); var simpleGit = require('simple-git')(); var semver = require('semver'); gulp.task('build', function () { // VERSION var versionFile = fs.readFileSync('package.json').toString().split('\n'); var version = versionFile[3].match(/\w*"version": "(.*)",/)[1]; version = semver.inc(version, 'patch'); versionFile[3] = ' "version": "' + version + '",'; fs.writeFileSync('package.json', versionFile.join('\n')); // CHANGELOG var data = fs.readFileSync('CHANGELOG.md').toString().split('\n'); var today = moment().format('YYYY-MM-DD'); data.splice(3, 0, '\n## RELEASE ' + version + ' - ' + today); var text = data.join('\n'); fs.writeFileSync('CHANGELOG.md', text); // COMMIT simpleGit.add(['CHANGELOG.md', 'package.json'], function () { simpleGit.commit('Release ' + version); }); });
'use strict'; var gulp = require('gulp'); var moment = require('moment'); var fs = require('fs'); var simpleGit = require('simple-git')(); var semver = require('semver'); gulp.task('build', function () { var numberToIncrement = 'patch'; if (process.argv && process.argv[3]) { var option = process.argv[3].replace('--', ''); if (['major', 'minor', 'patch'].indexOf(option) !== -1) { numberToIncrement = option; } } // VERSION var versionFile = fs.readFileSync('package.json').toString().split('\n'); var version = versionFile[3].match(/\w*"version": "(.*)",/)[1]; version = semver.inc(version, numberToIncrement); versionFile[3] = ' "version": "' + version + '",'; fs.writeFileSync('package.json', versionFile.join('\n')); // CHANGELOG var data = fs.readFileSync('CHANGELOG.md').toString().split('\n'); var today = moment().format('YYYY-MM-DD'); data.splice(3, 0, '\n## RELEASE ' + version + ' - ' + today); var text = data.join('\n'); fs.writeFileSync('CHANGELOG.md', text); // COMMIT simpleGit.add(['CHANGELOG.md', 'package.json'], function () { simpleGit.commit('Release ' + version); }); });
Build - Pass the major/minor/patch value as an option of the build command
Build - Pass the major/minor/patch value as an option of the build command
JavaScript
mit
SeyZ/forest-express-mongoose
--- +++ @@ -6,10 +6,18 @@ var semver = require('semver'); gulp.task('build', function () { + var numberToIncrement = 'patch'; + if (process.argv && process.argv[3]) { + var option = process.argv[3].replace('--', ''); + if (['major', 'minor', 'patch'].indexOf(option) !== -1) { + numberToIncrement = option; + } + } + // VERSION var versionFile = fs.readFileSync('package.json').toString().split('\n'); var version = versionFile[3].match(/\w*"version": "(.*)",/)[1]; - version = semver.inc(version, 'patch'); + version = semver.inc(version, numberToIncrement); versionFile[3] = ' "version": "' + version + '",'; fs.writeFileSync('package.json', versionFile.join('\n'));
f0015af6ec09fcadea4a0ac4daaf8a5635725952
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var gReact = require('gulp-react'); var del = require('del'); var shell = require('gulp-shell'); gulp.task('clean', function(cb) { del(['lib/', 'Flux.js'], cb); }); gulp.task('default', ['clean'], function() { return gulp.src('src/*.js') .pipe(gReact({harmony: true})) .pipe(gulp.dest('lib')); }); gulp.task('build-examples-website', ['clean'], shell.task([ 'git checkout gh-pages', 'git merge master', 'cd examples/vector-widget; ../../node_modules/.bin/webpack app.js bundle.js', 'cp -r examples/* .', 'git add --all .', 'git commit -m "Update website"', 'git push origin gh-pages', 'git checkout master' ]));
var gulp = require('gulp'); var gReact = require('gulp-react'); var del = require('del'); var shell = require('gulp-shell'); gulp.task('clean', function(cb) { del(['lib/', 'Flux.js'], cb); }); gulp.task('default', ['clean'], function() { return gulp.src('src/*.js') .pipe(gReact({harmony: true})) .pipe(gulp.dest('lib')); }); gulp.task('build-examples-website', ['clean'], shell.task([[ 'pushd ../react-art-gh-pages', 'git checkout -- .', 'git clean -dfx', 'git pull', 'rm -rf *', 'popd', 'pushd examples/vector-widget', 'npm install', 'npm run build', 'popd', 'cp -r examples/vector-widget/{index.html,bundle.js} ../react-art-gh-pages', 'pushd ../react-art-gh-pages', 'git add -A .', 'git commit -m "Update website"', 'popd', 'echo "react-art-gh-pages ready to push"' ].join(';')]));
Update to work with directory outside of cwd
Update to work with directory outside of cwd
JavaScript
bsd-3-clause
benchling/react-art,toddw/react-art,Sirlon/react-art,scgilardi/react-art,micahlmartin/react-art,kidaa/react-art,kidaa/react-art,reactjs/react-art
--- +++ @@ -14,13 +14,21 @@ }); -gulp.task('build-examples-website', ['clean'], shell.task([ - 'git checkout gh-pages', - 'git merge master', - 'cd examples/vector-widget; ../../node_modules/.bin/webpack app.js bundle.js', - 'cp -r examples/* .', - 'git add --all .', +gulp.task('build-examples-website', ['clean'], shell.task([[ + 'pushd ../react-art-gh-pages', + 'git checkout -- .', + 'git clean -dfx', + 'git pull', + 'rm -rf *', + 'popd', + 'pushd examples/vector-widget', + 'npm install', + 'npm run build', + 'popd', + 'cp -r examples/vector-widget/{index.html,bundle.js} ../react-art-gh-pages', + 'pushd ../react-art-gh-pages', + 'git add -A .', 'git commit -m "Update website"', - 'git push origin gh-pages', - 'git checkout master' -])); + 'popd', + 'echo "react-art-gh-pages ready to push"' +].join(';')]));
5d912e756862ff62f160e7ada15531a8162811ac
web/gcode-parser.js
web/gcode-parser.js
/** * Parses a string of gcode instructions, and invokes handlers for * each type of command. * * Special handler: * 'default': Called if no other handler matches. */ function GCodeParser(handlers) { this.handlers = handlers || {}; } GCodeParser.prototype.parseLine = function(text, info) { text = text.replace(/;.*$/, '').trim(); // Remove comments if (text) { var tokens = text.split(' '); if (tokens) { var cmd = tokens[0]; var args = { 'cmd': cmd }; tokens.splice(1).forEach(function(token) { var key = token[0].toLowerCase(); var value = parseFloat(token.substring(1)); args[key] = value; }); var handler = this.handlers[tokens[0]] || this.handlers['default']; if (handler) { return handler(args, info); } } } }; GCodeParser.prototype.parse = function(gcode) { var lines = gcode.split('\n'); for (var i = 0; i < lines.length; i++) { if (this.parseLine(lines[i], i) === false) { break; } } };
/** * Parses a string of gcode instructions, and invokes handlers for * each type of command. * * Special handler: * 'default': Called if no other handler matches. */ function GCodeParser(handlers) { this.handlers = handlers || {}; } GCodeParser.prototype.parseLine = function(text, info) { text = text.replace(/[;(].*$/, '').trim(); // Remove comments if (text) { var tokens = text.split(' '); if (tokens) { var cmd = tokens[0]; var args = { 'cmd': cmd }; tokens.splice(1).forEach(function(token) { var key = token[0].toLowerCase(); var value = parseFloat(token.substring(1)); args[key] = value; }); var handler = this.handlers[tokens[0]] || this.handlers['default']; if (handler) { return handler(args, info); } } } }; GCodeParser.prototype.parse = function(gcode) { var lines = gcode.split('\n'); for (var i = 0; i < lines.length; i++) { if (this.parseLine(lines[i], i) === false) { break; } } };
Support mach3 style comments with parentheses.
Support mach3 style comments with parentheses.
JavaScript
mit
jherrm/gcode-viewer,cheton/gcode-viewer,cheton/gcode-viewer
--- +++ @@ -10,7 +10,7 @@ } GCodeParser.prototype.parseLine = function(text, info) { - text = text.replace(/;.*$/, '').trim(); // Remove comments + text = text.replace(/[;(].*$/, '').trim(); // Remove comments if (text) { var tokens = text.split(' '); if (tokens) {
f0131fe468efcca8fafdc020269e1eda52374f4c
client/common/event_actions.js
client/common/event_actions.js
/** * Assigns handlers/listeners for `[data-action]` links. * * Actions associated with a link will be invoked via Wire with the jQuery * event object as an argument. **/ 'use strict'; /*global NodecaLoader, N, window*/ var $ = window.jQuery; $(function () { ['click', 'submit', 'input'].forEach(function (action) { var eventName = action + '.nodeca.data-api' , attribute = '[data-on-' + action + ']'; $('body').on(eventName, attribute, function (event) { var apiPath = $(this).data('on-' + action); NodecaLoader.loadAssets(apiPath.split('.').shift(), function () { if (N.wire.has(apiPath)) { N.wire.emit(apiPath, event); } else { N.logger.error('Unknown client Wire handler: %s', apiPath); } }); return false; }); }); });
/** * Assigns handlers/listeners for `[data-action]` links. * * Actions associated with a link will be invoked via Wire with the jQuery * event object as an argument. **/ 'use strict'; /*global NodecaLoader, N, window*/ var $ = window.jQuery; $(function () { ['click', 'submit', 'input'].forEach(function (action) { var eventName = action + '.nodeca.data-api' , attribute = '[data-on-' + action + ']'; $('body').on(eventName, attribute, function (event) { var apiPath = $(this).data('on-' + action); NodecaLoader.loadAssets(apiPath.split('.').shift(), function () { if (N.wire.has(apiPath)) { N.wire.emit(apiPath, event); } else { N.logger.error('Unknown client Wire handler: %s', apiPath); } }); event.preventDefault(); return false; }); }); });
Add `event.preventDefault()` call in UJS action handlers.
Add `event.preventDefault()` call in UJS action handlers.
JavaScript
mit
nodeca/nodeca.core,nodeca/nodeca.core
--- +++ @@ -31,6 +31,7 @@ } }); + event.preventDefault(); return false; }); });
abe4633a8484bce38e188871d24facf909099b2f
server/routes/rootRoute.js
server/routes/rootRoute.js
/** * Created by Omnius on 6/25/16. */ 'use strict'; const security = { xframe: { rule: 'sameorigin' }, hsts: { maxAge: '31536000', includeSubdomains: true }, xss: true }; module.exports = [ { // Web login path: '/', method: 'GET', config: { handler: { rootHandler: { type: 'index' } }, cache: { privacy: 'public' }, security } }, // Invalid paths { path: '/{path*}', method: '*', config: { handler: { rootHandler: { type: 'notfound' } }, cache: { privacy: 'public' }, security } } ];
/** * Created by Omnius on 6/25/16. */ 'use strict'; const security = { xframe: { rule: 'sameorigin' }, hsts: { maxAge: '31536000', includeSubdomains: true }, xss: true }; module.exports = [ { // Web login path: '/', method: 'GET', config: { cache: { privacy: 'public' }, handler: { rootHandler: { type: 'index' } }, security } }, // Invalid paths { path: '/{path*}', method: '*', config: { cache: { privacy: 'public' }, handler: { rootHandler: { type: 'notfound' } }, security } } ];
Rearrange object codes - no significant change
Rearrange object codes - no significant change
JavaScript
mit
identityclash/hapi-login-test,identityclash/hapi-login-test
--- +++ @@ -20,13 +20,13 @@ path: '/', method: 'GET', config: { + cache: { + privacy: 'public' + }, handler: { rootHandler: { type: 'index' } - }, - cache: { - privacy: 'public' }, security } @@ -36,14 +36,14 @@ path: '/{path*}', method: '*', config: { + cache: { + privacy: 'public' + }, handler: { rootHandler: { type: 'notfound' } }, - cache: { - privacy: 'public' - }, security } }
9ec4e70f81966dd0590b03f418fe5b973a5a838b
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var stylus = require('gulp-stylus'); var rename = require('gulp-rename'); var mainStyl = './styl/main.styl'; gulp.task('build:dev', function() { gulp.src(mainStyl) .pipe(sourcemaps.init()) .pipe(stylus()) .pipe(sourcemaps.write()) .pipe(rename('baremetal.css')) .pipe(gulp.dest('./build/development')); }); gulp.task('build:prod', function() { gulp.src(mainStyl) .pipe(stylus({ compress: true })) .pipe(rename('baremetal.min.css')) .pipe(gulp.dest('./build/production')); gulp.src(mainStyl) .pipe(stylus()) .pipe(rename('baremetal.css')) .pipe(gulp.dest('./build/production')); }); gulp.task('stylus:watch', function() { gulp.watch('./styl/**/*.styl', ['stylus:main']); }); gulp.task('watch', ['build:dev', 'stylus:watch']); gulp.task('default', ['build:dev', 'build:prod']);
var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var stylus = require('gulp-stylus'); var rename = require('gulp-rename'); var mainStyl = './styl/main.styl'; gulp.task('build:dev', function() { gulp.src(mainStyl) .pipe(sourcemaps.init()) .pipe(stylus()) .pipe(sourcemaps.write()) .pipe(rename('baremetal.css')) .pipe(gulp.dest('./build/development')); }); gulp.task('build:prod', function() { gulp.src(mainStyl) .pipe(stylus({ compress: true })) .pipe(rename('baremetal.min.css')) .pipe(gulp.dest('./build/production')); gulp.src(mainStyl) .pipe(stylus()) .pipe(rename('baremetal.css')) .pipe(gulp.dest('./build/production')); }); gulp.task('stylus:watch', function() { gulp.watch('./styl/**/*.styl', ['build:dev']); }); gulp.task('watch', ['build:dev', 'stylus:watch']); gulp.task('default', ['build:dev', 'build:prod']);
Fix wrong gulp task during watch
Fix wrong gulp task during watch
JavaScript
mit
RyenNelsen/baremetal
--- +++ @@ -26,7 +26,7 @@ }); gulp.task('stylus:watch', function() { - gulp.watch('./styl/**/*.styl', ['stylus:main']); + gulp.watch('./styl/**/*.styl', ['build:dev']); }); gulp.task('watch', ['build:dev', 'stylus:watch']);
d1f84e072d74c50dd67be17bd448cbaf672e6d19
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var casperjs = require('gulp-casperjs'); var spawn = require('child_process').spawn; var gutil = require('gulp-util'); gulp.task('integrate', function(){ gulp.src('./spec/integration/**') .pipe(casperjs({command:'test'})); }); gulp.task('integrate:win', function () { var tests = ['./spec/integration']; var casperChild = spawn('casperjs.cmd', ['test'].concat(tests)); casperChild.stdout.on('data', function (data) { gutil.log('CasperJS:', data.toString().slice(0, -1)); // Remove \n }); casperChild.on('close', function (code) { console.log("Test has finished!"); }); });
'use strict'; var gulp = require('gulp'); var casperjs = require('gulp-casperjs'); var spawn = require('child_process').spawn; gulp.task('integrate', function(){ gulp.src('./spec/integration/**') .pipe(casperjs({command:'test'})); });
Remove unused Windows integrate code
Remove unused Windows integrate code
JavaScript
mit
startersacademy/fullstack-project-01,startersacademy/fullstack-project-01
--- +++ @@ -3,22 +3,8 @@ var gulp = require('gulp'); var casperjs = require('gulp-casperjs'); var spawn = require('child_process').spawn; -var gutil = require('gulp-util'); gulp.task('integrate', function(){ gulp.src('./spec/integration/**') .pipe(casperjs({command:'test'})); }); - -gulp.task('integrate:win', function () { - var tests = ['./spec/integration']; - var casperChild = spawn('casperjs.cmd', ['test'].concat(tests)); - casperChild.stdout.on('data', function (data) { - gutil.log('CasperJS:', data.toString().slice(0, -1)); // Remove \n - }); - - casperChild.on('close', function (code) { - console.log("Test has finished!"); - }); - -});
ce0da6d74e4103431422f120134ef8a43f700cc4
webpack.config.js
webpack.config.js
module.exports = { entry: "./index.jsx", output: { path: __dirname, filename: "./build/bundle.js" }, module: { loaders: [ {test: /\.(jsx|js)$/, loader: "babel-loader"}, {test: /\.md$/, loader: "raw-loader"}, {test: /\.json$/, loader: "json-loader"} ] } };
module.exports = { entry: "./index.jsx", output: { path: __dirname, filename: "./build/bundle.js" }, resolve: { extensions: ['', '.js', '.jsx', '.json'] }, module: { loaders: [ {test: /\.(jsx|js)$/, loader: "babel-loader"}, {test: /\.md$/, loader: "raw-loader"}, {test: /\.json$/, loader: "json-loader"} ] } };
Resolve the jsx in import-s
Resolve the jsx in import-s
JavaScript
mit
ikr/estimates-template,ikr/estimates-template
--- +++ @@ -4,6 +4,10 @@ output: { path: __dirname, filename: "./build/bundle.js" + }, + + resolve: { + extensions: ['', '.js', '.jsx', '.json'] }, module: {
d497926e4a55d4b71c997cab7ebe6a00ee4e7ad9
client/new-paula.js
client/new-paula.js
import React from 'react'; import {connect} from 'react-redux'; import * as actions from './actions'; export default class NewPaula extends React.Component { update(e) { e.preventDefault(); this.props.dispatch(actions.replace_paula(this.refs.paula.value)); } render() { return <form onSubmit={this.update}> <input ref="paula" /> <input type="submit" value="Replace Paula" /> </form>; } }
import React from 'react'; import {connect} from 'react-redux'; import * as actions from './actions'; export default connect()(class NewPaula extends React.Component { update(e) { e.preventDefault(); this.props.dispatch(actions.replace_paula(this.refs.paula.value)); } render() { return <form onSubmit={this.update.bind(this)}> <input ref="paula" /> <input type="submit" value="Replace Paula" /> </form>; } })
Debug Paula's bean for her
Debug Paula's bean for her
JavaScript
mit
Rosuav/monopoly-open-bid,oshirodk/dogMatch,alexpoe22/fuzzyFinder,oshirodk/dogMatch,jbenjaminy/fullstack-app-template,jbenjaminy/fullstack-app-template,alexpoe22/fuzzyFinder,Rosuav/monopoly-open-bid,Rosuav/monopoly-open-bid
--- +++ @@ -2,16 +2,16 @@ import {connect} from 'react-redux'; import * as actions from './actions'; -export default class NewPaula extends React.Component { +export default connect()(class NewPaula extends React.Component { update(e) { e.preventDefault(); this.props.dispatch(actions.replace_paula(this.refs.paula.value)); } render() { - return <form onSubmit={this.update}> + return <form onSubmit={this.update.bind(this)}> <input ref="paula" /> <input type="submit" value="Replace Paula" /> </form>; } -} +})