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
718b82fb3e43b2dc1f40effa365cad90a40f8476
src/editor/selection-rect.js
src/editor/selection-rect.js
var Rect = require('./rect'); exports.get = function() { var selection = window.getSelection(); if (!selection.rangeCount) { return; } else if (selection.isCollapsed) { var range = selection.getRangeAt(0); var rects = range.getClientRects(); var rect = rects[rects.length - 1]; if (!rect) { var shadowCaret = document.createTextNode('|'); range.insertNode(shadowCaret); range.selectNode(shadowCaret); rect = range.getBoundingClientRect(); shadowCaret.parentNode.removeChild(shadowCaret); } return new Rect(rect); } else { return new Rect(selection.getRangeAt(0).getBoundingClientRect()); } };
var Rect = require('./rect'); exports.get = function() { var selection = window.getSelection(); if (!selection.rangeCount) { return; } else if (selection.isCollapsed) { var range = selection.getRangeAt(0); var rects = range.getClientRects(); var rect = rects[rects.length - 1]; if (!rect && range.startContainer.nodeType === Node.ELEMENT_NODE) { var child = range.startContainer.childNodes[range.startOffset]; rect = child.getBoundingClientRect(); } if (!rect) { var shadowCaret = document.createTextNode('|'); range.insertNode(shadowCaret); rect = range.getBoundingClientRect(); shadowCaret.parentNode.removeChild(shadowCaret); } return new Rect(rect); } else { return new Rect(selection.getRangeAt(0).getBoundingClientRect()); } };
Fix selection rect to be less obtrusive
Fix selection rect to be less obtrusive
JavaScript
mit
jacwright/typewriter,jacwright/typewriter
--- +++ @@ -8,10 +8,13 @@ var range = selection.getRangeAt(0); var rects = range.getClientRects(); var rect = rects[rects.length - 1]; + if (!rect && range.startContainer.nodeType === Node.ELEMENT_NODE) { + var child = range.startContainer.childNodes[range.startOffset]; + rect = child.getBoundingClientRect(); + } if (!rect) { var shadowCaret = document.createTextNode('|'); range.insertNode(shadowCaret); - range.selectNode(shadowCaret); rect = range.getBoundingClientRect(); shadowCaret.parentNode.removeChild(shadowCaret); }
33251e65666c4619c8551c515d85ca28d161a112
src/SdkConfig.js
src/SdkConfig.js
/* Copyright 2016 OpenMarket Ltd 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 DEFAULTS = { // URL to a page we show in an iframe to configure integrations integrations_ui_url: "https://scalar.vector.im/", // Base URL to the REST interface of the integrations server integrations_rest_url: "https://scalar.vector.im/api", }; class SdkConfig { static get() { return global.mxReactSdkConfig; } static put(cfg) { var defaultKeys = Object.keys(DEFAULTS); for (var i = 0; i < defaultKeys.length; ++i) { if (cfg[defaultKeys[i]] === undefined) { cfg[defaultKeys[i]] = DEFAULTS[defaultKeys[i]]; } } global.mxReactSdkConfig = cfg; } static unset() { global.mxReactSdkConfig = undefined; } } module.exports = SdkConfig;
/* Copyright 2016 OpenMarket Ltd 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 DEFAULTS = { }; class SdkConfig { static get() { return global.mxReactSdkConfig; } static put(cfg) { var defaultKeys = Object.keys(DEFAULTS); for (var i = 0; i < defaultKeys.length; ++i) { if (cfg[defaultKeys[i]] === undefined) { cfg[defaultKeys[i]] = DEFAULTS[defaultKeys[i]]; } } global.mxReactSdkConfig = cfg; } static unset() { global.mxReactSdkConfig = undefined; } } module.exports = SdkConfig;
Remove default options that shouldn't be part of this PR
Remove default options that shouldn't be part of this PR
JavaScript
apache-2.0
matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk
--- +++ @@ -15,10 +15,6 @@ */ var DEFAULTS = { - // URL to a page we show in an iframe to configure integrations - integrations_ui_url: "https://scalar.vector.im/", - // Base URL to the REST interface of the integrations server - integrations_rest_url: "https://scalar.vector.im/api", }; class SdkConfig {
4699d58fb0fa8a93db109a9ba3da550c5daac0e3
src/cli-apply.js
src/cli-apply.js
import execute from './core'; import adminApi from './adminApi'; import colors from 'colors'; import configLoader from './configLoader'; import program from 'commander'; program .version(require("../package.json").version) .option('--path <value>', 'Path to the configuration file') .option('--host <value>', 'Kong admin host (default: localhost:8001)', 'localhost:8001') .parse(process.argv); if (!program.path) { console.log('--path to the config file is required'.red); process.exit(1); } let config = configLoader(program.path); let host = program.host || config.host; if (!host) { console.log('Kong admin host must be specified in config or --host'.red); process.exit(1); } console.log(`Apply config to ${host}`.green); execute(config, adminApi(host)) .catch(error => { console.log(`${error}`.red, '\n', error.stack); process.exit(1); });
import execute from './core'; import adminApi from './adminApi'; import colors from 'colors'; import configLoader from './configLoader'; import program from 'commander'; program .version(require("../package.json").version) .option('--path <value>', 'Path to the configuration file') .option('--host <value>', 'Kong admin host (default: localhost:8001)') .parse(process.argv); if (!program.path) { console.log('--path to the config file is required'.red); process.exit(1); } let config = configLoader(program.path); let host = program.host || config.host || 'localhost:8001'; if (!host) { console.log('Kong admin host must be specified in config or --host'.red); process.exit(1); } console.log(`Apply config to ${host}`.green); execute(config, adminApi(host)) .catch(error => { console.log(`${error}`.red, '\n', error.stack); process.exit(1); });
Fix reading the host from the config file
Fix reading the host from the config file
JavaScript
mit
JnMik/kongfig,mybuilder/kongfig,JnMik/kongfig
--- +++ @@ -7,7 +7,7 @@ program .version(require("../package.json").version) .option('--path <value>', 'Path to the configuration file') - .option('--host <value>', 'Kong admin host (default: localhost:8001)', 'localhost:8001') + .option('--host <value>', 'Kong admin host (default: localhost:8001)') .parse(process.argv); if (!program.path) { @@ -16,7 +16,7 @@ } let config = configLoader(program.path); -let host = program.host || config.host; +let host = program.host || config.host || 'localhost:8001'; if (!host) { console.log('Kong admin host must be specified in config or --host'.red);
280934c9c513cba3be83fb7478a0d2c349281d26
srv/api.js
srv/api.js
/** * API endpoints for backend */ const api = require('express').Router(); api.use((req, res, next) => { // redirect requests like ?t=foo/bar to foo/bar if (req.query.t) { return res.redirect(req.query.t); } next(); }); api.use((req, res) => { res.status(400).send('Unknown API endpoint'); }); module.exports = api;
/** * API endpoints for backend */ const api = require('express').Router(); api.use((req, res, next) => { // redirect requests like ?t=foo/bar to foo/bar if (req.query.t) { return res.redirect(`${req.query.t}?old=true`); } next(); }); api.use((req, res) => { res.status(400).send('Unknown API endpoint'); }); module.exports = api;
Add old flag to old-style requests (ready for new database system)
Add old flag to old-style requests (ready for new database system)
JavaScript
mit
felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget
--- +++ @@ -7,7 +7,7 @@ api.use((req, res, next) => { // redirect requests like ?t=foo/bar to foo/bar if (req.query.t) { - return res.redirect(req.query.t); + return res.redirect(`${req.query.t}?old=true`); } next();
1f11d411a5b6c915e7b35dae4d847a3ccb98e830
src/reducers/initialState.js
src/reducers/initialState.js
export default { restaurantReviews: { filter: '', searchType: 'name', restaurants: [], pagerNum: 1, loading: true, loadingError: null, activeItem: null, initialLoad: true, ratingFilter: 1234 } };
export default { restaurantReviews: { filter: '', searchType: 'name', restaurants: [], pagerNum: 1, loading: true, loadingError: null, activeItem: null, initialLoad: true, ratingFilter: 0 } };
Set rating filter to zero
Set rating filter to zero
JavaScript
mit
aragonwa/kc-restaurant-reviews,aragonwa/kc-restaurant-reviews
--- +++ @@ -9,6 +9,6 @@ loadingError: null, activeItem: null, initialLoad: true, - ratingFilter: 1234 + ratingFilter: 0 } };
ee776c085d9c4f064f87a1e5a093a7482ded4b57
public/js/controllers/SignIn.js
public/js/controllers/SignIn.js
define(['jquery', 'app', 'services/User'], function ($, app) { var services = [ { name: 'Facebook' }, { name: 'Github' }, { name: 'Google' } ]; return app.controller('SignInController', ['$scope', '$window', 'userService', function (scope, win, User) { scope.services = services; scope.userAvatar = User.getUserHash() || ''; scope.signInWithStrategy = function () { win.location = '/auth/' + this.service.name.toLowerCase(); }; scope.signedIn = function () { return User.signedIn(); }; scope.signOut = function () { return User.signOut(); }; scope.toggleTOS = function () { scope.tosExpanded = !scope.tosExpanded; }; $('#signIn') .on('opened', function () { $(this).find('button')[0].focus(); }) .on('closed', function () { $('[data-dropdown="signIn"]').focus(); }); }]); });
define(['jquery', 'app', 'services/User'], function ($, app) { var services = [ { name: 'Facebook' }, { name: 'Github' }, { name: 'Google' } ]; return app.controller('SignInController', ['$scope', '$window', 'userService', 'historyService', 'settingsService', function (scope, win, User, historyService, settingsService) { scope.services = services; scope.userAvatar = User.getUserHash() || ''; scope.signInWithStrategy = function () { win.location = '/auth/' + this.service.name.toLowerCase(); }; scope.signedIn = function () { return User.signedIn(); }; scope.signOut = function () { return User.signOut().then(function () { historyService.destroy(); settingsService.destroy(); }); }; scope.toggleTOS = function () { scope.tosExpanded = !scope.tosExpanded; }; $('#signIn') .on('opened', function () { $(this).find('button')[0].focus(); }) .on('closed', function () { $('[data-dropdown="signIn"]').focus(); }); }]); });
Clear local storage on log out
Clear local storage on log out
JavaScript
mit
BrettBukowski/tomatar
--- +++ @@ -5,7 +5,8 @@ { name: 'Google' } ]; - return app.controller('SignInController', ['$scope', '$window', 'userService', function (scope, win, User) { + return app.controller('SignInController', ['$scope', '$window', 'userService', 'historyService', 'settingsService', + function (scope, win, User, historyService, settingsService) { scope.services = services; scope.userAvatar = User.getUserHash() || ''; @@ -18,7 +19,10 @@ }; scope.signOut = function () { - return User.signOut(); + return User.signOut().then(function () { + historyService.destroy(); + settingsService.destroy(); + }); }; scope.toggleTOS = function () {
6f66d99cb9bf120919991600dd96cbe066dcbe5f
phantomas.js
phantomas.js
/** * PhantomJS-based web performance metrics collector * * Usage: * node phantomas.js * --url=<page to check> * --debug * --verbose * * @version 0.2 */ // parse script arguments var params = require('./lib/args').parse(phantom.args), phantomas = require('./core/phantomas').phantomas; // run phantomas var instance = new phantomas(params); // add 3rd party modules instance.addModule('assetsTypes'); instance.addModule('cacheHits'); instance.addModule('cookies'); instance.addModule('domComplexity'); //instance.addModule('domQueries'); // FIXME: jQuery mockup generates random issues instance.addModule('domains'); instance.addModule('headers'); instance.addModule('requestsStats'); instance.addModule('localStorage'); instance.addModule('waterfall'); instance.addModule('windowPerformance'); // and finally - run it! instance.run();
/** * PhantomJS-based web performance metrics collector * * Usage: * node phantomas.js * --url=<page to check> * --debug * --verbose * * @version 0.2 */ // parse script arguments var args = require("system").args, params = require('./lib/args').parse(args), phantomas = require('./core/phantomas').phantomas; // run phantomas var instance = new phantomas(params); // add 3rd party modules instance.addModule('assetsTypes'); instance.addModule('cacheHits'); instance.addModule('cookies'); instance.addModule('domComplexity'); //instance.addModule('domQueries'); // FIXME: jQuery mockup generates random issues instance.addModule('domains'); instance.addModule('headers'); instance.addModule('requestsStats'); instance.addModule('localStorage'); instance.addModule('waterfall'); instance.addModule('windowPerformance'); // and finally - run it! instance.run();
Use system module to get command line arguments
Use system module to get command line arguments
JavaScript
bsd-2-clause
ingoclaro/phantomas,william-p/phantomas,william-p/phantomas,gmetais/phantomas,ingoclaro/phantomas,gmetais/phantomas,macbre/phantomas,macbre/phantomas,macbre/phantomas,ingoclaro/phantomas,william-p/phantomas,gmetais/phantomas
--- +++ @@ -11,7 +11,8 @@ */ // parse script arguments -var params = require('./lib/args').parse(phantom.args), +var args = require("system").args, + params = require('./lib/args').parse(args), phantomas = require('./core/phantomas').phantomas; // run phantomas
e3e3cb7b768a6d0f2e4e64cd265f088d1713c90b
src/shared/components/idme/idme.js
src/shared/components/idme/idme.js
import React, { Component } from 'react'; import config from 'config/environment'; import troopImage from 'images/Troop.png'; import styles from './idme.css'; class Idme extends Component { onKeyUp = (event) => { if (event.key === 'Enter') { this.idMe(); } }; onClick = () => { window.open(`${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${ config.host }/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`); }; render() { return ( <div className={styles.wrapper}> <span className={styles.authbtn} role="link" onClick={this.onClick} onKeyUp={this.onKeyUp} tabIndex={0} > <img className={styles.authImage} src={troopImage} alt="Verify your status with Id.Me" /> </span> </div> ); } } export default Idme;
import React, { Component } from 'react'; import config from 'config/environment'; import troopImage from 'images/Troop.png'; import styles from './idme.css'; class Idme extends Component { openIDME = () => { window.open(`${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${ config.host }/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`); }; render() { return ( <div className={styles.wrapper}> {/* eslint-disable jsx-a11y/click-events-have-key-events */} <span className={styles.authbtn} role="link" onClick={this.openIDME} tabIndex={0}> <img className={styles.authImage} src={troopImage} alt="Verify your status with Id.Me" /> </span> </div> ); } } export default Idme;
Revert refactor to keep PR scoped well
Revert refactor to keep PR scoped well
JavaScript
mit
NestorSegura/operationcode_frontend,sethbergman/operationcode_frontend,hollomancer/operationcode_frontend,NestorSegura/operationcode_frontend,OperationCode/operationcode_frontend,sethbergman/operationcode_frontend,OperationCode/operationcode_frontend,hollomancer/operationcode_frontend,sethbergman/operationcode_frontend,hollomancer/operationcode_frontend,NestorSegura/operationcode_frontend,OperationCode/operationcode_frontend
--- +++ @@ -4,13 +4,7 @@ import styles from './idme.css'; class Idme extends Component { - onKeyUp = (event) => { - if (event.key === 'Enter') { - this.idMe(); - } - }; - - onClick = () => { + openIDME = () => { window.open(`${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${ config.host }/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`); @@ -19,13 +13,8 @@ render() { return ( <div className={styles.wrapper}> - <span - className={styles.authbtn} - role="link" - onClick={this.onClick} - onKeyUp={this.onKeyUp} - tabIndex={0} - > + {/* eslint-disable jsx-a11y/click-events-have-key-events */} + <span className={styles.authbtn} role="link" onClick={this.openIDME} tabIndex={0}> <img className={styles.authImage} src={troopImage} alt="Verify your status with Id.Me" /> </span> </div>
8bcf3a1c8a8aa3d1a95f6731a277f4c27b292e37
test/can_test.js
test/can_test.js
steal('can/util/mvc.js') .then('funcunit/qunit', 'can/test/fixture.js') .then(function() { // Set the test timeout to five minutes QUnit.config.testTimeout = 300000; }) .then('./mvc_test.js', 'can/construct/construct_test.js', 'can/observe/observe_test.js', 'can/view/view_test.js', 'can/control/control_test.js', 'can/model/model_test.js', 'can/view/ejs/ejs_test.js')
steal('can/util/mvc.js') .then('funcunit/qunit', 'can/test/fixture.js') .then(function() { var oldmodule = window.module, library = 'jQuery'; // Set the test timeout to five minutes QUnit.config.testTimeout = 300000; if (window.STEALDOJO){ library = 'Dojo'; } else if( window.STEALMOO) { library = 'Mootools'; } else if(window.STEALYUI){ library = 'YUI'; } else if(window.STEALZEPTO){ library = 'Zepto'; } window.module = function(name, testEnvironment) { oldmodule(library + '/' + name, testEnvironment); } }) .then('./mvc_test.js', 'can/construct/construct_test.js', 'can/observe/observe_test.js', 'can/view/view_test.js', 'can/control/control_test.js', 'can/model/model_test.js', 'can/view/ejs/ejs_test.js')
Add library name to QUnit modules
Add library name to QUnit modules
JavaScript
mit
yusufsafak/canjs,Psykoral/canjs,rasjani/canjs,whitecolor/canjs,tracer99/canjs,bitovi/canjs,bitovi/canjs,airhadoken/canjs,schmod/canjs,asavoy/canjs,jebaird/canjs,thecountofzero/canjs,beno/canjs,WearyMonkey/canjs,Psykoral/canjs,UXsree/canjs,gsmeets/canjs,juristr/canjs,cohuman/canjs,cohuman/canjs,bitovi/canjs,patrick-steele-idem/canjs,mindscratch/canjs,airhadoken/canjs,asavoy/canjs,scorphus/canjs,ackl/canjs,tracer99/canjs,SpredfastLegacy/canjs,WearyMonkey/canjs,rjgotten/canjs,rasjani/canjs,sporto/canjs,cohuman/canjs,scorphus/canjs,dispatchrabbi/canjs,mindscratch/canjs,rasjani/canjs,beno/canjs,schmod/canjs,UXsree/canjs,janza/canjs,jebaird/canjs,janza/canjs,thomblake/canjs,yusufsafak/canjs,dispatchrabbi/canjs,gsmeets/canjs,schmod/canjs,bitovi/canjs,tracer99/canjs,shiftplanning/canjs,thomblake/canjs,Psykoral/canjs,patrick-steele-idem/canjs,shiftplanning/canjs,dimaf/canjs,gsmeets/canjs,azazel75/canjs,whitecolor/canjs,thecountofzero/canjs,rasjani/canjs,juristr/canjs,rjgotten/canjs,dimaf/canjs,azazel75/canjs,ackl/canjs,sporto/canjs,Psykoral/canjs,ackl/canjs,SpredfastLegacy/canjs,sporto/canjs,patrick-steele-idem/canjs,rjgotten/canjs,whitecolor/canjs,beno/canjs,rjgotten/canjs,WearyMonkey/canjs,jebaird/canjs
--- +++ @@ -2,8 +2,23 @@ .then('funcunit/qunit', 'can/test/fixture.js') .then(function() { + var oldmodule = window.module, + library = 'jQuery'; // Set the test timeout to five minutes QUnit.config.testTimeout = 300000; + + if (window.STEALDOJO){ + library = 'Dojo'; + } else if( window.STEALMOO) { + library = 'Mootools'; + } else if(window.STEALYUI){ + library = 'YUI'; + } else if(window.STEALZEPTO){ + library = 'Zepto'; + } + window.module = function(name, testEnvironment) { + oldmodule(library + '/' + name, testEnvironment); + } }) .then('./mvc_test.js', 'can/construct/construct_test.js',
c454f86695e6360e31d7539967979185e4732655
src/Sprite.js
src/Sprite.js
/** * Creates an utility to manage sprites. * * @param Image The image data of the sprite */ var Sprite = function(img) { this.img = img; this.descriptors = []; }; Sprite.prototype = { registerId: function(id, position, width, height) { this.descriptors.push({ id: id, position: position, width: width, height: height, }); return this; }, draw: function(ctx, id, position) { var spritePart = search(this.descriptors, 'id', id); if(spritePart === null) { return this; } ctx.drawImage( this.img, spritePart.position.x, spritePart.position.y, spritePart.width, spritePart.height, position.x, position.y, spritePart.width, spritePart.height ); return this; }, };
/** * Creates an utility to manage sprites. * * @param Image The image data of the sprite */ var Sprite = function(img) { this.img = img; this.descriptors = []; }; Sprite.prototype = { registerIds: function(array) { for(var i = array.length - 1; i >= 0; i--) { this.registerId( array[i].id, array[i].position, array[i].width, array[i].height ); } }, registerId: function(id, position, width, height) { this.descriptors.push({ id: id, position: position, width: width, height: height, }); return this; }, draw: function(ctx, id, position) { var spritePart = search(this.descriptors, 'id', id); if(spritePart === null) { return this; } ctx.drawImage( this.img, spritePart.position.x, spritePart.position.y, spritePart.width, spritePart.height, position.x, position.y, spritePart.width, spritePart.height ); return this; }, };
Add ability to register multiple sprite ids at once
Add ability to register multiple sprite ids at once
JavaScript
mit
bendem/JsGameLib
--- +++ @@ -9,6 +9,17 @@ }; Sprite.prototype = { + registerIds: function(array) { + for(var i = array.length - 1; i >= 0; i--) { + this.registerId( + array[i].id, + array[i].position, + array[i].width, + array[i].height + ); + } + }, + registerId: function(id, position, width, height) { this.descriptors.push({ id: id,
49f7f0e3a2c4f00d38c5ad807c38f94a447e1376
lib/exec/source-map.js
lib/exec/source-map.js
var fs = require('fs'), sourceMap = require('source-map'); module.exports.create = function() { var cache = {}; function loadSourceMap(file) { try { var body = fs.readFileSync(file + '.map'); return new sourceMap.SourceMapConsumer(body.toString()); } catch (err) { /* NOP */ } } return { map: function(file, line, column) { if (cache[file] === undefined) { cache[file] = loadSourceMap(file) || false; } if (!cache[file]) { return {source: file, line: line, column: column}; } else { return cache[file].originalPositionFor({line: line, column: column || 1}); } }, reset: function() { cache = {}; } }; };
var fs = require('fs'), sourceMap = require('source-map'); module.exports.create = function() { var cache = {}; function loadSourceMap(file) { try { var body = fs.readFileSync(file + '.map'); return new sourceMap.SourceMapConsumer(body.toString()); } catch (err) { /* NOP */ } } return { map: function(file, line, column) { if (cache[file] === undefined) { cache[file] = loadSourceMap(file) || false; } if (!cache[file]) { return {source: file, line: line, column: column}; } else { return cache[file].originalPositionFor({line: line, column: column || 1}); } } }; };
Drop unused sourcemap reset API
Drop unused sourcemap reset API
JavaScript
mit
walmartlabs/fruit-loops,walmartlabs/fruit-loops
--- +++ @@ -23,9 +23,6 @@ } else { return cache[file].originalPositionFor({line: line, column: column || 1}); } - }, - reset: function() { - cache = {}; } }; };
8fd27f37f55e3c8105fc15698d10575839cbe213
catson/static/catson.js
catson/static/catson.js
function handleFileSelect(evt) { evt.stopPropagation(); evt.preventDefault(); $('#drop_zone').remove(); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image; img.src = URL.createObjectURL(evt.dataTransfer.files[0]); img.onload = function() { canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); } } function handleDragOver(evt) { evt.stopPropagation(); evt.preventDefault(); evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy. }
function handleFileSelect(evt) { evt.stopPropagation(); evt.preventDefault(); $('#drop_zone').remove(); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image; img.src = URL.createObjectURL(evt.dataTransfer.files[0]); img.onload = function() { canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); } } function handleDragOver(evt) { evt.stopPropagation(); evt.preventDefault(); evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy. } function number_of_cats() { // Try to get it from the hostname var cats = window.cats; if (cats !== undefined) return cats; cats = parseInt(window.location.hostname.split(".")[0], 10); if (isNaN(cats)) cats = Math.floor(Math.random() * 100); window.cats = cats; return cats; }
Work out how many cats to draw
Work out how many cats to draw
JavaScript
mit
richo/catson.me,richo/catson.me
--- +++ @@ -22,3 +22,18 @@ evt.preventDefault(); evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy. } + +function number_of_cats() { + // Try to get it from the hostname + var cats = window.cats; + + if (cats !== undefined) + return cats; + + cats = parseInt(window.location.hostname.split(".")[0], 10); + if (isNaN(cats)) + cats = Math.floor(Math.random() * 100); + + window.cats = cats; + return cats; +}
8eb18fbf907a7612c3928eeb598edf7830b8094b
lib/model/arrayList.js
lib/model/arrayList.js
var createClass = require('../utilities/createClass'); var Lang = require('../utilities/lang'); var ArrayList = createClass({ instance: { constructor: function() { debugger; }, _backing: [], add: function(el, index) { if (!Lang.isNumber(index)) { index = this._backing.length; } if (!this._validateValue(el)) { throw new Error('Invalid value'); } this.fire('add', function() { this._backing.splice(index, 0, el); }.bind(this), { index: index, value: el }); }, remove: function(index) { if (index < 0 || index >= this.size()) { throw new Error('Index out of bounds.'); } this.fire('remove', function() { this._backing.splice(index, 1); }.bind(this), { index: index, value: this._backing[index] }); }, toArray: function() { return this._backing.slice(); }, size: function() { return this._backing.length; }, /** * Validate values for this array. Intended to be overwritten. * @method _validateValue * @param {Any} val * @protected * @return {Boolea} valid? */ /* eslint-disable */ _validateValue: function(val) { return true; } /* eslint-enable */ } }); module.exports = ArrayList;
var createClass = require('../utilities/createClass'); var Lang = require('../utilities/lang'); var ArrayList = createClass({ constructor: function() { this._backing = []; }, instance: { add: function(el, index) { if (!Lang.isNumber(index)) { index = this._backing.length; } if (!this._validateValue(el)) { throw new Error('Invalid value'); } this.fire('add', function() { this._backing.splice(index, 0, el); }.bind(this), { index: index, value: el }); }, remove: function(index) { if (index < 0 || index >= this.size()) { throw new Error('Index out of bounds.'); } this.fire('remove', function() { this._backing.splice(index, 1); }.bind(this), { index: index, value: this._backing[index] }); }, toArray: function() { return this._backing.slice(); }, size: function() { return this._backing.length; }, /** * Validate values for this array. Intended to be overwritten. * @method _validateValue * @param {Any} val * @protected * @return {Boolea} valid? */ /* eslint-disable */ _validateValue: function(val) { return true; } /* eslint-enable */ } }); module.exports = ArrayList;
Fix bug: all arraylists were the same
Fix bug: all arraylists were the same
JavaScript
apache-2.0
twosigma/goll-e,RobertWarrenGilmore/goll-e,RobertWarrenGilmore/goll-e,twosigma/goll-e
--- +++ @@ -2,11 +2,11 @@ var Lang = require('../utilities/lang'); var ArrayList = createClass({ + constructor: function() { + this._backing = []; + }, + instance: { - constructor: function() { - debugger; - }, - _backing: [], add: function(el, index) { if (!Lang.isNumber(index)) { index = this._backing.length;
83ba65a17c8af9782681cb99a1fa1fdcd99c296c
src/server.js
src/server.js
var http = require('http'); var handler = require('./handler.js'); var dictionaryFile = require('./readDictionary.js'); var server = http.createServer(handler); function startServer() { dictionaryFile.readDictionary(null,null, function() { server.listen(3000, function(){ console.log("Dictionary loaded, server listening to port 3000, ready to accept requests"); }); }) } startServer();
var http = require('http'); var handler = require('./handler.js'); var dictionaryFile = require('./readDictionary.js'); var server = http.createServer(handler); var port = process.env.PORT || 3000; function startServer() { dictionaryFile.readDictionary(null,null, function() { server.listen(port, function(){ console.log("Dictionary loaded, server listening to port 3000, ready to accept requests"); }); }) } startServer();
Change port variable to process.env.PORT for heroku deployment
Change port variable to process.env.PORT for heroku deployment
JavaScript
mit
NodeGroup2/autocomplete-project,NodeGroup2/autocomplete-project
--- +++ @@ -3,10 +3,11 @@ var dictionaryFile = require('./readDictionary.js'); var server = http.createServer(handler); +var port = process.env.PORT || 3000; function startServer() { dictionaryFile.readDictionary(null,null, function() { - server.listen(3000, function(){ + server.listen(port, function(){ console.log("Dictionary loaded, server listening to port 3000, ready to accept requests"); }); })
19de825c36cb0b53fbfb92500507b9eb13d63f68
backend/servers/mcapid/initializers/apikey.js
backend/servers/mcapid/initializers/apikey.js
const {Initializer, api} = require('actionhero'); const apikeyCache = require('../lib/apikey-cache'); module.exports = class APIKeyInitializer extends Initializer { constructor() { super(); this.name = 'apikey'; this.startPriority = 1000; } initialize() { // ************************************************************************************************* // require('../lib/apikey-cache') in initialize so that rethinkdb initializer has run before the require // statement, otherwise rethinkdb in r is not defined. // ************************************************************************************************* const middleware = { name: this.name, global: true, preProcessor: async (data) => { if (data.actionTemplate.do_not_authenticate) { return; } if (!data.params.apikey) { throw new Error('Not authorized'); } let user = await apikeyCache.find(data.params.apikey); if (! user) { throw new Error('Not authorized'); } data.user = user; } }; api.actions.addMiddleware(middleware) } };
const {Initializer, api} = require('actionhero'); const apikeyCache = require('../lib/apikey-cache'); module.exports = class APIKeyInitializer extends Initializer { constructor() { super(); this.name = 'apikey'; this.startPriority = 1000; } initialize() { const middleware = { name: this.name, global: true, preProcessor: async (data) => { if (data.actionTemplate.do_not_authenticate) { return; } if (!data.params.apikey) { throw new Error('Not authorized'); } let user = await apikeyCache.find(data.params.apikey); if (!user) { throw new Error('Not authorized'); } data.user = user; } }; api.actions.addMiddleware(middleware) } };
Reformat and remove commented out code
Reformat and remove commented out code
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -9,11 +9,6 @@ } initialize() { - // ************************************************************************************************* - // require('../lib/apikey-cache') in initialize so that rethinkdb initializer has run before the require - // statement, otherwise rethinkdb in r is not defined. - // ************************************************************************************************* - const middleware = { name: this.name, global: true, @@ -27,13 +22,13 @@ } let user = await apikeyCache.find(data.params.apikey); - if (! user) { + if (!user) { throw new Error('Not authorized'); } data.user = user; } }; - api.actions.addMiddleware(middleware) + api.actions.addMiddleware(middleware) } };
ac6962630953b3387f95422049b0b1c01b981966
server/commands/redux/reduxDispatchPrompt.js
server/commands/redux/reduxDispatchPrompt.js
import RS from 'ramdasauce' const COMMAND = 'redux.dispatch.prompt' /** Prompts for a path to grab some redux keys from. */ const process = (context, action) => { context.prompt('Action to dispatch', (value) => { let action = null // try not to blow up the frame try { eval('action = ' + value) // lulz } catch (e) { } // try harder to not blow up the frame if (RS.isNilOrEmpty(action)) return // got an object? ship an object. context.post({type: 'redux.dispatch', action}) }) } export default { name: COMMAND, repeatable: true, process }
import RS from 'ramdasauce' const COMMAND = 'redux.dispatch.prompt' /** Prompts for a path to grab some redux keys from. */ const process = (context, action) => { context.prompt('Action to dispatch (e.g. {type: \'MY_ACTION\'})', (value) => { let action = null // try not to blow up the frame try { eval('action = ' + value) // lulz } catch (e) { } // try harder to not blow up the frame if (RS.isNilOrEmpty(action)) return // got an object? ship an object. context.post({type: 'redux.dispatch', action}) }) } export default { name: COMMAND, repeatable: true, process }
Add a more detailed prompt for dispatching an action
Add a more detailed prompt for dispatching an action
JavaScript
mit
infinitered/reactotron,reactotron/reactotron,rmevans9/reactotron,reactotron/reactotron,rmevans9/reactotron,infinitered/reactotron,reactotron/reactotron,rmevans9/reactotron,rmevans9/reactotron,infinitered/reactotron,reactotron/reactotron,infinitered/reactotron,reactotron/reactotron,rmevans9/reactotron
--- +++ @@ -5,7 +5,7 @@ Prompts for a path to grab some redux keys from. */ const process = (context, action) => { - context.prompt('Action to dispatch', (value) => { + context.prompt('Action to dispatch (e.g. {type: \'MY_ACTION\'})', (value) => { let action = null // try not to blow up the frame
d9b11cd20e08cd9b71052c9141f3f9f9bcca57fb
client/utils/fetcher.js
client/utils/fetcher.js
import fetch from 'isomorphic-fetch'; import _ from 'lodash'; import { push } from 'react-router-redux'; async function request(url, userOptions, dispatch) { const defaultOptions = { credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Content-Security-Policy': 'default-src \'self\'', 'X-Frame-Options': 'SAMEORIGIN', 'X-XSS-Protection': 1, }, }; if (userOptions.body && typeof userOptions.body === 'object') { userOptions.body = JSON.stringify(userOptions.body); } const options = { ...defaultOptions, ...userOptions }; try { const response = await fetch(url, options); const body = await response.json(); if (body.redirectTo) { if (!dispatch) { throw new Error('Dispatch not found!'); } dispatch(push(body.redirectTo)); } if (response.ok) { return body; } throw body; } catch (e) { const error = _.get(e, 'error', e) || 'An unexpected error has occurred!'; return { error }; } } const wrapper = {}; ['get', 'post', 'put', 'delete'].forEach((method) => { wrapper[method] = (url, options = {}) => { options.method = method; return request(url, options); }; }); export default wrapper;
import fetch from 'isomorphic-fetch'; import _ from 'lodash'; import { push } from 'react-router-redux'; // grab the CSRF token from the cookie const csrfToken = document.cookie.replace(/(?:(?:^|.*;\s*)csrftoken\s*=s*([^;]*).*$)|^.*$/, '$1'); async function request(url, userOptions, dispatch) { const defaultOptions = { credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Content-Security-Policy': 'default-src \'self\'', 'X-Frame-Options': 'SAMEORIGIN', 'X-XSS-Protection': 1, 'X-CSRFToken': csrfToken, }, }; if (userOptions.body && typeof userOptions.body === 'object') { userOptions.body = JSON.stringify(userOptions.body); } const options = { ...defaultOptions, ...userOptions }; try { const response = await fetch(url, options); const body = await response.json(); if (body.redirectTo) { if (!dispatch) { throw new Error('Dispatch not found!'); } dispatch(push(body.redirectTo)); } if (response.ok) { return body; } throw body; } catch (e) { const error = _.get(e, 'error', e) || 'An unexpected error has occurred!'; return { error }; } } const wrapper = {}; ['get', 'post', 'put', 'delete'].forEach((method) => { wrapper[method] = (url, options = {}) => { options.method = method; return request(url, options); }; }); export default wrapper;
Add CSRF token to all requests
Add CSRF token to all requests
JavaScript
apache-2.0
ctcusc/django-react-boilerplate,ctcusc/django-react-boilerplate,ctcusc/django-react-boilerplate,ctcusc/django-react-boilerplate
--- +++ @@ -1,6 +1,9 @@ import fetch from 'isomorphic-fetch'; import _ from 'lodash'; import { push } from 'react-router-redux'; + +// grab the CSRF token from the cookie +const csrfToken = document.cookie.replace(/(?:(?:^|.*;\s*)csrftoken\s*=s*([^;]*).*$)|^.*$/, '$1'); async function request(url, userOptions, dispatch) { const defaultOptions = { @@ -11,6 +14,7 @@ 'Content-Security-Policy': 'default-src \'self\'', 'X-Frame-Options': 'SAMEORIGIN', 'X-XSS-Protection': 1, + 'X-CSRFToken': csrfToken, }, };
47da0f80a936649d64c53c522e30ea2386276455
themes/default/config.js
themes/default/config.js
(function(c) { /* * !!! CHANGE THIS !!! */ c["general"].rootUrl = '//localhost/resto2/'; /* * !! DO NOT EDIT UNDER THIS LINE !! */ c["general"].serverRootUrl = null; c["general"].proxyUrl = null; c["general"].confirmDeletion = false; c["general"].themePath = "/js/lib/mapshup/theme/default"; c["i18n"].path = "/js/lib/mapshup/i18n"; c["general"].displayContextualMenu = false; c["general"].displayCoordinates = true; c["general"].displayScale = false; c["general"].overviewMap = "none"; c['general'].enableHistory = false; c["general"].timeLine = { enable: false }; c.extend("Navigation", { position: 'nw', orientation: 'h' }); c.remove("layers", "Streets"); c.remove("layers", "Satellite"); c.remove("layers", "Relief"); c.remove("layers", "MapQuest OSM"); c.remove("layers", "OpenStreetMap"); c.add("layers", { type: "Bing", title: "Satellite", key: "AmraZAAcRFVn6Vbxk_TVhhVZNt66x4_4SV_EvlfzvRC9qZ_2y6k1aNsuuoYS0UYy", bingType: "AerialWithLabels" }); })(window.M.Config);
(function(c) { /* * !!! CHANGE THIS !!! */ c["general"].rootUrl = '//localhost/resto2/'; /* * !! DO NOT EDIT UNDER THIS LINE !! */ c["general"].serverRootUrl = null; c["general"].proxyUrl = null; c["general"].confirmDeletion = false; c["general"].themePath = "/js/lib/mapshup/theme/default"; c["i18n"].path = "/js/lib/mapshup/i18n"; c["general"].displayContextualMenu = false; c["general"].displayCoordinates = true; c["general"].displayScale = false; c["general"].overviewMap = "none"; c['general'].enableHistory = false; c["general"].timeLine = { enable: false }; c.extend("Navigation", { position: 'nw', orientation: 'h' }); c.remove("layers", "Streets"); c.remove("layers", "Satellite"); c.remove("layers", "Relief"); c.remove("layers", "MapQuest OSM"); //c.remove("layers", "OpenStreetMap"); /* c.add("layers", { type: "Bing", title: "Satellite", key: "AmraZAAcRFVn6Vbxk_TVhhVZNt66x4_4SV_EvlfzvRC9qZ_2y6k1aNsuuoYS0UYy", bingType: "AerialWithLabels" });*/ })(window.M.Config);
Replace Bing maps by OpenStreetMap to avoid licensing issue
[THEIA] Replace Bing maps by OpenStreetMap to avoid licensing issue
JavaScript
apache-2.0
atospeps/resto,Baresse/resto2,RailwayMan/resto,RailwayMan/resto,Baresse/resto2,atospeps/resto,jjrom/resto,jjrom/resto
--- +++ @@ -29,12 +29,13 @@ c.remove("layers", "Satellite"); c.remove("layers", "Relief"); c.remove("layers", "MapQuest OSM"); - c.remove("layers", "OpenStreetMap"); + //c.remove("layers", "OpenStreetMap"); + /* c.add("layers", { type: "Bing", title: "Satellite", key: "AmraZAAcRFVn6Vbxk_TVhhVZNt66x4_4SV_EvlfzvRC9qZ_2y6k1aNsuuoYS0UYy", bingType: "AerialWithLabels" - }); + });*/ })(window.M.Config);
ed307dc8e1e7c83433d1589fc977e724efbcda77
config.js
config.js
var path = require('path'), config; config = { production: { url: process.env.BASE_URL || 'http://blog.ertrzyiks.pl/', mail: {}, database: { client: 'postgres', connection: process.env.DATABASE_URL }, server: { host: '0.0.0.0', port: process.env.PORT }, storage: { active: 'ghost-cloudinary-store', 'ghost-cloudinary-store': { cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET } }, paths:{ contentPath: path.join(__dirname, '/content/') } }, development: { url: 'http://localhost:2368', mail: {}, fileStorage: true, database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, server: { host: '0.0.0.0', port: '2368' }, paths: { contentPath: path.join(__dirname, '/content/') } } }; module.exports = config;
var path = require('path'), config; config = { production: { url: process.env.BASE_URL || 'http://blog.ertrzyiks.pl/', mail: {}, database: { client: 'postgres', connection: process.env.DATABASE_URL, pool: { min: 0, max: 2 } }, server: { host: '0.0.0.0', port: process.env.PORT }, storage: { active: 'ghost-cloudinary-store', 'ghost-cloudinary-store': { cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET } }, paths:{ contentPath: path.join(__dirname, '/content/') } }, development: { url: 'http://localhost:2368', mail: {}, fileStorage: true, database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, server: { host: '0.0.0.0', port: '2368' }, paths: { contentPath: path.join(__dirname, '/content/') } } }; module.exports = config;
Set max connection pool limit
Set max connection pool limit
JavaScript
mit
ertrzyiks/blog.ertrzyiks.pl,ertrzyiks/blog.ertrzyiks.pl,ertrzyiks/blog.ertrzyiks.pl
--- +++ @@ -9,7 +9,8 @@ database: { client: 'postgres', - connection: process.env.DATABASE_URL + connection: process.env.DATABASE_URL, + pool: { min: 0, max: 2 } }, server: {
b607a3c6157948aab36b056c02d0d126450f56a8
amaranth-chrome-ext/src/background.js
amaranth-chrome-ext/src/background.js
chrome.webNavigation.onHistoryStateUpdated.addListener(function({url}) { // Code should only be injected if on a restaurant's page if (url.includes('restaurant')) { const scriptsToInject = [ 'lib/tf.min.js', 'src/CalorieLabel.js', 'src/AmaranthUtil.js', 'src/CalorieLabeller.js', 'src/content.js', ]; scriptsToInject.forEach(scriptPath => { chrome.tabs.executeScript(null, { file: scriptPath, }); }); } });
chrome.webNavigation.onHistoryStateUpdated.addListener(function({url}) { // Code should only be injected if on grubhub.com/restaurant/... if (url.includes('restaurant')) { const scriptsToInject = [ 'lib/tf.min.js', 'src/CalorieLabel.js', 'src/AmaranthUtil.js', 'src/CalorieLabeller.js', 'src/content.js', ]; scriptsToInject.forEach(scriptPath => { chrome.tabs.executeScript(null, { file: scriptPath, }); }); chrome.tabs.insertCSS(null, { file: 'src/style.css', }); } });
Insert CSS along with JS on statePush
Insert CSS along with JS on statePush
JavaScript
apache-2.0
googleinterns/amaranth,googleinterns/amaranth
--- +++ @@ -1,5 +1,5 @@ chrome.webNavigation.onHistoryStateUpdated.addListener(function({url}) { - // Code should only be injected if on a restaurant's page + // Code should only be injected if on grubhub.com/restaurant/... if (url.includes('restaurant')) { const scriptsToInject = [ 'lib/tf.min.js', @@ -14,5 +14,9 @@ file: scriptPath, }); }); + + chrome.tabs.insertCSS(null, { + file: 'src/style.css', + }); } });
ae0cdf06604abb68774e8e36f873df3b65de0cf3
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require bootstrap/dropdown //= require jquery_nested_form //= require_tree . Turbolinks.enableTransitionCache(); Turbolinks.enableProgressBar();
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require bootstrap/dropdown //= require bootstrap/collapse //= require jquery_nested_form //= require_tree . Turbolinks.enableTransitionCache(); Turbolinks.enableProgressBar();
Add missing menu collapse functionality
Add missing menu collapse functionality
JavaScript
mit
user890104/fauna,user890104/fauna,user890104/fauna,initLab/fauna,initLab/fauna,initLab/fauna
--- +++ @@ -14,6 +14,7 @@ //= require jquery_ujs //= require turbolinks //= require bootstrap/dropdown +//= require bootstrap/collapse //= require jquery_nested_form //= require_tree .
fc6040a58f26f1a0b54700fc90ddd633f1326ff5
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); }
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 500); }
Remove finishedLoading() call, change timeout to 500 from 5000
Remove finishedLoading() call, change timeout to 500 from 5000
JavaScript
mit
fma2/nyc-high-school-programs,fma2/nyc-high-school-programs
--- +++ @@ -20,13 +20,14 @@ $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); + startLoading(); function startLoading() { loader.className = ''; } -function finishedLoading() { +function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; - }, 5000); + }, 500); }
47d86fff8bc283772af80dc241169ee32972085b
src/parsers/guides/legend-title.js
src/parsers/guides/legend-title.js
import {GuideTitleStyle} from './constants'; import guideMark from './guide-mark'; import {lookup} from './guide-util'; import {TextMark} from '../marks/marktypes'; import {LegendTitleRole} from '../marks/roles'; import {addEncode, encoder} from '../encode/encode-util'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter; encode.enter = enter = { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, opacity: zero }; addEncode(enter, 'align', lookup('titleAlign', spec, config)); addEncode(enter, 'baseline', lookup('titleBaseline', spec, config)); addEncode(enter, 'fill', lookup('titleColor', spec, config)); addEncode(enter, 'font', lookup('titleFont', spec, config)); addEncode(enter, 'fontSize', lookup('titleFontSize', spec, config)); addEncode(enter, 'fontWeight', lookup('titleFontWeight', spec, config)); addEncode(enter, 'limit', lookup('titleLimit', spec, config)); encode.exit = { opacity: zero }; encode.update = { opacity: {value: 1}, text: encoder(spec.title) }; return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode); }
import {GuideTitleStyle} from './constants'; import guideMark from './guide-mark'; import {lookup} from './guide-util'; import {TextMark} from '../marks/marktypes'; import {LegendTitleRole} from '../marks/roles'; import {addEncode, encoder} from '../encode/encode-util'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter; encode.enter = enter = { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, opacity: zero }; addEncode(enter, 'align', lookup('titleAlign', spec, config)); addEncode(enter, 'baseline', lookup('titleBaseline', spec, config)); addEncode(enter, 'fill', lookup('titleColor', spec, config)); addEncode(enter, 'font', lookup('titleFont', spec, config)); addEncode(enter, 'fontSize', lookup('titleFontSize', spec, config)); addEncode(enter, 'fontWeight', lookup('titleFontWeight', spec, config)); addEncode(enter, 'limit', lookup('titleLimit', spec, config)); encode.exit = { opacity: zero }; encode.update = { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, opacity: {value: 1}, text: encoder(spec.title) }; return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode); }
Fix legend title to respond to legend padding changes.
Fix legend title to respond to legend padding changes.
JavaScript
bsd-3-clause
vega/vega-parser
--- +++ @@ -27,6 +27,8 @@ }; encode.update = { + x: {field: {group: 'padding'}}, + y: {field: {group: 'padding'}}, opacity: {value: 1}, text: encoder(spec.title) };
7b090d0d9144546c583702d04b41b74f6f408861
cli/index.js
cli/index.js
#!/usr/bin/env node const cli = require('commander'); const path = require('path'); const glob = require('glob'); const options = { realpath: true, cwd: path.resolve(__dirname, './lib'), }; glob .sync('*/index.js', options) .map(require) .forEach(fn => fn(cli)); cli.version('0.0.6-alpha'); cli.parse(process.argv); if (!cli.args.length) cli.help();
#!/usr/bin/env node const cli = require('commander'); const path = require('path'); const glob = require('glob'); const options = { realpath: true, cwd: path.resolve(__dirname, './lib'), }; glob .sync('*/index.js', options) .map(require) .forEach(fn => fn(cli)); cli.version('0.0.7-alpha'); cli.parse(process.argv); if (!cli.args.length) cli.help();
Update CLI version to 0.0.7-alpha
Update CLI version to 0.0.7-alpha
JavaScript
mit
ArturAralin/express-object-router
--- +++ @@ -14,7 +14,7 @@ .map(require) .forEach(fn => fn(cli)); -cli.version('0.0.6-alpha'); +cli.version('0.0.7-alpha'); cli.parse(process.argv); if (!cli.args.length) cli.help();
8ba6b443ea4d5a3ad49ae6121130dc987d9a375e
utils.js
utils.js
'use strict'; const assert = require('assert'); const url = require('url'); /** * @param engine {string} * @param id {string} * @returns {string} */ function getPlatformStatusId(engine, id) { return engine + '-' + encodeURIComponent(id); } const PLATFORM_STATUS_URL_MAP = new Map([ ['chromium', 'https://www.chromestatus.com/features/'], ['edge', 'https://developer.microsoft.com/en-us/microsoft-edge/platform/status/'], ['webkit', 'https://webkit.org/status/#feature-'], ['gecko', 'https://platform-status.mozilla.org/#'], ]); /** * @param engine {string} * @param id {string} * @returns {string} */ function getPlatformStatusUrl(engine, id) { assert(PLATFORM_STATUS_URL_MAP.has(engine)); const baseUrl = PLATFORM_STATUS_URL_MAP.get(engine); return baseUrl + encodeURIComponent(id); } /** * @param urlString {string} * @returns {string} */ function getHost(urlString) { return url.parse(urlString).host; } module.exports = { getPlatformStatusId: getPlatformStatusId, getPlatformStatusUrl: getPlatformStatusUrl, getHost: getHost, };
'use strict'; const assert = require('assert'); const url = require('url'); /** * @param engine {string} * @param id {string} * @returns {string} */ function getPlatformStatusId(engine, id) { return engine + '-' + encodeURIComponent(id); } const PLATFORM_STATUS_URL_MAP = new Map([ ['chromium', 'https://www.chromestatus.com/features/'], ['edge', 'https://developer.microsoft.com/en-us/microsoft-edge/platform/status/'], ['webkit', 'https://webkit.org/status/#'], ['gecko', 'https://platform-status.mozilla.org/#'], ]); /** * @param engine {string} * @param id {string} * @returns {string} */ function getPlatformStatusUrl(engine, id) { assert(PLATFORM_STATUS_URL_MAP.has(engine)); const baseUrl = PLATFORM_STATUS_URL_MAP.get(engine); return baseUrl + encodeURIComponent(id); } /** * @param urlString {string} * @returns {string} */ function getHost(urlString) { return url.parse(urlString).host; } module.exports = { getPlatformStatusId: getPlatformStatusId, getPlatformStatusUrl: getPlatformStatusUrl, getHost: getHost, };
Fix platform status url of webkit
Fix platform status url of webkit
JavaScript
mit
takenspc/ps-viewer,takenspc/ps-viewer
--- +++ @@ -16,7 +16,7 @@ const PLATFORM_STATUS_URL_MAP = new Map([ ['chromium', 'https://www.chromestatus.com/features/'], ['edge', 'https://developer.microsoft.com/en-us/microsoft-edge/platform/status/'], - ['webkit', 'https://webkit.org/status/#feature-'], + ['webkit', 'https://webkit.org/status/#'], ['gecko', 'https://platform-status.mozilla.org/#'], ]);
1dab7f5cd24b0995a28ab4bab3884e313dbda0cb
server/models/borrowrequests.js
server/models/borrowrequests.js
import * as Sequelize from 'sequelize'; import { v4 as uuidv4 } from 'uuid'; const borrowRequestSchema = (sequelize) => { const BorrowRequests = sequelize.define('BorrowRequests', { id: { type: Sequelize.UUID, allowNull: false, primaryKey: true, defaultValue: uuidv4(), }, reason: { type: Sequelize.ENUM, values: ['Research', 'Assignment', 'Leisure reading'], allowNull: false, }, comments: { type: Sequelize.TEXT, allowNull: false, }, returnDate: { type: Sequelize.DATE, allowNull: false, }, }); BorrowRequests.associate = (models) => { BorrowRequests.belongsTo(models.User, { foreignKey: 'userId', as: 'userBorrowRequests', onDelete: 'CASCADE', }); BorrowRequests.belongsTo(models.Book, { foreignKey: 'bookId', as: 'borrowRequests', }); }; return BorrowRequests; }; export default borrowRequestSchema;
import * as Sequelize from 'sequelize'; import { v4 as uuidv4 } from 'uuid'; const borrowRequestSchema = (sequelize) => { const BorrowRequests = sequelize.define('BorrowRequests', { id: { type: Sequelize.UUID, allowNull: false, primaryKey: true, defaultValue: uuidv4(), }, reason: { type: Sequelize.ENUM, values: ['Research', 'Assignment', 'Leisure reading'], allowNull: false, }, comments: { type: Sequelize.TEXT, allowNull: false, }, returnDate: { type: Sequelize.DATE, allowNull: false, }, status: { type: Sequelize.STRING, defaultValue: 'Pending', allowNull: false, }, }); BorrowRequests.associate = (models) => { BorrowRequests.belongsTo(models.User, { foreignKey: 'userId', as: 'userBorrowRequests', onDelete: 'CASCADE', }); BorrowRequests.belongsTo(models.Book, { foreignKey: 'bookId', as: 'borrowRequests', }); }; return BorrowRequests; }; export default borrowRequestSchema;
Add model for borrow requests
Add model for borrow requests
JavaScript
mit
amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books
--- +++ @@ -22,6 +22,11 @@ type: Sequelize.DATE, allowNull: false, }, + status: { + type: Sequelize.STRING, + defaultValue: 'Pending', + allowNull: false, + }, }); BorrowRequests.associate = (models) => { BorrowRequests.belongsTo(models.User, {
a42809d946e00e5542531f06ad52c11d7481c95d
server/votes/votesController.js
server/votes/votesController.js
var Vote = require( './votes' ); module.exports = { getAllVotes: function() {}, addVote: function() {} };
var Vote = require( './votes' ); module.exports = { getAllVotes: function() {}, addVote: function( req, res, next ) { console.log( 'TESTING: addVote', req.body ); res.send( 'TESTING: vote added' ); } };
Add placeholder functionality to votes controller on server side
Add placeholder functionality to votes controller on server side
JavaScript
mpl-2.0
RubiginousChanticleer/rubiginouschanticleer,CantillatingZygote/rubiginouschanticleer,CantillatingZygote/rubiginouschanticleer,RubiginousChanticleer/rubiginouschanticleer
--- +++ @@ -4,6 +4,9 @@ getAllVotes: function() {}, - addVote: function() {} + addVote: function( req, res, next ) { + console.log( 'TESTING: addVote', req.body ); + res.send( 'TESTING: vote added' ); + } };
b2c5d65ef0ad3d86f76616805eff5f548a1168a4
test/index.js
test/index.js
import 'es5-shim'; beforeEach(() => { sinon.stub(console, 'error'); }); afterEach(() => { if (typeof console.error.restore === 'function') { assert(!console.error.called, () => { return `${console.error.getCall(0).args[0]} \nIn '${this.currentTest.fullTitle()}'`; }); console.error.restore(); } }); describe('Process environment for tests', () => { it('Should be development for React console warnings', () => { assert.equal(process.env.NODE_ENV, 'development'); }); }); // Ensure all files in src folder are loaded for proper code coverage analysis const srcContext = require.context('../src', true, /.*\.js$/); srcContext.keys().forEach(srcContext); const testsContext = require.context('.', true, /Spec$/); testsContext.keys().forEach(testsContext);
import 'es5-shim'; beforeEach(() => { sinon.stub(console, 'error'); }); afterEach(function checkNoUnexpectedWarnings() { if (typeof console.error.restore === 'function') { assert(!console.error.called, () => { return `${console.error.getCall(0).args[0]} \nIn '${this.currentTest.fullTitle()}'`; }); console.error.restore(); } }); describe('Process environment for tests', () => { it('Should be development for React console warnings', () => { assert.equal(process.env.NODE_ENV, 'development'); }); }); // Ensure all files in src folder are loaded for proper code coverage analysis const srcContext = require.context('../src', true, /.*\.js$/); srcContext.keys().forEach(srcContext); const testsContext = require.context('.', true, /Spec$/); testsContext.keys().forEach(testsContext);
Fix logging from afterEach hook in tests
Fix logging from afterEach hook in tests
JavaScript
mit
react-bootstrap/react-bootstrap,apkiernan/react-bootstrap,dozoisch/react-bootstrap,react-bootstrap/react-bootstrap,egauci/react-bootstrap,jesenko/react-bootstrap,mmarcant/react-bootstrap,Lucifier129/react-bootstrap,Sipree/react-bootstrap,Lucifier129/react-bootstrap,glenjamin/react-bootstrap,HPate-Riptide/react-bootstrap,Terminux/react-bootstrap,glenjamin/react-bootstrap,react-bootstrap/react-bootstrap,pombredanne/react-bootstrap
--- +++ @@ -4,7 +4,7 @@ sinon.stub(console, 'error'); }); -afterEach(() => { +afterEach(function checkNoUnexpectedWarnings() { if (typeof console.error.restore === 'function') { assert(!console.error.called, () => { return `${console.error.getCall(0).args[0]} \nIn '${this.currentTest.fullTitle()}'`;
d613bc2e1c500df22978b9ca8f70058f00ac3d4b
src/system-extension-contextual.js
src/system-extension-contextual.js
addStealExtension(function (loader) { loader._contextualModules = {}; loader.setContextual = function(moduleName, definer){ this._contextualModules[moduleName] = definer; }; var normalize = loader.normalize; loader.normalize = function(name, parentName){ var loader = this; if (parentName) { var definer = this._contextualModules[name]; // See if `name` is a contextual module if (definer) { name = name + '/' + parentName; if(!loader.has(name)) { // `definer` could be a function or could be a moduleName if (typeof definer === 'string') { definer = loader['import'](definer); } return Promise.resolve(definer) .then(function(definer) { if (definer['default']) { definer = definer['default']; } var definePromise = Promise.resolve( definer.call(loader, parentName) ); return definePromise; }) .then(function(moduleDef){ loader.set(name, loader.newModule(moduleDef)); return name; }); } return Promise.resolve(name); } } return normalize.apply(this, arguments); }; });
addStealExtension(function (loader) { loader._contextualModules = {}; loader.setContextual = function(moduleName, definer){ this._contextualModules[moduleName] = definer; }; var normalize = loader.normalize; loader.normalize = function(name, parentName){ var loader = this; var pluginLoader = loader.pluginLoader || loader; if (parentName) { var definer = this._contextualModules[name]; // See if `name` is a contextual module if (definer) { name = name + '/' + parentName; if(!loader.has(name)) { // `definer` could be a function or could be a moduleName if (typeof definer === 'string') { definer = pluginLoader['import'](definer); } return Promise.resolve(definer) .then(function(definer) { if (definer['default']) { definer = definer['default']; } var definePromise = Promise.resolve( definer.call(loader, parentName) ); return definePromise; }) .then(function(moduleDef){ loader.set(name, loader.newModule(moduleDef)); return name; }); } return Promise.resolve(name); } } return normalize.apply(this, arguments); }; });
Use pluginLoader in contextual extension
Use pluginLoader in contextual extension If a contextual module is defined passing a string as the `definer` parameter, the `pluginLoader` needs to be used to dynamically load the `definer` function; otherwise steal-tools won't build the app. Closes #952
JavaScript
mit
stealjs/steal,stealjs/steal
--- +++ @@ -8,6 +8,7 @@ var normalize = loader.normalize; loader.normalize = function(name, parentName){ var loader = this; + var pluginLoader = loader.pluginLoader || loader; if (parentName) { var definer = this._contextualModules[name]; @@ -19,7 +20,7 @@ if(!loader.has(name)) { // `definer` could be a function or could be a moduleName if (typeof definer === 'string') { - definer = loader['import'](definer); + definer = pluginLoader['import'](definer); } return Promise.resolve(definer)
c4e09637aa700ad08cea7948b6156acaaaf17157
404/main.js
404/main.js
// 404 page using mapbox to show cities around the world. // Helper to generate the kind of coordinate pairs I'm using to store cities function bounds() { var center = map.getCenter(); return {lat: center.lat, lng: center.lng, zoom: map.getZoom()}; } L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg"; var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false}); function go(city) { var placenames = Object.keys(places); city = typeof city === "undefined" ? placenames[Math.floor(Math.random() * placenames.length)] : city; var pos = places[city]; map.setView( [pos.lat, pos.lng], pos.zoom ); } go();
// 404 page using mapbox to show cities around the world. // Helper to generate the kind of coordinate pairs I'm using to store cities function bounds() { var center = map.getCenter(); return {lat: center.lat, lng: center.lng, zoom: map.getZoom()}; } L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg"; var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false}); function go(city) { var placenames = Object.keys(places); city = city || placenames[Math.floor(Math.random() * placenames.length)]; var pos = places[city]; map.setView( [pos.lat, pos.lng], pos.zoom ); } go();
Simplify 'go' for string identifiers
Simplify 'go' for string identifiers
JavaScript
mit
controversial/controversial.io,controversial/controversial.io,controversial/controversial.io
--- +++ @@ -12,10 +12,7 @@ function go(city) { var placenames = Object.keys(places); - city = typeof city === "undefined" ? - placenames[Math.floor(Math.random() * placenames.length)] : - city; - + city = city || placenames[Math.floor(Math.random() * placenames.length)]; var pos = places[city]; map.setView( [pos.lat, pos.lng],
2c604630deb0c5f5a4befd08735c7795ad2480b3
examples/ice-configuration.js
examples/ice-configuration.js
var quickconnect = require('../'); var opts = { ns: 'dctest', iceServers: [ { url: 'stun:stun.l.google.com:19302' } ] }; quickconnect('http://rtc.io/switchboard/', opts) // tell quickconnect we want a datachannel called test .createDataChannel('test') // when the test channel is open, let us know .on('test:open', function(dc, id) { dc.onmessage = function(evt) { console.log('peer ' + id + ' says: ' + evt.data); }; console.log('test dc open for peer: ' + id); dc.send('hi'); });
var quickconnect = require('../'); var opts = { ns: 'dctest', iceServers: [ { url: 'stun:stun.l.google.com:19302' } ] }; quickconnect('http://rtc.io/switchboard/', opts) // tell quickconnect we want a datachannel called test .createDataChannel('iceconfig') // when the test channel is open, let us know .on('iceconfig:open', function(dc, id) { dc.onmessage = function(evt) { console.log('peer ' + id + ' says: ' + evt.data); }; console.log('test dc open for peer: ' + id); dc.send('hi'); });
Tweak example to use a configured channel name
Tweak example to use a configured channel name
JavaScript
apache-2.0
rtc-io/rtc-quickconnect,rtc-io/rtc-quickconnect
--- +++ @@ -8,9 +8,9 @@ quickconnect('http://rtc.io/switchboard/', opts) // tell quickconnect we want a datachannel called test - .createDataChannel('test') + .createDataChannel('iceconfig') // when the test channel is open, let us know - .on('test:open', function(dc, id) { + .on('iceconfig:open', function(dc, id) { dc.onmessage = function(evt) { console.log('peer ' + id + ' says: ' + evt.data); };
d1078188378529d084c059b06fe2e1157adc034c
webclient/app/common/ec-as-date.js
webclient/app/common/ec-as-date.js
(function(){ 'use strict'; angular .module('everycent.common') .directive('ecAsDate', ecAsDate); ecAsDate.$inject = []; function ecAsDate(){ var directive = { restrict:'A', require:'ngModel', link: link }; return directive; function link(scope, element, attrs, ngModel){ ngModel.$formatters.push(function(modelValue){ return new Date(modelValue); }); ngModel.$parsers.push(function(modelValue){ return new Date(modelValue); }); } } })();
(function(){ 'use strict'; angular .module('everycent.common') .directive('ecAsDate', ecAsDate); ecAsDate.$inject = []; function ecAsDate(){ var directive = { restrict:'A', require:'ngModel', link: link }; return directive; function link(scope, element, attrs, ngModel){ ngModel.$formatters.push(function(modelValue){ // convert the date value to a timezone specific version var newModelValue = modelValue + 'T10:00:00-0400'; return new Date(newModelValue); }); ngModel.$parsers.push(function(modelValue){ return new Date(modelValue); }); } } })();
Fix the issue with dates not being in the correct timezone
Fix the issue with dates not being in the correct timezone
JavaScript
mit
snorkpete/everycent,snorkpete/everycent,snorkpete/everycent,snorkpete/everycent,snorkpete/everycent
--- +++ @@ -18,8 +18,11 @@ function link(scope, element, attrs, ngModel){ ngModel.$formatters.push(function(modelValue){ - return new Date(modelValue); + // convert the date value to a timezone specific version + var newModelValue = modelValue + 'T10:00:00-0400'; + return new Date(newModelValue); }); + ngModel.$parsers.push(function(modelValue){ return new Date(modelValue); });
fe48398d485afe58415688a50479c6fe0ace33c0
examples/minimal-formatter.js
examples/minimal-formatter.js
var example = require("washington") var assert = require("assert") var color = require("cli-color") example.use({ success: function (success, report) { process.stdout.write(color.green(".")) }, pending: function (pending, report) { process.stdout.write(color.yellow("-")) }, failure: function (failure, report) { process.stdout.write(color.red("X")) }, complete: function (report, code) { process.exit(code) } }) example("Good", function () { assert.equal(1, 1) }) example("Pending") example("Bad", function () { assert.equal(1, 2) }) example.go()
var example = require("washington") var assert = require("assert") var RED = "\u001b[31m" var GREEN = "\u001b[32m" var YELLOW = "\u001b[33m" var CLEAR = "\u001b[0m" example.use({ success: function (success, report) { process.stdout.write(GREEN + "." + CLEAR) }, pending: function (pending, report) { process.stdout.write(YELLOW + "-" + CLEAR) }, failure: function (failure, report) { process.stdout.write(RED + "X" + CLEAR) }, complete: function (report, code) { process.exit(code) } }) example("Good", function () { assert.equal(1, 1) }) example("Pending") example("Bad", function () { assert.equal(1, 2) }) example.go()
Drop dependency on cli-color in example
Drop dependency on cli-color in example [skip ci]
JavaScript
bsd-2-clause
xaviervia/washington,xaviervia/washington
--- +++ @@ -1,18 +1,22 @@ var example = require("washington") var assert = require("assert") -var color = require("cli-color") + +var RED = "\u001b[31m" +var GREEN = "\u001b[32m" +var YELLOW = "\u001b[33m" +var CLEAR = "\u001b[0m" example.use({ success: function (success, report) { - process.stdout.write(color.green(".")) + process.stdout.write(GREEN + "." + CLEAR) }, pending: function (pending, report) { - process.stdout.write(color.yellow("-")) + process.stdout.write(YELLOW + "-" + CLEAR) }, failure: function (failure, report) { - process.stdout.write(color.red("X")) + process.stdout.write(RED + "X" + CLEAR) }, complete: function (report, code) {
ce63223ec6191228eecc05108b4af4569becf059
src/front/js/components/__tests__/Header.spec.js
src/front/js/components/__tests__/Header.spec.js
jest.unmock('../Header'); import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { Header } from '../Header'; xdescribe('Header', () => { it('should have title', () => { const container = <Header name="test title" />; const DOM = TestUtils.renderIntoDocument(container); const title = TestUtils.findRenderedDOMComponentWithTag( DOM, 'h1'); expect(title.textContent).toEqual('test title'); }); it('should have only one h1', () => { const container = <Header name="title" />; const DOM = TestUtils.renderIntoDocument(container); const title = TestUtils.scryRenderedDOMComponentsWithTag( DOM, 'h1'); expect(title.length).toEqual(1); }); });
import React from "react"; import Header from "../Header"; import { shallow } from "enzyme"; describe('Header', () => { let wrapper; it('should have only title', () => { const props = { name: 'name' }; wrapper = shallow(<Header {...props} />); expect(wrapper.find('.breadcrumbs__item').length).toEqual(1); }); it('should have only header info', () => { const props = { headerInfo: <Header/>//TODO mockElement }; wrapper = shallow(<Header {...props} />); expect(wrapper.find('.breadcrumbs__item').length).toEqual(1); }); it('should have both name and header info', () => { const props = { name: 'name', headerInfo: <Header/>//TODO mockElement }; console.log(wrapper.find('.breadcrumbs__item').length); wrapper = shallow(<Header {...props} />); expect(wrapper.find('.breadcrumbs__item').length).toEqual(2); }); });
Fix unit tests for Header component
Fix unit tests for Header component
JavaScript
mit
raccoon-app/ui-kit,raccoon-app/ui-kit
--- +++ @@ -1,26 +1,34 @@ -jest.unmock('../Header'); +import React from "react"; +import Header from "../Header"; +import { shallow } from "enzyme"; -import React from 'react'; -import TestUtils from 'react-addons-test-utils'; -import { Header } from '../Header'; +describe('Header', () => { + let wrapper; -xdescribe('Header', () => { - - it('should have title', () => { - const container = <Header name="test title" />; - const DOM = TestUtils.renderIntoDocument(container); - const title = TestUtils.findRenderedDOMComponentWithTag( - DOM, 'h1'); - - expect(title.textContent).toEqual('test title'); + it('should have only title', () => { + const props = { + name: 'name' + }; + wrapper = shallow(<Header {...props} />); + expect(wrapper.find('.breadcrumbs__item').length).toEqual(1); }); - it('should have only one h1', () => { - const container = <Header name="title" />; - const DOM = TestUtils.renderIntoDocument(container); - const title = TestUtils.scryRenderedDOMComponentsWithTag( - DOM, 'h1'); + it('should have only header info', () => { + const props = { + headerInfo: <Header/>//TODO mockElement + }; + wrapper = shallow(<Header {...props} />); + expect(wrapper.find('.breadcrumbs__item').length).toEqual(1); + }); - expect(title.length).toEqual(1); + it('should have both name and header info', () => { + const props = { + name: 'name', + headerInfo: <Header/>//TODO mockElement + }; + console.log(wrapper.find('.breadcrumbs__item').length); + wrapper = shallow(<Header {...props} />); + expect(wrapper.find('.breadcrumbs__item').length).toEqual(2); }); + });
10c444078b93f8ac179235584fb43a02b314f3f0
desktop/app/dockIcon.js
desktop/app/dockIcon.js
import app from 'app' var visibleCount = 0 export default function () { if (++visibleCount === 1) { app.dock.show() } let alreadyHidden = false return () => { if (alreadyHidden) { throw new Error('Tried to hide the dock icon twice') } alreadyHidden = true if (--visibleCount === 0) { app.dock.hide() } } }
import app from 'app' var visibleCount = 0 export default (() => { if (!app.dock) { return () => () => {} } return function () { if (++visibleCount === 1) { app.dock.show() } let alreadyHidden = false return () => { if (alreadyHidden) { throw new Error('Tried to hide the dock icon twice') } alreadyHidden = true if (--visibleCount === 0) { app.dock.hide() } } } })()
Make dock management a noop when dock doesn't exist
Make dock management a noop when dock doesn't exist
JavaScript
bsd-3-clause
keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client
--- +++ @@ -2,18 +2,23 @@ var visibleCount = 0 -export default function () { - if (++visibleCount === 1) { - app.dock.show() +export default (() => { + if (!app.dock) { + return () => () => {} } - let alreadyHidden = false - return () => { - if (alreadyHidden) { - throw new Error('Tried to hide the dock icon twice') + return function () { + if (++visibleCount === 1) { + app.dock.show() } - alreadyHidden = true - if (--visibleCount === 0) { - app.dock.hide() + let alreadyHidden = false + return () => { + if (alreadyHidden) { + throw new Error('Tried to hide the dock icon twice') + } + alreadyHidden = true + if (--visibleCount === 0) { + app.dock.hide() + } } } -} +})()
c933f9b91599f56d8ad5a946083b4a402c2133cc
src/logger.js
src/logger.js
const _ = require('lodash'); const { Logger, transports: { Console } } = require('winston'); module.exports = function wrappedDebug(module) { const logger = new Logger({ level: 'info', transports: [ new (Console)({ json: true, stringify: true, }), ], }); [ 'error', 'warn', 'info', 'verbose', 'debug', 'silly', ].forEach((method) => { const originalMethod = logger[method]; logger[method] = function logMethod(message, meta = {}) { const newMeta = _.defaultsDeep({}, meta, { ctx: { app: 'amion-scraper', module, }, }); return originalMethod(message, newMeta); }; }); return logger.info.bind(logger); };
const _ = require('lodash'); const { Logger, transports: { Console } } = require('winston'); module.exports = function wrappedDebug(module) { const logger = new Logger({ level: 'info', transports: [ new (Console)({ json: true, stringify: true, handleExceptions: true, }), ], }); [ 'error', 'warn', 'info', 'verbose', 'debug', 'silly', ].forEach((method) => { const originalMethod = logger[method]; logger[method] = function logMethod(message, meta = {}) { const newMeta = _.defaultsDeep({}, meta, { ctx: { app: 'amion-scraper', module, }, }); return originalMethod(message, newMeta); }; }); return logger.info.bind(logger); };
Update winston to handle uncaught exceptions
Update winston to handle uncaught exceptions
JavaScript
mit
cbaclig/amion-scraper
--- +++ @@ -8,6 +8,7 @@ new (Console)({ json: true, stringify: true, + handleExceptions: true, }), ], });
cf5178d1f603a4c029f5cb70250f002543195eea
test/document_update_spec.js
test/document_update_spec.js
var assert = require("assert"); var helpers = require("./helpers"); describe('Document updates,', function(){ var db; before(function(done){ helpers.resetDb(function(err, res){ db = res; done(); }); }); // update objects set body=jsonb_set(body, '{name,last}', '', true) where id=3; describe("Save data and update,", function() { var newDoc = {}; before(function(done) { db.saveDoc("docs", {name:"Foo", score:1}, function(err, doc){ newDoc = doc; done(); }); }); it('check saved attribute', function(){ assert.equal(1, newDoc.score); }); it('updates the document', function(done) { db.docs.setAttribute(newDoc.id, "vaccinated", true, function(err, doc){ assert.equal(doc.vaccinated, true); done(); }); }); it('updates the document without replacing existing attributes', function(done) { db.docs.setAttribute(newDoc.id, "score", 99, function(err, doc){ assert.equal(doc.score, 99); assert.equal(doc.vaccinated, true); assert.equal(doc.id, newDoc.id); done(); }); }); after(function (done) { db.docs.destroy({id: newDoc.id}, done); }); }); });
var assert = require("assert"); var helpers = require("./helpers"); describe('Document updates,', function(){ var db; before(function(done){ helpers.resetDb(function(err, res){ db = res; done(); }); }); // update objects set body=jsonb_set(body, '{name,last}', '', true) where id=3; describe("Save data and update,", function() { var newDoc = {}; before(function(done) { db.saveDoc("docs", {name:"Foo", score:1}, function(err, doc){ newDoc = doc; done(); }); }); it('check saved attribute', function(){ assert.equal(1, newDoc.score); }); it('updates the document', function(done) { db.docs.setAttribute(newDoc.id, "vaccinated", true, function(err, doc){ assert.ifError(err); assert.equal(doc.vaccinated, true); done(); }); }); it('updates the document without replacing existing attributes', function(done) { db.docs.setAttribute(newDoc.id, "score", 99, function(err, doc){ assert.equal(doc.score, 99); assert.equal(doc.vaccinated, true); assert.equal(doc.id, newDoc.id); done(); }); }); after(function (done) { db.docs.destroy({id: newDoc.id}, done); }); }); });
Add example error check to tests
Add example error check to tests
JavaScript
bsd-3-clause
ludvigsen/massive-js,robconery/massive-js
--- +++ @@ -27,6 +27,7 @@ it('updates the document', function(done) { db.docs.setAttribute(newDoc.id, "vaccinated", true, function(err, doc){ + assert.ifError(err); assert.equal(doc.vaccinated, true); done(); });
0c89717bfca88ae7a345450da3d922bddb59507e
test/html/js/minify/index.js
test/html/js/minify/index.js
import sinon from 'sinon'; import chai from 'chai'; const expect = chai.expect; import * as fetch from '../../../../src/functions/fetch.js'; import checkMinifiedJs from '../../../../src/html/js/minify'; describe('html', function() { describe('test minify promise', function() { let sandbox; beforeEach(function() { sandbox = sinon.sandbox.create(); }); afterEach(function() { sandbox.restore(); }); it('should return original URL even if JS is not minified', () => { const result = { body: 'function something(text) { console.log("not minified javascript file"); }', }; sandbox.stub(fetch, 'fetch').returns(result); return new Promise((resolve, reject) => { resolve('https://www.juffalow.com/jsfile.js'); }) .then(checkMinifiedJs) .then((url) => { expect(url).to.equal('https://www.juffalow.com/jsfile.js'); }); }); }); });
import sinon from 'sinon'; import chai from 'chai'; const expect = chai.expect; import * as fetch from '../../../../src/functions/fetch.js'; import checkMinifiedJs from '../../../../src/html/js/minify'; describe('html', function() { describe('test minify promise', function() { let sandbox; beforeEach(function() { sandbox = sinon.sandbox.create(); }); afterEach(function() { sandbox.restore(); }); it('should return original URL even if JS is not minified', () => { const html = { body: '<html><head><link rel="stylesheet" href="https://juffalow.com/cssfile.css" /></head><body><p>Text</p><a href="#">link</a><script src="https://juffalow.com/jsfile.js"></script></body></html>', }; const result = { body: 'function something(text) { console.log("not minified javascript file"); }', response: { statusCode: 200, }, }; sandbox.stub(fetch, 'fetch').callsFake((url) => { switch (url) { case 'https://juffalow.com/': return html; case 'https://juffalow.com/jsfile.js': return result; } }); return checkMinifiedJs('https://juffalow.com/') .then((results) => { expect(results.length).to.equal(1); expect(results[0].messages.length).to.equal(0); expect(results[0].errors.length).to.equal(1); }); }); }); });
Fix js minify promise test
Fix js minify promise test
JavaScript
mit
juffalow/pentest-tool-lite,juffalow/pentest-tool-lite
--- +++ @@ -17,18 +17,31 @@ }); it('should return original URL even if JS is not minified', () => { + const html = { + body: '<html><head><link rel="stylesheet" href="https://juffalow.com/cssfile.css" /></head><body><p>Text</p><a href="#">link</a><script src="https://juffalow.com/jsfile.js"></script></body></html>', + }; + const result = { body: 'function something(text) { console.log("not minified javascript file"); }', + response: { + statusCode: 200, + }, }; - sandbox.stub(fetch, 'fetch').returns(result); + sandbox.stub(fetch, 'fetch').callsFake((url) => { + switch (url) { + case 'https://juffalow.com/': + return html; + case 'https://juffalow.com/jsfile.js': + return result; + } + }); - return new Promise((resolve, reject) => { - resolve('https://www.juffalow.com/jsfile.js'); - }) - .then(checkMinifiedJs) - .then((url) => { - expect(url).to.equal('https://www.juffalow.com/jsfile.js'); + return checkMinifiedJs('https://juffalow.com/') + .then((results) => { + expect(results.length).to.equal(1); + expect(results[0].messages.length).to.equal(0); + expect(results[0].errors.length).to.equal(1); }); }); });
6ff0d1e0517379a432f84bade6817285058ffaf1
src/index.js
src/index.js
import 'index.scss'; import 'script-loader!TimelineJS3/compiled/js/timeline.js'; import generateTimeline from './timeline'; generateTimeline().then(timeline => { window.timeline = timeline; // eslint-disable-line no-undef });
import 'index.scss'; import 'script-loader!TimelineJS3/compiled/js/timeline-min.js'; import generateTimeline from './timeline'; generateTimeline().then(timeline => { window.timeline = timeline; // eslint-disable-line no-undef });
Load minified version of TimelineJS3
Load minified version of TimelineJS3 Shaves another ~200kB off of the javascript we ship in production. If we're debugging issues inside of TimelineJS3, we aren't really working on our timeline anymore!
JavaScript
mit
L4GG/timeline,L4GG/timeline,L4GG/timeline
--- +++ @@ -1,5 +1,5 @@ import 'index.scss'; -import 'script-loader!TimelineJS3/compiled/js/timeline.js'; +import 'script-loader!TimelineJS3/compiled/js/timeline-min.js'; import generateTimeline from './timeline'; generateTimeline().then(timeline => {
5c149bc0399bd39675ee02dd3c2f03fed9b7d850
src/index.js
src/index.js
'use strict'; const React = require('react'); const icon = require('./GitHub-Mark-64px.png'); const Preview = require('./preview'); const githubPlugin = ({term, display, actions}) => { display({ id: 'github', icon, title: `Search github for ${term}`, subtitle: `You entered ${term}`, getPreview: () => <Preview term={term} /> }) }; module.exports = { fn: githubPlugin, name: 'Search on Github', icon };
'use strict'; const React = require('react'); const icon = require('./GitHub-Mark-64px.png'); const Preview = require('./preview'); const githubPlugin = ({term, display, actions}) => { display({ id: 'github', icon, order: 11, title: `Search github for ${term}`, subtitle: `You entered ${term}`, getPreview: () => <Preview term={term} /> }) }; module.exports = { fn: githubPlugin, name: 'Search on Github', icon };
Update to ensure plugin searches on full user input
Update to ensure plugin searches on full user input
JavaScript
mit
tenorz007/cerebro-github,tenorz007/cerebro-github
--- +++ @@ -7,6 +7,7 @@ display({ id: 'github', icon, + order: 11, title: `Search github for ${term}`, subtitle: `You entered ${term}`, getPreview: () => <Preview term={term} />
bd9bd8137c46112a83209a6890c37bd0bdf45fd8
src/index.js
src/index.js
var Alexa = require('alexa-sdk'); var APP_ID = 'amzn1.ask.skill.85ae7ea2-b727-4d2a-9765-5c563a5ec379'; var SKILL_NAME = 'Snack Overflow'; var POSSIBLE_RECIPIES = [ 'Chicken Parmesan', 'Spaghetti', 'Turkey Sandwich' ]; exports.handler = function(event, context, callback) { var alexa = Alexa.handler(event, context, callback); alexa.registerHandlers(getRecipieHandlers); alexa.execute(); }; var getRecipieHandlers = { 'whatShouldIMakeIntent': function() { var recipieNum = Math.floor(Math.random() * POSSIBLE_RECIPIES.length); this.emit(':tell', POSSIBLE_RECIPIES[recipieNum]); } };
var Alexa = require('alexa-sdk'); var APP_ID = 'amzn1.ask.skill.85ae7ea2-b727-4d2a-9765-5c563a5ec379'; var SKILL_NAME = 'Snack Overflow'; var POSSIBLE_RECIPES = ['Chicken Parmesan', 'Spaghetti', 'Turkey Sandwich']; var WORKFLOW_STATES = { START : 1, RECIPE_GIVEN : 2 }; var currentWorkflowState = WORKFLOW_STATES.START; exports.handler = function(event, context, callback) { var alexa = Alexa.handler(event, context, callback); alexa.registerHandlers(getRecipeHandlers); alexa.registerHandlers(utilHandlers); alexa.execute(); }; var getRecipeHandlers = { 'whatShouldIMakeIntent': function() { var recipeNum = Math.floor(Math.random() * POSSIBLE_RECIPES.length); currentRecipe = POSSIBLE_RECIPES[recipeNum]; this.emit(':tell', "Would you like to make ", currentRecipe); currentWorkflowState = WORKFLOW_STATES.RECIPE_GIVEN; } }; var utilHandlers = { 'affirmativeIntent': function () { doAffirmativeAction(); } }; function doAffirmativeAction() { switch (currentWorkflowState) { case (WORKFLOW_STATES.START): break; case (WORKFLOW_STATES.RECIPE_GIVEN): tellRecipe(currentRecipe); break; } } function tellRecipe(recipe) { /* this.emit(":tell", "You will need"); for (var i = 0; i < recipe.ingredients.length; i++) { this.emit(":tell", recipe.ingredients[i].quantity, "of", recipe.ingredients[i].name); } for (var i = 0; i < recipe.steps.length; i++) { this.emit)(":tell", recipe.steps[i]); } */ }
Add in state-based logic for switching between Alexa commands.
Add in state-based logic for switching between Alexa commands.
JavaScript
mit
cwboden/amazon-hackathon-alexa
--- +++ @@ -3,19 +3,57 @@ var APP_ID = 'amzn1.ask.skill.85ae7ea2-b727-4d2a-9765-5c563a5ec379'; var SKILL_NAME = 'Snack Overflow'; -var POSSIBLE_RECIPIES = [ 'Chicken Parmesan', 'Spaghetti', 'Turkey Sandwich' ]; +var POSSIBLE_RECIPES = ['Chicken Parmesan', 'Spaghetti', 'Turkey Sandwich']; + +var WORKFLOW_STATES = { + START : 1, + RECIPE_GIVEN : 2 +}; + +var currentWorkflowState = WORKFLOW_STATES.START; exports.handler = function(event, context, callback) { - var alexa = Alexa.handler(event, context, callback); - alexa.registerHandlers(getRecipieHandlers); - alexa.execute(); + var alexa = Alexa.handler(event, context, callback); + alexa.registerHandlers(getRecipeHandlers); + alexa.registerHandlers(utilHandlers); + alexa.execute(); }; -var getRecipieHandlers = { +var getRecipeHandlers = { 'whatShouldIMakeIntent': function() { - var recipieNum = Math.floor(Math.random() * POSSIBLE_RECIPIES.length); - - this.emit(':tell', POSSIBLE_RECIPIES[recipieNum]); + var recipeNum = Math.floor(Math.random() * POSSIBLE_RECIPES.length); + currentRecipe = POSSIBLE_RECIPES[recipeNum]; + + this.emit(':tell', "Would you like to make ", currentRecipe); + currentWorkflowState = WORKFLOW_STATES.RECIPE_GIVEN; } }; +var utilHandlers = { + 'affirmativeIntent': function () { + doAffirmativeAction(); + } +}; + +function doAffirmativeAction() { + switch (currentWorkflowState) { + case (WORKFLOW_STATES.START): + break; + case (WORKFLOW_STATES.RECIPE_GIVEN): + tellRecipe(currentRecipe); + break; + } +} + +function tellRecipe(recipe) { + /* + this.emit(":tell", "You will need"); + for (var i = 0; i < recipe.ingredients.length; i++) { + this.emit(":tell", recipe.ingredients[i].quantity, "of", recipe.ingredients[i].name); + } + + for (var i = 0; i < recipe.steps.length; i++) { + this.emit)(":tell", recipe.steps[i]); + } + */ +}
db68227c3a02dcc059839592de9076abe52d3bfe
js/server.js
js/server.js
var http = require('http'); var util = require('./util'); var counter = 0; var port = 1337; http.createServer(function (req, res) { var answer = util.helloWorld(); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(answer + '\nYou are user number ' + counter + '.'); counter = counter + 1; console.log('Current count: ' + counter); }).listen(port, '127.0.0.1'); console.log('Server running at http://127.0.0.1:' + port + '/');
var http = require('http'); var util = require('./util'); var counter = 0; var port = 1337; http.createServer(function (req, res) { var answer = util.helloWorld(); counter = counter + 1; res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(answer + '\nYou are user number ' + counter + '.'); console.log('Current count: ' + counter); }).listen(port, '127.0.0.1'); console.log('Server running at http://127.0.0.1:' + port + '/');
FIX Increase counter before printing it
FIX Increase counter before printing it
JavaScript
mit
fhinkel/SimpleChatServer,fhinkel/SimpleChatServer
--- +++ @@ -5,9 +5,9 @@ http.createServer(function (req, res) { var answer = util.helloWorld(); + counter = counter + 1; res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(answer + '\nYou are user number ' + counter + '.'); - counter = counter + 1; console.log('Current count: ' + counter); }).listen(port, '127.0.0.1'); console.log('Server running at http://127.0.0.1:' + port + '/');
d130e6373de4b79cd414d6b02e37eecce1aee97d
public/javascripts/app/views/gameController.js
public/javascripts/app/views/gameController.js
define([ 'Backbone', //Templates 'text!templates/project-page/closeGameTemplate.html' ], function( Backbone, //Template closeGameTemplate ){ var GameController = Backbone.View.extend({ template: _.template(closeGameTemplate), close: function(event){ var task = this.selectedTask.get('id'); socket.emit('close game', task); }, killTask: function(){ var result = this.selectedTask.get('result'); this.selectedTask.destroy({data: 'result='+result}); }, render: function(){ var estimations = this.selectedTask.get('estimated') || []; var time = this.selectedTask.get('time'); var total = _.countBy(estimations, function(estimation){ return estimation.card; }); var max = _.max(total, function(point){return point;}); var result = _.compact(_.map(total, function(count, point){ return count === max ? point : false; })).pop(); if(!estimations[0]){ estimations.push({ player: 'No one estimated', card: '?' }); } if(time === '0'){ this.killTask(); } this.selectedTask.set({result: result}, {silent: true}); this.$el.html(this.template({ estimations: estimations, time: time, result: result })); } }); return GameController; });
define([ 'Backbone', //Templates 'text!templates/project-page/closeGameTemplate.html' ], function( Backbone, //Template closeGameTemplate ){ var GameController = Backbone.View.extend({ template: _.template(closeGameTemplate), close: function(event){ var task = this.selectedTask.get('id'); socket.emit('close game', task); }, killTask: function(){ var task = this.selectedTask.get('id'); var kill = _.once(function(){ socket.emit('kill task', task); }); kill(); }, render: function(){ var estimations = this.selectedTask.get('estimated') || []; var time = this.selectedTask.get('time'); var total = _.countBy(estimations, function(estimation){ return estimation.card; }); var max = _.max(total, function(point){return point;}); var result = _.compact(_.map(total, function(count, point){ return count === max ? point : false; })).pop(); if(!estimations[0]){ estimations.push({ player: 'No one estimated', card: '?' }); } if(time === '0'){ this.killTask(); } this.selectedTask.set({result: result}, {silent: true}); this.$el.html(this.template({ estimations: estimations, time: time, result: result })); } }); return GameController; });
Remove the task only once
Remove the task only once
JavaScript
mit
tangosource/pokerestimate,tangosource/pokerestimate
--- +++ @@ -21,8 +21,12 @@ }, killTask: function(){ - var result = this.selectedTask.get('result'); - this.selectedTask.destroy({data: 'result='+result}); + var task = this.selectedTask.get('id'); + var kill = _.once(function(){ + socket.emit('kill task', task); + }); + + kill(); }, render: function(){
2daacc00b849da8a3e86c089fe1768938486bd2b
draft-js-dnd-plugin/src/modifiers/onDropFile.js
draft-js-dnd-plugin/src/modifiers/onDropFile.js
import AddBlock from './addBlock'; export default function(config) { return function(e){ const {props, selection, files, editorState, onChange} = e; // Get upload function from config or editor props const upload = config.upload || props.upload; if (upload) { //this.setState({fileDrag: false, uploading: true}); console.log('Starting upload'); var data = new FormData(); for (var key in files) { data.append('files', files[key]); } upload(data, (files, tag)=> { console.log('Upload done'); // Success, tag can be function that returns editorState or a tag-type (default: image) var newEditorState = editorState(); files.forEach(function (x) { newEditorState = typeof tag === 'function' ? tag(x) : AddBlock(newEditorState, selection, tag || 'image', x); }); onChange(newEditorState); }, (err)=> { // Failed console.error(err) //this.setState({uploading: false, uploadError: err}); }, (percent)=> { // Progress //this.setState({percent: percent !== 100 ? percent : null}); console.log(percent) }); return true; } } }
import AddBlock from './addBlock'; export default function(config) { return function(e){ const {props, selection, files, editorState, onChange} = e; // Get upload function from config or editor props const upload = config.upload || props.upload; if (upload) { //this.setState({fileDrag: false, uploading: true}); console.log('Starting upload'); var formData = new FormData(); var data = { files: [] }; for (var key in files) { formData.append('files', files[key]); data.files.push(files[key]); } data.formData = data; upload(data, (files, tag)=> { console.log('Upload done'); // Success, tag can be function that returns editorState or a tag-type (default: image) var newEditorState = editorState(); files.forEach(function (x) { newEditorState = typeof tag === 'function' ? tag(x) : AddBlock(newEditorState, selection, tag || 'image', x); }); onChange(newEditorState); }, (err)=> { // Failed console.error(err) //this.setState({uploading: false, uploadError: err}); }, (percent)=> { // Progress //this.setState({percent: percent !== 100 ? percent : null}); console.log(percent) }); return true; } } }
Allow the upload function to acces not only formData, but also the raw files
Allow the upload function to acces not only formData, but also the raw files
JavaScript
mit
dagopert/draft-js-plugins,nikgraf/draft-js-plugin-editor,nikgraf/draft-js-plugin-editor,draft-js-plugins/draft-js-plugins-v1,draft-js-plugins/draft-js-plugins,draft-js-plugins/draft-js-plugins,koaninc/draft-js-plugins,dagopert/draft-js-plugins,dagopert/draft-js-plugins,koaninc/draft-js-plugins,draft-js-plugins/draft-js-plugins,draft-js-plugins/draft-js-plugins-v1,draft-js-plugins/draft-js-plugins,nikgraf/draft-js-plugin-editor
--- +++ @@ -9,10 +9,15 @@ //this.setState({fileDrag: false, uploading: true}); console.log('Starting upload'); - var data = new FormData(); + var formData = new FormData(); + var data = { + files: [] + }; for (var key in files) { - data.append('files', files[key]); + formData.append('files', files[key]); + data.files.push(files[key]); } + data.formData = data; upload(data, (files, tag)=> { console.log('Upload done'); // Success, tag can be function that returns editorState or a tag-type (default: image)
1853e1519030caaeeb7f31017d98823aa5696daf
flow-github/metro.js
flow-github/metro.js
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ declare module 'metro' { declare module.exports: any; } declare module 'metro/src/lib/TerminalReporter' { declare module.exports: any; } declare module 'metro/src/HmrServer' { declare module.exports: any; } declare module 'metro/src/lib/bundle-modules/HMRClient' { declare module.exports: any; }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ declare module 'metro' { declare module.exports: any; } declare module 'metro/src/HmrServer' { declare module.exports: any; } declare module 'metro/src/lib/attachWebsocketServer' { declare module.exports: any; } declare module 'metro/src/lib/bundle-modules/HMRClient' { declare module.exports: any; } declare module 'metro/src/lib/TerminalReporter' { declare module.exports: any; }
Add open source Flow declaration for Metro module
Add open source Flow declaration for Metro module Summary: Fix Flow failure by adding a declaration to the Flow config used in open source. This did not get caught internally because we use a different Flow config. Release Notes ------------- [INTERNAL] [MINOR] [Flow] - Fix Flow config. Reviewed By: rafeca Differential Revision: D8257641 fbshipit-source-id: 3f4b2cbe622b2e76aa018e9369216a6b9ac25f47
JavaScript
bsd-3-clause
hammerandchisel/react-native,hoangpham95/react-native,javache/react-native,exponent/react-native,facebook/react-native,hammerandchisel/react-native,javache/react-native,arthuralee/react-native,hammerandchisel/react-native,javache/react-native,exponentjs/react-native,exponent/react-native,pandiaraj44/react-native,pandiaraj44/react-native,hoangpham95/react-native,pandiaraj44/react-native,myntra/react-native,myntra/react-native,pandiaraj44/react-native,javache/react-native,javache/react-native,exponent/react-native,hoangpham95/react-native,facebook/react-native,javache/react-native,myntra/react-native,arthuralee/react-native,exponent/react-native,javache/react-native,myntra/react-native,hammerandchisel/react-native,arthuralee/react-native,facebook/react-native,exponentjs/react-native,facebook/react-native,arthuralee/react-native,exponentjs/react-native,hammerandchisel/react-native,pandiaraj44/react-native,hammerandchisel/react-native,exponentjs/react-native,hoangpham95/react-native,exponentjs/react-native,myntra/react-native,hammerandchisel/react-native,janicduplessis/react-native,janicduplessis/react-native,janicduplessis/react-native,exponent/react-native,janicduplessis/react-native,exponentjs/react-native,javache/react-native,facebook/react-native,myntra/react-native,exponent/react-native,facebook/react-native,hammerandchisel/react-native,janicduplessis/react-native,facebook/react-native,hoangpham95/react-native,janicduplessis/react-native,exponentjs/react-native,janicduplessis/react-native,myntra/react-native,exponent/react-native,myntra/react-native,hoangpham95/react-native,pandiaraj44/react-native,myntra/react-native,facebook/react-native,javache/react-native,hoangpham95/react-native,janicduplessis/react-native,arthuralee/react-native,hoangpham95/react-native,pandiaraj44/react-native,exponent/react-native,exponentjs/react-native,facebook/react-native,pandiaraj44/react-native
--- +++ @@ -12,14 +12,18 @@ declare module.exports: any; } -declare module 'metro/src/lib/TerminalReporter' { +declare module 'metro/src/HmrServer' { declare module.exports: any; } -declare module 'metro/src/HmrServer' { +declare module 'metro/src/lib/attachWebsocketServer' { declare module.exports: any; } declare module 'metro/src/lib/bundle-modules/HMRClient' { declare module.exports: any; } + +declare module 'metro/src/lib/TerminalReporter' { + declare module.exports: any; +}
2ca2a8144d19b46da40a24932471f8ea5f6c9c72
signature.js
signature.js
// source: var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var SIGNATURE = '__signature_' + require('hat')(); exports.parse = parse; function parse (fn) { if (typeof fn !== 'function') { throw new TypeError("Not a function: " + fn); } if (!fn[SIGNATURE]) { fn[SIGNATURE] = _parse(fn); } return fn[SIGNATURE]; } exports.clobber = clobber; function clobber (fn, names) { fn[SIGNATURE] = names; return fn; } exports.copy = copy; function copy (fromFn, toFn) { toFn[SIGNATURE] = fromFn[SIGNATURE] || _parse(fromFn); return toFn; } /** * This code is adapted from the AngularJS v1 dependency injector */ function _parse (fn) { var fnText = fn.toString().replace(STRIP_COMMENTS, ''); var argDecl = fnText.match(FN_ARGS); return argDecl[1].split(FN_ARG_SPLIT).map(function(arg){ return arg.replace(FN_ARG, function(all, underscore, name){ return name; }); }).filter(Boolean); }
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var SIGNATURE = '__signature_' + require('hat')(); exports.parse = parse; function parse (fn) { if (typeof fn !== 'function') { throw new TypeError("Not a function: " + fn); } if (!fn[SIGNATURE]) { fn[SIGNATURE] = _parse(fn); } return fn[SIGNATURE]; } exports.clobber = clobber; function clobber (fn, names) { fn[SIGNATURE] = names; return fn; } exports.copy = copy; function copy (fromFn, toFn) { toFn[SIGNATURE] = fromFn[SIGNATURE] || _parse(fromFn); return toFn; } /** * This code is adapted from the AngularJS v1 dependency injector */ function _parse (fn) { var fnText = fn.toString().replace(STRIP_COMMENTS, ''); var argDecl = fnText.match(FN_ARGS); return argDecl[1].split(FN_ARG_SPLIT).map(function(arg){ return arg.replace(FN_ARG, function(all, underscore, name){ return name; }); }).filter(Boolean); }
Remove noisy & pointless comment
Remove noisy & pointless comment
JavaScript
mit
grncdr/js-pockets
--- +++ @@ -1,4 +1,3 @@ -// source: var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
196e3fded155835c52ac56a1847a1dfb21fbdd1c
api/models/index.js
api/models/index.js
const Sequelize = require('sequelize'); const env = process.env.NODE_ENV || 'development'; const config = require('../config/config.json')[env]; const sequelize = new Sequelize(config.database, config.username, config.password, config); module.exports = sequelize;
const Sequelize = require('sequelize'); const env = process.env.NODE_ENV || 'development'; const config = require('../config/config.json')[env]; const sequelize = (() => { if (config.use_env_variable) { return new Sequelize(process.env[config.use_env_variable], config); } return new Sequelize(config.database, config.username, config.password, config); })(); module.exports = sequelize;
Implement use_env_variable in main app logic
Implement use_env_variable in main app logic
JavaScript
mit
tsg-ut/mnemo,tsg-ut/mnemo
--- +++ @@ -2,6 +2,12 @@ const env = process.env.NODE_ENV || 'development'; const config = require('../config/config.json')[env]; -const sequelize = new Sequelize(config.database, config.username, config.password, config); +const sequelize = (() => { + if (config.use_env_variable) { + return new Sequelize(process.env[config.use_env_variable], config); + } + + return new Sequelize(config.database, config.username, config.password, config); +})(); module.exports = sequelize;
5f848210657e1a10260e277c49d584ea5a10fc2d
client/app/scripts/services/action.js
client/app/scripts/services/action.js
angular .module('app') .factory('actionService', [ '$http', '$resource', function($http, $resource) { var Action = $resource('/api/actions/:id', { id: '@id' } ); Action.hasUserActed = function(project_id, user_id) { return $http.get('/api/actions/hasUserActed', {params:{'project_id':project_id, 'user_id':user_id}}).then(function(response) { if(response.status === 200 && response.data.length > 0) { return true; } return false; }); }; Action.getProjectActionUsers = function(project_id) { return $http.get('/api/projects/'+project_id+'/actions').then(function(response) { if(response.status === 200) { return response.data; } return false; }); }; return Action; }]);
angular .module('app') .factory('actionService', [ '$http', '$resource', function($http, $resource) { var Action = $resource('/api/actions/:id', { id: '@id' } ); Action.hasUserActed = function(project_id, user_id) { return $http.get('/api/actions/hasUserActed', {params:{'project_id':project_id, 'user_id':user_id}}).then(function(response) { if(response.status === 200 && response.data.length > 0) { return true; } return false; }); }; Action.getProjectActionUsers = function(project_id) { return $http.get('/api/projects/'+project_id+'/actions').then(function(response) { if(response.status === 200) { return response.data; } return false; }); }; Action.getAllActionUsers = function(project_id) { return $http.get('/api/actions').then(function(response) { if(response.status === 200) { return response.data; } return false; }); }; return Action; }]);
Add service function to get all activity
Add service function to get all activity
JavaScript
mit
brettshollenberger/rootstrikers,brettshollenberger/rootstrikers
--- +++ @@ -27,6 +27,15 @@ }); }; + Action.getAllActionUsers = function(project_id) { + return $http.get('/api/actions').then(function(response) { + if(response.status === 200) { + return response.data; + } + return false; + }); + }; + return Action; }]);
3a765c088255b7c2b5485d6566efc736519b2372
devServer.js
devServer.js
var webpack = require('webpack'); var webpackDevMiddleware = require('webpack-dev-middleware'); var webpackHotMiddleware = require('webpack-hot-middleware'); var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); var config = require('./webpack.config'); var port = 3000; var compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ console.log('a user connected'); socket.on('chat message', function(data) { io.emit('chat message', data); }); socket.on('disconnect', function(){ console.log('user disconnected'); }); }); server.listen(port, function(error) { if (error) { console.error(error); } else { console.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port); } });
var webpack = require('webpack'); var webpackDevMiddleware = require('webpack-dev-middleware'); var webpackHotMiddleware = require('webpack-hot-middleware'); var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); var config = require('./webpack.config'); var port = process.env.PORT || 3000; var compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ console.log('a user connected'); socket.on('chat message', function(data) { io.emit('chat message', data); }); socket.on('disconnect', function(){ console.log('user disconnected'); }); }); server.listen(port, function(error) { if (error) { console.error(error); } else { console.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port); } });
Update to use env port
Update to use env port
JavaScript
mit
Irraquated/gryph,Irraquated/gryph,FakeSloth/gryph,FakeSloth/gryph
--- +++ @@ -6,7 +6,7 @@ var io = require('socket.io')(server); var config = require('./webpack.config'); -var port = 3000; +var port = process.env.PORT || 3000; var compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
71f21303b3aff0e7cf4e3f52fb5c1e95984b9970
generators/needle/needle-base.js
generators/needle/needle-base.js
const chalk = require('chalk'); const jhipsterUtils = require('../utils'); module.exports = class { addBlockContentToFile(fullPath, content, needleTag) { try { jhipsterUtils.rewriteFile( { file: fullPath, needle: needleTag, splicable: [content] }, this ); } catch (e) { this.log( chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(' or missing required jhipster-needle. Content not added to JHipster app.\n') ); this.debug('Error:', e); } } };
const chalk = require('chalk'); const jhipsterUtils = require('../utils'); module.exports = class { constructor(generator) { this.generator = generator; } addBlockContentToFile(rewriteFileModel, errorMessage) { try { jhipsterUtils.rewriteFile( { file: rewriteFileModel.file, needle: rewriteFileModel.needle, splicable: rewriteFileModel.splicable }, this.generator ); } catch (e) { this.logNeedleNotFound(e, errorMessage, rewriteFileModel.file); } } logNeedleNotFound(exception, message, fullPath) { if (!message) { message = 'Content not added to file'; } this.generator.log(chalk.yellow('\nUnable to find ') + fullPath + chalk.yellow(` or missing required jhipster-needle. ${message}\n`)); this.generator.debug('Error:', exception); } generateFileModelWithPath(aPath, aFile, needleTag, ...content) { return Object.assign(this.generateFileModel(aFile, needleTag, ...content), { path: aPath }); } generateFileModel(aFile, needleTag, ...content) { return { file: aFile, needle: needleTag, splicable: content }; } };
Define constructor and add generateFileModel
Define constructor and add generateFileModel
JavaScript
apache-2.0
dynamicguy/generator-jhipster,ruddell/generator-jhipster,jhipster/generator-jhipster,sendilkumarn/generator-jhipster,mosoft521/generator-jhipster,cbornet/generator-jhipster,mosoft521/generator-jhipster,pascalgrimaud/generator-jhipster,PierreBesson/generator-jhipster,vivekmore/generator-jhipster,wmarques/generator-jhipster,jhipster/generator-jhipster,wmarques/generator-jhipster,mraible/generator-jhipster,duderoot/generator-jhipster,sendilkumarn/generator-jhipster,hdurix/generator-jhipster,mraible/generator-jhipster,ctamisier/generator-jhipster,vivekmore/generator-jhipster,ruddell/generator-jhipster,pascalgrimaud/generator-jhipster,gmarziou/generator-jhipster,duderoot/generator-jhipster,mosoft521/generator-jhipster,liseri/generator-jhipster,dynamicguy/generator-jhipster,sendilkumarn/generator-jhipster,wmarques/generator-jhipster,PierreBesson/generator-jhipster,jhipster/generator-jhipster,wmarques/generator-jhipster,atomfrede/generator-jhipster,mraible/generator-jhipster,hdurix/generator-jhipster,liseri/generator-jhipster,duderoot/generator-jhipster,cbornet/generator-jhipster,gmarziou/generator-jhipster,liseri/generator-jhipster,jhipster/generator-jhipster,ctamisier/generator-jhipster,ctamisier/generator-jhipster,wmarques/generator-jhipster,atomfrede/generator-jhipster,hdurix/generator-jhipster,dynamicguy/generator-jhipster,gmarziou/generator-jhipster,ruddell/generator-jhipster,ctamisier/generator-jhipster,mraible/generator-jhipster,PierreBesson/generator-jhipster,hdurix/generator-jhipster,mosoft521/generator-jhipster,gmarziou/generator-jhipster,atomfrede/generator-jhipster,vivekmore/generator-jhipster,jhipster/generator-jhipster,gmarziou/generator-jhipster,mraible/generator-jhipster,ruddell/generator-jhipster,pascalgrimaud/generator-jhipster,duderoot/generator-jhipster,cbornet/generator-jhipster,atomfrede/generator-jhipster,liseri/generator-jhipster,liseri/generator-jhipster,vivekmore/generator-jhipster,duderoot/generator-jhipster,ctamisier/generator-jhipster,vivekmore/generator-jhipster,PierreBesson/generator-jhipster,PierreBesson/generator-jhipster,cbornet/generator-jhipster,atomfrede/generator-jhipster,ruddell/generator-jhipster,mosoft521/generator-jhipster,sendilkumarn/generator-jhipster,hdurix/generator-jhipster,pascalgrimaud/generator-jhipster,pascalgrimaud/generator-jhipster,dynamicguy/generator-jhipster,sendilkumarn/generator-jhipster,cbornet/generator-jhipster
--- +++ @@ -2,23 +2,44 @@ const jhipsterUtils = require('../utils'); module.exports = class { - addBlockContentToFile(fullPath, content, needleTag) { + constructor(generator) { + this.generator = generator; + } + + addBlockContentToFile(rewriteFileModel, errorMessage) { try { jhipsterUtils.rewriteFile( { - file: fullPath, - needle: needleTag, - splicable: [content] + file: rewriteFileModel.file, + needle: rewriteFileModel.needle, + splicable: rewriteFileModel.splicable }, - this + this.generator ); } catch (e) { - this.log( - chalk.yellow('\nUnable to find ') + - fullPath + - chalk.yellow(' or missing required jhipster-needle. Content not added to JHipster app.\n') - ); - this.debug('Error:', e); + this.logNeedleNotFound(e, errorMessage, rewriteFileModel.file); } } + + logNeedleNotFound(exception, message, fullPath) { + if (!message) { + message = 'Content not added to file'; + } + this.generator.log(chalk.yellow('\nUnable to find ') + + fullPath + + chalk.yellow(` or missing required jhipster-needle. ${message}\n`)); + this.generator.debug('Error:', exception); + } + + generateFileModelWithPath(aPath, aFile, needleTag, ...content) { + return Object.assign(this.generateFileModel(aFile, needleTag, ...content), { path: aPath }); + } + + generateFileModel(aFile, needleTag, ...content) { + return { + file: aFile, + needle: needleTag, + splicable: content + }; + } };
4b0dfc61b9d837724df287b7a9d86eedb35f4060
website/src/app/global.services/store/mcstore.js
website/src/app/global.services/store/mcstore.js
import MCStoreBus from './mcstorebus'; export const EVTYPE = { EVUPDATE: 'EVUPDATE', EVREMOVE: 'EVREMOVE', EVADD: 'EVADD' }; const _KNOWN_EVENTS = _.values(EVTYPE); function isKnownEvent(event) { return _.findIndex(_KNOWN_EVENTS, event) !== -1; } export class MCStore { constructor(initialState) { this.store = initialState; this.bus = new MCStoreBus(); this.EVUPDATE = 'EVUPDATE'; this.EVREMOVE = 'EVREMOVE'; this.EVADD = 'EVADD'; this.knownEvents = [this.EVUPDATE, this.EVREMOVE, this.EVADD]; } subscribe(event, fn) { if (!isKnownEvent(event)) { throw new Error(`Unknown Event ${event}`); } return this.bus.subscribe(event, fn); } _knownEvent(event) { return _.findIndex(this.knownEvents, event) !== -1; } update(fn) { this._performStoreAction(this.EVUPDATE, fn); } remove(fn) { this._performStoreAction(this.EVREMOVE, fn); } add(fn) { this._performStoreAction(this.EVADD, fn); } _performStoreAction(event, fn) { fn(this.store); this.bus.fireEvent(event, this.store); } }
import MCStoreBus from './mcstorebus'; export const EVTYPE = { EVUPDATE: 'EVUPDATE', EVREMOVE: 'EVREMOVE', EVADD: 'EVADD' }; const _KNOWN_EVENTS = _.values(EVTYPE); function isKnownEvent(event) { return _KNOWN_EVENTS.indexOf(event) !== -1; } export class MCStore { constructor(initialState) { this.store = initialState; this.bus = new MCStoreBus(); this.EVUPDATE = 'EVUPDATE'; this.EVREMOVE = 'EVREMOVE'; this.EVADD = 'EVADD'; this.knownEvents = [this.EVUPDATE, this.EVREMOVE, this.EVADD]; } subscribe(event, fn) { if (!isKnownEvent(event)) { throw new Error(`Unknown Event ${event}`); } return this.bus.subscribe(event, fn); } _knownEvent(event) { return _.findIndex(this.knownEvents, event) !== -1; } update(fn) { this._performStoreAction(this.EVUPDATE, fn); } remove(fn) { this._performStoreAction(this.EVREMOVE, fn); } add(fn) { this._performStoreAction(this.EVADD, fn); } _performStoreAction(event, fn) { fn(this.store); this.bus.fireEvent(event, this.store); } }
Switch Array.indexOf to determine if event string exists
Switch Array.indexOf to determine if event string exists
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -9,7 +9,7 @@ const _KNOWN_EVENTS = _.values(EVTYPE); function isKnownEvent(event) { - return _.findIndex(_KNOWN_EVENTS, event) !== -1; + return _KNOWN_EVENTS.indexOf(event) !== -1; } export class MCStore {
197e6eeeed36e81b5b87375ea7e2446455ca112c
jquery.initialize.js
jquery.initialize.js
// Complete rewrite of adampietrasiak/jquery.initialize // @link https://github.com/adampietrasiak/jquery.initialize // @link https://github.com/dbezborodovrp/jquery.initialize ;(function($) { var MutationSelectorObserver = function(selector, callback) { this.selector = selector; this.callback = callback; } var msobservers = []; msobservers.observe = function(selector, callback) { this.push(new MutationSelectorObserver(selector, callback)); }; msobservers.initialize = function(selector, callback) { $(selector).each(callback); this.observe(selector, callback); }; var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { for (var j = 0; j < msobservers.length; j++) { $(mutation.addedNodes).find(msobservers[j].selector).addBack(msobservers[j].selector).each(msobservers[j].callback); } }); }); observer.observe(document.documentElement, {childList: true, subtree: true}); $.fn.initialize = function(callback) { msobservers.initialize(this.selector, callback); }; })(jQuery);
// Complete rewrite of adampietrasiak/jquery.initialize // @link https://github.com/adampietrasiak/jquery.initialize // @link https://github.com/dbezborodovrp/jquery.initialize ;(function($) { var MutationSelectorObserver = function(selector, callback) { this.selector = selector; this.callback = callback; } var msobservers = []; msobservers.observe = function(selector, callback) { this.push(new MutationSelectorObserver(selector, callback)); }; msobservers.initialize = function(selector, callback) { $(selector).each(callback); this.observe(selector, callback); }; var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { for (var j = 0; j < msobservers.length; j++) { if (mutation.type == 'childList') { $(mutation.addedNodes).find(msobservers[j].selector).addBack(msobservers[j].selector).each(msobservers[j].callback); } if (mutation.type == 'attributes') { $(mutation.target).filter(msobservers[j].selector).each(msobservers[j].callback); } } }); }); observer.observe(document.documentElement, {childList: true, subtree: true, attributes: true}); $.fn.initialize = function(callback) { msobservers.initialize(this.selector, callback); }; })(jQuery);
Add support for observing attributes.
Add support for observing attributes.
JavaScript
mit
AdamPietrasiak/jquery.initialize,timpler/jquery.initialize,AdamPietrasiak/jquery.initialize,timpler/jquery.initialize
--- +++ @@ -18,12 +18,17 @@ var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { for (var j = 0; j < msobservers.length; j++) { - $(mutation.addedNodes).find(msobservers[j].selector).addBack(msobservers[j].selector).each(msobservers[j].callback); + if (mutation.type == 'childList') { + $(mutation.addedNodes).find(msobservers[j].selector).addBack(msobservers[j].selector).each(msobservers[j].callback); + } + if (mutation.type == 'attributes') { + $(mutation.target).filter(msobservers[j].selector).each(msobservers[j].callback); + } } }); }); - observer.observe(document.documentElement, {childList: true, subtree: true}); + observer.observe(document.documentElement, {childList: true, subtree: true, attributes: true}); $.fn.initialize = function(callback) { msobservers.initialize(this.selector, callback);
f0827ef606c7f11edb1767853d8ed9b052faa7de
gui/dev/fix-dist-artifacts.js
gui/dev/fix-dist-artifacts.js
#!/usr/bin/env node const fs = require('fs') function fixFile (file, bad, good) { if (fs.existsSync(file)) { console.log('Fixing ' + file + ' ...') fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(bad, good)) } } // electron-builder uses the app/package.name instead of .productName to // generate the latest.yml and latest-mac.json files, so they don't match the // built artifacts by default. // // And GitHub will replaces spaces with dots in uploaded release artifacts. fixFile('dist/latest.yml', 'cozy-desktop-gui-setup', 'Cozy.Desktop.Setup') fixFile('dist/github/latest-mac.json', 'cozy-desktop-gui', 'Cozy.Desktop')
#!/usr/bin/env node const fs = require('fs') function fixFile (file, bad, good) { if (fs.existsSync(file)) { console.log('Fixing ' + file + ' ...') fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(bad, good)) } } // electron-builder uses the app/package.name instead of .productName to // generate the latest.yml and latest-mac.json files, so they don't match the // built artifacts by default. // // And GitHub will replaces spaces with dots in uploaded release artifacts. fixFile('dist/latest.yml', 'cozy-desktop-gui-setup-', 'Cozy.Desktop.Setup.') fixFile('dist/github/latest-mac.json', 'cozy-desktop-gui', 'Cozy.Desktop')
Fix GitHub artifact name on Windows
Fix GitHub artifact name on Windows
JavaScript
agpl-3.0
cozy-labs/cozy-desktop,nono/cozy-desktop,nono/cozy-desktop,nono/cozy-desktop,cozy-labs/cozy-desktop,cozy-labs/cozy-desktop,nono/cozy-desktop,cozy-labs/cozy-desktop
--- +++ @@ -15,6 +15,6 @@ // // And GitHub will replaces spaces with dots in uploaded release artifacts. -fixFile('dist/latest.yml', 'cozy-desktop-gui-setup', 'Cozy.Desktop.Setup') +fixFile('dist/latest.yml', 'cozy-desktop-gui-setup-', 'Cozy.Desktop.Setup.') fixFile('dist/github/latest-mac.json', 'cozy-desktop-gui', 'Cozy.Desktop')
22524569d06a330922e74b2552b471a42da1d3ab
js/command-parser.js
js/command-parser.js
define([], function() { var CommandParser = (function() { var parse = function(str, lookForQuotes) { var args = []; var readingPart = false; var part = ''; for(var i=0; i < str.length; i++) { if(str.charAt(i) === ' ' && !readingPart) { args.push(part); part = ''; } else { if(str.charAt(i) === '\"' === "'" && lookForQuotes) { readingPart = !readingPart; } else { part += str.charAt(i); } } } args.push(part); return args; } return { parse: parse } })(); return CommandParser })
define([], function() { var CommandParser = (function() { var parse = function(str, lookForQuotes) { var args = []; var readingPart = false; var part = ''; for(var i=0; i < str.length; i++) { if(str.charAt(i) === ' ' && !readingPart) { args.push(part); part = ''; } else { if(str.charAt(i) === '\"' && lookForQuotes) { readingPart = !readingPart; } else { part += str.charAt(i); } } } args.push(part); return args; } return { parse: parse } })(); return CommandParser })
Fix bug in command parser
Fix bug in command parser
JavaScript
mit
git-school/visualizing-git,git-school/visualizing-git
--- +++ @@ -9,7 +9,7 @@ args.push(part); part = ''; } else { - if(str.charAt(i) === '\"' === "'" && lookForQuotes) { + if(str.charAt(i) === '\"' && lookForQuotes) { readingPart = !readingPart; } else { part += str.charAt(i);
321b5b9b916d5afd386de72da882873e7e67e70c
src/admin/dumb_components/preview_custom_email.js
src/admin/dumb_components/preview_custom_email.js
import React from 'react' export default ({members, preview, props: { submit_custom_email, edit_custom }}) => <div className='custom-email-preview'> <div className='email-recipients'> <h2>Email Recipients</h2> <ul> {members.map((member, i) => <li key={member.first_name + i} className='email-recipient' > {`${member.first_name || member.title} ${member.last_name}`} </li> )} </ul> </div> <h2>Subject: {preview[0]}</h2> <br /> <h3>Dear Member,</h3> <br /> {preview[1] .split('\n') .filter(el => el !== '') .map((par, i) => <div key={i}> <p>{par}</p> <br /> </div> ) } <button className='custom-email-button' onClick={() => submit_custom_email(members, preview)}>Send Email</button> <button className='custom-email-button' onClick={() => edit_custom(preview)}>Edit Email</button> </div>
import React from 'react' export default ({members, preview, props: { submit_custom_email, edit_custom }}) => <div className='custom-email-preview'> <div className='email-recipients'> <h2>Email Recipients</h2> <ul> {members.map((member, i) => <li key={member.first_name + i} className='email-recipient' > {`${member.first_name || member.title} ${member.last_name}`} </li> )} </ul> </div> <h2>Subject: {preview[0]}</h2> <br /> <h4>Freinds of Chichester Harbour</h4> <h4>Dear Member,</h4> <br /> {preview[1] .split('\n') .filter(el => el !== '') .map((par, i) => <div key={i}> <p>{par}</p> <br /> </div> ) } <button className='custom-email-button' onClick={() => submit_custom_email(members, preview)}>Send Email</button> <button className='custom-email-button' onClick={() => edit_custom(preview)}>Edit Email</button> </div>
Add 'Friends of Chichester Harbour' to preview custom email
Add 'Friends of Chichester Harbour' to preview custom email
JavaScript
mit
foundersandcoders/sail-back,foundersandcoders/sail-back
--- +++ @@ -17,7 +17,8 @@ </div> <h2>Subject: {preview[0]}</h2> <br /> - <h3>Dear Member,</h3> + <h4>Freinds of Chichester Harbour</h4> + <h4>Dear Member,</h4> <br /> {preview[1] .split('\n')
61c34e2ca7eeea7bf7393ea1a227a16e4355a921
tasks/copy.js
tasks/copy.js
'use strict'; module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-copy'); return { target: { files: [ { expand: true, cwd: 'src/', src: [ '**/*.html', '**/*.css', '**/*.png', '**/*.jpg', '**/*.jpeg', '**/*.svg', '**/*.json', '**/*.pdf', '**/*.exe', '**/*.zip', '**/*.gz' ], dest: '.dist/' } ] } }; };
'use strict'; module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-copy'); return { target: { files: [ { expand: true, cwd: 'src/', src: [ '**/*.html', '**/*.css', '**/*.png', '**/*.jpg', '**/*.jpeg', '**/*.svg', '**/*.json', '**/*.pdf', '**/*.exe', '**/*.zip', '**/*.gz', '**/*.dmg', '**/*.sig' ], dest: '.dist/' } ] } }; };
Add .dmg and .sig to copied file extensions
Add .dmg and .sig to copied file extensions
JavaScript
mit
sinahab/BitcoinUnlimitedWeb,gandrewstone/BitcoinUnlimitedWeb,BitcoinUnlimited/BitcoinUnlimitedWeb,thofmann/BitcoinUnlimitedWeb,BitcoinUnlimited/BitcoinUnlimitedWeb,sinahab/BitcoinUnlimitedWeb,gandrewstone/BitcoinUnlimitedWeb,BitcoinUnlimited/BitcoinUnlimitedWeb,thofmann/BitcoinUnlimitedWeb
--- +++ @@ -21,7 +21,9 @@ '**/*.pdf', '**/*.exe', '**/*.zip', - '**/*.gz' + '**/*.gz', + '**/*.dmg', + '**/*.sig' ], dest: '.dist/' }
64fa9848ca66290a1e84bc50069a83705753f248
gruntfile.js
gruntfile.js
var Path = require('path'); module.exports = function (grunt) { require('time-grunt')(grunt); require('jit-grunt')(grunt); grunt.initConfig({ exec: { update_nimble_submodules: { command: 'git submodule update --init --recursive', stdout: true, stderr: true } }, jshint: { files: ['gruntfile.js', 'app.js', 'lib/**/*.js'] } }); grunt.registerTask('default', ['jshint']); grunt.registerTask('init', ['exec:update_nimble_submodules']); };
var Path = require('path'); module.exports = function (grunt) { require('time-grunt')(grunt); require('jit-grunt')(grunt); grunt.initConfig({ exec: { update_nimble_submodules: { command: 'git submodule update --init --recursive && npm install', stdout: true, stderr: true } }, jshint: { files: ['gruntfile.js', 'app.js', 'lib/**/*.js'] } }); grunt.registerTask('default', ['jshint']); grunt.registerTask('init', ['exec:update_nimble_submodules']); };
Add npm install to grunt init
Add npm install to grunt init
JavaScript
mpl-2.0
mozilla/nimble.webmaker.org
--- +++ @@ -7,7 +7,7 @@ grunt.initConfig({ exec: { update_nimble_submodules: { - command: 'git submodule update --init --recursive', + command: 'git submodule update --init --recursive && npm install', stdout: true, stderr: true }
161b09e250f0e5f822907994488a39ec6a16e607
src/Disposable.js
src/Disposable.js
class Disposable{ constructor(callback){ this.disposed = false this.callback = callback } dispose(){ if(this.disposed) return this.callback() this.callback = null } } module.exports = Disposable
class Disposable{ constructor(callback){ this.disposed = false this.callback = callback } dispose(){ if(this.disposed) return if(this.callback){ this.callback() this.callback = null } } } module.exports = Disposable
Allow null callback in DIsposable
:bug: Allow null callback in DIsposable
JavaScript
mit
ZoomPK/event-kit,steelbrain/event-kit
--- +++ @@ -5,8 +5,10 @@ } dispose(){ if(this.disposed) return - this.callback() - this.callback = null + if(this.callback){ + this.callback() + this.callback = null + } } } module.exports = Disposable
8dcc55af2eb7c286565351909134bded508b3d98
test/rank.js
test/rank.js
var should = require("should"); var rank = require("../index.js").rank; describe("Rank calculation", function() { var points = 72; var hours = 36; var gravity = 1.8; describe("Calulate the rank for an element", function() { var score; before(function(done) { score = rank.rank(points, hours, gravity); done(); }); it('is bigger than 0', function(done) { (score > 0).should.be.true; done(); }); it('is correct', function(done) { should.equal(0.1032100580982522, score); done(); }); }); describe("Rank variation factor based on published time", function() { var score; before(function(done) { score = rank.rank(points, hours, gravity); done(); }); it('decreases rank if it is older', function(done) { var older_hours = hours + 1; var older_score = rank.rank(points, older_hours, gravity); (score > older_score).should.be.true; done(); }); it('increases rank if it is fresh', function(done) { var earlier_hours = hours - 1; var earlier_score = rank.rank(points, earlier_hours, gravity); (score < earlier_score).should.be.true; done(); }); }); });
var should = require("should"); var rank = require("../index.js").rank; describe("Rank calculation", function() { var points = 72; var hours = 36; var gravity = 1.8; describe("Calulate the rank for an element", function() { var score; before(function(done) { score = rank.rank(points, hours, gravity); done(); }); it('is bigger than 0', function(done) { (score > 0).should.be.true; done(); }); it('is correct', function(done) { should.equal(0.1137595839488455, score); done(); }); }); describe("Rank variation factor based on published time", function() { var score; before(function(done) { score = rank.rank(points, hours, gravity); done(); }); it('decreases rank if it is older', function(done) { var older_hours = hours + 1; var older_score = rank.rank(points, older_hours, gravity); (score > older_score).should.be.true; done(); }); it('increases rank if it is fresh', function(done) { var earlier_hours = hours - 1; var earlier_score = rank.rank(points, earlier_hours, gravity); (score < earlier_score).should.be.true; done(); }); }); });
Fix tests according to the defaults
Fix tests according to the defaults
JavaScript
mit
tlksio/librank
--- +++ @@ -25,7 +25,7 @@ }); it('is correct', function(done) { - should.equal(0.1032100580982522, score); + should.equal(0.1137595839488455, score); done(); });
b3ca504604f8fd25ef428042909a4bad75736967
app/js/arethusa.core/directives/root_token.js
app/js/arethusa.core/directives/root_token.js
"use strict"; angular.module('arethusa.core').directive('rootToken', [ 'state', 'depTree', function(state, depTree) { return { restrict: 'A', scope: {}, link: function(scope, element, attrs) { function apply(fn) { scope.$apply(fn()); } var changeHeads = depTree.mode === 'editor'; element.bind('click', function() { apply(function() { if (changeHeads) { state.handleChangeHead('0000', 'click'); state.deselectAll(); } }); }); element.bind('mouseenter', function () { apply(function() { element.addClass('hovered'); }); }); element.bind('mouseleave', function () { apply(function() { element.removeClass('hovered'); }); }); } }; } ]);
"use strict"; angular.module('arethusa.core').directive('rootToken', [ 'state', 'depTree', function(state, depTree) { return { restrict: 'A', scope: {}, link: function(scope, element, attrs) { function apply(fn) { scope.$apply(fn()); } var changeHeads = depTree.mode === 'editor'; element.bind('click', function() { apply(function() { if (changeHeads) { state.handleChangeHead('0000', 'click'); state.deselectAll(); } }); }); element.bind('mouseenter', function () { apply(function() { element.addClass('hovered'); if (changeHeads && state.hasSelections()) { element.addClass('copy-cursor'); } }); }); element.bind('mouseleave', function () { apply(function() { element.removeClass('hovered'); element.removeClass('copy-cursor'); }); }); } }; } ]);
Change cursor on rootToken as well
Change cursor on rootToken as well
JavaScript
mit
PonteIneptique/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa
--- +++ @@ -26,11 +26,15 @@ element.bind('mouseenter', function () { apply(function() { element.addClass('hovered'); + if (changeHeads && state.hasSelections()) { + element.addClass('copy-cursor'); + } }); }); element.bind('mouseleave', function () { apply(function() { element.removeClass('hovered'); + element.removeClass('copy-cursor'); }); }); }
e87f9a09f2199d239cfc662f8580010fa3caa8e4
test/index.js
test/index.js
import test from 'tape' import { connection } from '../config/rethinkdb' import './server/helpers/config' import './server/helpers/createStore' import './server/helpers/renderApp' import './server/config/rethinkdb' import './server/routes/errors' import './server/routes/main' import './server/routes/search' import './server/routes/sockets' import './client/main' import './client/helpers/actions' import './client/helpers/reducers' import './client/helpers/history' import './client/helpers/snippet' import './client/containers/bkmrkd' import './client/containers/toaster' import './client/components/toast' import './client/components/colophon' import './client/components/bookmark' import './client/components/bookmarks' import './client/components/searchForm' import './client/components/search' test.onFinish(() => { // give time for the socket to close out setTimeout(() => { connection.close() }, 1000) })
import test from 'tape' import { connection } from '../config/rethinkdb' import './server/helpers/config' import './server/helpers/createStore' import './server/helpers/renderApp' import './server/config/rethinkdb' import './server/routes/errors' import './server/routes/main' import './server/routes/search' import './server/routes/sockets' import './client/main' import './client/helpers/actions' import './client/helpers/reducers' import './client/helpers/history' import './client/helpers/snippet' import './client/containers/bkmrkd' import './client/containers/toaster' import './client/components/toast' import './client/components/colophon' import './client/components/bookmark' import './client/components/bookmarks' import './client/components/searchForm' import './client/components/search' test.onFinish(() => { // give time for the socket to close out setTimeout(() => { connection.close() }, 5000) })
Increase timeout for changes to properly close
Increase timeout for changes to properly close
JavaScript
mit
mike-engel/bkmrkd,mike-engel/bkmrkd,mike-engel/bkmrkd
--- +++ @@ -28,5 +28,5 @@ // give time for the socket to close out setTimeout(() => { connection.close() - }, 1000) + }, 5000) })
c7f38e0b6f91a920c6d9e38ee7cceaced50cdf49
app/models/trip.js
app/models/trip.js
import mongoose from 'mongoose'; import { Promise } from 'es6-promise'; mongoose.Promise = Promise; import findOrCreate from 'mongoose-findorcreate'; const Schema = mongoose.Schema; const TripSchema = new Schema( { userId: { type: String, required: true }, lastUpdated: { type: Date, default: Date.now, required: true }, tripLocations: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Location' } ], } ); TripSchema.plugin( findOrCreate ); export default mongoose.model( 'Trip', TripSchema );
import mongoose from 'mongoose'; import { Promise } from 'es6-promise'; mongoose.Promise = Promise; import findOrCreate from 'mongoose-findorcreate'; const Schema = mongoose.Schema; const getDefaultDate = () => new Date( ( new Date() ).valueOf() - 1000 * 60 * 60 ).getTime(); const TripSchema = new Schema( { userId: { type: String, required: true }, lastUpdated: { type: Date, default: getDefaultDate, required: true }, tripLocations: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Location' } ], } ); TripSchema.plugin( findOrCreate ); export default mongoose.model( 'Trip', TripSchema );
Make default date older to allow pretty much any updates
Make default date older to allow pretty much any updates
JavaScript
mit
sirbrillig/voyageur-js-server
--- +++ @@ -4,10 +4,11 @@ import findOrCreate from 'mongoose-findorcreate'; const Schema = mongoose.Schema; +const getDefaultDate = () => new Date( ( new Date() ).valueOf() - 1000 * 60 * 60 ).getTime(); const TripSchema = new Schema( { userId: { type: String, required: true }, - lastUpdated: { type: Date, default: Date.now, required: true }, + lastUpdated: { type: Date, default: getDefaultDate, required: true }, tripLocations: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Location' } ], } );
a40324a5b03ab497822a4e2287b9d6ef37d5848b
src/World.js
src/World.js
/** World functions */ import _ from 'underscore'; export const create = () => { return { tripods: [], food: [] }; }; export const addTripod = (world, tripod) => { world.tripods.push(tripod); }; export const addFood = (world, food) => { world.food.push(food); }; export const eatFood = (world, food) => { const idx = _.indexOf(world.food, food); if (idx > -1) { world.food.splice(idx, 1); } };
/** World functions */ import _ from 'underscore'; export const create = () => { return { tripods: [], food: [] }; }; export const addTripod = (world, tripod) => { world.tripods.push(tripod); }; export const addFood = (world, food) => { world.food.push(food); }; export const eatFood = (world, food) => { const idx = _.indexOf(world.food, food); if (idx > -1) { world.food.splice(idx, 1); } }; export const closestFood = (world, position) => { if (_.isEmpty(world.food)) return null; return _.min(world.food, (f) => position.distance(f)); };
Add getClosestFood function to world
Add getClosestFood function to world
JavaScript
bsd-2-clause
rumblesan/tripods,rumblesan/tripods
--- +++ @@ -25,3 +25,8 @@ world.food.splice(idx, 1); } }; + +export const closestFood = (world, position) => { + if (_.isEmpty(world.food)) return null; + return _.min(world.food, (f) => position.distance(f)); +};
638a38a53544f1ed1854b2215125ef224ef085b2
app/src/js/bolt.js
app/src/js/bolt.js
/** * Instance of the Bolt module. * * @namespace Bolt * * @mixes Bolt.actions * @mixes Bolt.activity * @mixes Bolt.app * @mixes Bolt.ckeditor * @mixes Bolt.conf * @mixes Bolt.data * @mixes Bolt.datetime * @mixes Bolt.files * @mixes Bolt.stack * @mixes Bolt.secmenu * @mixes Bolt.video * * @mixes Bolt.fields * @mixes Bolt.fields.categories * @mixes Bolt.fields.geolocation * @mixes Bolt.fields.relationship * @mixes Bolt.fields.select * @mixes Bolt.fields.slug * @mixes Bolt.fields.tags */ var Bolt = {};
/** * Instance of the Bolt module. * * @namespace Bolt * * @mixes Bolt.actions * @mixes Bolt.activity * @mixes Bolt.app * @mixes Bolt.ckeditor * @mixes Bolt.conf * @mixes Bolt.data * @mixes Bolt.datetime * @mixes Bolt.files * @mixes Bolt.stack * @mixes Bolt.secmenu * @mixes Bolt.video * * @mixes Bolt.fields * @mixes Bolt.fields.categories * @mixes Bolt.fields.geolocation * @mixes Bolt.fields.relationship * @mixes Bolt.fields.select * @mixes Bolt.fields.slug * @mixes Bolt.fields.tags * @mixes Bolt.fields.templateselect */ var Bolt = {};
Add doc block for templateselect mixin
Add doc block for templateselect mixin
JavaScript
mit
Eiskis/bolt-base,tekjava/bolt,HonzaMikula/masivnipostele,pygillier/bolt,Intendit/bolt,pygillier/bolt,richardhinkamp/bolt,hugin2005/bolt,cdowdy/bolt,HonzaMikula/masivnipostele,nantunes/bolt,romulo1984/bolt,GawainLynch/bolt,codesman/bolt,GawainLynch/bolt,CarsonF/bolt,richardhinkamp/bolt,bolt/bolt,Intendit/bolt,nikgo/bolt,pygillier/bolt,Raistlfiren/bolt,one988/cm,Raistlfiren/bolt,electrolinux/bolt,nikgo/bolt,codesman/bolt,cdowdy/bolt,bolt/bolt,one988/cm,CarsonF/bolt,Calinou/bolt,hugin2005/bolt,romulo1984/bolt,marcin-piela/bolt,hannesl/bolt,CarsonF/bolt,codesman/bolt,joshuan/bolt,xeddmc/bolt,lenvanessen/bolt,winiceo/bolt,rarila/bolt,nikgo/bolt,Raistlfiren/bolt,hugin2005/bolt,xeddmc/bolt,winiceo/bolt,joshuan/bolt,marcin-piela/bolt,hugin2005/bolt,nantunes/bolt,romulo1984/bolt,Calinou/bolt,one988/cm,nikgo/bolt,electrolinux/bolt,rossriley/bolt,Calinou/bolt,richardhinkamp/bolt,CarsonF/bolt,GawainLynch/bolt,tekjava/bolt,hannesl/bolt,hannesl/bolt,GawainLynch/bolt,xeddmc/bolt,hannesl/bolt,lenvanessen/bolt,Eiskis/bolt-base,Intendit/bolt,codesman/bolt,winiceo/bolt,tekjava/bolt,Raistlfiren/bolt,xeddmc/bolt,electrolinux/bolt,joshuan/bolt,one988/cm,kendoctor/bolt,winiceo/bolt,rossriley/bolt,electrolinux/bolt,Eiskis/bolt-base,HonzaMikula/masivnipostele,bolt/bolt,lenvanessen/bolt,kendoctor/bolt,richardhinkamp/bolt,rarila/bolt,rarila/bolt,HonzaMikula/masivnipostele,Intendit/bolt,joshuan/bolt,cdowdy/bolt,rossriley/bolt,marcin-piela/bolt,pygillier/bolt,rarila/bolt,cdowdy/bolt,romulo1984/bolt,marcin-piela/bolt,Eiskis/bolt-base,bolt/bolt,tekjava/bolt,lenvanessen/bolt,rossriley/bolt,kendoctor/bolt,kendoctor/bolt,Calinou/bolt,nantunes/bolt,nantunes/bolt
--- +++ @@ -22,5 +22,6 @@ * @mixes Bolt.fields.select * @mixes Bolt.fields.slug * @mixes Bolt.fields.tags + * @mixes Bolt.fields.templateselect */ var Bolt = {};
ba2bfd1d5711ad48da8f16faa59948e91a88318e
modules/mds/src/main/resources/webapp/js/app.js
modules/mds/src/main/resources/webapp/js/app.js
(function () { 'use strict'; var mds = angular.module('mds', [ 'motech-dashboard', 'entityService','instanceService', 'mdsSettingsService', 'ngCookies', 'ui.directives', 'ngRoute', 'ui.directives' ]); $.get('../mds/available/mdsTabs').done(function(data) { mds.constant('AVAILABLE_TABS', data); }); mds.run(function ($rootScope, AVAILABLE_TABS) { $rootScope.AVAILABLE_TABS = AVAILABLE_TABS; }); mds.config(function ($routeProvider, AVAILABLE_TABS) { angular.forEach(AVAILABLE_TABS, function (tab) { $routeProvider.when( '/{0}'.format(tab), { templateUrl: '../mds/resources/partials/{0}.html'.format(tab), controller: '{0}Ctrl'.format(tab.capitalize()) } ); }); $routeProvider.otherwise({ redirectTo: '/{0}'.format(AVAILABLE_TABS[0]) }); }); }());
(function () { 'use strict'; var mds = angular.module('mds', [ 'motech-dashboard', 'entityService','instanceService', 'mdsSettingsService', 'ngCookies', 'ui.directives', 'ngRoute', 'ui.directives' ]); $.ajax({ url: '../mds/available/mdsTabs', success: function(data) { mds.constant('AVAILABLE_TABS', data); }, async: false }); mds.run(function ($rootScope, AVAILABLE_TABS) { $rootScope.AVAILABLE_TABS = AVAILABLE_TABS; }); mds.config(function ($routeProvider, AVAILABLE_TABS) { angular.forEach(AVAILABLE_TABS, function (tab) { $routeProvider.when( '/{0}'.format(tab), { templateUrl: '../mds/resources/partials/{0}.html'.format(tab), controller: '{0}Ctrl'.format(tab.capitalize()) } ); }); $routeProvider.otherwise({ redirectTo: '/{0}'.format(AVAILABLE_TABS[0]) }); }); }());
Fix ajax error while checking available tabs
MDS: Fix ajax error while checking available tabs Change-Id: I4f8a4d538e59dcdb03659c7f5405c40abcdafed8
JavaScript
bsd-3-clause
koshalt/motech,kmadej/motech,shubhambeehyv/motech,smalecki/motech,justin-hayes/motech,ngraczewski/motech,kmadej/motech,adamkalmus/motech,koshalt/motech,frankhuster/motech,smalecki/motech,wstrzelczyk/motech,justin-hayes/motech,justin-hayes/motech,ngraczewski/motech,frankhuster/motech,tectronics/motech,adamkalmus/motech,tectronics/motech,LukSkarDev/motech,tstalka/motech,pgesek/motech,shubhambeehyv/motech,adamkalmus/motech,LukSkarDev/motech,wstrzelczyk/motech,pgesek/motech,kmadej/motech,jefeweisen/motech,ngraczewski/motech,shubhambeehyv/motech,sebbrudzinski/motech,tectronics/motech,pgesek/motech,frankhuster/motech,tectronics/motech,wstrzelczyk/motech,justin-hayes/motech,koshalt/motech,smalecki/motech,smalecki/motech,jefeweisen/motech,LukSkarDev/motech,ngraczewski/motech,LukSkarDev/motech,koshalt/motech,adamkalmus/motech,tstalka/motech,jefeweisen/motech,wstrzelczyk/motech,pgesek/motech,jefeweisen/motech,sebbrudzinski/motech,sebbrudzinski/motech,tstalka/motech,shubhambeehyv/motech,tstalka/motech,frankhuster/motech,sebbrudzinski/motech,kmadej/motech
--- +++ @@ -6,8 +6,12 @@ 'ngRoute', 'ui.directives' ]); - $.get('../mds/available/mdsTabs').done(function(data) { - mds.constant('AVAILABLE_TABS', data); + $.ajax({ + url: '../mds/available/mdsTabs', + success: function(data) { + mds.constant('AVAILABLE_TABS', data); + }, + async: false }); mds.run(function ($rootScope, AVAILABLE_TABS) {
b439d4a79f607eca47b7444254270b66c4676603
server/controllers/Play.js
server/controllers/Play.js
var GameController = require("./GameController"); exports.fire = function (req, res) { var player = req.body.username; var x = req.body.x; var y = req.body.y; GameController.findGame(player).then(function(game) { if (game != null) { // If game is over, the other player won. // The game's finished field is then set to true, so that findGame will not return it anymore.. if (game.gameOver) { res.json({'message': "You lost"}); game.finished = true; game.save(); return; } // Fire at the enemy board. If game over after hit, you won. var shipWasHit = game.fire(player, x, y); var msg = game.gameOver ? "You won" : "Ongoing game"; res.json({'message': msg, 'shipWasHit': shipWasHit}); } else { res.json({'message': 'No game was found'}); } }); };
var GameController = require("./GameController"); exports.fire = function (req, res) { var player = req.body.username; var x = req.body.x; var y = req.body.y; GameController.findGame(player).then(function(game) { if (game != null) { // If game is over, the other player won. // The game's finished field is then set to true, so that findGame will not return it anymore.. if (game.gameOver()) { res.json({'message': "You lost"}); game.finished = true; game.save(); return; } // Fire at the enemy board. If game over after hit, you won. var shipWasHit = game.fire(player, x, y); var msg = game.gameOver ? "You won" : "Ongoing game"; res.json({'message': msg, 'shipWasHit': shipWasHit}); } else { res.json({'message': 'No game was found'}); } }); };
Add paranthesis to function call
Add paranthesis to function call
JavaScript
mit
andereld/progark,andereld/progark
--- +++ @@ -10,7 +10,7 @@ if (game != null) { // If game is over, the other player won. // The game's finished field is then set to true, so that findGame will not return it anymore.. - if (game.gameOver) { + if (game.gameOver()) { res.json({'message': "You lost"}); game.finished = true; game.save();
d85193139375a5e907bb90bf9dc1fc01b5e4e732
src/fleet.js
src/fleet.js
/** * @package admiral * @author Andrew Munsell <andrew@wizardapps.net> * @copyright 2015 WizardApps */ var Fleetctl = require('fleetctl'), Promise = require('bluebird'); exports = module.exports = function(nconf) { var options = {}; if(nconf.get('t')) { options.tunnel = nconf.get('t'); options['ssh-username'] = nconf.get('tunnel-username'); } var fleetctl = new Fleetctl(options); return Promise.promisifyAll(fleetctl); }; exports['@singleton'] = true; exports['@require'] = ['nconf'];
/** * @package admiral * @author Andrew Munsell <andrew@wizardapps.net> * @copyright 2015 WizardApps */ var Fleetctl = require('fleetctl'), Promise = require('bluebird'); exports = module.exports = function(nconf) { var options = {}; if(nconf.get('t')) { options.tunnel = nconf.get('t'); options['ssh-username'] = nconf.get('tunnel-username'); } else { options.endpoint = 'http://' + nconf.get('h') + ':' + nconf.get('p'); } var fleetctl = new Fleetctl(options); return Promise.promisifyAll(fleetctl); }; exports['@singleton'] = true; exports['@require'] = ['nconf'];
Set the endpoint if the tunnel is not specified
Set the endpoint if the tunnel is not specified
JavaScript
mit
andrewmunsell/admiral
--- +++ @@ -13,6 +13,8 @@ if(nconf.get('t')) { options.tunnel = nconf.get('t'); options['ssh-username'] = nconf.get('tunnel-username'); + } else { + options.endpoint = 'http://' + nconf.get('h') + ':' + nconf.get('p'); } var fleetctl = new Fleetctl(options);
8091723fda06b99d76fd59946602835c7e8d8689
lib/index.js
lib/index.js
/** * Module dependencies */ var autoprefixer = require('autoprefixer'); var postcss = require('postcss'); var atImport = require('postcss-import'); var calc = require('postcss-calc'); var customMedia = require('postcss-custom-media'); var customProperties = require('postcss-custom-properties'); var reporter = require('postcss-reporter'); var bemLinter = require('postcss-bem-linter'); /** * Module export */ module.exports = preprocessor; /** * Process CSS * * @param {String} css * @return {String} */ function preprocessor(css, options) { if (typeof css !== 'string') { throw new Error('suitcss-preprocessor: did not receive a String'); } options = options || {}; css = postcss([ atImport({ root: options.root, transform: function(css, filename) { return postcss([bemLinter, reporter]).process(css, {from: filename}).css; } }), calc, customProperties, customMedia, autoprefixer({browsers: options.browsers}), reporter({clearMessages: true}) ]).process(css).css; return css; }
/** * Module dependencies */ var autoprefixer = require('autoprefixer'); var postcss = require('postcss'); var atImport = require('postcss-import'); var calc = require('postcss-calc'); var customMedia = require('postcss-custom-media'); var customProperties = require('postcss-custom-properties'); var reporter = require('postcss-reporter'); var bemLinter = require('postcss-bem-linter'); /** * Module export */ module.exports = preprocessor; /** * Process CSS * * @param {String} css * @return {String} */ function preprocessor(css, options) { if (typeof css !== 'string') { throw new Error('suitcss-preprocessor: did not receive a String'); } options = options || {}; css = postcss([ atImport({ root: options.root, transform: function(css, filename) { return postcss([bemLinter, reporter]).process(css, {from: filename}).css; } }), customProperties, calc, customMedia, autoprefixer({browsers: options.browsers}), reporter({clearMessages: true}) ]).process(css).css; return css; }
Use correct order of postcss plugins
Use correct order of postcss plugins
JavaScript
mit
travco/preprocessor,suitcss/preprocessor
--- +++ @@ -38,8 +38,8 @@ return postcss([bemLinter, reporter]).process(css, {from: filename}).css; } }), + customProperties, calc, - customProperties, customMedia, autoprefixer({browsers: options.browsers}), reporter({clearMessages: true})
a5f7c7977f91fd490a8f48bd259d5007591a97da
lib/index.js
lib/index.js
/** * Library version. */ exports.version = '0.0.1'; /** * Constructors. */ exports.Batch = require('./batch'); exports.Parser = require('./parser'); exports.Socket = require('./sockets/sock'); exports.Queue = require('./sockets/queue'); exports.PubSocket = require('./sockets/pub'); exports.SubSocket = require('./sockets/sub'); exports.PushSocket = require('./sockets/push'); exports.PullSocket = require('./sockets/pull'); exports.EmitterSocket = require('./sockets/emitter'); /** * Socket types. */ exports.types = { stream: exports.Socket, queue: exports.Queue, pub: exports.PubSocket, sub: exports.SubSocket, push: exports.PushSocket, pull: exports.PullSocket, emitter: exports.EmitterSocket }; /** * Codecs. */ exports.codec = require('./codecs'); /** * Return a new socket of the given `type`. * * @param {String} type * @param {Object} options * @return {Socket} * @api public */ exports.socket = function(type, options){ var fn = exports.types[type]; if (!fn) throw new Error('invalid socket type "' + type + '"'); return new fn(options); };
/** * Library version. */ exports.version = '0.0.1'; /** * Constructors. */ exports.Batch = require('./batch'); exports.Decoder = require('./decoder'); exports.Encoder = require('./encoder'); exports.Socket = require('./sockets/sock'); exports.Queue = require('./sockets/queue'); exports.PubSocket = require('./sockets/pub'); exports.SubSocket = require('./sockets/sub'); exports.PushSocket = require('./sockets/push'); exports.PullSocket = require('./sockets/pull'); exports.EmitterSocket = require('./sockets/emitter'); /** * Socket types. */ exports.types = { stream: exports.Socket, queue: exports.Queue, pub: exports.PubSocket, sub: exports.SubSocket, push: exports.PushSocket, pull: exports.PullSocket, emitter: exports.EmitterSocket }; /** * Codecs. */ exports.codec = require('./codecs'); /** * Return a new socket of the given `type`. * * @param {String} type * @param {Object} options * @return {Socket} * @api public */ exports.socket = function(type, options){ var fn = exports.types[type]; if (!fn) throw new Error('invalid socket type "' + type + '"'); return new fn(options); };
Remove Parser, export Encoder and Decoder
Remove Parser, export Encoder and Decoder
JavaScript
mit
Unitech/pm2-axon,Unitech/axon,DavidCai1993/axon,Unitech/axon,DavidCai1993/axon,tj/axon,tj/axon,Unitech/pm2-axon
--- +++ @@ -10,7 +10,8 @@ */ exports.Batch = require('./batch'); -exports.Parser = require('./parser'); +exports.Decoder = require('./decoder'); +exports.Encoder = require('./encoder'); exports.Socket = require('./sockets/sock'); exports.Queue = require('./sockets/queue'); exports.PubSocket = require('./sockets/pub');
936c009c1887b4f45690f9265c48aabc19c0cb4c
lib/index.js
lib/index.js
var StubGenerator = require('./stub-generator'); var CachingBrowserify = require('./caching-browserify'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-browserify', included: function(app){ this.app = app; this.options = { root: this.app.project.root, browserifyOptions: app.project.config(app.env).browserify || {}, enableSourcemap: app.options.sourcemaps.indexOf('js') > -1, fullPaths: app.env !== 'production' }; app.import('browserify/browserify.js'); if (app.importWhitelistFilters) { app.importWhitelistFilters.push(function(moduleName){ return moduleName.slice(0,4) === 'npm:'; }); } }, postprocessTree: function(type, tree){ if (type !== 'js'){ return tree; } return mergeTrees([ tree, new CachingBrowserify(new StubGenerator(tree), this.options) ]); } };
var StubGenerator = require('./stub-generator'); var CachingBrowserify = require('./caching-browserify'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-browserify', included: function(app){ this.app = app; this.options = { root: this.app.project.root, browserifyOptions: app.project.config(app.env).browserify || {}, enableSourcemap: app.options.sourcemaps ? app.options.sourcemaps.indexOf('js') > -1 : false, fullPaths: app.env !== 'production' }; app.import('browserify/browserify.js'); if (app.importWhitelistFilters) { app.importWhitelistFilters.push(function(moduleName){ return moduleName.slice(0,4) === 'npm:'; }); } }, postprocessTree: function(type, tree){ if (type !== 'js'){ return tree; } return mergeTrees([ tree, new CachingBrowserify(new StubGenerator(tree), this.options) ]); } };
Fix undefined error if sourcemaps option not defined
Fix undefined error if sourcemaps option not defined
JavaScript
mit
chadhietala/ember-browserify,ef4/ember-browserify,stefanpenner/ember-browserify,asakusuma/ember-browserify
--- +++ @@ -10,7 +10,7 @@ this.options = { root: this.app.project.root, browserifyOptions: app.project.config(app.env).browserify || {}, - enableSourcemap: app.options.sourcemaps.indexOf('js') > -1, + enableSourcemap: app.options.sourcemaps ? app.options.sourcemaps.indexOf('js') > -1 : false, fullPaths: app.env !== 'production' };
9bd6a642236fbb1d3a638d29f3f85b5dc6997f46
src/index.js
src/index.js
import hasCallback from 'has-callback'; import promisify from 'es6-promisify'; import yargsBuilder from 'yargs-builder'; import renamerArgsBuilder from './renamerArgsBuilder'; import fsRenamer from './fsRenamer'; import getExistingFilenames from './getExistingFilenames'; import {ERROR_ON_MISSING_FILE} from './flags'; const parseArgs = (argv) => { const args = yargsBuilder({ options: { [ERROR_ON_MISSING_FILE]: { default: false, describe: 'Fail if source file missing', type: 'boolean' } } }, argv).argv; return [ args._, args ]; } const batchFileRenamer = async ({ rule, argv }) => { rule = hasCallback(rule) ? promisify(rule) : rule; const [filenames, options] = parseArgs(argv); const oldnames = await getExistingFilenames(filenames, options); let newnames = []; for (let oldname of oldnames) { let newname = await rule(oldname, options); newnames.push(newname); } let args = renamerArgsBuilder(oldnames, newnames); await fsRenamer(args) } export default batchFileRenamer;
import hasCallback from 'has-callback'; import promisify from 'es6-promisify'; import yargsBuilder from 'yargs-builder'; import renamerArgsBuilder from './renamerArgsBuilder'; import fsRenamer from './fsRenamer'; import getExistingFilenames from './getExistingFilenames'; import {ERROR_ON_MISSING_FILE} from './flags'; const parseArgs = (argv) => { const args = yargsBuilder({ options: { [ERROR_ON_MISSING_FILE]: { default: false, describe: 'Fail if source file missing', type: 'boolean' } } }, argv).argv; return [ args._, args ]; } const batchFileRenamer = async ({ rule, argv }) => { rule = hasCallback(rule) ? promisify(rule) : rule; const [filenames, options] = parseArgs(argv); const oldnames = await getExistingFilenames(filenames, options); let newnames = []; for (let oldname of oldnames) { let newname = await rule(oldname, options); newnames.push(newname); } let pairs = renamerArgsBuilder(oldnames, newnames); await fsRenamer(pairs); } export default batchFileRenamer;
Rename args variable to pairs for clarity
Rename args variable to pairs for clarity
JavaScript
mit
rohanorton/batch-file-renamer
--- +++ @@ -29,8 +29,8 @@ newnames.push(newname); } - let args = renamerArgsBuilder(oldnames, newnames); - await fsRenamer(args) + let pairs = renamerArgsBuilder(oldnames, newnames); + await fsRenamer(pairs); } export default batchFileRenamer;
d5e7c6daa667e5fa5d0258a84791902b0ec08ca8
app/assets/javascripts/map/views/SearchboxView.js
app/assets/javascripts/map/views/SearchboxView.js
/** * The Searchbox module. * * @return searchbox class (extends Backbone.View). */ define([ 'underscore', 'backbone', 'handlebars', 'map/views/Widget', 'map/presenters/SearchboxPresenter', 'text!map/templates/searchbox.handlebars' ], function(_, Backbone, Handlebars, Widget, Presenter, tpl) { 'use strict'; var Searchbox = Widget.extend({ className: 'widget widget-searchbox', template: Handlebars.compile(tpl), initialize: function() { _.bindAll(this, 'setAutocomplete', 'onPlaceSelected'); this.presenter = new Presenter(this); Searchbox.__super__.initialize.apply(this); this.setAutocomplete(); }, setAutocomplete: function() { this.autocomplete = new google.maps.places.Autocomplete( this.$el.find('input')[0], {types: ['geocode']}); google.maps.event.addListener( this.autocomplete, 'place_changed', this.onPlaceSelected); }, onPlaceSelected: function() { var place = this.autocomplete.getPlace(); // TODO: When there isn't viewport, and there is location... if (place && place.geometry && place.geometry.viewport) { this.presenter.fitBounds(place.geometry.viewport); } ga('send', 'event', 'Map', 'Searchbox', 'Find location'); } }); return Searchbox; });
/** * The Searchbox module. * * @return searchbox class (extends Backbone.View). */ define([ 'underscore', 'backbone', 'handlebars', 'map/views/Widget', 'map/presenters/SearchboxPresenter', 'text!map/templates/searchbox.handlebars' ], function(_, Backbone, Handlebars, Widget, Presenter, tpl) { 'use strict'; var Searchbox = Widget.extend({ className: 'widget widget-searchbox', template: Handlebars.compile(tpl), initialize: function() { _.bindAll(this, 'setAutocomplete', 'onPlaceSelected'); this.presenter = new Presenter(this); Searchbox.__super__.initialize.apply(this); this.setAutocomplete(); }, setAutocomplete: function() { this.autocomplete = new google.maps.places.SearchBox(this.$el.find('input')[0]); google.maps.event.addListener(this.autocomplete, 'places_changed', this.onPlaceSelected); }, onPlaceSelected: function() { var place = this.autocomplete.getPlaces(); if (place.length == 1) { place = place[0]; if (place && place.geometry && place.geometry.viewport) { this.presenter.fitBounds(place.geometry.viewport); } // TODO: When there isn't viewport, and there is location... if (place && place.geometry && place.geometry.location && !place.geometry.viewport) { console.log(place.geometry.location); this.presenter.setCenter(place.geometry.location.k,place.geometry.location.B); } }; ga('send', 'event', 'Map', 'Searchbox', 'Find location'); } }); return Searchbox; });
Change autocomplete plugin to search box plugin, it allows us to use the enter key
Change autocomplete plugin to search box plugin, it allows us to use the enter key
JavaScript
mit
KarlaRenschler/gfw,Vizzuality/gfw,codeminery/gfw,KarlaRenschler/gfw,codeminery/gfw,KarlaRenschler/gfw,Vizzuality/gfw,codeminery/gfw,cciciarelli8/gfw,apercas/gfw,KarlaRenschler/gfw,apercas/gfw,apercas/gfw,apercas/gfw,codeminery/gfw,cciciarelli8/gfw
--- +++ @@ -28,19 +28,23 @@ }, setAutocomplete: function() { - this.autocomplete = new google.maps.places.Autocomplete( - this.$el.find('input')[0], {types: ['geocode']}); - - google.maps.event.addListener( - this.autocomplete, 'place_changed', this.onPlaceSelected); + this.autocomplete = new google.maps.places.SearchBox(this.$el.find('input')[0]); + google.maps.event.addListener(this.autocomplete, 'places_changed', this.onPlaceSelected); }, onPlaceSelected: function() { - var place = this.autocomplete.getPlace(); - // TODO: When there isn't viewport, and there is location... - if (place && place.geometry && place.geometry.viewport) { - this.presenter.fitBounds(place.geometry.viewport); - } + var place = this.autocomplete.getPlaces(); + if (place.length == 1) { + place = place[0]; + if (place && place.geometry && place.geometry.viewport) { + this.presenter.fitBounds(place.geometry.viewport); + } + // TODO: When there isn't viewport, and there is location... + if (place && place.geometry && place.geometry.location && !place.geometry.viewport) { + console.log(place.geometry.location); + this.presenter.setCenter(place.geometry.location.k,place.geometry.location.B); + } + }; ga('send', 'event', 'Map', 'Searchbox', 'Find location'); }
9bbd4b0e9dc448e9461df0ba11a4198b03693f66
src/index.js
src/index.js
module.exports = require('./ServerlessOffline.js'); // Serverless exits with code 1 when a promise rejection is unhandled. Not AWS. // Users can still use their own unhandledRejection event though. process.removeAllListeners('unhandledRejection');
'use strict'; module.exports = require('./ServerlessOffline.js'); // Serverless exits with code 1 when a promise rejection is unhandled. Not AWS. // Users can still use their own unhandledRejection event though. process.removeAllListeners('unhandledRejection');
Add missing strict mode directive
Add missing strict mode directive
JavaScript
mit
dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline
--- +++ @@ -1,3 +1,5 @@ +'use strict'; + module.exports = require('./ServerlessOffline.js'); // Serverless exits with code 1 when a promise rejection is unhandled. Not AWS.
8be34454952c75759258c463206855a39bfc1dde
lib/index.js
lib/index.js
'use strict'; const url = require('url'); module.exports = function(env, callback) { class CNAME extends env.plugins.Page { getFilename() { return 'CNAME'; } getView() { return (env, locals, contents, templates, callback) => { if (locals.url) { callback(null, new Buffer(url.parse(locals.url).host)); } else { callback(); } }; } } env.registerGenerator('cname', (contents, callback) => { callback(null, {'CNAME': new CNAME()}); }); callback(); };
'use strict'; const url = require('url'); module.exports = function(env, callback) { class CNAME extends env.plugins.Page { getFilename() { return 'CNAME'; } getView() { return (env, locals, contents, templates, callback) => { if (locals.url) { callback(null, new Buffer(url.parse(locals.url).host)); } else { callback(new Error('locals.url must be defined.')); } }; } } env.registerGenerator('cname', (contents, callback) => { callback(null, {'CNAME': new CNAME()}); }); callback(); };
Raise error when plugin is not configured
Raise error when plugin is not configured
JavaScript
mit
xavierdutreilh/wintersmith-cname
--- +++ @@ -13,7 +13,7 @@ if (locals.url) { callback(null, new Buffer(url.parse(locals.url).host)); } else { - callback(); + callback(new Error('locals.url must be defined.')); } }; }
20b21a65d7c3beb0e91bc3edec78139205767fa8
src/index.js
src/index.js
export Icon from './components/base/icons/Icon'; export Alert from './components/base/containers/Alert'; export Drawer from './components/base/containers/Drawer'; export Fieldset from './components/base/containers/Fieldset'; export FormGroup from './components/base/containers/FormGroup'; export Tooltip from './components/base/containers/Tooltip'; export PopoverLink from './components/base/containers/PopoverLink'; export Textbox from './components/controls/textbox/Textbox'; export Button from './components/controls/buttons/Button'; export RadioGroup from './components/controls/radio-buttons/RadioGroup'; export Dropdown from './components/controls/dropdown/Dropdown'; export Datepicker from './components/controls/datepicker/DatePicker';
export Icon from './components/base/icons/Icon'; export Alert from './components/base/containers/Alert'; export Drawer from './components/base/containers/Drawer'; export Fieldset from './components/base/containers/Fieldset'; export FormGroup from './components/base/containers/FormGroup'; export Tooltip from './components/base/containers/Tooltip'; export PopoverLink from './components/base/containers/PopoverLink'; export Textbox from './components/controls/textbox/Textbox'; export Button from './components/controls/buttons/Button'; export RadioGroup from './components/controls/radio-buttons/RadioGroup'; export Dropdown from './components/controls/dropdown/Dropdown'; export DatePicker from './components/controls/datepicker/DatePicker';
Change export from Datepicker to DatePicker
Change export from Datepicker to DatePicker
JavaScript
mit
jrios/es-components,jrios/es-components,TWExchangeSolutions/es-components,jrios/es-components,TWExchangeSolutions/es-components
--- +++ @@ -11,4 +11,4 @@ export Button from './components/controls/buttons/Button'; export RadioGroup from './components/controls/radio-buttons/RadioGroup'; export Dropdown from './components/controls/dropdown/Dropdown'; -export Datepicker from './components/controls/datepicker/DatePicker'; +export DatePicker from './components/controls/datepicker/DatePicker';
43d99e445612c68b56861c6c456096468e19ccd1
src/index.js
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { AutoSizer } from 'react-virtualized'; import Kanban from './Kanban'; import Perf from 'react-addons-perf'; import 'react-virtualized/styles.css'; import './index.css'; window.Perf = Perf; ReactDOM.render( <div className='KanbanWrapper'> <AutoSizer> {({ width, height }) => <Kanban width={width} height={height} />} </AutoSizer> </div>, document.getElementById('root') );
import React from 'react'; import ReactDOM from 'react-dom'; import { AutoSizer } from 'react-virtualized'; import Perf from 'react-addons-perf'; import Kanban from './Kanban'; import { generateLists } from './utils/generate_lists'; import 'react-virtualized/styles.css'; import './index.css'; window.Perf = Perf; const lists = generateLists(5, 20); ReactDOM.render( <div className='KanbanWrapper'> <AutoSizer> {({ width, height }) => { return ( <Kanban lists={lists} width={width} height={height} /> ); }} </AutoSizer> </div>, document.getElementById('root') );
Move lists generation outside Kanban
Move lists generation outside Kanban
JavaScript
mit
edulan/react-virtual-kanban,edulan/react-virtual-kanban
--- +++ @@ -1,20 +1,31 @@ import React from 'react'; import ReactDOM from 'react-dom'; import { AutoSizer } from 'react-virtualized'; +import Perf from 'react-addons-perf'; import Kanban from './Kanban'; -import Perf from 'react-addons-perf'; +import { generateLists } from './utils/generate_lists'; import 'react-virtualized/styles.css'; import './index.css'; window.Perf = Perf; +const lists = generateLists(5, 20); + ReactDOM.render( <div className='KanbanWrapper'> <AutoSizer> - {({ width, height }) => <Kanban width={width} height={height} />} + {({ width, height }) => { + return ( + <Kanban + lists={lists} + width={width} + height={height} + /> + ); + }} </AutoSizer> </div>, document.getElementById('root')
7e5b2f723ec07571d987f176083694396b6f4098
src/index.js
src/index.js
import { GRAPHQL_URL } from 'constants'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import withScroll from 'scroll-behavior'; import ApolloClient, { createNetworkInterface } from 'apollo-client'; // import { Provider } from 'react-redux'; import { ApolloProvider } from 'react-apollo'; import createAppStore from './store'; import getRoutes from './routes'; import { checkLogin } from './actions'; const networkInterface = createNetworkInterface(GRAPHQL_URL); const client = new ApolloClient({ networkInterface, }); const scrollBrowserHistory = withScroll(browserHistory); const store = createAppStore(scrollBrowserHistory, client); const history = syncHistoryWithStore(scrollBrowserHistory, store); checkLogin(store.dispatch); const rootEl = document.getElementById('app'); ReactDOM.render( <ApolloProvider store={store} client={client}> <Router history={history}>{getRoutes(store)}</Router> </ApolloProvider>, rootEl );
import { GRAPHQL_URL } from 'constants'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import withScroll from 'scroll-behavior'; import ApolloClient, { createNetworkInterface } from 'apollo-client'; // import { Provider } from 'react-redux'; import { ApolloProvider } from 'react-apollo'; import createAppStore from './store'; import getRoutes from './routes'; import { checkLogin } from './actions'; const networkInterface = createNetworkInterface(GRAPHQL_URL); networkInterface.use([{ /* eslint-disable no-param-reassign */ applyMiddleware(req, next) { if (!req.options.headers) { req.options.headers = {}; // Create the header object if needed. } // get the authentication token from local storage if it exists const idToken = localStorage.getItem('idToken') || null; if (idToken) { req.options.headers.authorization = `Bearer '${idToken}`; } next(); }, /* eslint-enable no-param-reassign */ }]); const client = new ApolloClient({ networkInterface, }); const scrollBrowserHistory = withScroll(browserHistory); const store = createAppStore(scrollBrowserHistory, client); const history = syncHistoryWithStore(scrollBrowserHistory, store); checkLogin(store.dispatch); const rootEl = document.getElementById('app'); ReactDOM.render( <ApolloProvider store={store} client={client}> <Router history={history}>{getRoutes(store)}</Router> </ApolloProvider>, rootEl );
Add idToken to graphql requests
Add idToken to graphql requests
JavaScript
mit
garden-aid/web-client,garden-aid/web-client,garden-aid/web-client
--- +++ @@ -17,6 +17,22 @@ const networkInterface = createNetworkInterface(GRAPHQL_URL); +networkInterface.use([{ + /* eslint-disable no-param-reassign */ + applyMiddleware(req, next) { + if (!req.options.headers) { + req.options.headers = {}; // Create the header object if needed. + } + // get the authentication token from local storage if it exists + const idToken = localStorage.getItem('idToken') || null; + if (idToken) { + req.options.headers.authorization = `Bearer '${idToken}`; + } + next(); + }, + /* eslint-enable no-param-reassign */ +}]); + const client = new ApolloClient({ networkInterface, });
974cb4efbbabcad2cf93eb4938c5414ccb92eb41
src/index.js
src/index.js
import React, { Component, PropTypes } from 'react'; import SVGInjector from 'svg-injector'; export default class ReactSVG extends Component { static defaultProps = { evalScripts: 'never', callback: () => {} } static propTypes = { path: PropTypes.string.isRequired, className: PropTypes.string, evalScripts: PropTypes.oneOf(['always', 'once', 'never']), fallbackPath: PropTypes.string, callback: PropTypes.func } render() { const { className, path, fallbackPath } = this.props; return ( <img className={className} data-src={path} data-fallback={fallbackPath} ref={(img) => this._img = img} /> ); } componentDidMount() { this.updateSVG(); } componentDidUpdate() { this.updateSVG(); } updateSVG() { const { evalScripts, callback: each } = this.props; SVGInjector(this._img, { evalScripts, each }); } }
import React, { PureComponent, PropTypes } from 'react' import SVGInjector from 'svg-injector' export default class ReactSVG extends PureComponent { static defaultProps = { callback: () => {}, className: '', evalScripts: 'once' } static propTypes = { callback: PropTypes.func, className: PropTypes.string, evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]), srcPath: PropTypes.string.isRequired } injectSVG() { const { evalScripts, callback: each } = this.props if (this._img) { SVGInjector(this._img, { evalScripts, each }) } } componentDidMount() { this.injectSVG() } componentDidUpdate() { this.injectSVG() } render() { const { className, srcPath } = this.props return ( <img ref={img => this._img = img} className={className} data-src={srcPath} /> ) } }
Make pure, ditch fallback png option
Make pure, ditch fallback png option
JavaScript
mit
atomic-app/react-svg
--- +++ @@ -1,59 +1,56 @@ -import React, { Component, PropTypes } from 'react'; -import SVGInjector from 'svg-injector'; +import React, { PureComponent, PropTypes } from 'react' +import SVGInjector from 'svg-injector' -export default class ReactSVG extends Component { +export default class ReactSVG extends PureComponent { static defaultProps = { - evalScripts: 'never', - callback: () => {} + callback: () => {}, + className: '', + evalScripts: 'once' } static propTypes = { - path: PropTypes.string.isRequired, + callback: PropTypes.func, className: PropTypes.string, - evalScripts: PropTypes.oneOf(['always', 'once', 'never']), - fallbackPath: PropTypes.string, - callback: PropTypes.func + evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]), + srcPath: PropTypes.string.isRequired + } + + injectSVG() { + const { + evalScripts, + callback: each + } = this.props + + if (this._img) { + SVGInjector(this._img, { + evalScripts, + each + }) + } + } + + componentDidMount() { + this.injectSVG() + } + + componentDidUpdate() { + this.injectSVG() } render() { - const { className, - path, - fallbackPath - } = this.props; + srcPath + } = this.props return ( <img + ref={img => this._img = img} className={className} - data-src={path} - data-fallback={fallbackPath} - ref={(img) => this._img = img} + data-src={srcPath} /> - ); - - } - - componentDidMount() { - this.updateSVG(); - } - - componentDidUpdate() { - this.updateSVG(); - } - - updateSVG() { - - const { - evalScripts, - callback: each - } = this.props; - - SVGInjector(this._img, { - evalScripts, - each - }); + ) }
36e75858d0c6b10d11d998d2d205be7d237c7bb8
src/index.js
src/index.js
import {Video} from '@thiagopnts/kaleidoscope'; import {ContainerPlugin, Mediator, Events} from 'clappr'; export default class Video360 extends ContainerPlugin { constructor(container) { super(container); Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this); let {height, width, autoplay} = container.options; container.playback.el.setAttribute('crossorigin', 'anonymous'); container.el.style.touchAction = "none"; container.el.addEventListener("touchmove", function(event) { event.preventDefault(); }, false); this.viewer = new Video({height: isNaN(height) ? 300 : height, width: isNaN(width) ? 400 : width, container: this.container.el, source: this.container.playback.el}); this.viewer.render(); } get name() { return 'Video360'; } updateSize() { setTimeout(() => this.viewer.setSize({height: this.container.$el.height(), width: this.container.$el.width()}) , 250) } }
import {Video} from '@thiagopnts/kaleidoscope'; import {ContainerPlugin, Mediator, Events} from 'clappr'; export default class Video360 extends ContainerPlugin { constructor(container) { super(container); Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this); let {height, width, autoplay} = container.options; container.playback.el.setAttribute('crossorigin', 'anonymous'); container.playback.el.setAttribute('preload', 'metadata'); container.playback.el.setAttribute('playsinline', 'true'); container.el.style.touchAction = "none"; container.el.addEventListener("touchmove", function(event) { event.preventDefault(); }, false); this.viewer = new Video({height: isNaN(height) ? 300 : height, width: isNaN(width) ? 400 : width, container: this.container.el, source: this.container.playback.el}); this.viewer.render(); } get name() { return 'Video360'; } updateSize() { setTimeout(() => this.viewer.setSize({height: this.container.$el.height(), width: this.container.$el.width()}) , 250) } }
Fix video jumping to fullscreen on iPhones
Fix video jumping to fullscreen on iPhones
JavaScript
mit
thiagopnts/video-360,thiagopnts/video-360
--- +++ @@ -8,6 +8,8 @@ Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this); let {height, width, autoplay} = container.options; container.playback.el.setAttribute('crossorigin', 'anonymous'); + container.playback.el.setAttribute('preload', 'metadata'); + container.playback.el.setAttribute('playsinline', 'true'); container.el.style.touchAction = "none"; container.el.addEventListener("touchmove", function(event) { event.preventDefault();
5bd8a33f12bb38bfb32cbc330d483c711dd32655
src/index.js
src/index.js
import {Video} from 'kaleidoscopejs'; import {ContainerPlugin, Mediator, Events} from 'clappr'; export default class Video360 extends ContainerPlugin { constructor(container) { super(container); Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this); let {height, width, autoplay} = container.options; container.playback.el.setAttribute('crossorigin', 'anonymous'); this.viewer = new Video({height: isNaN(height) ? 300 : height, width: isNaN(width) ? 400 : width, container: this.container.el, source: this.container.playback.el}); this.viewer.render(); } get name() { return 'Video360'; } updateSize() { setTimeout(() => this.viewer.renderer.setSize({height: this.container.$el.height(), width: this.container.$el.width()}) , 250) } }
import {Video} from 'kaleidoscopejs'; import {ContainerPlugin, Mediator, Events} from 'clappr'; export default class Video360 extends ContainerPlugin { constructor(container) { super(container); Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this); let {height, width, autoplay} = container.options; container.playback.el.setAttribute('crossorigin', 'anonymous'); this.viewer = new Video({height: isNaN(height) ? 300 : height, width: isNaN(width) ? 400 : width, container: this.container.el, source: this.container.playback.el}); this.viewer.render(); } get name() { return 'Video360'; } updateSize() { setTimeout(() => this.viewer.setSize({height: this.container.$el.height(), width: this.container.$el.width()}) , 250) } }
Change setSize() callee so that camera get new size too
Change setSize() callee so that camera get new size too
JavaScript
mit
thiagopnts/video-360,thiagopnts/video-360
--- +++ @@ -18,7 +18,7 @@ updateSize() { setTimeout(() => - this.viewer.renderer.setSize({height: this.container.$el.height(), width: this.container.$el.width()}) + this.viewer.setSize({height: this.container.$el.height(), width: this.container.$el.width()}) , 250) } }
52e91f6eadb2d6577bd67e525d851fc4e3213187
src/index.js
src/index.js
import path from 'path'; import fs from 'fs'; import collect from './collect'; let runOnAllFiles; function hasFlowPragma(source) { return source .getAllComments() .some(comment => /@flow/.test(comment.value)); } export default { rules: { 'show-errors': function showErrors(context) { return { Program() { const onTheFly = true; let collected; if (onTheFly) { const source = context.getSourceCode(); const root = process.cwd(); // Check to see if we should run on every file if (runOnAllFiles === undefined) { try { runOnAllFiles = fs .readFileSync(path.join(root, '.flowconfig')) .toString() .includes('all=true'); } catch (err) { runOnAllFiles = false; } } if (runOnAllFiles === false && !hasFlowPragma(source)) { return true; } collected = collect(source.getText(), root, context.getFilename()); } else { collected = collect(); } const pluginErrors = Array.isArray(collected) ? (onTheFly ? collected : collected.filter( each => each.path === context.getFilename() )) : []; pluginErrors.forEach(({ loc, message }) => { context.report({ loc, message }); }); } }; } } };
import path from 'path'; import fs from 'fs'; import collect from './collect'; let runOnAllFiles; function hasFlowPragma(source) { return source .getAllComments() .some(comment => /@flow/.test(comment.value)); } export default { rules: { 'show-errors': function showErrors(context) { return { Program() { const onTheFly = true; let collected; if (onTheFly) { const source = context.getSourceCode(); const root = process.cwd(); const flowDirSetting = context.settings && context.settings['flowtype-errors'] && context.settings['flowtype-errors']['flowDir']; const flowDir = fs.existsSync(path.join(root, flowDirSetting, '.flowconfig')) ? path.join(root, flowDirSetting) : root // Check to see if we should run on every file if (runOnAllFiles === undefined) { try { runOnAllFiles = fs .readFileSync(path.join(flowDir, '.flowconfig')) .toString() .includes('all=true'); } catch (err) { runOnAllFiles = false; } } if (runOnAllFiles === false && !hasFlowPragma(source)) { return true; } collected = collect(source.getText(), flowDir, context.getFilename()); } else { collected = collect(); } const pluginErrors = Array.isArray(collected) ? (onTheFly ? collected : collected.filter( each => each.path === context.getFilename() )) : []; pluginErrors.forEach(({ loc, message }) => { context.report({ loc, message }); }); } }; } } };
Add eslint setting 'flowDir' to specify location of .flowconfig
Add eslint setting 'flowDir' to specify location of .flowconfig
JavaScript
mit
namjul/eslint-plugin-flowtype-errors
--- +++ @@ -22,12 +22,19 @@ if (onTheFly) { const source = context.getSourceCode(); const root = process.cwd(); + const flowDirSetting = context.settings + && context.settings['flowtype-errors'] + && context.settings['flowtype-errors']['flowDir']; + + const flowDir = fs.existsSync(path.join(root, flowDirSetting, '.flowconfig')) + ? path.join(root, flowDirSetting) + : root // Check to see if we should run on every file if (runOnAllFiles === undefined) { try { runOnAllFiles = fs - .readFileSync(path.join(root, '.flowconfig')) + .readFileSync(path.join(flowDir, '.flowconfig')) .toString() .includes('all=true'); } catch (err) { @@ -39,7 +46,7 @@ return true; } - collected = collect(source.getText(), root, context.getFilename()); + collected = collect(source.getText(), flowDir, context.getFilename()); } else { collected = collect(); }
aeaafbdeaf6d4f13cc38d5ba9bc05b9508550bad
src/index.js
src/index.js
import '../vendor/gridforms.css' import React, {cloneElement, Children, PropTypes} from 'react' let classNames = (...args) => args.filter(cn => !!cn).join(' ') export let GridForm = ({children, className, component: Component, ...props}) => <Component {...props} className={classNames('grid-form', className)}> {children} </Component> GridForm.propTypes = { component: PropTypes.any } GridForm.defaultProps = { component: 'form' } export let Fieldset = ({children, legend, ...props}) => <fieldset {...props}> {legend && <legend>{legend}</legend>} {children} </fieldset> Fieldset.propTypes = { name: PropTypes.string.isRequired } export let Row = ({children, className}) => { let span = 0 Children.forEach(children, child => span += Number(child.props.span)) return <div data-row-span={span} className={className}> {children} </div> } export let Field = ({children, className, span}) => <div data-field-span={span} className={className}> {children} </div> Field.propTypes = { span: PropTypes.oneOfType([ PropTypes.number, PropTypes.string ]) } Field.defaultProps = { span: '1' }
import '../vendor/gridforms.css' import React, {cloneElement, Children, PropTypes} from 'react' let classNames = (...args) => args.filter(cn => !!cn).join(' ') export let GridForm = React.createClass({ getDefaultProps() { return { component: 'form' } }, render() { let {children, className, component: Component, ...props} = this.props return <Component {...props} className={classNames('grid-form', className)}> {children} </Component> } }) export let Fieldset = React.createClass({ render() { let {children, legend, ...props} = this.props return <fieldset {...props}> {legend && <legend>{legend}</legend>} {children} </fieldset> } }) export let Row = React.createClass({ render() { let {children, className} = this.props let span = 0 Children.forEach(children, child => span += Number(child.props.span)) return <div data-row-span={span} className={className}> {children} </div> } }) export let Field = React.createClass({ propTypes: { span: PropTypes.oneOfType([ PropTypes.number, PropTypes.string ]) }, getDefaultProps() { return { span: 1 } }, render() { let {children, className, span} = this.props return <div data-field-span={span} className={className}> {children} </div> } })
Use a regular React component impl until hot reloading issues are resolved
Use a regular React component impl until hot reloading issues are resolved Hot reloading a function component curently blows any state within it away
JavaScript
mit
insin/react-gridforms
--- +++ @@ -4,49 +4,57 @@ let classNames = (...args) => args.filter(cn => !!cn).join(' ') -export let GridForm = ({children, className, component: Component, ...props}) => - <Component {...props} className={classNames('grid-form', className)}> - {children} - </Component> +export let GridForm = React.createClass({ + getDefaultProps() { + return { + component: 'form' + } + }, + render() { + let {children, className, component: Component, ...props} = this.props + return <Component {...props} className={classNames('grid-form', className)}> + {children} + </Component> + } +}) -GridForm.propTypes = { - component: PropTypes.any -} +export let Fieldset = React.createClass({ + render() { + let {children, legend, ...props} = this.props + return <fieldset {...props}> + {legend && <legend>{legend}</legend>} + {children} + </fieldset> + } +}) -GridForm.defaultProps = { - component: 'form' -} +export let Row = React.createClass({ + render() { + let {children, className} = this.props + let span = 0 + Children.forEach(children, child => span += Number(child.props.span)) + return <div data-row-span={span} className={className}> + {children} + </div> + } +}) -export let Fieldset = ({children, legend, ...props}) => - <fieldset {...props}> - {legend && <legend>{legend}</legend>} - {children} - </fieldset> - -Fieldset.propTypes = { - name: PropTypes.string.isRequired -} - -export let Row = ({children, className}) => { - let span = 0 - Children.forEach(children, child => span += Number(child.props.span)) - return <div data-row-span={span} className={className}> - {children} - </div> -} - -export let Field = ({children, className, span}) => - <div data-field-span={span} className={className}> - {children} - </div> - -Field.propTypes = { - span: PropTypes.oneOfType([ - PropTypes.number, - PropTypes.string - ]) -} - -Field.defaultProps = { - span: '1' -} +export let Field = React.createClass({ + propTypes: { + span: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.string + ]) + }, + getDefaultProps() { + return { + span: 1 + } + }, + render() { + let {children, className, span} = this.props + return <div data-field-span={span} className={className}> + {children} + </div> + } +})
53bf7d8625644477eb9d5fc6c5a5070979b573c4
src/index.js
src/index.js
import arrayBufferToImage from './arrayBufferToImage.js'; import createImage from './createImage.js'; import { loadImage, configure } from './loadImage.js'; import { external } from './externalModules.js'; export { arrayBufferToImage, createImage, loadImage, configure, external };
import arrayBufferToImage from './arrayBufferToImage.js'; import createImage from './createImage.js'; import { loadImage, configure } from './loadImage.js'; import { external } from './externalModules.js'; const cornerstoneWebImageLoader = { arrayBufferToImage, createImage, loadImage, configure, external }; export { arrayBufferToImage, createImage, loadImage, configure, external }; export default cornerstoneWebImageLoader;
Add a (default) export named cornerstoneWebImageLoader
chore(exports): Add a (default) export named cornerstoneWebImageLoader
JavaScript
mit
cornerstonejs/cornerstoneWebImageLoader,chafey/cornerstoneWebImageLoader
--- +++ @@ -2,6 +2,14 @@ import createImage from './createImage.js'; import { loadImage, configure } from './loadImage.js'; import { external } from './externalModules.js'; + +const cornerstoneWebImageLoader = { + arrayBufferToImage, + createImage, + loadImage, + configure, + external +}; export { arrayBufferToImage, @@ -10,3 +18,5 @@ configure, external }; + +export default cornerstoneWebImageLoader;
b4c7d9e420f19ce8c30411288bdcdbe32c329d5d
tests/unit.js
tests/unit.js
// Listing of all the infrastructure unit tests define([ "./Destroyable", "./register", "./Widget-attr", "./handlebars", "./Widget-lifecycle", "./Widget-placeAt", "./Widget-utility", "./HasDropDown", "./CssState", "./Container", "./a11y", "./Widget-on", "./Stateful", "./Selection" ]);
// Listing of all the infrastructure unit tests define([ "./Destroyable", "./register", "./Widget-attr", "./handlebars", "./Widget-lifecycle", "./Widget-placeAt", "./Widget-utility", "./HasDropDown", "./CssState", "./Container", "./a11y", "./Widget-on", "./Stateful", "./Selection", "./StoreMap", "./Store" ]);
Store and StoreMap intern tests added
Store and StoreMap intern tests added
JavaScript
bsd-3-clause
EAlexRojas/deliteful,brunano21/deliteful,brunano21/deliteful,EAlexRojas/deliteful,cjolif/deliteful,tkrugg/deliteful,kitsonk/deliteful,tkrugg/deliteful,harbalk/deliteful,harbalk/deliteful,kitsonk/deliteful,cjolif/deliteful
--- +++ @@ -13,5 +13,7 @@ "./a11y", "./Widget-on", "./Stateful", - "./Selection" + "./Selection", + "./StoreMap", + "./Store" ]);
e3e7b721228250a7dc4c899f1e4e4d7841a71b0b
utils/analytics.js
utils/analytics.js
'use strict'; const _ = require('underscore'); const app = require('express')(); const Analytics = require('analytics-node'); const { secrets } = require('app/config/config'); const { guid } = require('./users'); const segmentKey = process.env.SEGMENT_WRITE_KEY || secrets.segmentKey; const env = app.get('env'); let analytics; // Flush events immediately if on dev environment if (env !== 'production') { analytics = new Analytics(segmentKey, { flushAt: 1 }); } else { analytics = new Analytics(segmentKey); } function generateOpts() { return { // Log the environment to differentiate events from production vs dev context: { environment: env, platform: 'Web' } }; } module.exports = { // https://segment.com/docs/sources/server/node/#identify identify(user) { let opts = generateOpts(); if (!user) { opts.anonymousId = guid(); } else { const { id: userId, email, name, username } = user; opts = { userId, traits: { name, email, username } }; } analytics.identify(opts); }, // https://segment.com/docs/sources/server/node/#track track(user, event, properties) { const { id: userId } = user; let opts = _.extend(generateOpts(), { userId, event, properties }); analytics.track(opts); } };
'use strict'; const _ = require('underscore'); const app = require('express')(); const Analytics = require('analytics-node'); const { secrets } = require('app/config/config'); const { guid } = require('./users'); const segmentKey = process.env.SEGMENT_WRITE_KEY || secrets.segmentKey; const env = app.get('env'); let analytics; // Flush events immediately if on dev environment if (env !== 'production') { analytics = new Analytics(segmentKey, { flushAt: 1 }); } else { analytics = new Analytics(segmentKey); } function generateOpts() { return { // Log the environment to differentiate events from production vs dev context: { environment: env, platform: 'Web' } }; } module.exports = { // https://segment.com/docs/sources/server/node/#identify identify(user) { let opts = generateOpts(); if (!user) { opts.anonymousId = guid(); } else { const { id: userId, email, name, username } = user; opts = { userId, traits: { name, email, username } }; } analytics.identify(opts); }, // https://segment.com/docs/sources/server/node/#track track(user, event, properties) { const { id: userId } = user; let opts = _.extend(generateOpts(), { userId, event, properties }); analytics.track(opts); }, // https://segment.com/docs/sources/server/node/#page page(user, category, name, properties) { const { id: userId } = user; let opts = _.extend(generateOpts(), { userId, category, name, properties }); analytics.page(opts); } };
Implement support for page() event tracking
Implement support for page() event tracking We won't begin logging page() calls until we implement the client API endpoint. [Finishes #131391691]
JavaScript
mit
heymanhn/journey-backend
--- +++ @@ -47,5 +47,13 @@ let opts = _.extend(generateOpts(), { userId, event, properties }); analytics.track(opts); + }, + + // https://segment.com/docs/sources/server/node/#page + page(user, category, name, properties) { + const { id: userId } = user; + let opts = _.extend(generateOpts(), { userId, category, name, properties }); + + analytics.page(opts); } };
b6a4044bee87508bfa9aa64225444d505a2265a9
src/index.js
src/index.js
const { ApolloServer } = require('apollo-server-micro') const { schema } = require('./schema') const { createErrorFormatter, sentryIgnoreErrors } = require('./errors') module.exports = function createHandler(options) { let Sentry if (options.sentryDsn) { Sentry = require('@sentry/node') Sentry.init({ dsn: options.sentryDsn, release: options.release, environment: process.env.NODE_ENV, ignoreErrors: sentryIgnoreErrors, onFatalError(error) { console.error(error, error.response) }, debug: true, }) } const formatError = createErrorFormatter(Sentry) const apolloServer = new ApolloServer({ schema, formatError }) return apolloServer.createHandler({ path: '/' }) }
const { ApolloServer } = require('apollo-server-micro') const { schema } = require('./schema') const { createErrorFormatter, sentryIgnoreErrors } = require('./errors') module.exports = function createHandler(options) { let Sentry if (options.sentryDsn) { Sentry = require('@sentry/node') Sentry.init({ dsn: options.sentryDsn, release: options.release, environment: process.env.NODE_ENV, ignoreErrors: sentryIgnoreErrors, onFatalError(error) { console.error(error, error.response) }, debug: process.env.DEBUG_SENTRY == 'true', }) } const formatError = createErrorFormatter(Sentry) const apolloServer = new ApolloServer({ schema, formatError }) return apolloServer.createHandler({ path: '/' }) }
Make sentry debug controllable with env variable
fix: Make sentry debug controllable with env variable DEBUG_SENTRY=true will enable it.
JavaScript
mit
relekang/micro-rss-parser
--- +++ @@ -16,7 +16,7 @@ onFatalError(error) { console.error(error, error.response) }, - debug: true, + debug: process.env.DEBUG_SENTRY == 'true', }) }
d9311ed552d14982e998e7bef1af66f0be0e1394
src/index.js
src/index.js
define([ "less!src/stylesheets/main.less" ], function() { var manager = new codebox.tabs.Manager({ draggable: false }); manager.$el.addClass("component-panels"); // Add tabs to grid codebox.app.grid.addView(manager, { width: 20, at: 0 }); // Render the tabs manager manager.render(); // Make the tab manager global codebox.panels = manager; });
define([ "less!src/stylesheets/main.less" ], function() { var manager = new codebox.tabs.Manager({ tabMenu: false }); manager.$el.addClass("component-panels"); // Add tabs to grid codebox.app.grid.addView(manager, { width: 20, at: 0 }); // Render the tabs manager manager.render(); // Make the tab manager global codebox.panels = manager; });
Disable menu on tabs, accept drag and drop
Disable menu on tabs, accept drag and drop
JavaScript
apache-2.0
etopian/codebox-package-panels,CodeboxIDE/package-panels
--- +++ @@ -2,7 +2,7 @@ "less!src/stylesheets/main.less" ], function() { var manager = new codebox.tabs.Manager({ - draggable: false + tabMenu: false }); manager.$el.addClass("component-panels");
a7db683614c87ef00adec299f4b1c4a359b4c2f2
public/javascripts/autofill-todays-date.js
public/javascripts/autofill-todays-date.js
function AutoFillTodaysDate(day, month, year) { var dod_elm = document.getElementById("todaysDateOfDisposalLabel"); var dod_day = document.getElementById("dateOfDisposal_day"); var dod_month = document.getElementById("dateOfDisposal_month"); var dod_year = document.getElementById("dateOfDisposal_year"); if (dod_elm.checked === false) { dod_day.value = ''; dod_month.value = ''; dod_year.value = ''; } else { dod_day.value = day; dod_month.value = month; dod_year.value = year; } }
function AutoFillTodaysDate(day, month, year) { var dod_elm = document.getElementById("todaysDateOfDisposal"); var dod_day = document.getElementById("dateOfDisposal_day"); var dod_month = document.getElementById("dateOfDisposal_month"); var dod_year = document.getElementById("dateOfDisposal_year"); if (dod_elm.checked === false) { dod_day.value = ''; dod_month.value = ''; dod_year.value = ''; } else { dod_day.value = day; dod_month.value = month; dod_year.value = year; } }
Fix unticking the box should reset to default
US432: Fix unticking the box should reset to default Former-commit-id: 5e70eb557d10e1f269e4d12b45e0276e1a5c5b92
JavaScript
mit
dvla/vehicles-online,dvla/vehicles-presentation-common,dvla/vrm-retention-online,dvla/vehicles-presentation-common,dvla/vehicles-presentation-common,dvla/vehicles-online,dvla/vehicles-online,dvla/vrm-retention-online,dvla/vrm-retention-online,dvla/vrm-retention-online,dvla/vehicles-online
--- +++ @@ -1,6 +1,6 @@ function AutoFillTodaysDate(day, month, year) { - var dod_elm = document.getElementById("todaysDateOfDisposalLabel"); + var dod_elm = document.getElementById("todaysDateOfDisposal"); var dod_day = document.getElementById("dateOfDisposal_day"); var dod_month = document.getElementById("dateOfDisposal_month"); var dod_year = document.getElementById("dateOfDisposal_year");
2825d4a0991fb7d2db5ab72f4e6cba84ef0b552b
src/utils/__tests__/getComponentName.test.js
src/utils/__tests__/getComponentName.test.js
import React, { Component } from 'react'; import getComponentName from '../getComponentName'; /* eslint-disable */ class Foo extends Component { render() { return <div />; } } function Bar() { return <div />; } const OldComp = React.createClass({ render: function() { return <div />; } }); const OldCompRev = React.createClass({ displayName: 'Rev(OldComp)', render: function() { return <div />; } }); class FooRev extends Component { static displayName = 'Rev(Foo)'; render() { return <span />; } } /* eslint-enable */ it('reads name from React components', () => { expect(getComponentName(Foo)).toBe('Foo'); expect(getComponentName(Bar)).toBe('Bar'); expect(getComponentName(OldComp)).toBe('OldComp'); }); it('reads name from components with custom name', () => { expect(getComponentName(OldCompRev)).toBe('Rev(OldComp)'); expect(getComponentName(FooRev)).toBe('Rev(Foo)'); });
import React, { Component } from 'react'; import getComponentName from '../getComponentName'; /* eslint-disable */ class Foo extends Component { render() { return <div />; } } function Bar() { return <div />; } const OldComp = React.createClass({ render: function() { return <div />; } }); const OldCompRev = React.createClass({ displayName: 'Rev(OldComp)', render: function() { return <div />; } }); class FooRev extends Component { static displayName = 'Rev(Foo)'; render() { return <span />; } } /* eslint-enable */ it('reads name from React components', () => { expect(getComponentName(Foo)).toBe('Foo'); expect(getComponentName(Bar)).toBe('Bar'); expect(getComponentName(OldComp)).toBe('OldComp'); }); it('reads name from components with custom name', () => { expect(getComponentName(OldCompRev)).toBe('Rev(OldComp)'); expect(getComponentName(FooRev)).toBe('Rev(Foo)'); }); it('throws if no Component passed in', () => { expect(() => getComponentName()).toThrow(); });
Test getComponentName() should throw when nothing passed in
Test getComponentName() should throw when nothing passed in
JavaScript
apache-2.0
iCHEF/gypcrete,iCHEF/gypcrete
--- +++ @@ -44,3 +44,7 @@ expect(getComponentName(OldCompRev)).toBe('Rev(OldComp)'); expect(getComponentName(FooRev)).toBe('Rev(Foo)'); }); + +it('throws if no Component passed in', () => { + expect(() => getComponentName()).toThrow(); +});
42c9b6b124955a68f37517f72a20203eaaa3eb6c
src/store.js
src/store.js
import { compose, createStore } from 'redux'; import middleware from './middleware'; import reducers from './reducers'; function configureStore() { return compose(middleware)(createStore)(reducers); } export var store = configureStore();
import { compose, createStore } from 'redux'; import middleware from './middleware'; import reducers from './reducers'; // Poor man's hot reloader. var lastState = JSON.parse(localStorage["farmbot"] || "{auth: {}}"); export var store = compose(middleware)(createStore)(reducers, lastState); if (lastState.auth.authenticated) { store.dispatch({ type: "LOGIN_OK", payload: lastState.auth }); }; function saveState(){ localStorage["farmbot"] = JSON.stringify(store.getState()); } store.subscribe(saveState);
Add improvised localstorage saving mechanism
[STABLE] Add improvised localstorage saving mechanism
JavaScript
mit
roryaronson/farmbot-web-frontend,FarmBot/farmbot-web-frontend,RickCarlino/farmbot-web-frontend,MrChristofferson/farmbot-web-frontend,RickCarlino/farmbot-web-frontend,roryaronson/farmbot-web-frontend,roryaronson/farmbot-web-frontend,MrChristofferson/farmbot-web-frontend,FarmBot/farmbot-web-frontend
--- +++ @@ -2,8 +2,18 @@ import middleware from './middleware'; import reducers from './reducers'; -function configureStore() { - return compose(middleware)(createStore)(reducers); +// Poor man's hot reloader. + +var lastState = JSON.parse(localStorage["farmbot"] || "{auth: {}}"); + +export var store = compose(middleware)(createStore)(reducers, lastState); + +if (lastState.auth.authenticated) { + store.dispatch({ type: "LOGIN_OK", payload: lastState.auth }); +}; + +function saveState(){ + localStorage["farmbot"] = JSON.stringify(store.getState()); } -export var store = configureStore(); +store.subscribe(saveState);
f03f47aa8653bcf91169eb1364d9f7198da9f435
src/utils.js
src/utils.js
define(function () { "use strict"; var noNew = function (Constructor) { return function () { var instance = Object.create(Constructor.prototype); Constructor.apply(instance, arguments); return instance; }; }; return { noNew: noNew, }; });
define(function () { "use strict"; // Allows constructors to be called without using `new` var noNew = function (Constructor) { return function () { var instance = Object.create(Constructor.prototype); Constructor.apply(instance, arguments); return instance; }; }; return { noNew: noNew, }; });
Add comment for noNew utility
Add comment for noNew utility
JavaScript
mpl-2.0
frewsxcv/graphosaurus
--- +++ @@ -1,6 +1,7 @@ define(function () { "use strict"; + // Allows constructors to be called without using `new` var noNew = function (Constructor) { return function () { var instance = Object.create(Constructor.prototype);
911db01256b1f2e9f3639e7767804a82351da48a
schemata/Assignment.js
schemata/Assignment.js
var mongoose = require('mongoose'); var Assignment = new mongoose.Schema({ due: { type: Date, required: true }, description: { type: String }, posted: { type: Number, required: true } }); mongoose.model('Assignment', Assignment); module.exports = Assignment;
var mongoose = require('mongoose'); var Assignment = new mongoose.Schema({ due: { type: Number, required: true }, description: { type: String }, posted: { type: Number, required: true } }); mongoose.model('Assignment', Assignment); module.exports = Assignment;
Move from Date to Number
Move from Date to Number
JavaScript
mit
librecms/librecms-api
--- +++ @@ -1,7 +1,7 @@ var mongoose = require('mongoose'); var Assignment = new mongoose.Schema({ due: { - type: Date, + type: Number, required: true }, description: {
633a10075f7c1feab809526cf64b07e7ce8d1832
src/utils.js
src/utils.js
/** * @module utils */ var utils = module.exports = {}; /** * Given a JSON string, convert it to its base64 representation. * * @method * @memberOf utils */ utils.jsonToBase64 = function (json) { var bytes = new Buffer(JSON.stringify(json)); return bytes .toString('base64') .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''); }; /** * Simple wrapper that, given a class, a property name and a method name, * creates a new method in the class that is a wrapper for the given * property method. * * @method * @memberOf utils */ utils.wrapPropertyMethod = function (Parent, name, propertyMethod) { var path = propertyMethod.split('.'); var property = path.shift(); var method = path.pop(); Object.defineProperty(Parent.prototype, name, { enumerable: false, get: function () { return this[property][method].bind(this[property]); } }); }
var Promise = require('bluebird'); var request = require('superagent'); /** * @module utils */ var utils = module.exports = {}; /** * Given a JSON string, convert it to its base64 representation. * * @method * @memberOf utils */ utils.jsonToBase64 = function (json) { var bytes = new Buffer(JSON.stringify(json)); return bytes .toString('base64') .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''); }; /** * Simple wrapper that, given a class, a property name and a method name, * creates a new method in the class that is a wrapper for the given * property method. * * @method * @memberOf utils */ utils.wrapPropertyMethod = function (Parent, name, propertyMethod) { var path = propertyMethod.split('.'); var property = path.shift(); var method = path.pop(); Object.defineProperty(Parent.prototype, name, { enumerable: false, get: function () { return this[property][method].bind(this[property]); } }); } /** * Perform a request with the given settings and return a promise that resolves * when the request is successfull and rejects when there's an error. * * @method * @memberOf utils */ utils.getRequestPromise = function (settings) { return new Promise(function (resolve, reject) { var method = settings.method.toLowerCase(); var req = request[method](settings.url); for (var name in settings.headers) { req = req.set(name, settings.headers[name]); } if (typeof settings.data === 'object') { req = req.send(settings.data); } req.end(function (err, res) { if (err) { reject(err); return; } resolve(res.body); }); }); };
Add utility function that abstracts the request process
Add utility function that abstracts the request process
JavaScript
mit
auth0/node-auth0,Annyv2/node-auth0
--- +++ @@ -1,3 +1,7 @@ +var Promise = require('bluebird'); +var request = require('superagent'); + + /** * @module utils */ @@ -42,3 +46,35 @@ }); } + +/** + * Perform a request with the given settings and return a promise that resolves + * when the request is successfull and rejects when there's an error. + * + * @method + * @memberOf utils + */ +utils.getRequestPromise = function (settings) { + return new Promise(function (resolve, reject) { + var method = settings.method.toLowerCase(); + var req = request[method](settings.url); + + for (var name in settings.headers) { + req = req.set(name, settings.headers[name]); + } + + if (typeof settings.data === 'object') { + req = req.send(settings.data); + } + + req.end(function (err, res) { + if (err) { + reject(err); + return; + } + + resolve(res.body); + }); + }); +}; +
8bf28e5dd3a48791426944ad6044c9a5db1ba08c
src/igTruncate.js
src/igTruncate.js
angular.module('igTruncate', []).filter('truncate', function (){ return function (text, length, end){ if (text !== undefined){ if (isNaN(length)){ length = 10; } if (end === undefined){ end = "..."; } if (text.length <= length || text.length - end.length <= length){ return text; }else{ return String(text).substring(0, length - end.length) + end; } } }; });
angular.module('igTruncate', []).filter('truncate', function (){ return function (text, length, end){ if (text !== undefined){ if (isNaN(length)){ length = 10; } end = end || "..."; if (text.length <= length || text.length - end.length <= length){ return text; }else{ return String(text).substring(0, length - end.length) + end; } } }; });
Simplify default for end variable.
Simplify default for end variable.
JavaScript
mit
OpenCST/angular-truncate,igreulich/angular-truncate
--- +++ @@ -5,9 +5,7 @@ length = 10; } - if (end === undefined){ - end = "..."; - } + end = end || "..."; if (text.length <= length || text.length - end.length <= length){ return text;
771de23463c5cb631aaee43df25f497741fab5e8
src/action.js
src/action.js
var parser = require('./parser'); var Interpreter = require('./interpreter'); function TileAction(tile, tileX, tileY, key, data, renderer, callback) { this.tile = tile; this.key = key; this.data = data; this.tileX = tileX; this.tileY = tileY; this.renderer = renderer; this.callback = callback; } TileAction.prototype.exec = function() { this.before = this.tile[this.key]; this.tile[this.key] = this.data; this.update(); } TileAction.prototype.undo = function() { this.tile[this.key] = this.before; this.update(); } TileAction.prototype.update = function() { // Fill the data with 0 if it's required and null. var command = Interpreter.CommandMap[this.tile.command]; if(command != null && command.argument && this.tile.data == null) { this.tile.data = 0; } this.tile.original = parser.encodeSyllable(this.tile); this.renderer.map.set(this.tileX, this.tileY, this.tile); this.renderer.updateTile(this.tileX, this.tileY); if(this.callback) this.callback(); } module.exports = TileAction;
var parser = require('./parser'); var Interpreter = require('./interpreter'); function TileAction(tile, tileX, tileY, key, data, renderer, callback) { this.tile = tile; this.key = key; this.data = data; this.tileX = tileX; this.tileY = tileY; this.renderer = renderer; this.callback = callback; } TileAction.prototype.exec = function() { this.before = this.tile[this.key]; this.tile[this.key] = this.data; this.update(); } TileAction.prototype.undo = function() { this.tile[this.key] = this.before; this.update(); } TileAction.prototype.update = function() { // Fill the data with 0 if it's required and null. var command = Interpreter.CommandMap[this.tile.command]; if(command != null && command.argument && this.tile.data == null) { this.tile.data = 0; } if(this.tile.command == 'push' && this.tile.data > 9) { // Force set data to 0 as it can't handle larger than 9 this.tile.data = 0; } this.tile.original = parser.encodeSyllable(this.tile); this.renderer.map.set(this.tileX, this.tileY, this.tile); this.renderer.updateTile(this.tileX, this.tileY); if(this.callback) this.callback(); } module.exports = TileAction;
Fix tile data for push command bug
Fix tile data for push command bug
JavaScript
mit
tnRaro/AheuiChem,tnRaro/AheuiChem,yoo2001818/AheuiChem,yoo2001818/AheuiChem
--- +++ @@ -28,6 +28,10 @@ if(command != null && command.argument && this.tile.data == null) { this.tile.data = 0; } + if(this.tile.command == 'push' && this.tile.data > 9) { + // Force set data to 0 as it can't handle larger than 9 + this.tile.data = 0; + } this.tile.original = parser.encodeSyllable(this.tile); this.renderer.map.set(this.tileX, this.tileY, this.tile); this.renderer.updateTile(this.tileX, this.tileY);
4faef2bde754588c884b3488071f1592d5c17611
lib/js.js
lib/js.js
'use strict'; var assign = require('lodash').assign; var utils = require('gulp-util'); var webpack = require('webpack'); var PluginError = utils.PluginError; var defaults = { optimize: false, plugins: { webpack: { entry: './src/main.js', output: { path: './dist' }, plugins: [] } } }; module.exports = function (gulp, options) { var opts = assign(defaults, options); var plugins = opts.plugins; var optimize = opts.optimize; gulp.task('js', function (done) { var settings = plugins.webpack; if (optimize) { settings.plugins.push( new webpack.optimize.UglifyJsPlugin() ); } webpack(settings, function (err, stats) { if (err) throw new PluginError('webpack', err); done(); }); }); };
'use strict'; var assign = require('lodash').assign; var utils = require('gulp-util'); var webpack = require('webpack'); var PluginError = utils.PluginError; var defaults = { optimize: false, plugins: { webpack: { entry: './src/main.js', output: { path: './dist', filename: 'main.js' }, plugins: [] } } }; module.exports = function (gulp, options) { var opts = assign(defaults, options); var plugins = opts.plugins; var optimize = opts.optimize; gulp.task('js', function (done) { var settings = plugins.webpack; if (optimize) { settings.plugins.push( new webpack.optimize.UglifyJsPlugin() ); } webpack(settings, function (err, stats) { if (err) throw new PluginError('webpack', err); done(); }); }); };
Add default setting for Webpack output.filename
Add default setting for Webpack output.filename
JavaScript
mit
cloudfour/core-gulp-tasks
--- +++ @@ -11,7 +11,8 @@ webpack: { entry: './src/main.js', output: { - path: './dist' + path: './dist', + filename: 'main.js' }, plugins: [] }
98aea0edf7154b80fcc7c0acb3921f3776e23190
client/src/features/userSettings/sagas.js
client/src/features/userSettings/sagas.js
import { call, takeLatest, select } from 'redux-saga/effects'; import { TOGGLE_NOTIFICATION } from 'common/actionTypes/userSettings'; import { ENABLE_VOTING } from 'common/actionTypes/voting'; import { notify, notifyPermission } from '../../utils/notification'; import { getIssueText } from '../issue/selectors'; import { notificationIsEnabled } from '../userSettings/selectors'; function* openIssue() { const notificationEnabled = yield select(notificationIsEnabled); const { description } = yield select(getIssueText); if (notificationEnabled) { yield call(notify, description); } } function* toggleNotification() { const notificationEnabled = yield select(notificationIsEnabled); if (notificationEnabled) { yield call(notifyPermission); } } export default function* issueSaga() { yield takeLatest(ENABLE_VOTING, openIssue); yield takeLatest(TOGGLE_NOTIFICATION, toggleNotification); }
import { call, takeLatest, select } from 'redux-saga/effects'; import { TOGGLE_NOTIFICATION } from 'common/actionTypes/userSettings'; import { ENABLE_VOTING } from 'common/actionTypes/voting'; import { notify, notifyPermission } from '../../utils/notification'; import { getIssueText } from '../issue/selectors'; import { notificationIsEnabled } from '../userSettings/selectors'; function* openIssue() { const notificationEnabled = yield select(notificationIsEnabled); const description = yield select(getIssueText); if (notificationEnabled) { yield call(notify, description); } } function* toggleNotification() { const notificationEnabled = yield select(notificationIsEnabled); if (notificationEnabled) { yield call(notifyPermission); } } export default function* issueSaga() { yield takeLatest(ENABLE_VOTING, openIssue); yield takeLatest(TOGGLE_NOTIFICATION, toggleNotification); }
Fix voting notification returning undefined
Fix voting notification returning undefined getIssueText returns issue text not object.
JavaScript
mit
dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta
--- +++ @@ -7,7 +7,7 @@ function* openIssue() { const notificationEnabled = yield select(notificationIsEnabled); - const { description } = yield select(getIssueText); + const description = yield select(getIssueText); if (notificationEnabled) { yield call(notify, description); }
552909944462a4c541a00af5b7508dbf391f41fc
bin/gear.js
bin/gear.js
#!/usr/bin/env node /* Gear task runner. Executes Gearfile using a tasks workflow. * See http://gearjs.org/#tasks.tasks * * Usage: * > gear */ var gear = require('../index'), vm = require('vm'), path = require('path'), fs = require('fs'), filename = 'Gearfile', existsSync = fs.existsSync || path.existsSync; // 0.6 compat if (!existsSync(filename)) { notify(filename + ' not found'); return 1; } try { var tasks = vm.runInNewContext('var tasks = ' + fs.readFileSync(filename) + '; tasks;', { require: require, process: process, console: console, gear: gear }, filename, true); } catch(e) { notify(e); return 1; } if (tasks) { new gear.Queue({registry: new gear.Registry({module: 'gear-lib'})}) .tasks(tasks) .run(function(err, res) { if (err) { notify(err); } }); } function notify(msg) { console.error('gear: ', msg); }
#!/usr/bin/env node 'use strict'; /* Gear task runner. Executes Gearfile using a tasks workflow. * See http://gearjs.org/#tasks.tasks * * Usage: * > gear [options] * * Available options: * --cwd <dir> change working directory * --Gearfile <path> execute a specific gearfile */ var Liftoff = require('liftoff'), vm = require('vm'), path = require('path'), fs = require('fs'), filename = 'Gearfile', existsSync = fs.existsSync || path.existsSync; // 0.6 compat var GearCLI = new Liftoff({ name: 'Gear', configName: filename, extensions: { '': null, '.js': null } }); GearCLI.launch(function(env) { // Loads a local install of gear. Falls back to the global install. var gear = require(env.modulePath || '../index'); if(process.cwd !== env.cwd) { process.chdir(env.cwd); } if (!env.configPath) { notify(filename + ' not found'); process.exit(1); } var tasks; try { tasks = vm.runInNewContext('var tasks = ' + fs.readFileSync(filename) + '; tasks;', { require: require, process: process, console: console, gear: gear }, env.configPath, true); } catch(e) { notify(e); process.exit(1); } if (tasks) { new gear.Queue({registry: new gear.Registry({module: 'gear-lib'})}) .tasks(tasks) .run(function(err, res) { if (err) { notify(err); } }); } }); function notify(msg) { console.error('gear: ', msg); }
Use node-liftoff to improve CLI mode.
Use node-liftoff to improve CLI mode.
JavaScript
bsd-3-clause
twobit/gear
--- +++ @@ -1,44 +1,68 @@ #!/usr/bin/env node +'use strict'; /* Gear task runner. Executes Gearfile using a tasks workflow. * See http://gearjs.org/#tasks.tasks * * Usage: - * > gear - */ -var gear = require('../index'), + * > gear [options] + * + * Available options: + * --cwd <dir> change working directory + * --Gearfile <path> execute a specific gearfile + */ +var Liftoff = require('liftoff'), vm = require('vm'), path = require('path'), fs = require('fs'), filename = 'Gearfile', existsSync = fs.existsSync || path.existsSync; // 0.6 compat -if (!existsSync(filename)) { - notify(filename + ' not found'); - return 1; -} +var GearCLI = new Liftoff({ + name: 'Gear', + configName: filename, + extensions: { + '': null, + '.js': null + } +}); -try { - var tasks = vm.runInNewContext('var tasks = ' + fs.readFileSync(filename) + '; tasks;', { - require: require, - process: process, - console: console, - gear: gear - }, filename, true); -} catch(e) { - notify(e); - return 1; -} +GearCLI.launch(function(env) { + // Loads a local install of gear. Falls back to the global install. + var gear = require(env.modulePath || '../index'); + if(process.cwd !== env.cwd) { + process.chdir(env.cwd); + } -if (tasks) { - new gear.Queue({registry: new gear.Registry({module: 'gear-lib'})}) - .tasks(tasks) - .run(function(err, res) { - if (err) { - notify(err); - } - }); -} + if (!env.configPath) { + notify(filename + ' not found'); + process.exit(1); + } + + var tasks; + try { + tasks = vm.runInNewContext('var tasks = ' + fs.readFileSync(filename) + '; tasks;', { + require: require, + process: process, + console: console, + gear: gear + }, env.configPath, true); + } catch(e) { + notify(e); + process.exit(1); + } + + if (tasks) { + new gear.Queue({registry: new gear.Registry({module: 'gear-lib'})}) + .tasks(tasks) + .run(function(err, res) { + if (err) { + notify(err); + } + }); + } +}); + function notify(msg) { console.error('gear: ', msg);
3901dd45585eacebe1e0b4d7fd55aab0b94cefa2
update-npm.js
update-npm.js
var childProcess = require('child_process'); var fs = require('fs'); var path = require('path'); function isMangarack(key) { return /^mangarack/.test(key); } fs.readdirSync(__dirname).forEach(function(folderName) { if (!isMangarack(folderName)) return; var fullPath = path.join(__dirname, folderName); childProcess.execSync('npm publish', {cwd: fullPath, stdio: [0, 1, 2]}}); });
var childProcess = require('child_process'); var fs = require('fs'); var path = require('path'); function isMangarack(key) { return /^mangarack/.test(key); } fs.readdirSync(__dirname).forEach(function(folderName) { if (!isMangarack(folderName)) return; var fullPath = path.join(__dirname, folderName); childProcess.execSync('npm publish', {cwd: fullPath, stdio: [0, 1, 2]}); });
Fix the npm update utility.
Fix the npm update utility.
JavaScript
mit
Deathspike/mangarack.js,MangaRack/mangarack,MangaRack/mangarack,Deathspike/mangarack.js,MangaRack/mangarack,Deathspike/mangarack.js
--- +++ @@ -9,5 +9,5 @@ fs.readdirSync(__dirname).forEach(function(folderName) { if (!isMangarack(folderName)) return; var fullPath = path.join(__dirname, folderName); - childProcess.execSync('npm publish', {cwd: fullPath, stdio: [0, 1, 2]}}); + childProcess.execSync('npm publish', {cwd: fullPath, stdio: [0, 1, 2]}); });
639e97117d9651f6cee03474686b787f5e59c9a8
src/setupTests.js
src/setupTests.js
// jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import "@testing-library/jest-dom/extend-expect"; // need this for async/await in tests import "core-js/stable"; import "regenerator-runtime/runtime"; import jquery from "jquery"; window.$ = window.jQuery = jquery; jquery.expr.pseudos.visible = function () { // Fix jQuery ":visible" selector always returns false in JSDOM. // https://github.com/jsdom/jsdom/issues/1048#issuecomment-401599392 return true; }; // pat-subform // See https://github.com/jsdom/jsdom/issues/1937#issuecomment-461810980 window.HTMLFormElement.prototype.submit = () => {};
// jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import "@testing-library/jest-dom/extend-expect"; // need this for async/await in tests import "core-js/stable"; import "regenerator-runtime/runtime"; import jquery from "jquery"; window.$ = window.jQuery = jquery; jquery.expr.pseudos.visible = function () { // Fix jQuery ":visible" selector always returns false in JSDOM. // https://github.com/jsdom/jsdom/issues/1048#issuecomment-401599392 return true; }; class URL { constructor(url) { this.url = url; this.protocol = url.split("//")[0]; } } window.URL = URL; // pat-subform // See https://github.com/jsdom/jsdom/issues/1937#issuecomment-461810980 window.HTMLFormElement.prototype.submit = () => {};
Add URL mock for Jest tests. Only supporting protocol attribute yet.
Add URL mock for Jest tests. Only supporting protocol attribute yet.
JavaScript
bsd-3-clause
plone/mockup,plone/mockup,plone/mockup
--- +++ @@ -16,6 +16,14 @@ return true; }; +class URL { + constructor(url) { + this.url = url; + this.protocol = url.split("//")[0]; + } +} +window.URL = URL; + // pat-subform // See https://github.com/jsdom/jsdom/issues/1937#issuecomment-461810980 window.HTMLFormElement.prototype.submit = () => {};