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 |
|---|---|---|---|---|---|---|---|---|---|---|
97e271d4db24cbc89d367d19c6a65ae402972c8e | lib/commands/search.js | lib/commands/search.js | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var api = require('../api');
function arrayToQueryString(args) {
var searchString = '?q=' + args._.join('+');
if (args.user) {
searchString = searchString.concat('+user:' + args.user);
}
if (args.language) {
searchString = searchString.concat('+language:' + args.language);
}
return searchString;
}
function performQuery(config, request, args) {
api.search(request, arrayToQueryString(args), function(error, result) {
if (error) {
console.log('Something unexpected has happended..');
return;
}
/* jshint camelcase: false */
var res = result.total_count || 0;
console.log('Showing %d out of %d repositories ' +
'that match your search query',
Math.min(res, 30), res);
_.forEach(result.items, function(repo) {
console.log(repo.full_name);
});
/* jshint camelcase: true */
});
}
function help() {
console.log(fs.readFileSync(
path.resolve(__dirname, '../templates/help-search.txt'), 'utf8'));
}
module.exports = function(config, request, args) {
if (args.help) {
help();
} else {
performQuery(config, request, args);
}
};
| 'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var api = require('../api');
function queryStringFromArgs(args) {
var searchString = '?q=' + args._.join('+');
if (args.user) {
searchString = searchString.concat('+user:' + args.user);
}
if (args.language) {
searchString = searchString.concat('+language:' + args.language);
}
return searchString;
}
function performQuery(config, request, args) {
api.search(request, queryStringFromArgs(args), function(error, result) {
if (error) {
console.log('Something unexpected has happended..');
return;
}
/* jshint camelcase: false */
var res = result.total_count || 0;
console.log('Showing %d out of %d repositories ' +
'that match your search query',
Math.min(res, 30), res);
_.forEach(result.items, function(repo) {
console.log(repo.full_name);
});
/* jshint camelcase: true */
});
}
function help() {
console.log(fs.readFileSync(
path.resolve(__dirname, '../templates/help-search.txt'), 'utf8'));
}
module.exports = function(config, request, args) {
if (args.help) {
help();
} else {
performQuery(config, request, args);
}
};
| Rename function for generating query string. | Rename function for generating query string.
| JavaScript | mit | stillesjo/buh | ---
+++
@@ -5,7 +5,7 @@
var path = require('path');
var api = require('../api');
-function arrayToQueryString(args) {
+function queryStringFromArgs(args) {
var searchString = '?q=' + args._.join('+');
if (args.user) {
searchString = searchString.concat('+user:' + args.user);
@@ -17,7 +17,7 @@
}
function performQuery(config, request, args) {
- api.search(request, arrayToQueryString(args), function(error, result) {
+ api.search(request, queryStringFromArgs(args), function(error, result) {
if (error) {
console.log('Something unexpected has happended..');
return; |
843c48748261d44331f81ac915621766ce5ca0b6 | test/index.js | test/index.js | 'use strict';
var angular = require('angular');
var expect = require('chai').use(require('sinon-chai')).expect;
var sinon = require('sinon');
var sap = require('sinon-as-promised');
describe('animate-change', function () {
var $scope, $animate, element;
beforeEach(angular.mock.module(require('../')));
beforeEach(angular.mock.module(function ($provide) {
$provide.value('$animate', ($animate = {}));
}));
beforeEach(angular.mock.inject(function ($injector) {
$compile = $injector.get('$compile');
$scope = $injector.get('$rootScope').$new();
sap($injector.get('$q'));
sap.setScheduler(function (fn) {
$scope.$evalAsync(fn);
});
$animate.addClass = sinon.stub().resolves();
$animate.removeClass = sinon.stub().resolves();
element = $compile('<span animate-change="foo" change-class="on"></span>')($scope);
}));
it('adds the animation class when the model changes', function () {
$scope.$digest();
$scope.foo = 'bar';
$scope.$digest();
expect($animate.addClass).to.have.been.calledWith(element, 'on');
expect($animate.removeClass).to.have.been.calledWith(element, 'on');
});
it('does not animate the initial value', function () {
$scope.foo = 'bar';
$scope.$digest();
expect($animate.addClass).to.not.have.been.called;
});
});
| 'use strict';
var angular = require('angular');
var expect = require('chai').use(require('sinon-chai')).expect;
var sinon = require('sinon');
var sap = require('sinon-as-promised');
describe('animate-change', function () {
var $scope, $animate, element;
beforeEach(angular.mock.module(require('../')));
beforeEach(angular.mock.module(function ($provide) {
$provide.value('$animate', ($animate = {}));
}));
beforeEach(angular.mock.inject(function ($injector) {
$compile = $injector.get('$compile');
$scope = $injector.get('$rootScope').$new();
sap($injector.get('$q'));
sap.setScheduler(function (fn) {
$scope.$evalAsync(fn);
});
$animate.addClass = sinon.stub().resolves();
element = $compile('<span animate-change="foo" change-class="on"></span>')($scope);
}));
it('adds the toggles class when the model changes', function () {
$scope.$digest();
sinon.stub(element, 'removeClass');
$scope.foo = 'bar';
$scope.$digest();
expect($animate.addClass).to.have.been.calledWith(element, 'on');
expect(element.removeClass).to.have.been.calledWith('on');
});
it('does not animate the initial value', function () {
$scope.foo = 'bar';
$scope.$digest();
expect($animate.addClass).to.not.have.been.called;
});
});
| Update tests for using element.removeClass instead of $animate | Update tests for using element.removeClass instead of $animate | JavaScript | mit | bendrucker/angular-animate-change,bendrucker/angular-animate-change | ---
+++
@@ -20,16 +20,16 @@
$scope.$evalAsync(fn);
});
$animate.addClass = sinon.stub().resolves();
- $animate.removeClass = sinon.stub().resolves();
element = $compile('<span animate-change="foo" change-class="on"></span>')($scope);
}));
- it('adds the animation class when the model changes', function () {
+ it('adds the toggles class when the model changes', function () {
$scope.$digest();
+ sinon.stub(element, 'removeClass');
$scope.foo = 'bar';
$scope.$digest();
expect($animate.addClass).to.have.been.calledWith(element, 'on');
- expect($animate.removeClass).to.have.been.calledWith(element, 'on');
+ expect(element.removeClass).to.have.been.calledWith('on');
});
it('does not animate the initial value', function () { |
56d7dc2661360d21325ac94338556036c774eb1a | test/model.js | test/model.js | var async = require("async");
var bay6 = require("../lib/");
var expect = require("chai").expect;
var mongoose = require("mongoose");
var request = require("supertest");
describe("Model", function() {
var app;
var model;
beforeEach(function() {
app = bay6();
app.options.prefix = "";
model = app.model("Document", {
title: String,
contents: String
});
mongoose.set("debug", true);
});
describe("#limit", function() {
it("should return a maximum of n documents", function(done) {
model.limit(5);
var server = app.serve(9000);
var Document = app.mongoose.model("Document");
async.each([1, 2, 3, 4, 5, 6], function(useless, done2) {
var doc = new Document({ title: "war and peace", contents: "yolo" });
doc.save(done2);
}, function(err) {
if (err) {
throw err;
}
request(server).get("/documents").end(function(err, res) {
expect(res.body.length).to.equal(5);
server.close();
done();
});
});
});
});
afterEach(function(done) {
app.mongoose.db.dropDatabase(done);
});
});
| var async = require("async");
var bay6 = require("../lib/");
var expect = require("chai").expect;
var mongoose = require("mongoose");
var request = require("supertest");
describe("Model", function() {
var app;
var model;
beforeEach(function() {
app = bay6();
app.options.prefix = "";
model = app.model("Document", {
title: String,
contents: String
});
});
describe("#limit", function() {
it("should return a maximum of n documents", function(done) {
model.limit(5);
var server = app.serve(9000);
var Document = app.mongoose.model("Document");
async.each([1, 2, 3, 4, 5, 6], function(useless, done2) {
var doc = new Document({ title: "war and peace", contents: "yolo" });
doc.save(done2);
}, function(err) {
if (err) {
throw err;
}
request(server).get("/documents").end(function(err, res) {
expect(res.body.length).to.equal(5);
server.close();
done();
});
});
});
});
afterEach(function(done) {
app.mongoose.db.dropDatabase(done);
});
});
| Remove mongoose debug mode from test | Remove mongoose debug mode from test
Signed-off-by: Ian Macalinao <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@ian.pw>
| JavaScript | mit | simplyianm/bay6 | ---
+++
@@ -15,7 +15,6 @@
title: String,
contents: String
});
- mongoose.set("debug", true);
});
describe("#limit", function() { |
ce8df49212f484ef04b03225b02db5f519b12113 | lib/display-message.js | lib/display-message.js | const $ = require('jquery');
function DisplayMessage(){
}
DisplayMessage.prototype.showWinMessage = function(){
var div = $('#post-game');
div.empty()
.show()
.append(`<h1>You Win!</h1>
<p>Click to play the next level.</p>`
);
div.on('click', function(){
div.hide();
});
}
DisplayMessage.prototype.showHighScoreMessage = function(game, leaderboard){
var div = $('#post-game');
div.empty()
.show()
.append(`<h1>High Score!</h1>
<p>Name:</p>
<input class='input'></input>
<button>Submit</button>`
);
div.on('click', 'button', function(){
var input = $('.input').val();
game.getName(input, leaderboard);
div.hide();
});
}
DisplayMessage.prototype.showScore = function(score){
$('#score').empty().append(this.scoreElement(score));
};
DisplayMessage.prototype.scoreElement = function(score){
return '<h1>Score: ' + score + '</h1>';
};
module.exports = DisplayMessage;
| const $ = require('jquery');
function DisplayMessage(){
}
DisplayMessage.prototype.showWinMessage = function(){
var div = $('#post-game');
div.empty()
.show()
.append(`<h1>You Win!</h1>
<p>Click to play the next level.</p>`
);
div.on('click', function(){
div.hide();
});
}
DisplayMessage.prototype.showHighScoreMessage = function(game, leaderboard){
var div = $('#post-game');
div.empty()
.show()
.append(`<h1>High Score!</h1>
<p>Name:</p>
<input class='input'></input>
<button id="high-submit-button">Submit</button>`
);
div.unbind('click').on('click', 'button', function() {
var input = $('.input').val();
game.getName(input, leaderboard);
div.hide();
});
}
DisplayMessage.prototype.showScore = function(score){
$('#score').empty().append(this.scoreElement(score));
};
DisplayMessage.prototype.scoreElement = function(score){
return '<h1>Score: ' + score + '</h1>';
};
module.exports = DisplayMessage;
| Remove event listener in game win to avoid multiplication | Remove event listener in game win to avoid multiplication
| JavaScript | mit | plato721/lights-out,plato721/lights-out | ---
+++
@@ -23,10 +23,9 @@
.append(`<h1>High Score!</h1>
<p>Name:</p>
<input class='input'></input>
- <button>Submit</button>`
+ <button id="high-submit-button">Submit</button>`
);
-
- div.on('click', 'button', function(){
+ div.unbind('click').on('click', 'button', function() {
var input = $('.input').val();
game.getName(input, leaderboard);
div.hide(); |
1f59f1a7b1a1a5a3346c3f607a20309d332fd3ac | lib/helpers/helpers.js | lib/helpers/helpers.js | 'use strict';
function Helpers() {
}
Helpers.prototype = {
getClassesFromSelector: function (selector) {
if (!selector) {
return [];
}
var classRegEx = /[_a-zA-Z\*][_a-zA-Z0-9-]*/g;
return selector.match(classRegEx);
},
getSelectorLength: function (selector) {
var classes = this.getClassesFromSelector(selector);
return classes ? classes.length : 0;
}
};
module.exports = Helpers;
| 'use strict';
function Helpers() {
}
Helpers.prototype = {
getClassesFromSelector: function (selector) {
if (!selector) {
return [];
}
var classRegEx = /[_a-zA-Z][_a-zA-Z0-9-]*/g;
return selector.match(classRegEx);
},
getSelectorLength: function (selector) {
var classes = this.getClassesFromSelector(selector);
return classes ? classes.length : 0;
}
};
module.exports = Helpers;
| Revert "support * selectors", it appears this bug was already fixed but not released | Revert "support * selectors", it appears this bug was already fixed but not released
| JavaScript | mit | timeinfeldt/grunt-csschecker,timeinfeldt/grunt-csschecker | ---
+++
@@ -8,7 +8,7 @@
if (!selector) {
return [];
}
- var classRegEx = /[_a-zA-Z\*][_a-zA-Z0-9-]*/g;
+ var classRegEx = /[_a-zA-Z][_a-zA-Z0-9-]*/g;
return selector.match(classRegEx);
},
getSelectorLength: function (selector) { |
3916cb06b6c1d8694eceb25534e67bcd2830ebb2 | app.js | app.js | var express = require('express'),
schedule = require('node-schedule'),
cacheService = require('./cache-service.js')(),
app = express(),
dataCache = {
news: null,
weather: null
};
setUpSchedule();
app.get('/', function (req, res) {
res.send('Welcome to Scraper API\n');
});
//news
app.get('/news', function (req, res) {
res.send(dataCache.news);
});
//weather
app.get('/weather', function (req, res) {
res.send(dataCache.weather);
});
//reset-cache
app.get('/reset-cache', function (req, res) {
setUpCache();
res.send(true);
});
app.set('port', process.env.PORT || 8080);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
function setUpSchedule() {
schedule.scheduleJob({ hour: 7 }, setUpCache);
schedule.scheduleJob({ hour: 17 }, setUpCache);
}
function setUpCache() {
cacheService.news(dataCache);
//cacheService.weather(dataCache, 'Sofia');
}
| var express = require('express'),
schedule = require('node-schedule'),
cacheService = require('./cache-service.js')(),
app = express(),
dataCache = {
news: null,
weather: null
};
setUpSchedule();
app.get('/', function (req, res) {
res.send('Welcome to Scraper API\n' + 'Server time: ' + new Date().toString());
});
//news
app.get('/news', function (req, res) {
res.send(dataCache.news);
});
//weather
app.get('/weather', function (req, res) {
res.send(dataCache.weather);
});
//reset-cache
app.get('/reset-cache', function (req, res) {
setUpCache();
res.send(true);
});
app.set('port', process.env.PORT || 8080);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
function setUpSchedule() {
schedule.scheduleJob({ hour: 7 }, setUpCache);
schedule.scheduleJob({ hour: 17 }, setUpCache);
}
function setUpCache() {
cacheService.news(dataCache);
//cacheService.weather(dataCache, 'Sofia');
}
| Add log of server time | Add log of server time | JavaScript | mit | AlexanderAntov/scraper-js,AlexanderAntov/scraper-js | ---
+++
@@ -10,7 +10,7 @@
setUpSchedule();
app.get('/', function (req, res) {
- res.send('Welcome to Scraper API\n');
+ res.send('Welcome to Scraper API\n' + 'Server time: ' + new Date().toString());
});
//news |
78826dbdb3e81b084918f550c34527652f8d5de7 | examples/cli.js | examples/cli.js | #!/usr/bin/node
var convert = require('../'),
fs = require('fs'),
geojson = JSON.parse(fs.readFileSync(process.argv[2])),
mtl = process.argv[3],
mtllibs = process.argv.slice(4),
options = {
coordToPoint: convert.findLocalProj(geojson),
mtllib: mtllibs
};
if (mtl) {
options.featureMaterial = function() {
return mtl;
};
}
convert.toObj(geojson, process.stdout, options);
| #!/usr/bin/node
var convert = require('../'),
localProj = require('local-proj'),
fs = require('fs'),
geojson = JSON.parse(fs.readFileSync(process.argv[2])),
mtl = process.argv[3],
mtllibs = process.argv.slice(4),
options = {
coordToPoint: localProj.find(geojson).forward,
mtllib: mtllibs
};
if (mtl) {
options.featureMaterial = function(f, cb) {
process.nextTick(function() { cb(undefined, mtl); });
};
}
convert.toObj(geojson, process.stdout, function(err) {
if (err) {
process.stderr.write(err + '\n');
}
}, options);
| Update to async; fix problem with missing findLocalProj | Update to async; fix problem with missing findLocalProj
| JavaScript | isc | perliedman/geojson2obj | ---
+++
@@ -1,19 +1,24 @@
#!/usr/bin/node
var convert = require('../'),
+ localProj = require('local-proj'),
fs = require('fs'),
geojson = JSON.parse(fs.readFileSync(process.argv[2])),
mtl = process.argv[3],
mtllibs = process.argv.slice(4),
options = {
- coordToPoint: convert.findLocalProj(geojson),
+ coordToPoint: localProj.find(geojson).forward,
mtllib: mtllibs
};
if (mtl) {
- options.featureMaterial = function() {
- return mtl;
+ options.featureMaterial = function(f, cb) {
+ process.nextTick(function() { cb(undefined, mtl); });
};
}
-convert.toObj(geojson, process.stdout, options);
+convert.toObj(geojson, process.stdout, function(err) {
+ if (err) {
+ process.stderr.write(err + '\n');
+ }
+}, options); |
18957b36ddcd96b41c8897542609c53c166052c3 | config/initializers/middleware.js | config/initializers/middleware.js | express = require('express')
expressValidator = require('express-validator')
module.exports = (function(){
function configure(app) {
app.set('port', process.env.PORT || 3000);
app.set('host', process.env.HOST || '127.0.0.1')
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser())
app.use(expressValidator());
app.use(express.cookieParser());
app.use(express.session({secret: 'oi09ajsdf09fwlkej33lkjpx'}));
app.use(express.methodOverride())
app.use(function(err, req, res, next) {
res.send({ error: err });
});
}
return { configure: configure }
})()
| express = require('express')
expressValidator = require('express-validator')
module.exports = (function(){
function configure(app) {
app.set('port', process.env.PORT || 3000);
app.set('host', process.env.HOST || '127.0.0.1')
app.use(express.static(__dirname + '/public'));
app.use(function(req,res,next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
})
app.use(express.bodyParser())
app.use(expressValidator());
app.use(express.cookieParser());
app.use(express.session({secret: 'oi09ajsdf09fwlkej33lkjpx'}));
app.use(express.methodOverride())
app.use(function(err, req, res, next) {
res.send({ error: err });
});
}
return { configure: configure }
})()
| Add access control allow origin middlewar | [FEATURE] Add access control allow origin middlewar
| JavaScript | isc | zealord/gatewayd,crazyquark/gatewayd,xdv/gatewayd,xdv/gatewayd,Parkjeahwan/awegeeks,whotooktwarden/gatewayd,Parkjeahwan/awegeeks,crazyquark/gatewayd,whotooktwarden/gatewayd,zealord/gatewayd | ---
+++
@@ -6,6 +6,10 @@
app.set('port', process.env.PORT || 3000);
app.set('host', process.env.HOST || '127.0.0.1')
app.use(express.static(__dirname + '/public'));
+ app.use(function(req,res,next) {
+ res.header("Access-Control-Allow-Origin", "*");
+ res.header("Access-Control-Allow-Headers", "X-Requested-With");
+ })
app.use(express.bodyParser())
app.use(expressValidator());
app.use(express.cookieParser()); |
5762d478a22bb76807e3b92a3b881c42686b3b69 | lib/replace-prelude.js | lib/replace-prelude.js | 'use strict';
var bpack = require('browser-pack');
var fs = require('fs');
var path = require('path');
var xtend = require('xtend');
var preludePath = path.join(__dirname, 'prelude.js');
var prelude = fs.readFileSync(preludePath, 'utf8');
// This plugin replaces the prelude and adds a transform
var plugin = exports.plugin = function (bfy, opts) {
function replacePrelude() {
var packOpts = {
raw : true, // Added in regular Browserifiy as well
preludePath : preludePath,
prelude : prelude
};
// browserify sets "hasExports" directly on bfy._bpack
bfy._bpack = bpack(xtend(bfy._options, packOpts));
// Replace the 'pack' pipeline step with the new browser-pack instance
bfy.pipeline.splice('pack', 1, bfy._bpack);
}
bfy.transform(require('./transform'));
bfy.on('reset', replacePrelude);
replacePrelude();
};
// Maintain support for the old interface
exports.browserify = function (files) {
console.error('You are setting up proxyquireify via the old API which will be deprecated in future versions.');
console.error('It is recommended to use it as a browserify-plugin instead - see the example in the README.');
return require('browserify')(files).plugin(plugin);
};
| 'use strict';
var bpack = require('browser-pack');
var fs = require('fs');
var path = require('path');
var xtend = require('xtend');
var preludePath = path.join(__dirname, 'prelude.js');
var prelude = fs.readFileSync(preludePath, 'utf8');
// This plugin replaces the prelude and adds a transform
var plugin = exports.plugin = function (bfy, opts) {
function replacePrelude() {
var packOpts = {
raw : true, // Added in regular Browserifiy as well
preludePath : preludePath,
prelude : prelude
};
// browserify sets "hasExports" directly on bfy._bpack
bfy._bpack = bpack(xtend(bfy._options, packOpts, {hasExports: bfy._bpack.hasExports}));
// Replace the 'pack' pipeline step with the new browser-pack instance
bfy.pipeline.splice('pack', 1, bfy._bpack);
}
bfy.transform(require('./transform'));
bfy.on('reset', replacePrelude);
replacePrelude();
};
// Maintain support for the old interface
exports.browserify = function (files) {
console.error('You are setting up proxyquireify via the old API which will be deprecated in future versions.');
console.error('It is recommended to use it as a browserify-plugin instead - see the example in the README.');
return require('browserify')(files).plugin(plugin);
};
| Copy `hasExports` setting from bpack when bundle is reset | Copy `hasExports` setting from bpack when bundle is reset
Browserify copies this setting manually in b.reset:
https://github.com/substack/node-browserify/blob/a18657c6f363272ce3c7722528c8ec5f325d0eaf/index.js#L732
Since we replace the bpack instance the `hasExports` value has to be
manually copied from the default bpack
Closes bendrucker/proxyquire-universal#7
@thlorenz this should be released as a patch when you have a chance
| JavaScript | mit | royriojas/browsyquire,royriojas/proxyquireify,royriojas/browsyquire,royriojas/proxyquireify,thlorenz/proxyquireify | ---
+++
@@ -18,7 +18,7 @@
};
// browserify sets "hasExports" directly on bfy._bpack
- bfy._bpack = bpack(xtend(bfy._options, packOpts));
+ bfy._bpack = bpack(xtend(bfy._options, packOpts, {hasExports: bfy._bpack.hasExports}));
// Replace the 'pack' pipeline step with the new browser-pack instance
bfy.pipeline.splice('pack', 1, bfy._bpack);
} |
10f4293f4ac9ec29d80ddcaaae9cf31f1b054fed | tests/test-load-ok.js | tests/test-load-ok.js | /**
* Jasmine test to check success callback
*/
describe('stan-loader-ok', function() {
// Declare status var
var status;
// Activate async
beforeEach(function(done) {
// Initiate $STAN loader using normal window load events
$STAN_Load([
'//code.jquery.com/jquery-1.10.1.min.js',
'//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js'
], function() {
status = 'ok';
done();
}, function() {
status = 'error';
done();
});
});
// Perform tests
it("JS libs loaded in to the DOM", function() {
// Check status has been set to ok
expect(status).toBe('ok');
// Check jQuery is loaded
expect($).toBeDefined();
// Check bootstrap is loaded
expect($().tab()).toBeDefined();
});
});
| /**
* Jasmine test to check success callback
*/
describe('stan-loader-ok', function() {
// Declare status var
var status;
// Activate async
beforeEach(function(done) {
// Initiate $STAN loader using normal window load events
$STAN_Load([
'//code.jquery.com/jquery-1.11.2.min.js',
'//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js'
], function() {
status = 'ok';
done();
}, function() {
status = 'error';
done();
});
});
// Perform tests
it("JS libs loaded in to the DOM", function() {
// Check status has been set to ok
expect(status).toBe('ok');
// Check jQuery is loaded
expect($).toBeDefined();
// Check bootstrap is loaded
expect($().tab()).toBeDefined();
});
});
| Update jQuery and BS to latest version for tests | Update jQuery and BS to latest version for tests
| JavaScript | apache-2.0 | awomersley/stan-loader,awomersley/stan-loader | ---
+++
@@ -11,8 +11,8 @@
// Initiate $STAN loader using normal window load events
$STAN_Load([
- '//code.jquery.com/jquery-1.10.1.min.js',
- '//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js'
+ '//code.jquery.com/jquery-1.11.2.min.js',
+ '//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js'
], function() {
status = 'ok';
done(); |
b1aaf8485740f65770acb7b9a20ca9e35c37b9ad | lib/htmlfile.js | lib/htmlfile.js | module.exports = HtmlFile;
function HtmlFile(path) {
this.path = path;
}
HtmlFile.prototype.querySelectorAll = function(ph, style, cb) {
var _this = this;
return new Promise(function(resolve) {
ph.createPage(function(page) {
page.open(_this.path, function() {
page.evaluate((function() {
return 'function() { return document.querySelectorAll("' + style + '"); }';
}()), function(value) {
cb(value);
resolve();
});
});
});
});
};
| module.exports = HtmlFile;
function HtmlFile(path) {
this.path = path;
}
HtmlFile.prototype.querySelectorAll = function(ph, style, cb) {
var _this = this;
return new Promise(function(resolve) {
ph.createPage(function(page) {
page.open(_this.path, function() {
var func = 'function() { return document.querySelectorAll("' + style + '"); }';
page.evaluate(func, function(value) {
cb(value);
resolve();
});
});
});
});
};
| Fix "Wrap only the function expression in parens" | Fix "Wrap only the function expression in parens"
| JavaScript | mit | sinsoku/clairvoyance,sinsoku/clairvoyance | ---
+++
@@ -9,9 +9,8 @@
return new Promise(function(resolve) {
ph.createPage(function(page) {
page.open(_this.path, function() {
- page.evaluate((function() {
- return 'function() { return document.querySelectorAll("' + style + '"); }';
- }()), function(value) {
+ var func = 'function() { return document.querySelectorAll("' + style + '"); }';
+ page.evaluate(func, function(value) {
cb(value);
resolve();
}); |
41de713c677477bae0548bd9b17c5edb100bc53b | aura-components/src/main/components/ui/abstractList/abstractListRenderer.js | aura-components/src/main/components/ui/abstractList/abstractListRenderer.js | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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.
*/
({
/*
* These helper methods are in the renderer due to the many ways
* that abstractList can be implemented. Since controller methods
* can be overridden, and component creation can be dynamic, putting
* the relevant helper method call in the renderer ensures that the
* emptyListContent is handled no matter how the list is implemented.
*/
afterRender : function(component, helper){
this.superAfterRender();
helper.updateEmptyListContent(component);
},
rerender : function(component){
this.superRerender();
var concreteCmp = component.getConcreteComponent();
if (concreteCmp.isDirty('v.items')) {
concreteCmp.getDef().getHelper().updateEmptyListContent(component);
}
}
})// eslint-disable-line semi
| /*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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.
*/
({
/*
* These helper methods are in the renderer due to the many ways
* that abstractList can be implemented. Since controller methods
* can be overridden, and component creation can be dynamic, putting
* the relevant helper method call in the renderer ensures that the
* emptyListContent is handled no matter how the list is implemented.
*/
afterRender : function(component, helper){
this.superAfterRender();
helper.updateEmptyListContent(component);
},
rerender : function(component, helper){
this.superRerender();
if (component.getConcreteComponent().isDirty('v.items')) {
helper.updateEmptyListContent(component);
}
}
})// eslint-disable-line semi
| Revert "Make renderer polymorphically call updateEmptyListContent" | Revert "Make renderer polymorphically call updateEmptyListContent"
This reverts commit ff82e198ca173fdbb5837982c3795af1dec3a15d.
| JavaScript | apache-2.0 | forcedotcom/aura,madmax983/aura,forcedotcom/aura,madmax983/aura,forcedotcom/aura,madmax983/aura,madmax983/aura,forcedotcom/aura,forcedotcom/aura,madmax983/aura,madmax983/aura | ---
+++
@@ -25,11 +25,10 @@
this.superAfterRender();
helper.updateEmptyListContent(component);
},
- rerender : function(component){
+ rerender : function(component, helper){
this.superRerender();
- var concreteCmp = component.getConcreteComponent();
- if (concreteCmp.isDirty('v.items')) {
- concreteCmp.getDef().getHelper().updateEmptyListContent(component);
+ if (component.getConcreteComponent().isDirty('v.items')) {
+ helper.updateEmptyListContent(component);
}
}
})// eslint-disable-line semi |
ce52b37873c55045b97c4288e9d6b8dfdd3a03f8 | test/testCacheAllTheThings.js | test/testCacheAllTheThings.js | var Assert = require('assert');
var CacheAllTheThings = require('../');
describe('CacheAllTheThings', function() {
it('When asked to boot a Redis instance, it should do so', function() {
var inst = new CacheAllTheThings('redis');
Assert(inst.name, 'RedisCache');
});
}); | var Assert = require('assert');
var CacheAllTheThings = require('../');
describe('CacheAllTheThings', function() {
it('When asked to boot a Redis instance, it should do so', function() {
var inst = new CacheAllTheThings('redis');
Assert(inst.name, 'RedisCache');
});
describe('Redis', function() {
it('Should set a key', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.set('lol', 'hai')
.then(function(e) {
Assert.equal(e, null);
done();
});
});
it('Should get a key that exists', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.get('lol')
.then(function(val) {
Assert(val, 'hai');
done();
}, function(e) {
Assert.notEqual(e, null);
done();
});
});
it('Should get a key that does not exist', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.get('lols')
.then(function(val) {
Assert(true);
done();
}, function(e) {
Assert.notEqual(e, null);
done();
});
});
});
}); | Add more tests to set and get values from Redis | Add more tests to set and get values from Redis
| JavaScript | mit | andrewhathaway/CacheAllTheThings,andrewhathaway/CacheAllTheThings | ---
+++
@@ -8,4 +8,47 @@
Assert(inst.name, 'RedisCache');
});
+ describe('Redis', function() {
+
+ it('Should set a key', function(done) {
+ var redisInst = new CacheAllTheThings('redis');
+
+ redisInst
+ .set('lol', 'hai')
+ .then(function(e) {
+ Assert.equal(e, null);
+ done();
+ });
+ });
+
+ it('Should get a key that exists', function(done) {
+ var redisInst = new CacheAllTheThings('redis');
+
+ redisInst
+ .get('lol')
+ .then(function(val) {
+ Assert(val, 'hai');
+ done();
+ }, function(e) {
+ Assert.notEqual(e, null);
+ done();
+ });
+ });
+
+ it('Should get a key that does not exist', function(done) {
+ var redisInst = new CacheAllTheThings('redis');
+
+ redisInst
+ .get('lols')
+ .then(function(val) {
+ Assert(true);
+ done();
+ }, function(e) {
+ Assert.notEqual(e, null);
+ done();
+ });
+ });
+
+ });
+
}); |
687b8066a908dc6a9bbd4c184e143981dec5493a | src/features/header/header-main/styled-components/Wrapper.js | src/features/header/header-main/styled-components/Wrapper.js | //@flow
import styled, { css } from "styled-components";
export const Wrapper = styled.div`
${({ theme }: { theme: Theme }) => css`
box-sizing: border-box;
position: relative;
width: 100%;
background-color: ${theme.color.background};
padding-top: ${theme.scale.s4(-1)};
@media (min-width: 675px) {
padding-top: 0;
}
`}
`;
| //@flow
import styled, { css } from "styled-components";
export const Wrapper = styled.div`
${({ theme }: { theme: Theme }) => css`
box-sizing: border-box;
position: relative;
width: 100%;
background-color: ${theme.color.background};
`}
`;
| Remove media query that accounds for status bar | Remove media query that accounds for status bar
Testing if the necessary space will be added by the mobile browser automatically
TODO: verify no additional padding required. | JavaScript | mit | slightly-askew/portfolio-2017,slightly-askew/portfolio-2017 | ---
+++
@@ -10,10 +10,6 @@
position: relative;
width: 100%;
background-color: ${theme.color.background};
- padding-top: ${theme.scale.s4(-1)};
-
- @media (min-width: 675px) {
- padding-top: 0;
- }
+
`}
`; |
4b14f7745c20c489cb8ee554ee98fbcde2058832 | backend/servers/mcapid/initializers/api.js | backend/servers/mcapid/initializers/api.js | const {Initializer, api} = require('actionhero');
const r = require('@lib/r');
module.exports = class ApiInitializer extends Initializer {
constructor() {
super();
this.name = 'api-initializer';
}
initialize() {
api.mc = {
r: r,
directories: require('@dal/directories')(r),
projects: require('@dal/projects')(r),
datasets: require('@dal/datasets')(r),
check: require('@dal/check')(r),
processes: require('@dal/processes')(r),
publishedDatasets: require('@dal/published-datasets')(r),
samples: require('@dal/samples')(r),
templates: require('@dal/templates')(r),
files: require('@dal/files')(r),
};
}
}; | const {Initializer, api} = require('actionhero');
const r = require('@lib/r');
module.exports = class ApiInitializer extends Initializer {
constructor() {
super();
this.name = 'api-initializer';
}
initialize() {
api.mc = {
r: r,
directories: require('@dal/directories')(r),
projects: require('@dal/projects')(r),
datasets: require('@dal/datasets')(r),
check: require('@dal/check')(r),
processes: require('@dal/processes')(r),
publishedDatasets: require('@dal/published-datasets')(r),
samples: require('@dal/samples')(r),
templates: require('@dal/templates')(r),
files: require('@dal/files')(r),
log: {
debug: (msg, params) => api.log(msg, 'debug', params),
info: (msg, params) => api.log(msg, 'info', params),
notice: (msg, params) => api.log(msg, 'notice', params),
warning: (msg, params) => api.log(msg, 'warning', params),
error: (msg, params) => api.log(msg, 'error', params),
critical: (msg, params) => api.log(msg, 'crit', params),
alert: (msg, params) => api.log(msg, 'alert', params),
emergency: (msg, params) => api.log(msg, 'emerg', params),
}
};
}
}; | Add log shortcuts instead of having to specify the log level if a parameter is added | Add log shortcuts instead of having to specify the log level if a parameter is added
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -19,6 +19,16 @@
samples: require('@dal/samples')(r),
templates: require('@dal/templates')(r),
files: require('@dal/files')(r),
+ log: {
+ debug: (msg, params) => api.log(msg, 'debug', params),
+ info: (msg, params) => api.log(msg, 'info', params),
+ notice: (msg, params) => api.log(msg, 'notice', params),
+ warning: (msg, params) => api.log(msg, 'warning', params),
+ error: (msg, params) => api.log(msg, 'error', params),
+ critical: (msg, params) => api.log(msg, 'crit', params),
+ alert: (msg, params) => api.log(msg, 'alert', params),
+ emergency: (msg, params) => api.log(msg, 'emerg', params),
+ }
};
}
}; |
7af9ca83021937683ab538c355b1e6a1a2c8cd8d | src/renderer/scr.state.js | src/renderer/scr.state.js | var STATE = (function(){
var FILE;
var MSGS;
var selectedChannel;
return {
uploadFile: function(file){
FILE = file;
MSGS = null;
},
getChannelList: function(){
var channels = FILE.getChannels();
return Object.keys(channels).map(key => ({ // reserve.txt
id: key,
name: channels[key].name,
server: FILE.getServer(channels[key].server),
msgcount: FILE.getMessageCount(key)
}));
},
getChannelName: function(channel){
return FILE.getChannelById(channel).name;
},
getUserName: function(user){
return FILE.getUserById(user).name;
},
selectChannel: function(channel){
selectedChannel = channel;
MSGS = Object.keys(FILE.getMessages(channel)).sort();
},
getMessageList: function(startIndex, count){
if (!MSGS){
return [];
}
var messages = FILE.getMessages(selectedChannel);
return MSGS.slice(startIndex, !count ? undefined : startIndex+count).map(key => {
var message = messages[key];
return { // reserve.txt
user: FILE.getUser(message.u),
timestamp: message.t,
contents: message.m
};
});
},
getMessageCount: function(){
return MSGS ? MSGS.length : 0;
}
};
})();
| var STATE = (function(){
var FILE;
var MSGS;
var selectedChannel;
return {
uploadFile: function(file){
FILE = file;
MSGS = null;
},
getChannelList: function(){
var channels = FILE.getChannels();
return Object.keys(channels).map(key => ({ // reserve.txt
id: key,
name: channels[key].name,
server: FILE.getServer(channels[key].server),
msgcount: FILE.getMessageCount(key)
}));
},
getChannelName: function(channel){
return FILE.getChannelById(channel).name;
},
getUserName: function(user){
return FILE.getUserById(user).name;
},
selectChannel: function(channel){
selectedChannel = channel;
MSGS = Object.keys(FILE.getMessages(channel)).sort((key1, key2) => {
if (key1.length === key2.length){
return key1 > key2 ? 1 : key1 < key2 ? -1 : 0;
}
else{
return key1.length > key2.length ? 1 : -1;
}
});
},
getMessageList: function(startIndex, count){
if (!MSGS){
return [];
}
var messages = FILE.getMessages(selectedChannel);
return MSGS.slice(startIndex, !count ? undefined : startIndex+count).map(key => {
var message = messages[key];
return { // reserve.txt
user: FILE.getUser(message.u),
timestamp: message.t,
contents: message.m
};
});
},
getMessageCount: function(){
return MSGS ? MSGS.length : 0;
}
};
})();
| Fix message sorting in renderer having issues with varying message key lengths | Fix message sorting in renderer having issues with varying message key lengths
| JavaScript | mit | chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker | ---
+++
@@ -31,7 +31,15 @@
selectChannel: function(channel){
selectedChannel = channel;
- MSGS = Object.keys(FILE.getMessages(channel)).sort();
+
+ MSGS = Object.keys(FILE.getMessages(channel)).sort((key1, key2) => {
+ if (key1.length === key2.length){
+ return key1 > key2 ? 1 : key1 < key2 ? -1 : 0;
+ }
+ else{
+ return key1.length > key2.length ? 1 : -1;
+ }
+ });
},
getMessageList: function(startIndex, count){ |
f9de0a7b6535fe2a3129db0a886f6f9cae8d2930 | tools/tests/dynamic-import.js | tools/tests/dynamic-import.js | var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("dynamic import(...) in development", function () {
const s = new Sandbox();
s.createApp("dynamic-import-test-app-devel", "dynamic-import");
s.cd("dynamic-import-test-app-devel", run.bind(s, false));
});
selftest.define("dynamic import(...) in production", function () {
const s = new Sandbox();
s.createApp("dynamic-import-test-app-prod", "dynamic-import");
s.cd("dynamic-import-test-app-prod", run.bind(s, true));
});
function run(prod) {
const sandbox = this;
const args = [
"test",
"--once",
"--full-app",
"--driver-package", "dispatch:mocha-phantomjs"
];
if (prod) {
args.push("--production");
}
const run = sandbox.run(...args);
run.waitSecs(60);
run.match("App running at");
run.match("SERVER FAILURES: 0");
run.match("CLIENT FAILURES: 0");
run.expectExit(0);
}
| var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("dynamic import(...) in development", function () {
const s = new Sandbox();
s.createApp("dynamic-import-test-app-devel", "dynamic-import");
s.cd("dynamic-import-test-app-devel", run.bind(s, false));
});
selftest.define("dynamic import(...) in production", function () {
const s = new Sandbox();
s.createApp("dynamic-import-test-app-prod", "dynamic-import");
s.cd("dynamic-import-test-app-prod", run.bind(s, true));
});
function run(isProduction) {
const sandbox = this;
const args = [
"test",
"--once",
"--full-app",
"--driver-package", "dispatch:mocha-phantomjs"
];
if (isProduction) {
sandbox.set("NODE_ENV", "production");
args.push("--production");
} else {
sandbox.set("NODE_ENV", "development");
}
const run = sandbox.run(...args);
run.waitSecs(60);
run.match("App running at");
run.match("SERVER FAILURES: 0");
run.match("CLIENT FAILURES: 0");
run.expectExit(0);
}
| Use NODE_ENV (with --production) to run production import(...) tests. | Use NODE_ENV (with --production) to run production import(...) tests.
| JavaScript | mit | Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor | ---
+++
@@ -13,7 +13,7 @@
s.cd("dynamic-import-test-app-prod", run.bind(s, true));
});
-function run(prod) {
+function run(isProduction) {
const sandbox = this;
const args = [
"test",
@@ -22,8 +22,11 @@
"--driver-package", "dispatch:mocha-phantomjs"
];
- if (prod) {
+ if (isProduction) {
+ sandbox.set("NODE_ENV", "production");
args.push("--production");
+ } else {
+ sandbox.set("NODE_ENV", "development");
}
const run = sandbox.run(...args); |
ceb264e849abfddfb250de15c78b78007287d83e | gulp/tasks/uploading.js | gulp/tasks/uploading.js | 'use strict';
const fs = require('fs');
const gulp = require('gulp');
const rsync = require('gulp-rsync');
// 'gulp deploy' -- reads rsync credentials file and incrementally uploads site to server
gulp.task('upload', () => {
var credentials = JSON.parse(fs.readFileSync('rsync-credentials.json', 'utf8'));
return gulp.src('dist')
.pipe(rsync({
// dryrun: true
root: 'dist/',
hostname: credentials.hostname,
username: credentials.username,
destination: credentials.destination,
incremental: true,
recursive: true,
compress: true,
progress: true,
clean: true,
chmod: "Du=rwx,Dgo=rx,Fu=rw,Fgo=r",
}));
});
| 'use strict';
const fs = require('fs');
const gulp = require('gulp');
const rsync = require('gulp-rsync');
// 'gulp deploy' -- reads rsync credentials file and incrementally uploads site to server
gulp.task('upload', () => {
var credentials = JSON.parse(fs.readFileSync('rsync-credentials.json', 'utf8'));
return gulp.src('dist')
.pipe(rsync({
// dryrun: true
root: 'dist/',
hostname: credentials.hostname,
username: credentials.username,
destination: credentials.destination,
incremental: true,
recursive: true,
compress: true,
clean: true,
chmod: "Du=rwx,Dgo=rx,Fu=rw,Fgo=r",
}));
});
| Disable duplicate Rsync progress output | Disable duplicate Rsync progress output
| JavaScript | mit | blogtips/blogtips.github.io,mmistakes/made-mistakes-jekyll,mmistakes/made-mistakes-jekyll,blogtips/blogtips.github.io,mmistakes/made-mistakes-jekyll,blogtips/blogtips.github.io | ---
+++
@@ -17,7 +17,6 @@
incremental: true,
recursive: true,
compress: true,
- progress: true,
clean: true,
chmod: "Du=rwx,Dgo=rx,Fu=rw,Fgo=r",
})); |
f157ca1c747d48ba416ec2896d2153c25ce2a8a8 | app/components/liquid-child.js | app/components/liquid-child.js | import Ember from "ember";
export default Ember.Component.extend({
classNames: ['liquid-child'],
attributeBindings: ['style'],
style: Ember.computed('visible', function() {
return new Ember.Handlebars.SafeString(this.get('visible') ? '' : 'visibility:hidden');
}),
tellContainerWeRendered: Ember.on('didInsertElement', function(){
this.sendAction('didRender', this);
})
});
| import Ember from "ember";
export default Ember.Component.extend({
classNames: ['liquid-child'],
updateElementVisibility: function() {
let visible = this.get('visible');
let $container = this.$();
if ($container && $container.length) {
$container.css('visibility', visible ? 'visible' : 'hidden');
}
}.on('willInsertElement').observes('visible'),
tellContainerWeRendered: Ember.on('didInsertElement', function(){
this.sendAction('didRender', this);
})
});
| Switch inline style attribute binding to jQuery CSS DOM Manip for CSP | Switch inline style attribute binding to jQuery CSS DOM Manip for CSP
| JavaScript | mit | ember-animation/liquid-fire-core,byelipk/liquid-fire,davewasmer/liquid-fire,ianstarz/liquid-fire,envoy/liquid-fire,csantero/liquid-fire,ember-animation/liquid-fire-velocity,ember-animation/ember-animated,jamesreggio/liquid-fire,ember-animation/liquid-fire-velocity,jayphelps/liquid-fire,acorncom/liquid-fire,chadhietala/liquid-fire,monegraph/liquid-fire,acorncom/liquid-fire,knownasilya/liquid-fire,jrjohnson/liquid-fire,runspired/liquid-fire,ember-animation/liquid-fire-core,dsokolowski/liquid-fire,twokul/liquid-fire,ember-animation/ember-animated,monegraph/liquid-fire,mikegrassotti/liquid-fire,gordonbisnor/liquid-fire,topaxi/liquid-fire,ianstarz/liquid-fire,davidgoli/liquid-fire,ember-animation/liquid-fire,gordonbisnor/liquid-fire,twokul/liquid-fire,chadhietala/liquid-fire,givanse/liquid-fire,dsokolowski/liquid-fire,davidgoli/liquid-fire,jamesreggio/liquid-fire,jayphelps/liquid-fire,jrjohnson/liquid-fire,knownasilya/liquid-fire,topaxi/liquid-fire,givanse/liquid-fire,mikegrassotti/liquid-fire,ember-animation/ember-animated,ef4/liquid-fire,byelipk/liquid-fire,davewasmer/liquid-fire,ember-animation/liquid-fire,runspired/liquid-fire,ef4/liquid-fire,csantero/liquid-fire | ---
+++
@@ -1,10 +1,16 @@
import Ember from "ember";
export default Ember.Component.extend({
classNames: ['liquid-child'],
- attributeBindings: ['style'],
- style: Ember.computed('visible', function() {
- return new Ember.Handlebars.SafeString(this.get('visible') ? '' : 'visibility:hidden');
- }),
+
+ updateElementVisibility: function() {
+ let visible = this.get('visible');
+ let $container = this.$();
+
+ if ($container && $container.length) {
+ $container.css('visibility', visible ? 'visible' : 'hidden');
+ }
+ }.on('willInsertElement').observes('visible'),
+
tellContainerWeRendered: Ember.on('didInsertElement', function(){
this.sendAction('didRender', this);
}) |
259d0c00fefb67aeded6f1f1831fbc6784d9fb2a | tests/dummy/app/components/trigger-with-did-receive-attrs.js | tests/dummy/app/components/trigger-with-did-receive-attrs.js | import Trigger from 'ember-basic-dropdown/components/basic-dropdown/trigger';
export default Trigger.extend({
didOpen: false,
didReceiveAttrs() {
let dropdown = this.get('dropdown');
let oldDropdown = this.get('oldDropdown');
if ((oldDropdown && oldDropdown.isOpen) === false && dropdown.isOpen) {
this.set('didOpen', true);
}
this.set('oldDropdown', dropdown);
}
}); | import Trigger from 'ember-basic-dropdown/components/basic-dropdown/trigger';
export default Trigger.extend({
didOpen: false,
didReceiveAttrs() {
let dropdown = this.get('dropdown');
let oldDropdown = this.get('oldDropdown');
if ((oldDropdown && oldDropdown.isOpen) === false && dropdown.isOpen) {
this.set('didOpen', true);
}
this.set('oldDropdown', dropdown);
}
});
| Transform all tests for the trigger | Transform all tests for the trigger
| JavaScript | mit | cibernox/ember-basic-dropdown,cibernox/ember-basic-dropdown,cibernox/ember-basic-dropdown,cibernox/ember-basic-dropdown | |
717722bb2a343c00fa00980fcee67717279b6264 | bids-validator/validators/tsv/tsvParser.js | bids-validator/validators/tsv/tsvParser.js | /*
* TSV
* Module for parsing TSV (and eventually other formats)
*/
const trimSplit = separator => str => str.trim().split(separator)
const isContentfulRow = row => row && !/^\s*$/.test(row)
function parseTSV(contents) {
const content = {
headers: [],
rows: [],
}
content.rows = trimSplit('\n')(contents)
.filter(isContentfulRow)
.map(trimSplit('\t'))
content.headers = content.rows.length ? content.rows[0] : []
return content
}
export default parseTSV
| /*
* TSV
* Module for parsing TSV (and eventually other formats)
*/
const normalizeEOL = str => str.replace('\r\n', '\n').replace('\r', '\n')
const isContentfulRow = row => row && !/^\s*$/.test(row)
function parseTSV(contents) {
const content = {
headers: [],
rows: [],
}
content.rows = normalizeEOL(contents)
.split('\n')
.filter(isContentfulRow)
.map(str => str.split('\t'))
content.headers = content.rows.length ? content.rows[0] : []
return content
}
export default parseTSV
| Normalize TSV end-of-line without stripping all whitespace | FIX: Normalize TSV end-of-line without stripping all whitespace
(cherry picked from commit 786cfbb5847f5508720416cc7846fa1fcadc36bc)
| JavaScript | mit | nellh/bids-validator,nellh/bids-validator,Squishymedia/BIDS-Validator,Squishymedia/bids-validator,nellh/bids-validator | ---
+++
@@ -3,7 +3,7 @@
* Module for parsing TSV (and eventually other formats)
*/
-const trimSplit = separator => str => str.trim().split(separator)
+const normalizeEOL = str => str.replace('\r\n', '\n').replace('\r', '\n')
const isContentfulRow = row => row && !/^\s*$/.test(row)
function parseTSV(contents) {
@@ -11,9 +11,10 @@
headers: [],
rows: [],
}
- content.rows = trimSplit('\n')(contents)
+ content.rows = normalizeEOL(contents)
+ .split('\n')
.filter(isContentfulRow)
- .map(trimSplit('\t'))
+ .map(str => str.split('\t'))
content.headers = content.rows.length ? content.rows[0] : []
return content
} |
bf3f03acdfcc7ddb98c820282af6ec5b7ae5c2d9 | server/worker/index.js | server/worker/index.js | /**
* A worker will listen for jobs on the job queue, and execute them.
*/
var async = require('async');
function bootstrapWorker (api, config, next) {
var follower = function (cb) {
api.messaging.listen('seguir-publish-to-followers', function (data, next) {
api.feed.insertFollowersTimeline(data, next);
}, cb);
};
var mentions = function (cb) {
api.messaging.listen('seguir-publish-mentioned', function (data, cb) {
api.feed.insertMentionedTimeline(data, cb);
}, cb);
};
async.series([
follower,
mentions
], function () {
console.log('Seguir worker ready for work ...');
return next && next();
});
}
/* istanbul ignore if */
if (require.main === module) {
var config = require('../config')();
require('../../api')(config, function (err, api) {
if (err) { return process.exit(0); }
bootstrapWorker(api, config);
});
} else {
// Used for testing
module.exports = function (config, next) {
require('../../api')(config, function (err, api) {
if (err) {
return next(new Error('Unable to bootstrap API: ' + err.message));
}
return bootstrapWorker(api, config, next);
});
};
}
| /**
* A worker will listen for jobs on the job queue, and execute them.
*/
var async = require('async');
var restify = require('restify');
var bunyan = require('bunyan');
var logger = bunyan.createLogger({
name: 'seguir',
serializers: restify.bunyan.serializers
});
function bootstrapWorker (api, config, next) {
var follower = function (cb) {
api.messaging.listen('seguir-publish-to-followers', function (data, next) {
logger.debug('Processing publish-to-followers message', data);
api.feed.insertFollowersTimeline(data, next);
}, cb);
};
var mentions = function (cb) {
api.messaging.listen('seguir-publish-mentioned', function (data, cb) {
logger.debug('Processing publish-mentioned message', data);
api.feed.insertMentionedTimeline(data, cb);
}, cb);
};
async.series([
follower,
mentions
], function () {
console.log('Seguir worker ready for work ...');
return next && next();
});
}
/* istanbul ignore if */
if (require.main === module) {
var config = require('../config')();
require('../../api')(config, function (err, api) {
if (err) { return process.exit(0); }
bootstrapWorker(api, config);
});
} else {
// Used for testing
module.exports = function (config, next) {
require('../../api')(config, function (err, api) {
if (err) {
return next(new Error('Unable to bootstrap API: ' + err.message));
}
return bootstrapWorker(api, config, next);
});
};
}
| Add logging to worker process, keep consistent with server logging via bunyan | Add logging to worker process, keep consistent with server logging via bunyan
| JavaScript | mit | tes/seguir,cliftonc/seguir | ---
+++
@@ -2,17 +2,25 @@
* A worker will listen for jobs on the job queue, and execute them.
*/
var async = require('async');
+var restify = require('restify');
+var bunyan = require('bunyan');
+var logger = bunyan.createLogger({
+ name: 'seguir',
+ serializers: restify.bunyan.serializers
+});
function bootstrapWorker (api, config, next) {
var follower = function (cb) {
api.messaging.listen('seguir-publish-to-followers', function (data, next) {
+ logger.debug('Processing publish-to-followers message', data);
api.feed.insertFollowersTimeline(data, next);
}, cb);
};
var mentions = function (cb) {
api.messaging.listen('seguir-publish-mentioned', function (data, cb) {
+ logger.debug('Processing publish-mentioned message', data);
api.feed.insertMentionedTimeline(data, cb);
}, cb);
}; |
7027fa2118cf7efc9dea127b68266b4aa2c6adf7 | app/js/controllers/homepage.js | app/js/controllers/homepage.js | 'use strict';
angular.module('ddsApp').controller('HomepageCtrl', function($scope, $state, droitsDescription, $timeout, ABTestingService, phishingExpressions) {
[ 'prestationsNationales', 'partenairesLocaux' ].forEach(function(type) {
$scope[type] = droitsDescription[type];
$scope[type + 'Count'] = Object.keys(droitsDescription[type]).reduce(function(total, provider) {
return total + Object.keys(droitsDescription[type][provider].prestations).length;
}, 0);
});
ABTestingService.setABTestingEnvironment();
var referrer = document.referrer;
if (referrer.match(/ameli\.fr/)) {
$state.go('ameli');
} else if (_.some(phishingExpressions, function(phishingExpression) { return referrer.match(phishingExpression); })) {
$state.go('hameconnage');
} else {
$timeout(function() {
document.querySelector('#valueProposition a').focus();
}, 1500);
}
});
| 'use strict';
angular.module('ddsApp').controller('HomepageCtrl', function($scope, $state, $sessionStorage, droitsDescription, $timeout, ABTestingService, phishingExpressions) {
[ 'prestationsNationales', 'partenairesLocaux' ].forEach(function(type) {
$scope[type] = droitsDescription[type];
$scope[type + 'Count'] = Object.keys(droitsDescription[type]).reduce(function(total, provider) {
return total + Object.keys(droitsDescription[type][provider].prestations).length;
}, 0);
});
ABTestingService.setABTestingEnvironment();
var referrer = document.referrer;
if (referrer.match(/ameli\.fr/)) {
$state.go('ameli');
} else if (_.some(phishingExpressions, function(phishingExpression) { return referrer.match(phishingExpression); })) {
if (! $sessionStorage.phishingNoticationDone) {
$sessionStorage.phishingNoticationDone = true;
$state.go('hameconnage');
}
} else {
$timeout(function() {
document.querySelector('#valueProposition a').focus();
}, 1500);
}
});
| Allow users from phishing website to continue | Allow users from phishing website to continue
| JavaScript | agpl-3.0 | sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui | ---
+++
@@ -1,6 +1,6 @@
'use strict';
-angular.module('ddsApp').controller('HomepageCtrl', function($scope, $state, droitsDescription, $timeout, ABTestingService, phishingExpressions) {
+angular.module('ddsApp').controller('HomepageCtrl', function($scope, $state, $sessionStorage, droitsDescription, $timeout, ABTestingService, phishingExpressions) {
[ 'prestationsNationales', 'partenairesLocaux' ].forEach(function(type) {
$scope[type] = droitsDescription[type];
@@ -15,7 +15,10 @@
if (referrer.match(/ameli\.fr/)) {
$state.go('ameli');
} else if (_.some(phishingExpressions, function(phishingExpression) { return referrer.match(phishingExpression); })) {
- $state.go('hameconnage');
+ if (! $sessionStorage.phishingNoticationDone) {
+ $sessionStorage.phishingNoticationDone = true;
+ $state.go('hameconnage');
+ }
} else {
$timeout(function() {
document.querySelector('#valueProposition a').focus(); |
0b41586db6bf65a9357093c5a447ea12fab4c4ff | app/client/templates/modals/user_profile_edit/user_profile_edit.js | app/client/templates/modals/user_profile_edit/user_profile_edit.js | /*****************************************************************************/
/* UserProfileEdit: Event Handlers */
/*****************************************************************************/
Template.UserProfileEdit.events({
'click #confirm': function(event) {
event.preventDefault();
var newUsername = $('#new-username').val();
var newFirstName = $('#new-firstname').val();
var newLastname = $('#new-lastname').val();
var newEmail = $('#new-email').val();
var newBio = $('#new-bio').val();
var newPassword = $('#new-password').val();
// Validate username, e-mail and password
// Save new data
if (newFirstName) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.firstName": newFirstName
}
});
}
}
});
/*****************************************************************************/
/* UserProfileEdit: Helpers */
/*****************************************************************************/
Template.UserProfileEdit.helpers({
data: function() {
return this;
}
});
/*****************************************************************************/
/* UserProfileEdit: Lifecycle Hooks */
/*****************************************************************************/
Template.UserProfileEdit.onCreated(function() {});
Template.UserProfileEdit.onRendered(function() {});
Template.UserProfileEdit.onDestroyed(function() {});
| /*****************************************************************************/
/* UserProfileEdit: Event Handlers */
/*****************************************************************************/
Template.UserProfileEdit.events({
'click #confirm': function(event) {
event.preventDefault();
var newUsername = $('#new-username').val();
var newFirstName = $('#new-firstname').val();
var newLastname = $('#new-lastname').val();
var newEmail = $('#new-email').val();
var newBio = $('#new-bio').val();
var newPassword = $('#new-password').val();
// Validate username, e-mail and password
// Save new data
if (newFirstName) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.firstName": newFirstName
}
});
}
if (newLastName) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.lastName": newLastName
}
});
}
if (newBio) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.bio": newBio
}
});
}
}
});
/*****************************************************************************/
/* UserProfileEdit: Helpers */
/*****************************************************************************/
Template.UserProfileEdit.helpers({
data: function() {
return this;
}
});
/*****************************************************************************/
/* UserProfileEdit: Lifecycle Hooks */
/*****************************************************************************/
Template.UserProfileEdit.onCreated(function() {});
Template.UserProfileEdit.onRendered(function() {});
Template.UserProfileEdit.onDestroyed(function() {});
| Improve user edit modal, now it saves the last name and bio | Improve user edit modal, now it saves the last name and bio
| JavaScript | agpl-3.0 | openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign | ---
+++
@@ -23,7 +23,24 @@
"profile.firstName": newFirstName
}
});
-
+ }
+ if (newLastName) {
+ Meteor.users.update({
+ _id: Meteor.userId()
+ }, {
+ $set: {
+ "profile.lastName": newLastName
+ }
+ });
+ }
+ if (newBio) {
+ Meteor.users.update({
+ _id: Meteor.userId()
+ }, {
+ $set: {
+ "profile.bio": newBio
+ }
+ });
}
} |
809b449002671226018fbd2e9d3285e6e7037ea0 | server/index.js | server/index.js | 'use strict';
var http = require('http'),
spotify = require('spotify-node-applescript');
var cb = function(request, response) {
debugger;
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('Hello spotkula servereerer!');
response.end();
};
http.createServer(cb).listen(3000, 'localhost');
| 'use strict';
var http = require('http'),
spotify = require('spotify-node-applescript'),
express = require('express');
var app = express();
app.get('/', function (request, response) {
response.send('ok');
});
app.listen(3000);
console.log("Listening on port 3000");
| Reimplement basic server as express app | Reimplement basic server as express app
| JavaScript | mit | ilkka/spotkula-server | ---
+++
@@ -1,15 +1,15 @@
'use strict';
var http = require('http'),
- spotify = require('spotify-node-applescript');
+ spotify = require('spotify-node-applescript'),
+ express = require('express');
-var cb = function(request, response) {
+var app = express();
- debugger;
+app.get('/', function (request, response) {
+ response.send('ok');
+});
- response.writeHead(200, {'Content-Type': 'text/html'});
- response.write('Hello spotkula servereerer!');
- response.end();
-};
+app.listen(3000);
+console.log("Listening on port 3000");
-http.createServer(cb).listen(3000, 'localhost'); |
2a26cba118a63f53321f9285351fa8a1a9ad9484 | lib/assets/test/spec/new-dashboard/unit/specs/core/metrics.spec.js | lib/assets/test/spec/new-dashboard/unit/specs/core/metrics.spec.js | import * as Metrics from 'new-dashboard/core/metrics';
import store from 'new-dashboard/store';
describe('Internal Metrics Tracker', () => {
describe('sendMetric', () => {
beforeEach(() => {
global.fetch = jest.fn();
});
it('should return call fetch with proper parameters', () => {
const eventName = 'fake_event';
const eventProperties = { page: 'dashboard' };
const baseURL = 'https://user.carto.com';
store.state.config.base_url = baseURL;
Metrics.sendMetric(eventName, eventProperties);
const requestURL = `${baseURL}/api/v3/metrics`;
const requestProperties = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: eventName,
properties: eventProperties
})
};
expect(global.fetch).toHaveBeenCalledWith(
requestURL,
requestProperties
);
});
});
});
| import * as Metrics from 'new-dashboard/core/metrics';
import store from 'new-dashboard/store';
describe('Internal Metrics Tracker', () => {
describe('sendMetric', () => {
let previousState;
beforeEach(() => {
global.fetch = jest.fn();
previousState = {
...store.state,
config: { ...store.state.config },
user: { ...store.state.user }
};
});
afterEach(() => {
store.replaceState(previousState);
});
it('should return call fetch with proper parameters', () => {
const eventName = 'fake_event';
const eventProperties = { page: 'dashboard', user_id: 'fake_id' };
const baseURL = 'https://user.carto.com';
store.state.config.base_url = baseURL;
store.state.user = { id: 'fake_id' };
Metrics.sendMetric(eventName, eventProperties);
const requestURL = `${baseURL}/api/v3/metrics`;
const requestProperties = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: eventName,
properties: eventProperties
})
};
expect(global.fetch).toHaveBeenCalledWith(
requestURL,
requestProperties
);
});
});
});
| Add base url and user id to metrics test | Add base url and user id to metrics test
| JavaScript | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb | ---
+++
@@ -3,15 +3,27 @@
describe('Internal Metrics Tracker', () => {
describe('sendMetric', () => {
+ let previousState;
+
beforeEach(() => {
global.fetch = jest.fn();
+ previousState = {
+ ...store.state,
+ config: { ...store.state.config },
+ user: { ...store.state.user }
+ };
+ });
+
+ afterEach(() => {
+ store.replaceState(previousState);
});
it('should return call fetch with proper parameters', () => {
const eventName = 'fake_event';
- const eventProperties = { page: 'dashboard' };
+ const eventProperties = { page: 'dashboard', user_id: 'fake_id' };
const baseURL = 'https://user.carto.com';
store.state.config.base_url = baseURL;
+ store.state.user = { id: 'fake_id' };
Metrics.sendMetric(eventName, eventProperties);
|
0cebcf119713d523a27fb54fa0bf1f1afe4eb267 | packages/crosswalk/package.js | packages/crosswalk/package.js | Package.describe({
summary: "Makes your Cordova application use the Crosswalk WebView \
instead of the System WebView on Android",
version: '1.4.1-rc.1',
documentation: null
});
Cordova.depends({
'cordova-plugin-crosswalk-webview': '1.4.0'
});
| Package.describe({
summary: "Makes your Cordova application use the Crosswalk WebView \
instead of the System WebView on Android",
version: '1.6.0-rc.1',
documentation: null
});
Cordova.depends({
'cordova-plugin-crosswalk-webview': '1.6.0'
});
| Update Crosswalk plugin to 1.6.0 | Update Crosswalk plugin to 1.6.0
| JavaScript | mit | nuvipannu/meteor,jdivy/meteor,AnthonyAstige/meteor,Hansoft/meteor,AnthonyAstige/meteor,nuvipannu/meteor,nuvipannu/meteor,AnthonyAstige/meteor,DAB0mB/meteor,nuvipannu/meteor,chasertech/meteor,AnthonyAstige/meteor,Hansoft/meteor,DAB0mB/meteor,DAB0mB/meteor,4commerce-technologies-AG/meteor,mjmasn/meteor,mjmasn/meteor,chasertech/meteor,Hansoft/meteor,chasertech/meteor,AnthonyAstige/meteor,lorensr/meteor,nuvipannu/meteor,lorensr/meteor,4commerce-technologies-AG/meteor,4commerce-technologies-AG/meteor,nuvipannu/meteor,Hansoft/meteor,Hansoft/meteor,jdivy/meteor,lorensr/meteor,AnthonyAstige/meteor,DAB0mB/meteor,4commerce-technologies-AG/meteor,DAB0mB/meteor,lorensr/meteor,4commerce-technologies-AG/meteor,lorensr/meteor,chasertech/meteor,DAB0mB/meteor,jdivy/meteor,chasertech/meteor,nuvipannu/meteor,chasertech/meteor,Hansoft/meteor,mjmasn/meteor,chasertech/meteor,lorensr/meteor,mjmasn/meteor,AnthonyAstige/meteor,lorensr/meteor,AnthonyAstige/meteor,mjmasn/meteor,jdivy/meteor,mjmasn/meteor,4commerce-technologies-AG/meteor,Hansoft/meteor,jdivy/meteor,DAB0mB/meteor,jdivy/meteor,jdivy/meteor,4commerce-technologies-AG/meteor,mjmasn/meteor | ---
+++
@@ -1,10 +1,10 @@
Package.describe({
summary: "Makes your Cordova application use the Crosswalk WebView \
instead of the System WebView on Android",
- version: '1.4.1-rc.1',
+ version: '1.6.0-rc.1',
documentation: null
});
Cordova.depends({
- 'cordova-plugin-crosswalk-webview': '1.4.0'
+ 'cordova-plugin-crosswalk-webview': '1.6.0'
}); |
11cec30a94f134f7442867bbbb33fc3490e6a2d2 | src/Section/StatisticsSection/StatisticsSection.js | src/Section/StatisticsSection/StatisticsSection.js | import React from 'react'
import PieChart from '../../Charts/PieChart/PieChart'
import BarChart from '../../Charts/BarChart/BarChart'
import Percent from '../../Statistics/Percent/Percent'
const StatisticsSection = ({metrics}) => {
return (
<div className="ui equal width center aligned stackable grid">
<div className="eight wide column">
<Percent metrics={metrics} label="openness" icon="users" description="Percentage of open source data." />
</div>
<div className="eight wide column">
<Percent metrics={metrics} label="download" icon="download" description="Percentage of successfully downloaded data." />
</div>
<div className="eight wide column">
<PieChart data={metrics.partitions.recordType} />
</div>
<div className="eight wide column">
<BarChart data={metrics.partitions.dataType} />
</div>
</div>
)
}
export default StatisticsSection
| import React from 'react'
import PieChart from '../../Charts/PieChart/PieChart'
import BarChart from '../../Charts/BarChart/BarChart'
import Percent from '../../Statistics/Percent/Percent'
const StatisticsSection = ({metrics}) => {
return (
<div className="ui equal width center aligned stackable grid">
<div className="eight wide column">
<Percent metrics={metrics} label="openness" icon="unlock alternate icon" description="Percentage of open source data." />
</div>
<div className="eight wide column">
<Percent metrics={metrics} label="download" icon="download" description="Percentage of successfully downloaded data." />
</div>
<div className="eight wide column">
<PieChart data={metrics.partitions.recordType} />
</div>
<div className="eight wide column">
<BarChart data={metrics.partitions.dataType} />
</div>
</div>
)
}
export default StatisticsSection
| Change openness users icon by unlock icon | Change openness users icon by unlock icon
| JavaScript | mit | sgmap/inspire,sgmap/inspire | ---
+++
@@ -7,7 +7,7 @@
return (
<div className="ui equal width center aligned stackable grid">
<div className="eight wide column">
- <Percent metrics={metrics} label="openness" icon="users" description="Percentage of open source data." />
+ <Percent metrics={metrics} label="openness" icon="unlock alternate icon" description="Percentage of open source data." />
</div>
<div className="eight wide column"> |
6aae6d6b876c88327ce8ef31dbf3dec8eb60d3a4 | src/Data/Ord.js | src/Data/Ord.js | "use strict";
// module Data.Ord
exports.ordArrayImpl = function (f) {
return function (xs) {
return function (ys) {
var i = 0;
var xlen = xs.length;
var ylen = ys.length;
while (i < xlen && i < ylen) {
var x = xs[i];
var y = ys[i];
var o = f(x)(y);
if (o !== 0) {
return o;
}
i++;
}
if (xlen === ylen) {
return 0;
} else if (xlen > ylen) {
return -1;
} else {
return 1;
}
};
};
};
exports.unsafeCompareImpl = function (lt) {
return function (eq) {
return function (gt) {
return function (x) {
return function (y) {
return x < y ? lt : x > y ? gt : eq;
};
};
};
};
};
| "use strict";
// module Data.Ord
exports.ordArrayImpl = function (f) {
return function (xs) {
return function (ys) {
var i = 0;
var xlen = xs.length;
var ylen = ys.length;
while (i < xlen && i < ylen) {
var x = xs[i];
var y = ys[i];
var o = f(x)(y);
if (o !== 0) {
return o;
}
i++;
}
if (xlen === ylen) {
return 0;
} else if (xlen > ylen) {
return -1;
} else {
return 1;
}
};
};
};
| Remove unused (moved) FFI function | Remove unused (moved) FFI function
| JavaScript | bsd-3-clause | purescript/purescript-prelude,hdgarrood/purescript-prelude | ---
+++
@@ -27,15 +27,3 @@
};
};
};
-
-exports.unsafeCompareImpl = function (lt) {
- return function (eq) {
- return function (gt) {
- return function (x) {
- return function (y) {
- return x < y ? lt : x > y ? gt : eq;
- };
- };
- };
- };
-}; |
361524e620348e32061165c02290f04a305cfa76 | draft-js-dnd-plugin/src/blockRendererFn.js | draft-js-dnd-plugin/src/blockRendererFn.js | import {Entity} from 'draft-js';
export default (config) => (contentBlock, getEditorState, updateEditorState) => {
const type = contentBlock.getType();
if (type === 'image') {
const entityKey = contentBlock.getEntityAt(0);
const data = entityKey ? Entity.get(entityKey).data : {};
return {
component: config.Image,
props: {
...data
}
};
}
return undefined;
};
| import {Entity} from 'draft-js';
import removeBlock from './modifiers/removeBlock';
export default (config) => (contentBlock, getEditorState, updateEditorState) => {
const type = contentBlock.getType();
if (type === 'image') {
const entityKey = contentBlock.getEntityAt(0);
const data = entityKey ? Entity.get(entityKey).data : {};
return {
component: config.Image,
props: {
...data,
remove: ()=>updateEditorState(removeBlock(getEditorState(), contentBlock.key))
}
};
}
return undefined;
};
| Allow Image block to access remove method | Allow Image block to access remove method
| JavaScript | mit | dagopert/draft-js-plugins,draft-js-plugins/draft-js-plugins,nikgraf/draft-js-plugin-editor,dagopert/draft-js-plugins,dagopert/draft-js-plugins,draft-js-plugins/draft-js-plugins-v1,nikgraf/draft-js-plugin-editor,draft-js-plugins/draft-js-plugins-v1,draft-js-plugins/draft-js-plugins,koaninc/draft-js-plugins,koaninc/draft-js-plugins,draft-js-plugins/draft-js-plugins,draft-js-plugins/draft-js-plugins,nikgraf/draft-js-plugin-editor | ---
+++
@@ -1,4 +1,5 @@
import {Entity} from 'draft-js';
+import removeBlock from './modifiers/removeBlock';
export default (config) => (contentBlock, getEditorState, updateEditorState) => {
const type = contentBlock.getType();
@@ -8,7 +9,8 @@
return {
component: config.Image,
props: {
- ...data
+ ...data,
+ remove: ()=>updateEditorState(removeBlock(getEditorState(), contentBlock.key))
}
};
} |
3ea31603656b25b7d8a6903f432a4d321067cc8a | packages/autoupdate/package.js | packages/autoupdate/package.js | Package.describe({
summary: "Update the client when new client code is available",
version: '1.1.4'
});
Cordova.depends({
'org.apache.cordova.file': '1.3.2',
'org.apache.cordova.file-transfer': '0.4.8'
});
Package.onUse(function (api) {
api.use('webapp', 'server');
api.use(['tracker', 'retry'], 'client');
api.use(['ddp', 'mongo', 'underscore'], ['client', 'server']);
api.use('tracker', 'client');
api.use('reload', 'client', {weak: true});
api.use(['http', 'random'], 'web.cordova');
api.export('Autoupdate');
api.addFiles('autoupdate_server.js', 'server');
api.addFiles('autoupdate_client.js', 'web.browser');
api.addFiles('autoupdate_cordova.js', 'web.cordova');
});
| Package.describe({
summary: "Update the client when new client code is available",
version: '1.1.4'
});
Cordova.depends({
'org.apache.cordova.file': '1.3.3',
'org.apache.cordova.file-transfer': '0.4.8'
});
Package.onUse(function (api) {
api.use('webapp', 'server');
api.use(['tracker', 'retry'], 'client');
api.use(['ddp', 'mongo', 'underscore'], ['client', 'server']);
api.use('tracker', 'client');
api.use('reload', 'client', {weak: true});
api.use(['http', 'random'], 'web.cordova');
api.export('Autoupdate');
api.addFiles('autoupdate_server.js', 'server');
api.addFiles('autoupdate_client.js', 'web.browser');
api.addFiles('autoupdate_cordova.js', 'web.cordova');
});
| Upgrade the file cordova dependency to 1.3.3 | Upgrade the file cordova dependency to 1.3.3
| JavaScript | mit | pandeysoni/meteor,benstoltz/meteor,benjamn/meteor,kengchau/meteor,tdamsma/meteor,ljack/meteor,justintung/meteor,AnjirHossain/meteor,juansgaitan/meteor,somallg/meteor,DAB0mB/meteor,namho102/meteor,jrudio/meteor,calvintychan/meteor,neotim/meteor,chmac/meteor,evilemon/meteor,brettle/meteor,shmiko/meteor,meteor-velocity/meteor,yonglehou/meteor,johnthepink/meteor,katopz/meteor,Theviajerock/meteor,jirengu/meteor,skarekrow/meteor,cbonami/meteor,framewr/meteor,vacjaliu/meteor,kencheung/meteor,pandeysoni/meteor,saisai/meteor,rozzzly/meteor,AnjirHossain/meteor,TribeMedia/meteor,4commerce-technologies-AG/meteor,yalexx/meteor,shrop/meteor,imanmafi/meteor,daslicht/meteor,ljack/meteor,jirengu/meteor,elkingtonmcb/meteor,HugoRLopes/meteor,arunoda/meteor,dboyliao/meteor,Urigo/meteor,michielvanoeffelen/meteor,D1no/meteor,Quicksteve/meteor,eluck/meteor,paul-barry-kenzan/meteor,shmiko/meteor,zdd910/meteor,modulexcite/meteor,evilemon/meteor,chmac/meteor,skarekrow/meteor,msavin/meteor,michielvanoeffelen/meteor,whip112/meteor,yonas/meteor-freebsd,LWHTarena/meteor,yinhe007/meteor,vacjaliu/meteor,calvintychan/meteor,framewr/meteor,udhayam/meteor,paul-barry-kenzan/meteor,yonas/meteor-freebsd,aramk/meteor,h200863057/meteor,benjamn/meteor,mubassirhayat/meteor,dev-bobsong/meteor,imanmafi/meteor,henrypan/meteor,framewr/meteor,nuvipannu/meteor,framewr/meteor,shrop/meteor,yiliaofan/meteor,joannekoong/meteor,AnthonyAstige/meteor,SeanOceanHu/meteor,modulexcite/meteor,DAB0mB/meteor,Prithvi-A/meteor,chinasb/meteor,daslicht/meteor,whip112/meteor,papimomi/meteor,GrimDerp/meteor,Eynaliyev/meteor,ndarilek/meteor,neotim/meteor,chinasb/meteor,lpinto93/meteor,tdamsma/meteor,katopz/meteor,juansgaitan/meteor,sdeveloper/meteor,brettle/meteor,D1no/meteor,lassombra/meteor,paul-barry-kenzan/meteor,justintung/meteor,JesseQin/meteor,brdtrpp/meteor,brdtrpp/meteor,jenalgit/meteor,stevenliuit/meteor,somallg/meteor,oceanzou123/meteor,benjamn/meteor,justintung/meteor,dfischer/meteor,jrudio/meteor,D1no/meteor,DAB0mB/meteor,4commerce-technologies-AG/meteor,ljack/meteor,calvintychan/meteor,cbonami/meteor,meteor-velocity/meteor,Eynaliyev/meteor,papimomi/meteor,tdamsma/meteor,Quicksteve/meteor,yyx990803/meteor,newswim/meteor,ndarilek/meteor,chinasb/meteor,Hansoft/meteor,esteedqueen/meteor,mjmasn/meteor,imanmafi/meteor,daltonrenaldo/meteor,4commerce-technologies-AG/meteor,skarekrow/meteor,mauricionr/meteor,Eynaliyev/meteor,brdtrpp/meteor,sclausen/meteor,sunny-g/meteor,brettle/meteor,vacjaliu/meteor,nuvipannu/meteor,AnthonyAstige/meteor,kidaa/meteor,GrimDerp/meteor,daltonrenaldo/meteor,udhayam/meteor,esteedqueen/meteor,lassombra/meteor,Puena/meteor,yonas/meteor-freebsd,ndarilek/meteor,SeanOceanHu/meteor,michielvanoeffelen/meteor,skarekrow/meteor,shadedprofit/meteor,AlexR1712/meteor,alexbeletsky/meteor,alexbeletsky/meteor,yanisIk/meteor,oceanzou123/meteor,mjmasn/meteor,newswim/meteor,lpinto93/meteor,iman-mafi/meteor,chiefninew/meteor,cbonami/meteor,DAB0mB/meteor,Hansoft/meteor,HugoRLopes/meteor,ndarilek/meteor,modulexcite/meteor,ashwathgovind/meteor,pandeysoni/meteor,servel333/meteor,lassombra/meteor,cherbst/meteor,benjamn/meteor,oceanzou123/meteor,wmkcc/meteor,karlito40/meteor,meonkeys/meteor,emmerge/meteor,TechplexEngineer/meteor,meonkeys/meteor,Theviajerock/meteor,msavin/meteor,l0rd0fwar/meteor,meteor-velocity/meteor,TechplexEngineer/meteor,IveWong/meteor,msavin/meteor,dboyliao/meteor,kencheung/meteor,alphanso/meteor,shmiko/meteor,jeblister/meteor,yanisIk/meteor,youprofit/meteor,imanmafi/meteor,lawrenceAIO/meteor,yalexx/meteor,tdamsma/meteor,ashwathgovind/meteor,kencheung/meteor,shadedprofit/meteor,alphanso/meteor,chasertech/meteor,eluck/meteor,neotim/meteor,brettle/meteor,yyx990803/meteor,aldeed/meteor,saisai/meteor,evilemon/meteor,yanisIk/meteor,shrop/meteor,Eynaliyev/meteor,chasertech/meteor,yalexx/meteor,akintoey/meteor,saisai/meteor,PatrickMcGuinness/meteor,newswim/meteor,alphanso/meteor,bhargav175/meteor,servel333/meteor,ashwathgovind/meteor,lawrenceAIO/meteor,Jeremy017/meteor,aldeed/meteor,h200863057/meteor,IveWong/meteor,eluck/meteor,namho102/meteor,judsonbsilva/meteor,zdd910/meteor,bhargav175/meteor,chiefninew/meteor,brdtrpp/meteor,williambr/meteor,Quicksteve/meteor,JesseQin/meteor,dboyliao/meteor,judsonbsilva/meteor,sdeveloper/meteor,namho102/meteor,cherbst/meteor,IveWong/meteor,vacjaliu/meteor,modulexcite/meteor,jirengu/meteor,karlito40/meteor,codingang/meteor,pjump/meteor,devgrok/meteor,lawrenceAIO/meteor,emmerge/meteor,karlito40/meteor,meonkeys/meteor,lieuwex/meteor,mjmasn/meteor,brdtrpp/meteor,Quicksteve/meteor,elkingtonmcb/meteor,pjump/meteor,yanisIk/meteor,dandv/meteor,chinasb/meteor,meonkeys/meteor,cbonami/meteor,yonglehou/meteor,yonas/meteor-freebsd,yalexx/meteor,Profab/meteor,Paulyoufu/meteor-1,Prithvi-A/meteor,D1no/meteor,codingang/meteor,AnjirHossain/meteor,vjau/meteor,aramk/meteor,PatrickMcGuinness/meteor,bhargav175/meteor,oceanzou123/meteor,mjmasn/meteor,allanalexandre/meteor,fashionsun/meteor,calvintychan/meteor,kencheung/meteor,papimomi/meteor,sitexa/meteor,mubassirhayat/meteor,allanalexandre/meteor,mubassirhayat/meteor,katopz/meteor,IveWong/meteor,jirengu/meteor,sdeveloper/meteor,papimomi/meteor,vjau/meteor,AnthonyAstige/meteor,chiefninew/meteor,guazipi/meteor,Eynaliyev/meteor,framewr/meteor,shmiko/meteor,calvintychan/meteor,Puena/meteor,eluck/meteor,eluck/meteor,rabbyalone/meteor,Hansoft/meteor,ljack/meteor,yinhe007/meteor,rozzzly/meteor,jdivy/meteor,sdeveloper/meteor,evilemon/meteor,lorensr/meteor,iman-mafi/meteor,paul-barry-kenzan/meteor,jagi/meteor,queso/meteor,JesseQin/meteor,luohuazju/meteor,williambr/meteor,codedogfish/meteor,ljack/meteor,baysao/meteor,Eynaliyev/meteor,luohuazju/meteor,stevenliuit/meteor,alphanso/meteor,TribeMedia/meteor,queso/meteor,alphanso/meteor,rabbyalone/meteor,cog-64/meteor,luohuazju/meteor,mirstan/meteor,shrop/meteor,williambr/meteor,fashionsun/meteor,LWHTarena/meteor,yanisIk/meteor,benjamn/meteor,lieuwex/meteor,ericterpstra/meteor,Prithvi-A/meteor,papimomi/meteor,PatrickMcGuinness/meteor,PatrickMcGuinness/meteor,colinligertwood/meteor,dev-bobsong/meteor,brettle/meteor,eluck/meteor,shadedprofit/meteor,yiliaofan/meteor,shmiko/meteor,lawrenceAIO/meteor,Profab/meteor,shmiko/meteor,jdivy/meteor,whip112/meteor,chmac/meteor,codingang/meteor,pandeysoni/meteor,mauricionr/meteor,esteedqueen/meteor,nuvipannu/meteor,fashionsun/meteor,mirstan/meteor,wmkcc/meteor,fashionsun/meteor,qscripter/meteor,arunoda/meteor,shrop/meteor,elkingtonmcb/meteor,codedogfish/meteor,Quicksteve/meteor,katopz/meteor,lorensr/meteor,karlito40/meteor,henrypan/meteor,TechplexEngineer/meteor,steedos/meteor,mubassirhayat/meteor,yyx990803/meteor,zdd910/meteor,chiefninew/meteor,michielvanoeffelen/meteor,nuvipannu/meteor,yonglehou/meteor,guazipi/meteor,sclausen/meteor,oceanzou123/meteor,mauricionr/meteor,emmerge/meteor,newswim/meteor,Theviajerock/meteor,servel333/meteor,steedos/meteor,akintoey/meteor,AnjirHossain/meteor,yonglehou/meteor,meonkeys/meteor,sdeveloper/meteor,HugoRLopes/meteor,lieuwex/meteor,qscripter/meteor,cherbst/meteor,mauricionr/meteor,papimomi/meteor,karlito40/meteor,Jeremy017/meteor,framewr/meteor,vacjaliu/meteor,rozzzly/meteor,vacjaliu/meteor,wmkcc/meteor,EduShareOntario/meteor,alexbeletsky/meteor,AnthonyAstige/meteor,Puena/meteor,jenalgit/meteor,akintoey/meteor,dfischer/meteor,udhayam/meteor,cherbst/meteor,lassombra/meteor,esteedqueen/meteor,modulexcite/meteor,jdivy/meteor,henrypan/meteor,colinligertwood/meteor,baiyunping333/meteor,Urigo/meteor,mauricionr/meteor,AnthonyAstige/meteor,jagi/meteor,youprofit/meteor,aramk/meteor,allanalexandre/meteor,namho102/meteor,juansgaitan/meteor,joannekoong/meteor,mauricionr/meteor,karlito40/meteor,youprofit/meteor,Puena/meteor,DCKT/meteor,Theviajerock/meteor,hristaki/meteor,Jonekee/meteor,jeblister/meteor,whip112/meteor,dfischer/meteor,chiefninew/meteor,lieuwex/meteor,EduShareOntario/meteor,elkingtonmcb/meteor,jenalgit/meteor,Ken-Liu/meteor,Paulyoufu/meteor-1,4commerce-technologies-AG/meteor,wmkcc/meteor,tdamsma/meteor,servel333/meteor,aldeed/meteor,zdd910/meteor,akintoey/meteor,Puena/meteor,baiyunping333/meteor,somallg/meteor,somallg/meteor,Paulyoufu/meteor-1,mubassirhayat/meteor,pjump/meteor,saisai/meteor,Prithvi-A/meteor,yonas/meteor-freebsd,DCKT/meteor,dandv/meteor,sitexa/meteor,ericterpstra/meteor,Quicksteve/meteor,skarekrow/meteor,GrimDerp/meteor,chiefninew/meteor,deanius/meteor,dev-bobsong/meteor,williambr/meteor,juansgaitan/meteor,daslicht/meteor,jenalgit/meteor,arunoda/meteor,karlito40/meteor,newswim/meteor,luohuazju/meteor,rozzzly/meteor,zdd910/meteor,msavin/meteor,justintung/meteor,namho102/meteor,shadedprofit/meteor,akintoey/meteor,daltonrenaldo/meteor,sclausen/meteor,vjau/meteor,cog-64/meteor,joannekoong/meteor,pandeysoni/meteor,steedos/meteor,yiliaofan/meteor,alexbeletsky/meteor,chasertech/meteor,esteedqueen/meteor,saisai/meteor,planet-training/meteor,colinligertwood/meteor,JesseQin/meteor,vjau/meteor,yalexx/meteor,AnjirHossain/meteor,kidaa/meteor,jenalgit/meteor,sclausen/meteor,h200863057/meteor,lawrenceAIO/meteor,h200863057/meteor,Jeremy017/meteor,henrypan/meteor,ashwathgovind/meteor,daltonrenaldo/meteor,servel333/meteor,evilemon/meteor,vjau/meteor,justintung/meteor,shadedprofit/meteor,chengxiaole/meteor,allanalexandre/meteor,daslicht/meteor,lassombra/meteor,wmkcc/meteor,youprofit/meteor,justintung/meteor,calvintychan/meteor,JesseQin/meteor,elkingtonmcb/meteor,arunoda/meteor,dfischer/meteor,whip112/meteor,SeanOceanHu/meteor,kencheung/meteor,youprofit/meteor,jg3526/meteor,whip112/meteor,steedos/meteor,codingang/meteor,allanalexandre/meteor,aldeed/meteor,h200863057/meteor,lpinto93/meteor,D1no/meteor,jdivy/meteor,henrypan/meteor,sunny-g/meteor,chengxiaole/meteor,IveWong/meteor,jagi/meteor,hristaki/meteor,katopz/meteor,dev-bobsong/meteor,chmac/meteor,nuvipannu/meteor,meonkeys/meteor,joannekoong/meteor,lieuwex/meteor,judsonbsilva/meteor,saisai/meteor,paul-barry-kenzan/meteor,devgrok/meteor,pandeysoni/meteor,joannekoong/meteor,yinhe007/meteor,GrimDerp/meteor,jrudio/meteor,rozzzly/meteor,jrudio/meteor,nuvipannu/meteor,planet-training/meteor,Theviajerock/meteor,Jonekee/meteor,ndarilek/meteor,michielvanoeffelen/meteor,jg3526/meteor,iman-mafi/meteor,henrypan/meteor,LWHTarena/meteor,queso/meteor,deanius/meteor,williambr/meteor,ndarilek/meteor,EduShareOntario/meteor,ericterpstra/meteor,Paulyoufu/meteor-1,LWHTarena/meteor,benjamn/meteor,D1no/meteor,chmac/meteor,codedogfish/meteor,fashionsun/meteor,planet-training/meteor,shmiko/meteor,yanisIk/meteor,deanius/meteor,guazipi/meteor,newswim/meteor,SeanOceanHu/meteor,DCKT/meteor,HugoRLopes/meteor,ashwathgovind/meteor,rabbyalone/meteor,Ken-Liu/meteor,Ken-Liu/meteor,baysao/meteor,Profab/meteor,alexbeletsky/meteor,eluck/meteor,vacjaliu/meteor,yinhe007/meteor,elkingtonmcb/meteor,hristaki/meteor,LWHTarena/meteor,shadedprofit/meteor,baiyunping333/meteor,dev-bobsong/meteor,pandeysoni/meteor,deanius/meteor,iman-mafi/meteor,yinhe007/meteor,kengchau/meteor,jagi/meteor,alexbeletsky/meteor,youprofit/meteor,sitexa/meteor,Jeremy017/meteor,luohuazju/meteor,yonas/meteor-freebsd,PatrickMcGuinness/meteor,AnjirHossain/meteor,Profab/meteor,imanmafi/meteor,emmerge/meteor,cbonami/meteor,baiyunping333/meteor,kengchau/meteor,imanmafi/meteor,meteor-velocity/meteor,jeblister/meteor,Hansoft/meteor,yinhe007/meteor,TribeMedia/meteor,lieuwex/meteor,AnthonyAstige/meteor,udhayam/meteor,shrop/meteor,TribeMedia/meteor,yanisIk/meteor,l0rd0fwar/meteor,oceanzou123/meteor,lpinto93/meteor,henrypan/meteor,ndarilek/meteor,deanius/meteor,esteedqueen/meteor,4commerce-technologies-AG/meteor,steedos/meteor,dboyliao/meteor,udhayam/meteor,qscripter/meteor,neotim/meteor,daltonrenaldo/meteor,aramk/meteor,TribeMedia/meteor,planet-training/meteor,servel333/meteor,guazipi/meteor,AnjirHossain/meteor,jenalgit/meteor,qscripter/meteor,chinasb/meteor,dfischer/meteor,karlito40/meteor,aleclarson/meteor,juansgaitan/meteor,IveWong/meteor,dandv/meteor,TechplexEngineer/meteor,Paulyoufu/meteor-1,lorensr/meteor,ljack/meteor,Jeremy017/meteor,brdtrpp/meteor,chasertech/meteor,dfischer/meteor,dandv/meteor,Jeremy017/meteor,jirengu/meteor,stevenliuit/meteor,luohuazju/meteor,colinligertwood/meteor,HugoRLopes/meteor,meonkeys/meteor,alphanso/meteor,Ken-Liu/meteor,Jonekee/meteor,Jonekee/meteor,benstoltz/meteor,AlexR1712/meteor,lorensr/meteor,baysao/meteor,daslicht/meteor,Urigo/meteor,benjamn/meteor,whip112/meteor,williambr/meteor,sitexa/meteor,devgrok/meteor,GrimDerp/meteor,codingang/meteor,allanalexandre/meteor,rozzzly/meteor,yinhe007/meteor,l0rd0fwar/meteor,baysao/meteor,sunny-g/meteor,Eynaliyev/meteor,evilemon/meteor,msavin/meteor,bhargav175/meteor,somallg/meteor,LWHTarena/meteor,DAB0mB/meteor,Eynaliyev/meteor,GrimDerp/meteor,jagi/meteor,allanalexandre/meteor,lassombra/meteor,daltonrenaldo/meteor,jdivy/meteor,modulexcite/meteor,luohuazju/meteor,skarekrow/meteor,johnthepink/meteor,jg3526/meteor,jeblister/meteor,fashionsun/meteor,yyx990803/meteor,Hansoft/meteor,daltonrenaldo/meteor,michielvanoeffelen/meteor,planet-training/meteor,yonglehou/meteor,Profab/meteor,johnthepink/meteor,planet-training/meteor,Jonekee/meteor,emmerge/meteor,yiliaofan/meteor,meteor-velocity/meteor,arunoda/meteor,brettle/meteor,devgrok/meteor,chmac/meteor,JesseQin/meteor,johnthepink/meteor,somallg/meteor,cog-64/meteor,daltonrenaldo/meteor,allanalexandre/meteor,kengchau/meteor,aramk/meteor,Prithvi-A/meteor,nuvipannu/meteor,aramk/meteor,mirstan/meteor,yiliaofan/meteor,AlexR1712/meteor,codedogfish/meteor,mjmasn/meteor,bhargav175/meteor,cbonami/meteor,JesseQin/meteor,yyx990803/meteor,AlexR1712/meteor,planet-training/meteor,qscripter/meteor,Quicksteve/meteor,hristaki/meteor,brdtrpp/meteor,sitexa/meteor,Hansoft/meteor,kidaa/meteor,DAB0mB/meteor,4commerce-technologies-AG/meteor,elkingtonmcb/meteor,brdtrpp/meteor,kengchau/meteor,dev-bobsong/meteor,katopz/meteor,stevenliuit/meteor,brettle/meteor,daslicht/meteor,juansgaitan/meteor,aldeed/meteor,akintoey/meteor,hristaki/meteor,Profab/meteor,cog-64/meteor,ericterpstra/meteor,EduShareOntario/meteor,EduShareOntario/meteor,chiefninew/meteor,GrimDerp/meteor,justintung/meteor,EduShareOntario/meteor,chiefninew/meteor,wmkcc/meteor,l0rd0fwar/meteor,sunny-g/meteor,deanius/meteor,jg3526/meteor,mirstan/meteor,IveWong/meteor,neotim/meteor,chmac/meteor,alphanso/meteor,colinligertwood/meteor,judsonbsilva/meteor,AnthonyAstige/meteor,TechplexEngineer/meteor,mubassirhayat/meteor,codedogfish/meteor,jg3526/meteor,kencheung/meteor,calvintychan/meteor,sunny-g/meteor,kengchau/meteor,servel333/meteor,Paulyoufu/meteor-1,jrudio/meteor,chengxiaole/meteor,lorensr/meteor,jeblister/meteor,AlexR1712/meteor,mjmasn/meteor,dev-bobsong/meteor,newswim/meteor,rabbyalone/meteor,DCKT/meteor,akintoey/meteor,benstoltz/meteor,sclausen/meteor,Ken-Liu/meteor,cherbst/meteor,meteor-velocity/meteor,esteedqueen/meteor,TribeMedia/meteor,mubassirhayat/meteor,kengchau/meteor,steedos/meteor,codingang/meteor,lpinto93/meteor,judsonbsilva/meteor,sunny-g/meteor,Jonekee/meteor,rabbyalone/meteor,chengxiaole/meteor,fashionsun/meteor,steedos/meteor,SeanOceanHu/meteor,alexbeletsky/meteor,yiliaofan/meteor,devgrok/meteor,SeanOceanHu/meteor,queso/meteor,baysao/meteor,chengxiaole/meteor,yyx990803/meteor,servel333/meteor,Ken-Liu/meteor,johnthepink/meteor,Jonekee/meteor,hristaki/meteor,yyx990803/meteor,mirstan/meteor,LWHTarena/meteor,ashwathgovind/meteor,l0rd0fwar/meteor,Urigo/meteor,baysao/meteor,cbonami/meteor,vjau/meteor,iman-mafi/meteor,chasertech/meteor,kidaa/meteor,bhargav175/meteor,jenalgit/meteor,Prithvi-A/meteor,lassombra/meteor,DCKT/meteor,jg3526/meteor,alexbeletsky/meteor,Urigo/meteor,jdivy/meteor,yiliaofan/meteor,TribeMedia/meteor,lawrenceAIO/meteor,codedogfish/meteor,rabbyalone/meteor,cog-64/meteor,Jeremy017/meteor,Ken-Liu/meteor,DCKT/meteor,l0rd0fwar/meteor,jagi/meteor,meteor-velocity/meteor,youprofit/meteor,katopz/meteor,modulexcite/meteor,lawrenceAIO/meteor,queso/meteor,TechplexEngineer/meteor,mirstan/meteor,dfischer/meteor,oceanzou123/meteor,kidaa/meteor,yalexx/meteor,somallg/meteor,mirstan/meteor,dandv/meteor,D1no/meteor,chasertech/meteor,DAB0mB/meteor,paul-barry-kenzan/meteor,vjau/meteor,mubassirhayat/meteor,sitexa/meteor,Prithvi-A/meteor,guazipi/meteor,udhayam/meteor,ljack/meteor,EduShareOntario/meteor,HugoRLopes/meteor,kidaa/meteor,rozzzly/meteor,namho102/meteor,stevenliuit/meteor,lorensr/meteor,udhayam/meteor,queso/meteor,queso/meteor,lieuwex/meteor,benstoltz/meteor,AlexR1712/meteor,paul-barry-kenzan/meteor,Hansoft/meteor,cog-64/meteor,Urigo/meteor,devgrok/meteor,sdeveloper/meteor,msavin/meteor,pjump/meteor,imanmafi/meteor,daslicht/meteor,sunny-g/meteor,namho102/meteor,joannekoong/meteor,judsonbsilva/meteor,baiyunping333/meteor,stevenliuit/meteor,yonas/meteor-freebsd,bhargav175/meteor,shadedprofit/meteor,PatrickMcGuinness/meteor,chengxiaole/meteor,sunny-g/meteor,jirengu/meteor,dboyliao/meteor,emmerge/meteor,dboyliao/meteor,jeblister/meteor,chasertech/meteor,guazipi/meteor,arunoda/meteor,emmerge/meteor,Profab/meteor,Theviajerock/meteor,jeblister/meteor,benstoltz/meteor,yalexx/meteor,aramk/meteor,judsonbsilva/meteor,mauricionr/meteor,cherbst/meteor,dandv/meteor,DCKT/meteor,yonglehou/meteor,colinligertwood/meteor,deanius/meteor,skarekrow/meteor,neotim/meteor,baiyunping333/meteor,sclausen/meteor,TechplexEngineer/meteor,juansgaitan/meteor,cog-64/meteor,zdd910/meteor,l0rd0fwar/meteor,aleclarson/meteor,Theviajerock/meteor,SeanOceanHu/meteor,somallg/meteor,neotim/meteor,AnthonyAstige/meteor,zdd910/meteor,4commerce-technologies-AG/meteor,Puena/meteor,yonglehou/meteor,qscripter/meteor,ljack/meteor,devgrok/meteor,PatrickMcGuinness/meteor,jirengu/meteor,guazipi/meteor,pjump/meteor,yanisIk/meteor,arunoda/meteor,jg3526/meteor,iman-mafi/meteor,chinasb/meteor,Urigo/meteor,stevenliuit/meteor,tdamsma/meteor,msavin/meteor,rabbyalone/meteor,chengxiaole/meteor,Paulyoufu/meteor-1,benstoltz/meteor,dboyliao/meteor,ericterpstra/meteor,pjump/meteor,aleclarson/meteor,colinligertwood/meteor,D1no/meteor,codingang/meteor,iman-mafi/meteor,jagi/meteor,ericterpstra/meteor,johnthepink/meteor,lpinto93/meteor,codedogfish/meteor,dboyliao/meteor,h200863057/meteor,hristaki/meteor,evilemon/meteor,wmkcc/meteor,cherbst/meteor,joannekoong/meteor,jrudio/meteor,lorensr/meteor,lpinto93/meteor,williambr/meteor,ericterpstra/meteor,kencheung/meteor,qscripter/meteor,sdeveloper/meteor,HugoRLopes/meteor,planet-training/meteor,saisai/meteor,h200863057/meteor,sitexa/meteor,dandv/meteor,HugoRLopes/meteor,ashwathgovind/meteor,aldeed/meteor,tdamsma/meteor,ndarilek/meteor,kidaa/meteor,tdamsma/meteor,Puena/meteor,jdivy/meteor,baiyunping333/meteor,eluck/meteor,pjump/meteor,benstoltz/meteor,shrop/meteor,johnthepink/meteor,SeanOceanHu/meteor,mjmasn/meteor,baysao/meteor,AlexR1712/meteor,michielvanoeffelen/meteor,papimomi/meteor,framewr/meteor,chinasb/meteor,aldeed/meteor,sclausen/meteor | ---
+++
@@ -4,7 +4,7 @@
});
Cordova.depends({
- 'org.apache.cordova.file': '1.3.2',
+ 'org.apache.cordova.file': '1.3.3',
'org.apache.cordova.file-transfer': '0.4.8'
});
|
e176f4ed812d0d91646ba62838e1769548b81f39 | example/src/redux/reducer/storage.js | example/src/redux/reducer/storage.js | import { types } from './storage.actions';
const initialState = {
file: null,
url: null,
};
export default function storageReducer(state=initialState, action={}) {
switch (action.type) {
case types.SET_FILE:
return {
...state,
file: action.file,
}
case types.SET_FILE_URL:
return {
...state,
url: action.url,
}
default:
return state;
}
}
| import { types } from './storage.actions';
const initialState = {
file: null,
loading: false,
url: null,
};
export default function storageReducer(state=initialState, action={}) {
switch (action.type) {
case types.SET_FILE:
return {
...state,
file: action.file,
}
case types.SET_FILE_URL:
return {
...state,
loading: false,
url: action.url,
}
case types.SEND_FILE:
return {
...state,
loading: true,
};
default:
return state;
}
}
| Store file upload loading state. | Store file upload loading state.
| JavaScript | mit | n6g7/redux-saga-firebase | ---
+++
@@ -2,6 +2,7 @@
const initialState = {
file: null,
+ loading: false,
url: null,
};
@@ -15,8 +16,14 @@
case types.SET_FILE_URL:
return {
...state,
+ loading: false,
url: action.url,
}
+ case types.SEND_FILE:
+ return {
+ ...state,
+ loading: true,
+ };
default:
return state;
} |
336d92edc418ef85c88390b3e33896ca73284c81 | computer-science/01-introduction-to-cs-and-programming-mit/src/02-lecture.js | computer-science/01-introduction-to-cs-and-programming-mit/src/02-lecture.js | // Modules
var prompt = require( 'prompt' );
// // Create a variable x and assign value 3 to it
// var x = 3;
// // Bind x to value 9
// x *= x; // or x = x * x;
// console.log( x );
// read input data from terminal
prompt.start();
prompt.get({
name : 'number',
description : 'Enter a number'
}, function( err, results ) {
console.log( results.number );
});
// // Verify if a integer number is even or odd.
// // If odd, verify if the number is divisible by 3
// // read input data from terminal
// process.stdin.resume();
// console.log( 'Enter a integer:' );
// process.stdin.setEncoding( 'utf8' );
// process.stdin.on( 'data', function( input ) {
// var int = parseInt( input, 10 );
// if ( int % 2 === 0 ) {
// console.log( 'Even' );
// } else {
// console.log( 'Odd' );
// if ( int % 3 !== 0 ) {
// console.log( 'And not divisible by 3' );
// }
// }
// process.exit();
// });
// // Find the lowest of three numbers
| // Modules
var prompt = require( 'prompt' );
// // Create a variable x and assign value 3 to it
// var x = 3;
// // Bind x to value 9
// x *= x; // or x = x * x;
// console.log( x );
// // read input data from terminal
// prompt.start();
// prompt.get({
// name : 'number',
// description : 'Enter a number'
// }, function( err, results ) {
// console.log( results.number );
// });
// Verify if a integer number is even or odd.
// If odd, verify if the number is divisible by 3
// read input data from terminal
prompt.start();
prompt.get([
{
name : 'number',
description : 'Enter a integer'
}
], function( err, results ) {
var int = parseInt( results.number, 10 );
if ( int % 2 === 0 ) {
console.log( int + ' is EVEN' );
} else {
var msg = int.toString() + ' is ODD';
if ( int % 3 !== 0 ) {
msg += ' and NOT divisible by 3';
}
console.log( msg );
}
});
// // Find the lowest of three numbers
| Verify if a integer number is even or odd - refactor | Verify if a integer number is even or odd - refactor
| JavaScript | mit | waterlooSunset/computer-science-and-engineering | ---
+++
@@ -8,47 +8,49 @@
// x *= x; // or x = x * x;
// console.log( x );
+// // read input data from terminal
+// prompt.start();
+// prompt.get({
+// name : 'number',
+// description : 'Enter a number'
+// }, function( err, results ) {
+
+// console.log( results.number );
+
+// });
+
+// Verify if a integer number is even or odd.
+// If odd, verify if the number is divisible by 3
// read input data from terminal
prompt.start();
-prompt.get({
- name : 'number',
- description : 'Enter a number'
-}, function( err, results ) {
- console.log( results.number );
+prompt.get([
+ {
+ name : 'number',
+ description : 'Enter a integer'
+ }
+], function( err, results ) {
+
+ var int = parseInt( results.number, 10 );
+
+ if ( int % 2 === 0 ) {
+
+ console.log( int + ' is EVEN' );
+
+ } else {
+
+ var msg = int.toString() + ' is ODD';
+
+ if ( int % 3 !== 0 ) {
+
+ msg += ' and NOT divisible by 3';
+
+ }
+
+ console.log( msg );
+
+ }
});
-// // Verify if a integer number is even or odd.
-// // If odd, verify if the number is divisible by 3
-// // read input data from terminal
-// process.stdin.resume();
-
-// console.log( 'Enter a integer:' );
-// process.stdin.setEncoding( 'utf8' );
-
-// process.stdin.on( 'data', function( input ) {
-
-// var int = parseInt( input, 10 );
-
-// if ( int % 2 === 0 ) {
-
-// console.log( 'Even' );
-
-// } else {
-
-// console.log( 'Odd' );
-
-// if ( int % 3 !== 0 ) {
-
-// console.log( 'And not divisible by 3' );
-
-// }
-
-// }
-
-// process.exit();
-
-// });
-
// // Find the lowest of three numbers |
7358e642ffbea4ce3d2dd54da8b26068cd3d0f4d | rules/es2017.js | rules/es2017.js | module.exports = {
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
rules: {
'arrow-body-style': ['error', 'as-needed', {
requireReturnForObjectLiteral: false,
}],
'arrow-spacing': ['error', { before: true, after: true }],
'no-const-assign': 'error',
'no-duplicate-imports': 'error',
'no-new-symbol': 'error',
'no-this-before-super': 'error',
'no-var': 'error',
'object-shorthand': ['error', 'always', {
ignoreConstructors: false,
avoidQuotes: true,
}],
'prefer-arrow-callback': ['error', {
allowNamedFunctions: false,
allowUnboundThis: true,
}],
'prefer-const': ['error', {
destructuring: 'any',
ignoreReadBeforeAssign: true,
}],
'prefer-rest-params': 'error',
// babel inserts `'use strict';` for us
'strict': ['error', 'never']
}
};
| module.exports = {
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
rules: {
'arrow-spacing': ['error', { before: true, after: true }],
'no-const-assign': 'error',
'no-duplicate-imports': 'error',
'no-new-symbol': 'error',
'no-this-before-super': 'error',
'no-var': 'error',
'object-shorthand': ['error', 'always', {
ignoreConstructors: false,
avoidQuotes: true,
}],
'prefer-arrow-callback': ['error', {
allowNamedFunctions: false,
allowUnboundThis: true,
}],
'prefer-const': ['error', {
destructuring: 'any',
ignoreReadBeforeAssign: true,
}],
'prefer-rest-params': 'error',
// babel inserts `'use strict';` for us
'strict': ['error', 'never']
}
};
| Remove arrow-body-style. Is too confusing | Remove arrow-body-style. Is too confusing
| JavaScript | mit | sevenval/eslint-config-sevenval | ---
+++
@@ -7,9 +7,6 @@
}
},
rules: {
- 'arrow-body-style': ['error', 'as-needed', {
- requireReturnForObjectLiteral: false,
- }],
'arrow-spacing': ['error', { before: true, after: true }],
'no-const-assign': 'error',
'no-duplicate-imports': 'error', |
b702adaf1fae5e798db51d36b1919254f387f031 | js/eventPage.js | js/eventPage.js | function runAlarm() {
chrome.tabs.create({
url: "http://example.com"
});
}
chrome.alarms.onAlarm.addListener(function(alarm) {
console.log(alarm);
chrome.tabs.query({}, function(tabs) {
if (tabs.length === 0) {
chrome.storage.local.set({
"missed": 1
});
} else {
runAlarm();
}
})
});
chrome.windows.onCreated.addListener(function(window) {
chrome.storage.local.get("missed", function(r) {
if (r.missed === 1) {
chrome.storage.local.set({
"missed": 0
});
runAlarm();
}
});
});
| function runAlarm() {
chrome.tabs.create({
url: "http://example.com"
});
}
chrome.alarms.onAlarm.addListener(function(alarm) {
console.log(alarm);
chrome.tabs.query({}, function(tabs) {
if (tabs.length === 0) {
chrome.storage.local.set({
"missed": 1
});
} else {
runAlarm();
}
});
});
chrome.windows.onCreated.addListener(function(window) {
chrome.storage.local.get("missed", function(r) {
if (r.missed === 1) {
chrome.storage.local.set({
"missed": 0
});
runAlarm();
}
});
});
chrome.runtime.onInstalled.addListener(function(details) {
chrome.storage.local.get("enabled", function(r) {
if (r.enabled === undefined) {
chrome.storage.local.set({
"sites": [],
"time": "08:00",
"enabled": false,
"missed": 0
});
}
});
});
| Create default settings upon first installation | Create default settings upon first installation
| JavaScript | mit | adrianhuna/tabscheduler | ---
+++
@@ -13,7 +13,7 @@
} else {
runAlarm();
}
- })
+ });
});
chrome.windows.onCreated.addListener(function(window) {
chrome.storage.local.get("missed", function(r) {
@@ -25,3 +25,15 @@
}
});
});
+chrome.runtime.onInstalled.addListener(function(details) {
+ chrome.storage.local.get("enabled", function(r) {
+ if (r.enabled === undefined) {
+ chrome.storage.local.set({
+ "sites": [],
+ "time": "08:00",
+ "enabled": false,
+ "missed": 0
+ });
+ }
+ });
+}); |
b049412bfd8d13c5055324ceac5f305b7b680e0e | js/modules/debuglogs.js | js/modules/debuglogs.js | /* eslint-env node */
const FormData = require('form-data');
const got = require('got');
const BASE_URL = 'https://debuglogs.org';
// Workaround: Submitting `FormData` using native `FormData::submit` procedure
// as integration with `got` results in S3 error saying we haven’t set the
// `Content-Length` header:
const submitFormData = (form, url) =>
new Promise((resolve, reject) => {
form.submit(url, (error) => {
if (error) {
return reject(error);
}
return resolve();
});
});
// upload :: String -> Promise URL
exports.upload = async (content) => {
const signedForm = await got.get(BASE_URL, { json: true });
const { fields, url } = signedForm.body;
const form = new FormData();
// The API expects `key` to be the first field:
form.append('key', fields.key);
Object.entries(fields)
.filter(([key]) => key !== 'key')
.forEach(([key, value]) => {
form.append(key, value);
});
const contentBuffer = Buffer.from(content, 'utf8');
const contentType = 'text/plain';
form.append('Content-Type', contentType);
form.append('file', contentBuffer, {
contentType,
filename: 'signal-desktop-debug-log.txt',
});
await submitFormData(form, url);
return `${BASE_URL}/${fields.key}`;
};
| /* eslint-env node */
const FormData = require('form-data');
const got = require('got');
const BASE_URL = 'https://debuglogs.org';
// Workaround: Submitting `FormData` using native `FormData::submit` procedure
// as integration with `got` results in S3 error saying we haven’t set the
// `Content-Length` header:
// https://github.com/sindresorhus/got/pull/466
const submitFormData = (form, url) =>
new Promise((resolve, reject) => {
form.submit(url, (error) => {
if (error) {
return reject(error);
}
return resolve();
});
});
// upload :: String -> Promise URL
exports.upload = async (content) => {
const signedForm = await got.get(BASE_URL, { json: true });
const { fields, url } = signedForm.body;
const form = new FormData();
// The API expects `key` to be the first field:
form.append('key', fields.key);
Object.entries(fields)
.filter(([key]) => key !== 'key')
.forEach(([key, value]) => {
form.append(key, value);
});
const contentBuffer = Buffer.from(content, 'utf8');
const contentType = 'text/plain';
form.append('Content-Type', contentType);
form.append('file', contentBuffer, {
contentType,
filename: 'signal-desktop-debug-log.txt',
});
// WORKAROUND: See comment on `submitFormData`:
// await got.post(url, { body: form });
await submitFormData(form, url);
return `${BASE_URL}/${fields.key}`;
};
| Document workaround for `got` `FormData` bug | Document workaround for `got` `FormData` bug
See: https://github.com/sindresorhus/got/pull/466
| JavaScript | agpl-3.0 | nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop | ---
+++
@@ -9,6 +9,7 @@
// Workaround: Submitting `FormData` using native `FormData::submit` procedure
// as integration with `got` results in S3 error saying we haven’t set the
// `Content-Length` header:
+// https://github.com/sindresorhus/got/pull/466
const submitFormData = (form, url) =>
new Promise((resolve, reject) => {
form.submit(url, (error) => {
@@ -42,6 +43,8 @@
filename: 'signal-desktop-debug-log.txt',
});
+ // WORKAROUND: See comment on `submitFormData`:
+ // await got.post(url, { body: form });
await submitFormData(form, url);
return `${BASE_URL}/${fields.key}`; |
44da4e0035a0a72346b72c696aee73c23096275f | tests/testWithCallBack.js | tests/testWithCallBack.js | const request = require('request')
function getLuke(cb) {
const lukeInfo = {
name: 'Luke',
}
request('https://swapi.co/api/people/1', (error, response, body) => {
if (error) return cb(error)
const data = JSON.parse(body)
const startShipURL = data.starships[0]
const vehicleURL = data.vehicles[0]
request(startShipURL, (error, response, body) => {
if (error) return cb(error)
const { name, model, starship_class } = JSON.parse(body)
lukeInfo.startShip = { name, model, type: starship_class}
request(vehicleURL, (error, response, body) => {
if (error) return cb(error)
const { name, model, vehicle_class } = JSON.parse(body)
lukeInfo.vehicle = { name, model, type: vehicle_class}
cb(null, lukeInfo) // <== Pass null in error and result as second arg
})
})
})
}
describe('Example with Callbacks (Callback Hell)', () => {
it('should get Luke details', (done) => {
getLuke((error, info) => {
if (error) return done(error)
console.log(info)
done()
});
})
})
| const request = require('request')
function getLuke(cb) {
const lukeInfo = {
name: 'Luke',
}
/* Here stars the callback hell. Please notice the if (error) return cb(error) redundant code */
request('https://swapi.co/api/people/1', (error, response, body) => {
if (error) return cb(error)
const data = JSON.parse(body)
const startShipURL = data.starships[0]
const vehicleURL = data.vehicles[0]
request(startShipURL, (error, response, body) => {
if (error) return cb(error)
const { name, model, starship_class } = JSON.parse(body)
lukeInfo.startShip = { name, model, type: starship_class}
request(vehicleURL, (error, response, body) => {
if (error) return cb(error)
const { name, model, vehicle_class } = JSON.parse(body)
lukeInfo.vehicle = { name, model, type: vehicle_class}
cb(null, lukeInfo) // <== Pass null in error and result as second arg
})
})
})
}
describe('Example with Callbacks (Callback Hell)', () => {
it('should get Luke details', (done) => {
getLuke((error, info) => {
if (error) return done(error)
console.log(info)
done()
});
})
})
| Add notice in callback example | Add notice in callback example
| JavaScript | mit | pierreroth64/js-async-tutorial | ---
+++
@@ -5,6 +5,7 @@
name: 'Luke',
}
+ /* Here stars the callback hell. Please notice the if (error) return cb(error) redundant code */
request('https://swapi.co/api/people/1', (error, response, body) => {
if (error) return cb(error)
|
987d9722ecbcfa8925a48765086beceb2a913a58 | tests/test_convert_tag.js | tests/test_convert_tag.js | var suite = require('suite.js');
var convertTag = require('../lib/convert_tag');
suite(convertTag, [
'foo', 'foo',
'self help', 'self_help',
'self-help', 'self__help',
'another self help', 'another_self_help',
'another-self-help', 'another__self__help',
'SciFi', 'sci_fi',
'sci-fi', 'sci__fi'
]);
| var suite = require('suite.js');
var convertTag = require('../lib/convert_tag');
suite(convertTag, [
'foo', 'foo',
'self help', 'self_help',
'self-help', 'self__help',
'another self help', 'another_self_help',
'another-self-help', 'another__self__help',
'SciFi', 'sci_fi',
'SciFiToo', 'sci_fi_too',
'sci-fi', 'sci__fi'
]);
| Add multipart case for upper case boundaries | Add multipart case for upper case boundaries
| JavaScript | mit | Kikobeats/blogger2ghost,bebraw/blogger2ghost | ---
+++
@@ -9,5 +9,6 @@
'another self help', 'another_self_help',
'another-self-help', 'another__self__help',
'SciFi', 'sci_fi',
+ 'SciFiToo', 'sci_fi_too',
'sci-fi', 'sci__fi'
]); |
c2a32db5fe2d291f4edd38b484aca17b51f5edae | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'lib/**/*.js',
'public/javascripts/lib/**/*.js',
'test/**/*.js'
]
},
cafemocha: {
options: {
ui: 'bdd',
reporter: 'dot'
},
src: 'test/unit/**/*.js'
},
// NOTE: need to start karma server first in
// separate window with `grunt karma:unit`
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
watch: {
files: '**/*.js',
tasks: ['jshint', 'cafemocha', 'karma:unit:run']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-cafe-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['jshint', 'cafemocha', 'karma:unit:run']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'lib/**/*.js',
'public/javascripts/lib/**/*.js',
'test/**/*.js'
]
},
cafemocha: {
options: {
ui: 'bdd',
reporter: 'dot'
},
src: 'test/unit/**/*.js'
},
// NOTE: need to start karma server first in
// separate window with `grunt karma:unit`
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
watch: {
files: ['<%= jshint.all %>'],
tasks: ['jshint', 'cafemocha', 'karma:unit:run'],
options: {interrupt: true}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-cafe-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['jshint', 'cafemocha', 'karma:unit:run']);
};
| Stop watchnig so many files, fixes errors | Stop watchnig so many files, fixes errors
| JavaScript | mit | jamiemill/lux,jamiemill/lux,jamiemill/lux | ---
+++
@@ -28,8 +28,9 @@
}
},
watch: {
- files: '**/*.js',
- tasks: ['jshint', 'cafemocha', 'karma:unit:run']
+ files: ['<%= jshint.all %>'],
+ tasks: ['jshint', 'cafemocha', 'karma:unit:run'],
+ options: {interrupt: true}
}
});
|
439f689096d46eac35c2adfe23b901e220a0f558 | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
uglify: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */\n'
},
build: {
src: 'src/progress-button.js',
dest: 'dist/progress-button.min.js'
}
}
})
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
grunt.registerTask('build', ['uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', [])
}
| module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
cssmin: {
build: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */'
},
src: 'src/progress-button.css',
dest: 'dist/progress-button.min.css'
}
},
uglify: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */\n'
},
build: {
src: 'src/progress-button.js',
dest: 'dist/progress-button.min.js'
}
}
})
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
grunt.registerTask('build', ['cssmin', 'uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', [])
}
| Add cssmin to Grunt task ‘build’ | Add cssmin to Grunt task ‘build’
| JavaScript | bsd-2-clause | SonicHedgehog/angular-progress-button,SonicHedgehog/angular-progress-button | ---
+++
@@ -6,6 +6,15 @@
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
+ }
+ },
+ cssmin: {
+ build: {
+ options: {
+ banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */'
+ },
+ src: 'src/progress-button.css',
+ dest: 'dist/progress-button.min.css'
}
},
uglify: {
@@ -19,10 +28,11 @@
}
})
+ grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
- grunt.registerTask('build', ['uglify'])
+ grunt.registerTask('build', ['cssmin', 'uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', [])
} |
ae5cad1e172ecd2a12a380c9f473b8b04af0f814 | Gruntfile.js | Gruntfile.js | /*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Task configuration.
csslint: {
src: ['public/**/*.css'],
},
docco: {
src: ['*.js', 'routes/**/*.js']
},
jshint: {
// See .jshintrc
src: ['*.js', 'routes/**/*.js'],
options: {
jshintrc: true
}
},
watch: {
files: '<%= jshint.src %>',
tasks: ['jshint']
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-docco');
// Default task.
grunt.registerTask('default', ['jshint']);
};
| /*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Task configuration.
csslint: {
src: ['public/**/*.css'],
},
docco: {
src: ['*.js', 'routes/**/*.js']
},
jshint: {
// See .jshintrc
src: ['*.js', 'routes/**/*.js'],
options: {
jshintrc: true
}
},
watch: {
files: '<%= jshint.src %>',
tasks: ['jshint']
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-docco');
// Default task.
grunt.registerTask('default', ['jshint', 'csslint', 'docco']);
};
| Add csslint and docco to the default grunt task | Add csslint and docco to the default grunt task
| JavaScript | mit | nicolasmccurdy/jsbox | ---
+++
@@ -30,6 +30,6 @@
grunt.loadNpmTasks('grunt-docco');
// Default task.
- grunt.registerTask('default', ['jshint']);
+ grunt.registerTask('default', ['jshint', 'csslint', 'docco']);
}; |
b345db1e7fce6d1f67aeaecb480c98f1e72dadf2 | Gruntfile.js | Gruntfile.js | /* jslint node: true */
'use strict'
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*_test.js']
}
})
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-nodeunit')
// Default task.
grunt.registerTask('test', ['nodeunit'])
grunt.registerTask('default', ['test'])
}
| /* jslint node: true */
'use strict'
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*_test.js']
}
})
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-nodeunit')
// Default task.
grunt.registerTask('test', ['nodeunit'])
grunt.registerTask('default', ['test'])
}
| Apply standard 11.x code style | Apply standard 11.x code style
| JavaScript | mit | bkimminich/z85-cli | ---
+++
@@ -2,17 +2,17 @@
'use strict'
module.exports = function (grunt) {
- // Project configuration.
+ // Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*_test.js']
}
})
- // These plugins provide necessary tasks.
+ // These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-nodeunit')
- // Default task.
+ // Default task.
grunt.registerTask('test', ['nodeunit'])
grunt.registerTask('default', ['test'])
} |
a3e29bcc9da540c6601c7ce74046c6451775809a | mergedSchema.js | mergedSchema.js | import { mergeSchemas, introspectSchema, makeRemoteExecutableSchema } from "graphql-tools"
import { createHttpLink } from "apollo-link-http"
import fetch from "node-fetch"
import localSchema from "./schema"
export default async function mergedSchema() {
const convectionLink = createHttpLink({
fetch,
uri: process.env.CONVECTION_GRAPH_URL,
headers: {
Authorization: `Bearer ${process.env.CONVECTION_TOKEN}`,
},
})
const convectionSchema = await makeRemoteExecutableSchema({
schema: await introspectSchema(convectionLink),
link: convectionLink,
})
const linkTypeDefs = `
extend type Submission {
artist: Artist
}
`
return mergeSchemas({
schemas: [localSchema, convectionSchema, linkTypeDefs],
// Prefer others over the local MP schema.
onTypeConflict: (_leftType, rightType) => {
// console.warn(`[!] Type collision ${rightType}`)
return rightType
},
resolvers: mergeInfo => ({
Submission: {
artist: {
fragment: `fragment SubmissionArtist on Submission { artist_id }`,
resolve: (parent, args, context, info) => {
const id = parent.artist_id
return mergeInfo.delegate("query", "artist", { id }, context, info)
},
},
},
}),
})
}
| import { mergeSchemas, introspectSchema, makeRemoteExecutableSchema } from "graphql-tools"
import { createHttpLink } from "apollo-link-http"
import fetch from "node-fetch"
import localSchema from "./schema"
export default async function mergedSchema() {
const convectionLink = createHttpLink({
fetch,
uri: process.env.CONVECTION_GRAPH_URL,
headers: {
Authorization: `Bearer ${process.env.CONVECTION_TOKEN}`,
},
})
const convectionSchema = await makeRemoteExecutableSchema({
schema: await introspectSchema(convectionLink),
link: convectionLink,
})
const linkTypeDefs = `
extend type Submission {
artist: Artist
}
`
return mergeSchemas({
schemas: [localSchema, convectionSchema, linkTypeDefs],
// Prefer others over the local MP schema.
onTypeConflict: (_leftType, rightType) => {
console.warn(`[!] Type collision ${rightType}`) // eslint-disable-line no-console
return rightType
},
resolvers: mergeInfo => ({
Submission: {
artist: {
fragment: `fragment SubmissionArtist on Submission { artist_id }`,
resolve: (parent, args, context, info) => {
const id = parent.artist_id
return mergeInfo.delegate("query", "artist", { id }, context, info)
},
},
},
}),
})
}
| Enable type name conflict logging. | [Stitching] Enable type name conflict logging.
| JavaScript | mit | artsy/metaphysics,mzikherman/metaphysics-1,craigspaeth/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,mzikherman/metaphysics-1,craigspaeth/metaphysics,artsy/metaphysics,artsy/metaphysics | ---
+++
@@ -28,7 +28,7 @@
schemas: [localSchema, convectionSchema, linkTypeDefs],
// Prefer others over the local MP schema.
onTypeConflict: (_leftType, rightType) => {
- // console.warn(`[!] Type collision ${rightType}`)
+ console.warn(`[!] Type collision ${rightType}`) // eslint-disable-line no-console
return rightType
},
resolvers: mergeInfo => ({ |
994d14b7619ff6997881cb87b0d4653b6aca645c | app.js | app.js | "use strict";
// Load the libraries and modules
var assets = require(__dirname + '/data/assets.json');
var config = {
npm: __dirname + '/node_modules/',
libraries: {
nodejs: {},
npm: {}
},
directory: __dirname + '/modules/',
modules: {
npm: {
'dragonnodejs-webserver': {
app: { port: process.env.PORT },
bower: {
libraries: [],
path: __dirname + '/bower_components/'
},
header: {
'X-UA-Compatible': 'IE=edge,chrome=1',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'X-Powered-By': null
},
language: {
default: 'en',
languages: ['de', 'en'],
path: __dirname + '/languages/'
},
static: { path: __dirname + '/web/' },
swig: { views: __dirname + '/views/' }
}
},
directory: {
detail: { assets: assets },
list: { assets: assets }
}
}
};
require('dragonnodejs')(config);
| "use strict";
// Load the libraries and modules
var assets = require(__dirname + '/data/assets.json');
var config = {
npm: __dirname + '/node_modules/',
libraries: {
nodejs: {},
npm: {}
},
directory: __dirname + '/modules/',
modules: {
npm: {
'dragonnodejs-webserver': {
app: { port: process.env.PORT },
auth: {
realm: process.env.AUTH_REALM,
user: process.env.AUTH_USER,
password: process.env.AUTH_PASSWORD
},
bower: {
libraries: [],
path: __dirname + '/bower_components/'
},
header: {
'X-UA-Compatible': 'IE=edge,chrome=1',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'X-Powered-By': null
},
language: {
default: 'en',
languages: ['de', 'en'],
path: __dirname + '/languages/'
},
static: { path: __dirname + '/web/' },
swig: { views: __dirname + '/views/' }
}
},
directory: {
detail: { assets: assets },
list: { assets: assets }
}
}
};
require('dragonnodejs')(config);
| Add basic http authentication for all http requests on testserver | Add basic http authentication for all http requests on testserver
| JavaScript | mit | SunnyUK/assetlist,SunnyUK/assetlist | ---
+++
@@ -14,6 +14,11 @@
npm: {
'dragonnodejs-webserver': {
app: { port: process.env.PORT },
+ auth: {
+ realm: process.env.AUTH_REALM,
+ user: process.env.AUTH_USER,
+ password: process.env.AUTH_PASSWORD
+ },
bower: {
libraries: [],
path: __dirname + '/bower_components/' |
df342fe730d44c0141bd169d90df7202f0d3a571 | app.js | app.js | 'use strict';
/**
* Module dependencies.
*/
const express = require('express');
const compression = require('compression');
const bodyParser = require('body-parser');
const router = require('./routes/routes');
/**
* Express configuration.
*/
const app = express();
app.use(compression());
// parse application/json
app.use(bodyParser.json());
// support encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router);
/**
* Express configuration.
*/
app.set('port', process.env.PORT || 3000);
/**
* Catch all error requests
*/
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});
module.exports = app;
| 'use strict';
/**
* Module dependencies.
*/
const express = require('express');
const compression = require('compression');
const bodyParser = require('body-parser');
const router = require('./routes/routes');
/**
* Express configuration.
*/
const app = express();
app.use(compression());
// parse application/json
app.use(bodyParser.json());
// support encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router);
/**
* Express configuration.
*/
app.set('port', process.env.PORT || 3000);
/**
* Catch all error requests
*/
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});
module.exports = app;
| Update error function to arrow function | Update error function to arrow function
| JavaScript | mit | lostatseajoshua/Challenger | ---
+++
@@ -28,7 +28,7 @@
/**
* Catch all error requests
*/
-app.use(function(err, req, res, next) {
+app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
}); |
3e67e31a319630328d2271ad323d43f7f5dd4e1c | app/ui/setup.js | app/ui/setup.js | const { configureStore } = require('../store');
const readline = require('readline');
const draw = require('./draw');
const { keys } = require('./input');
const actions = require('../actions');
const resize = (proc, store) => {
const action = actions.resize({
rows: proc.stdout.rows,
columns: proc.stdout.columns
});
store.dispatch(action);
};
module.exports = (initialState, proc = process) => {
const store = configureStore(proc, initialState);
const onStateChange = draw(proc, store);
store.subscribe(onStateChange);
onStateChange();
proc.stdin.addListener('keypress', keys(store));
proc.stdout.addListener('resize', () => resize(proc, store));
resize(proc, store);
readline.emitKeypressEvents(proc.stdin);
proc.stdin.setRawMode(true);
}; | const { configureStore } = require('../store');
const readline = require('readline');
const draw = require('./draw');
const { keys } = require('./input');
const actions = require('../actions');
const resize = (proc, store) => {
const action = actions.resize({
rows: proc.stdout.rows,
columns: proc.stdout.columns
});
store.dispatch(action);
};
module.exports = (initialState, proc = process) => {
const store = configureStore(proc, initialState);
const onStateChange = draw(proc, store);
store.subscribe(onStateChange);
proc.stdin.addListener('keypress', keys(store));
proc.stdout.addListener('resize', () => resize(proc, store));
resize(proc, store);
readline.emitKeypressEvents(proc.stdin);
proc.stdin.setRawMode(true);
}; | Remove the unnecessary render on start up | Remove the unnecessary render on start up
| JavaScript | mit | andybry/explorer-cli | ---
+++
@@ -16,7 +16,6 @@
const store = configureStore(proc, initialState);
const onStateChange = draw(proc, store);
store.subscribe(onStateChange);
- onStateChange();
proc.stdin.addListener('keypress', keys(store));
proc.stdout.addListener('resize', () => resize(proc, store));
resize(proc, store); |
510dab8128321ab8fa9f2ee4983cff3037b961a8 | bin/sssg.js | bin/sssg.js | #!/usr/bin/env node
var argv = require("yargs").argv;
var main = require('../');
var task = argv._[0];
var options = {};
if(task === "try"){
options.env = "development";
main.do("init", options, function(){
options.src = "./src";
options.dst = "./docs";
main.do("serve", options);
});
return;
}
options.src = argv.src || argv.s;
options.dst = argv.dst || argv.d;
options.root = argv.root || argv.r;
options.env = argv.env || argv.e;
main.do(task, options);
| #!/usr/bin/env node
var argv = require("yargs").argv;
var main = require('../');
var task = argv._[0];
var options = {};
if(task === "try"){
options.env = "development";
main.do("init", options, function(){
options.src = "./src";
options.dst = "./docs";
main.do("serve", options);
});
return;
}
options.src = argv.src || argv.s;
options.dst = argv.dst || argv.d;
options.root = argv.root || argv.r;
if(task === "serve"){
options.env = argv.env || argv.e || "development";
}
else {
options.env = argv.env || argv.e || "production";
}
main.do(task, options);
| Set env=development when task:serve is dispatched | Set env=development when task:serve is dispatched
| JavaScript | mit | Hinaser/sssg,Hinaser/sssg | ---
+++
@@ -12,7 +12,6 @@
main.do("init", options, function(){
options.src = "./src";
options.dst = "./docs";
-
main.do("serve", options);
});
@@ -22,6 +21,12 @@
options.src = argv.src || argv.s;
options.dst = argv.dst || argv.d;
options.root = argv.root || argv.r;
-options.env = argv.env || argv.e;
+
+if(task === "serve"){
+ options.env = argv.env || argv.e || "development";
+}
+else {
+ options.env = argv.env || argv.e || "production";
+}
main.do(task, options); |
2e926ceaa52929378444fcaa6394a90de3b8ee44 | app/common/modules/applications.js | app/common/modules/applications.js | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.dataSource = this.model.get('data-source');
options.dataSource['query-params'] = _.extend({flatten:true}, options.dataSource['query-params']);
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to')
};
}
};
}); | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.dataSource = this.model.get('data-source');
options.dataSource['query-params'] = _.extend({flatten:true}, options.dataSource['query-params']);
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
valueAttr: this.model.get('value-attribute'),
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to')
};
}
};
}); | Add valueAttr to the application module | Add valueAttr to the application module
| JavaScript | mit | tijmenb/spotlight,alphagov/spotlight,alphagov/spotlight,keithiopia/spotlight,tijmenb/spotlight,tijmenb/spotlight,keithiopia/spotlight,keithiopia/spotlight,alphagov/spotlight | ---
+++
@@ -36,6 +36,7 @@
visualisationOptions: function () {
return {
+ valueAttr: this.model.get('value-attribute'),
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to') |
3eb39cf29563deade1d8a2b6687bbb0f17101ba0 | app/controllers/messages/create.js | app/controllers/messages/create.js | var r = require('rethinkdb');
module.exports = function messageCreator(pool) {
return function(message) {
return pool.runQuery(r.table('messages').insert({
body: message.body,
creation: r.now()
}));
};
};
| var r = require('rethinkdb');
module.exports = function messageCreator(pool) {
return function(message) {
return pool.runQuery(r.table('messages').insert({
body: message.body,
scope: message.scope,
creation: r.now()
}));
};
};
| Include scope in controller when adding post | Include scope in controller when adding post
| JavaScript | mit | dingroll/dingroll.com,dingroll/dingroll.com | ---
+++
@@ -4,6 +4,7 @@
return function(message) {
return pool.runQuery(r.table('messages').insert({
body: message.body,
+ scope: message.scope,
creation: r.now()
}));
}; |
93204638953bebc77a46a5d8b0b3f9318046fc1a | src/pipeline.js | src/pipeline.js | import { basename, extname, join, dirname, relative, resolve } from 'path'
import { default as put } from 'output-file-sync'
import { parallel } from 'async'
const keys = Object.keys
export default function createPipeline(pkg, opts, build, progress) {
const
{ onBuild = noop
, onError = noop
} = progress
return (files, callback) => {
parallel(
[].concat(files).map(file => cont => {
const name = basename(file, extname(file))
build(name, file, (error, output) => {
let result = { input: file }
if (error) {
result.error = error
console.log(onError, result)
} else {
result.messages = output.messages
result.files = keys(output.files).map(name => {
let path = join(pkg.resolve(opts.lib), dirname(relative(pkg.resolve(opts.src), resolve(file))))
let outfile = join(path, name)
put(outfile, output.files[name])
return outfile
})
onBuild(result)
}
cont(null, result)
})
})
, callback
)
}
}
function noop() {} | import { basename, extname, join, dirname, relative, resolve } from 'path'
import { default as put } from 'output-file-sync'
import { parallel } from 'async'
const keys = Object.keys
export default function createPipeline(pkg, opts, build, progress) {
const
{ onBuild = noop
, onError = noop
} = progress
return (files, callback) => {
parallel(
[].concat(files).map(file => cont => {
const name = basename(file, extname(file))
build(name, file, (error, output) => {
let result = { input: file }
if (error) {
result.error = error
onError(result)
} else {
result.messages = output.messages
result.files = keys(output.files).map(name => {
let path = join(pkg.resolve(opts.lib), dirname(relative(pkg.resolve(opts.src), resolve(file))))
let outfile = join(path, name)
put(outfile, output.files[name])
return outfile
})
onBuild(result)
}
cont(null, result)
})
})
, callback
)
}
}
function noop() {} | Fix error logging to actually output useful data | Fix error logging to actually output useful data
| JavaScript | mit | zambezi/ez-build,zambezi/ez-build | ---
+++
@@ -19,7 +19,7 @@
let result = { input: file }
if (error) {
result.error = error
- console.log(onError, result)
+ onError(result)
} else {
result.messages = output.messages
result.files = keys(output.files).map(name => { |
e49af4ac9be10a34e24672f65bab16c6c1efa5ef | vue.config.js | vue.config.js | module.exports = {
assetsDir: 'styleguide/',
css: {
modules: true
}
};
| module.exports = {
css: {
modules: true
},
publicPath: '/styleguide/'
};
| Correct to the right property | Correct to the right property
| JavaScript | mit | rodet/styleguide,rodet/styleguide | ---
+++
@@ -1,6 +1,6 @@
module.exports = {
- assetsDir: 'styleguide/',
css: {
modules: true
- }
+ },
+ publicPath: '/styleguide/'
}; |
c3ad93cb30061349d175f48fe5df8d04f817c057 | web/src/js/components/Settings/SettingsMenuItem.js | web/src/js/components/Settings/SettingsMenuItem.js | import React from 'react'
import PropTypes from 'prop-types'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import NavLink from 'general/NavLink'
class SettingsMenuItem extends React.Component {
render () {
const menuItemStyle = Object.assign(
{},
this.props.style)
return (
<NavLink
to={this.props.to}
style={{ textDecoration: 'none' }}
>
<ListItem style={menuItemStyle}>
<ListItemText primary={this.props.children} />
</ListItem>
</NavLink>
)
}
}
SettingsMenuItem.propTypes = {
to: PropTypes.string.isRequired,
style: PropTypes.object
}
SettingsMenuItem.defaultProps = {
style: {}
}
export default SettingsMenuItem
| import React from 'react'
import PropTypes from 'prop-types'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import NavLink from 'general/NavLink'
class SettingsMenuItem extends React.Component {
render () {
return (
<NavLink
to={this.props.to}
style={{ textDecoration: 'none' }}
>
<ListItem button>
<ListItemText primary={this.props.children} />
</ListItem>
</NavLink>
)
}
}
SettingsMenuItem.propTypes = {
to: PropTypes.string.isRequired
}
export default SettingsMenuItem
| Add placeholder menu item hover style | Add placeholder menu item hover style
| JavaScript | mpl-2.0 | gladly-team/tab,gladly-team/tab,gladly-team/tab | ---
+++
@@ -6,15 +6,12 @@
class SettingsMenuItem extends React.Component {
render () {
- const menuItemStyle = Object.assign(
- {},
- this.props.style)
return (
<NavLink
to={this.props.to}
style={{ textDecoration: 'none' }}
>
- <ListItem style={menuItemStyle}>
+ <ListItem button>
<ListItemText primary={this.props.children} />
</ListItem>
</NavLink>
@@ -23,12 +20,6 @@
}
SettingsMenuItem.propTypes = {
- to: PropTypes.string.isRequired,
- style: PropTypes.object
+ to: PropTypes.string.isRequired
}
-
-SettingsMenuItem.defaultProps = {
- style: {}
-}
-
export default SettingsMenuItem |
9604f1566158623e5d009df9b72e133129b7a18f | src/components/LawList.js | src/components/LawList.js | import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { DataTable, FABButton, Icon } from 'react-mdl';
import Pagination from './Pagination';
import './lawList.scss';
const LawList = ({ laws, page, pageSize, selectPage, total }) => {
const columns = [
{ name: 'groupkey', label: <span>Ab­kür­zung</span> },
{ name: 'title', label: <span>Be­zeich­nung</span> },
{ name: 'action' },
];
const rows = laws.map(law => ({...law,
key: law.groupkey,
action: (
<Link to={'/gesetz/' + law.groupkey}>
<FABButton mini>
<Icon name='launch' />
</FABButton>
</Link>
)
}));
return (
<div>
<DataTable
columns={columns}
rows={rows}
className='law-list'
/>
<Pagination
page={page}
hasNext={total > (pageSize*page)}
hasPrev={page > 1}
selectPage={selectPage}
/>
</div>
);
};
LawList.propTypes = {
laws: PropTypes.array.isRequired,
page: PropTypes.number,
pageSize: PropTypes.number,
selectPage: PropTypes.func.isRequired,
total: PropTypes.number.isRequired,
};
LawList.defaultProps = {
page: 1,
pageSize: 20,
};
export default LawList;
| import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { DataTable, TableHeader, FABButton, Icon } from 'react-mdl';
import Pagination from './Pagination';
import './lawList.scss';
const LawList = ({ laws, page, pageSize, selectPage, total }) => {
const rows = laws.map(law => ({...law,
key: law.groupkey,
action: (
<Link to={'/gesetz/' + law.groupkey}>
<FABButton mini>
<Icon name='launch' />
</FABButton>
</Link>
)
}));
return (
<div>
<DataTable
rows={rows}
className='law-list'
>
<TableHeader name='groupkey'>Ab­kür­zung</TableHeader>
<TableHeader name='title'>Be­zeich­nung</TableHeader>
<TableHeader name='action' />
</DataTable>
<Pagination
page={page}
hasNext={total > (pageSize*page)}
hasPrev={page > 1}
selectPage={selectPage}
/>
</div>
);
};
LawList.propTypes = {
laws: PropTypes.array.isRequired,
page: PropTypes.number,
pageSize: PropTypes.number,
selectPage: PropTypes.func.isRequired,
total: PropTypes.number.isRequired,
};
LawList.defaultProps = {
page: 1,
pageSize: 20,
};
export default LawList;
| Implement new version of react-mdl's DataTable including TableHeader component. | Implement new version of react-mdl's DataTable including TableHeader component.
| JavaScript | agpl-3.0 | ahoereth/lawly,ahoereth/lawly,ahoereth/lawly | ---
+++
@@ -1,18 +1,12 @@
import React, { PropTypes } from 'react';
import { Link } from 'react-router';
-import { DataTable, FABButton, Icon } from 'react-mdl';
+import { DataTable, TableHeader, FABButton, Icon } from 'react-mdl';
import Pagination from './Pagination';
import './lawList.scss';
const LawList = ({ laws, page, pageSize, selectPage, total }) => {
- const columns = [
- { name: 'groupkey', label: <span>Ab­kür­zung</span> },
- { name: 'title', label: <span>Be­zeich­nung</span> },
- { name: 'action' },
- ];
-
const rows = laws.map(law => ({...law,
key: law.groupkey,
action: (
@@ -27,10 +21,13 @@
return (
<div>
<DataTable
- columns={columns}
rows={rows}
className='law-list'
- />
+ >
+ <TableHeader name='groupkey'>Ab­kür­zung</TableHeader>
+ <TableHeader name='title'>Be­zeich­nung</TableHeader>
+ <TableHeader name='action' />
+ </DataTable>
<Pagination
page={page}
hasNext={total > (pageSize*page)} |
71af63a1dbbf93b49b26bed20f11e9f5abbcb591 | app/webpack/entities/alarmClock.js | app/webpack/entities/alarmClock.js | import Entity from '../Entity.js';
import printMessage from '../printMessage.js';
import action from '../action.js';
import time from '../time.js';
export class AlarmClock extends Entity {
constructor() {
super();
this.ringing = true;
}
name() {
return "alarm clock";
}
actions() {
if(this.ringing) {
return [
action("Snooze", () => {
printMessage(`You sleep for another 5 minutes before the alarm clock rings again. It's now ${time()}.`);
}),
action("Turn if off.", () => {
this.ringing = false;
printMessage('You turn the alarm clock off.');
})
];
} else {
return [];
}
}
}
export default new AlarmClock();
| import Entity from '../Entity.js';
import printMessage from '../printMessage.js';
import action from '../action.js';
import time from '../time.js';
export class AlarmClock extends Entity {
constructor() {
super();
this.ringing = true;
}
name() {
return "alarm clock";
}
actions() {
const checkTime = action("Look at the time.", () => {
printMessage(`It is now ${time()}.`);
})
if(this.ringing) {
return [
action("Snooze", () => {
printMessage(`You sleep for another 5 minutes before the alarm clock rings again. It's now ${time()}.`);
}),
action("Turn if off.", () => {
this.ringing = false;
printMessage('You turn the alarm clock off.');
}),
checkTime
];
} else {
return [checkTime];
}
}
}
export default new AlarmClock();
| Check time after alarm disabled | Check time after alarm disabled
| JavaScript | mit | TEAMBUTT/LD35 | ---
+++
@@ -14,6 +14,10 @@
}
actions() {
+ const checkTime = action("Look at the time.", () => {
+ printMessage(`It is now ${time()}.`);
+ })
+
if(this.ringing) {
return [
action("Snooze", () => {
@@ -22,10 +26,11 @@
action("Turn if off.", () => {
this.ringing = false;
printMessage('You turn the alarm clock off.');
- })
+ }),
+ checkTime
];
} else {
- return [];
+ return [checkTime];
}
}
} |
a7114d6f043978002f6d7c9d1974f21c72dddf77 | lib/fs.utils.js | lib/fs.utils.js | const fs = require('fs')
function fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
function writeFile(filename, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, error => {
if (error) { reject(error); return }
resolve()
})
})
}
function readFile(filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, (error, data) => {
if (error) { reject(error); return }
resolve(data)
})
})
}
module.exports = exports = {
fileExist,
writeFile,
readFile
}
| const fs = require('fs')
function fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
function writeFile(filename, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, error => {
if (error) { reject(error); return }
resolve()
})
})
}
function readFile(filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, (error, data) => {
if (error) { reject(error); return }
resolve(data)
})
})
}
function chmod(filename, rights) {
return new Promise((resolve, reject) => {
fs.chmod(filename, rights, error => {
if (error) { reject(error); return }
resolve()
})
})
}
module.exports = exports = {
fileExist,
writeFile,
readFile,
chmod
}
| Add method to promisify chmod function | Add method to promisify chmod function
| JavaScript | apache-2.0 | Mindsers/configfile | ---
+++
@@ -30,8 +30,19 @@
})
}
+function chmod(filename, rights) {
+ return new Promise((resolve, reject) => {
+ fs.chmod(filename, rights, error => {
+ if (error) { reject(error); return }
+
+ resolve()
+ })
+ })
+}
+
module.exports = exports = {
fileExist,
writeFile,
- readFile
+ readFile,
+ chmod
} |
64e91980f64ca6299b774f2d47a7c352503b6466 | troposphere/static/js/components/modals/instance/launch/components/InstanceLaunchFooter.react.js | troposphere/static/js/components/modals/instance/launch/components/InstanceLaunchFooter.react.js | import React from 'react';
export default React.createClass({
propTypes: {
backIsDisabled: React.PropTypes.bool.isRequired,
launchIsDisabled: React.PropTypes.bool.isRequired,
advancedIsDisabled: React.PropTypes.bool.isRequired,
viewAdvanced: React.PropTypes.func,
onSubmitLaunch: React.PropTypes.func,
onCancel: React.PropTypes.func,
onBack: React.PropTypes.func,
},
renderBack: function() {
if (this.props.backIsDisabled) {
return
}
else {
return (
<a className="btn btn-default pull-left"
style={{marginRight:"10px"}}
onClick={this.props.onBack}
>
<span className="glyphicon glyphicon-arrow-left"/> Back
</a>
)
}
},
render: function() {
let launchIsDisabled = this.props.launchIsDisabled ? "disabled" : "";
let advancedIsDisabled = this.props.advancedIsDisabled ? "disabled" : "";
return (
<div className="modal-footer">
{this.renderBack()}
<a className={`pull-left btn ${advancedIsDisabled}`}
onClick={this.props.viewAdvanced}>
<i className="glyphicon glyphicon-cog"/>
Advanced Options
</a>
<button
disabled={this.props.launchIsDisabled}
type="button"
className={`btn btn-primary pull-right ${launchIsDisabled}`}
onClick={this.props.onSubmitLaunch}
>
Launch Instance
</button>
<button type="button"
className="btn btn-default pull-right"
style={{marginRight:"10px"}}
onClick={this.props.onCancel}
>
Cancel
</button>
</div>
)
}
});
| import React from 'react';
export default React.createClass({
propTypes: {
backIsDisabled: React.PropTypes.bool.isRequired,
launchIsDisabled: React.PropTypes.bool.isRequired,
advancedIsDisabled: React.PropTypes.bool.isRequired,
viewAdvanced: React.PropTypes.func,
onSubmitLaunch: React.PropTypes.func,
onCancel: React.PropTypes.func,
onBack: React.PropTypes.func,
},
renderBack: function() {
if (this.props.backIsDisabled) {
return
}
else {
return (
<a className="btn btn-default pull-left"
style={{marginRight:"10px"}}
onClick={this.props.onBack}
>
<span className="glyphicon glyphicon-arrow-left"/> Back
</a>
)
}
},
render: function() {
return (
<div className="modal-footer">
{this.renderBack()}
<a className="pull-left btn"
disabled={this.props.advancedIsDisabled}
onClick={this.props.viewAdvanced}>
<i className="glyphicon glyphicon-cog"/>
Advanced Options
</a>
<button
disabled={this.props.launchIsDisabled}
type="button"
className="btn btn-primary pull-right"
onClick={this.props.onSubmitLaunch}
>
Launch Instance
</button>
<button type="button"
className="btn btn-default pull-right"
style={{marginRight:"10px"}}
onClick={this.props.onCancel}
>
Cancel
</button>
</div>
)
}
});
| Make InstanceLaunchFooter functionally disabled instead of just visually | Make InstanceLaunchFooter functionally disabled instead of just visually
| JavaScript | apache-2.0 | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend | ---
+++
@@ -27,14 +27,13 @@
},
render: function() {
- let launchIsDisabled = this.props.launchIsDisabled ? "disabled" : "";
- let advancedIsDisabled = this.props.advancedIsDisabled ? "disabled" : "";
return (
<div className="modal-footer">
{this.renderBack()}
- <a className={`pull-left btn ${advancedIsDisabled}`}
+ <a className="pull-left btn"
+ disabled={this.props.advancedIsDisabled}
onClick={this.props.viewAdvanced}>
<i className="glyphicon glyphicon-cog"/>
Advanced Options
@@ -43,7 +42,7 @@
<button
disabled={this.props.launchIsDisabled}
type="button"
- className={`btn btn-primary pull-right ${launchIsDisabled}`}
+ className="btn btn-primary pull-right"
onClick={this.props.onSubmitLaunch}
>
Launch Instance |
fe97f331b8f2e94c03630f3b6adaec711c0978bd | test/acceptance/features/messages/step_definitions/messages.js | test/acceptance/features/messages/step_definitions/messages.js | const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
defineSupportCode(({ Then }) => {
const Messages = client.page.Messages()
Then(/^I see the success message$/, async () => {
await Messages
.waitForElementPresent('@flashMessage')
.assert.cssClassPresent('@flashMessage', 'c-message--success')
})
Then(/^I see the error message$/, () => {
Messages
.waitForElementPresent('@flashMessage')
.assert.cssClassPresent('@flashMessage', 'c-message--error')
})
})
| const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
defineSupportCode(({ Then }) => {
const Messages = client.page.Messages()
Then(/^I see the success message$/, async () => {
await Messages
.waitForElementPresent('@flashMessage')
.assert.cssClassPresent('@flashMessage', 'c-message--success')
})
})
| Remove redundant error message assertion | Remove redundant error message assertion
| JavaScript | mit | uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2 | ---
+++
@@ -9,10 +9,4 @@
.waitForElementPresent('@flashMessage')
.assert.cssClassPresent('@flashMessage', 'c-message--success')
})
-
- Then(/^I see the error message$/, () => {
- Messages
- .waitForElementPresent('@flashMessage')
- .assert.cssClassPresent('@flashMessage', 'c-message--error')
- })
}) |
071992c3a29c44ae565bd81c18b7144f87d356ff | Source/Our.Umbraco.Nexu.Core/Client/controllers/base-delete-controller.js | Source/Our.Umbraco.Nexu.Core/Client/controllers/base-delete-controller.js | angular.module('umbraco').controller('Our.Umbraco.Nexu.BaseDeleteController',
['$scope', '$controller', 'Our.Umbraco.Nexu.Resource',
function ($scope, $controller, nexuResource) {
// inherit core delete controller
angular.extend(this, $controller('Umbraco.Editors.Media.DeleteController', { $scope: $scope }));
$scope.links = {};
$scope.descendantsHaveLinks = false;
$scope.isLoading = true;
nexuResource.getIncomingLinks($scope.currentNode.id).then(function (result) {
$scope.links = result.data;
if (result.data.length == 0) {
nexuResource.checkDescendants($scope.currentNode.id, $scope.isMedia).then(function (result) {
$scope.descendantsHaveLinks = result.data;
$scope.isLoading = false;
});
} else {
$scope.isLoading = false;
}
});
}]); | angular.module('umbraco').controller('Our.Umbraco.Nexu.BaseDeleteController',
['$scope', '$controller', 'Our.Umbraco.Nexu.Resource',
function ($scope, $controller, nexuResource) {
// inherit core delete controller
if ($scope.isMedia) {
angular.extend(this, $controller('Umbraco.Editors.Media.DeleteController', { $scope: $scope }));
} else {
angular.extend(this, $controller('Umbraco.Editors.Content.DeleteController', { $scope: $scope }));
}
$scope.links = {};
$scope.descendantsHaveLinks = false;
$scope.isLoading = true;
nexuResource.getIncomingLinks($scope.currentNode.id).then(function (result) {
$scope.links = result.data;
if (result.data.length == 0) {
nexuResource.checkDescendants($scope.currentNode.id, $scope.isMedia).then(function (result) {
$scope.descendantsHaveLinks = result.data;
$scope.isLoading = false;
});
} else {
$scope.isLoading = false;
}
});
}]); | Set correct base controller for content type | Set correct base controller for content type
| JavaScript | mit | dawoe/umbraco-nexu,dawoe/umbraco-nexu,dawoe/umbraco-nexu | ---
+++
@@ -2,7 +2,12 @@
['$scope', '$controller', 'Our.Umbraco.Nexu.Resource',
function ($scope, $controller, nexuResource) {
// inherit core delete controller
- angular.extend(this, $controller('Umbraco.Editors.Media.DeleteController', { $scope: $scope }));
+ if ($scope.isMedia) {
+ angular.extend(this, $controller('Umbraco.Editors.Media.DeleteController', { $scope: $scope }));
+ } else {
+ angular.extend(this, $controller('Umbraco.Editors.Content.DeleteController', { $scope: $scope }));
+ }
+
$scope.links = {};
$scope.descendantsHaveLinks = false; |
463359038908a85f8624483473b29fe720050c06 | lib/markdown.js | lib/markdown.js | /* globals atom:false */
'use strict';
exports.provideBuilder = function () {
return {
niceName: 'Markdown',
isEligable: function () {
var textEditor = atom.workspace.getActiveTextEditor();
if (!textEditor || !textEditor.getPath()) {
return false;
}
var path = textEditor.getPath();
return path.endsWith('.md') || path.endsWith('.mkd');
},
settings: function () {
return [ {
name: 'Markdown: view',
exec: 'mark',
args: [ '{FILE_ACTIVE}' ]
}];
}
};
};
| /* globals atom:false */
'use strict';
exports.provideBuilder = function () {
return {
niceName: 'Markdown',
isEligable: function () {
var textEditor = atom.workspace.getActiveTextEditor();
if (!textEditor || !textEditor.getPath()) {
return false;
}
var path = textEditor.getPath();
return path.endsWith('.md') || path.endsWith('.mkd');
},
settings: function () {
return [ {
name: 'Markdown: view',
exec: 'open',
args: [ '-a', 'Marked.app', '{FILE_ACTIVE}' ]
}];
}
};
};
| Use `open` to find Marked.app, because of path problems finding the `mark` command. | Use `open` to find Marked.app, because of path problems finding the `mark` command. | JavaScript | mpl-2.0 | bwinton/atom-build-markdown | ---
+++
@@ -18,8 +18,8 @@
settings: function () {
return [ {
name: 'Markdown: view',
- exec: 'mark',
- args: [ '{FILE_ACTIVE}' ]
+ exec: 'open',
+ args: [ '-a', 'Marked.app', '{FILE_ACTIVE}' ]
}];
}
}; |
f659cc0dee2d9ed1df80793d87a1337a1403d7bc | packages/@sanity/desk-tool/src/DeskTool.js | packages/@sanity/desk-tool/src/DeskTool.js | import React, {PropTypes} from 'react'
import styles from '../styles/DeskTool.css'
import PaneResolver from 'config:desk-tool/pane-resolver'
DeskTool.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string.isRequired
})
}
function DeskTool({location}) {
return (
<div className={styles.deskTool}>
<PaneResolver location={location.pathname} />
</div>
)
}
export default DeskTool
| import React, {PropTypes} from 'react'
import styles from '../styles/DeskTool.css'
import PaneResolver from 'config:desk-tool/pane-resolver'
import ActionButton from 'component:@sanity/base/action-button?'
import schema from 'schema:@sanity/base/schema'
import config from 'config:sanity'
function DeskTool({location}) {
const actions = (schema.types || []).map(type => ({
url: `/${type.name}/${config.api.dataset}:`,
title: type.name.substr(0, 1).toUpperCase() + type.name.substr(1)
}))
return (
<div className={styles.deskTool}>
<PaneResolver location={location.pathname} />
{ActionButton && <ActionButton actions={actions} />}
</div>
)
}
DeskTool.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string.isRequired
})
}
export default DeskTool
| Use action button if it exists | Use action button if it exists
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -1,6 +1,24 @@
import React, {PropTypes} from 'react'
import styles from '../styles/DeskTool.css'
import PaneResolver from 'config:desk-tool/pane-resolver'
+import ActionButton from 'component:@sanity/base/action-button?'
+import schema from 'schema:@sanity/base/schema'
+import config from 'config:sanity'
+
+function DeskTool({location}) {
+ const actions = (schema.types || []).map(type => ({
+ url: `/${type.name}/${config.api.dataset}:`,
+ title: type.name.substr(0, 1).toUpperCase() + type.name.substr(1)
+ }))
+
+ return (
+ <div className={styles.deskTool}>
+ <PaneResolver location={location.pathname} />
+
+ {ActionButton && <ActionButton actions={actions} />}
+ </div>
+ )
+}
DeskTool.propTypes = {
location: PropTypes.shape({
@@ -8,12 +26,4 @@
})
}
-function DeskTool({location}) {
- return (
- <div className={styles.deskTool}>
- <PaneResolver location={location.pathname} />
- </div>
- )
-}
-
export default DeskTool |
f4f55a8ed829910cdec7d4025b4ea07ee606271b | rules/errors.js | rules/errors.js | 'use strict';
module.exports = {
'rules': {
// Enforce trailing commas in multiline object literals
'comma-dangle': [2, 'always-multiline'],
},
};
| 'use strict';
module.exports = {
'rules': {
// Enforce trailing commas in multiline object literals
'comma-dangle' : [2, 'always-multiline'],
// Disallow template literal placeholder syntax in regular strings
'no-template-curly-in-string': [2],
// Disallow negating the left operand of relational operators
'no-unsafe-negation' : [2],
// Enforce valid JSDoc comments
'valid-jsdoc' : [2],
},
};
| Enable more core “Errors” rules | Enable more core “Errors” rules | JavaScript | mit | nutshellcrm/eslint-config-nutshell | ---
+++
@@ -3,6 +3,12 @@
module.exports = {
'rules': {
// Enforce trailing commas in multiline object literals
- 'comma-dangle': [2, 'always-multiline'],
+ 'comma-dangle' : [2, 'always-multiline'],
+ // Disallow template literal placeholder syntax in regular strings
+ 'no-template-curly-in-string': [2],
+ // Disallow negating the left operand of relational operators
+ 'no-unsafe-negation' : [2],
+ // Enforce valid JSDoc comments
+ 'valid-jsdoc' : [2],
},
}; |
d13350e6592dce99e3d3b508b335e2b9f73000eb | routes/recipes/index.js | routes/recipes/index.js | var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
if (expand) {
try {
var relation = db.getData('/' + expand + 's');
_(recipes)
.forEach(function (recipe) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
});
}
catch(err) {
console.log(err);
}
}
res.json(recipes);
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
var relation;
if (expand) {
try {
relation = db.getData('/' + expand + 's');
}
catch(err) {
console.log(err.message);
}
}
// Obtain a possible search query
var q = req.query.q;
var qReg = q && new RegExp(q, 'i');
// Filter on the search query and then optionally
// expand recipes in the response
res.json(_(recipes)
.filter(function (recipe) {
if (qReg) {
return recipe.description.trim().match(qReg);
}
return true;
})
.map(function (recipe) {
if (relation) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
}
return recipe;
})
.value());
});
module.exports = router;
| Add section 2.4 code to search recipe descriptions | Add section 2.4 code to search recipe descriptions
| JavaScript | mit | adamsea/recipes-api | ---
+++
@@ -12,21 +12,37 @@
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
+ var relation;
if (expand) {
try {
- var relation = db.getData('/' + expand + 's');
- _(recipes)
- .forEach(function (recipe) {
- recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
- delete recipe[expand + 'Id'];
- });
+ relation = db.getData('/' + expand + 's');
}
catch(err) {
- console.log(err);
+ console.log(err.message);
}
}
- res.json(recipes);
+ // Obtain a possible search query
+ var q = req.query.q;
+ var qReg = q && new RegExp(q, 'i');
+
+ // Filter on the search query and then optionally
+ // expand recipes in the response
+ res.json(_(recipes)
+ .filter(function (recipe) {
+ if (qReg) {
+ return recipe.description.trim().match(qReg);
+ }
+ return true;
+ })
+ .map(function (recipe) {
+ if (relation) {
+ recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
+ delete recipe[expand + 'Id'];
+ }
+ return recipe;
+ })
+ .value());
});
module.exports = router; |
0a776b2259f3f3d5cda8d1103689539cfd9f862e | build/tasks/build-release/start.js | build/tasks/build-release/start.js | module.exports = function(grunt, config, parameters, done) {
function endForError(e) {
process.stderr.write(e.message || e);
done(false);
}
try {
var rimraf = require('rimraf'),
fs = require('fs'),
download = require('download'),
path = "./release";
rimraf.sync(path);
fs.mkdir(path);
// Download archive from git
process.stdout.write("Downloading Archive...\n");
var stream = download('https://github.com/concrete5/concrete5/archive/master.zip', path, {
extract: true
});
stream.on('close', function() {
done();
});
}
catch(e) {
endForError(e);
return;
}
}; | module.exports = function(grunt, config, parameters, done) {
function endForError(e) {
process.stderr.write(e.message || e);
done(false);
}
try {
var shell = require('shelljs'),
fs = require('fs'),
download = require('download'),
path = "./release";
shell.rm('-rf', path);
fs.mkdir(path);
// Download archive from git
process.stdout.write("Downloading Archive...\n");
var stream = download('https://github.com/concrete5/concrete5/archive/master.zip', path, {
extract: true
});
stream.on('close', function() {
done();
});
}
catch(e) {
endForError(e);
return;
}
}; | Use shelljs instead of rimraf | Use shelljs instead of rimraf
| JavaScript | mit | matt9mg/concrete5,TimDix/concrete5,TimDix/concrete5,avdevs/concrete5,matt9mg/concrete5,avdevs/concrete5,avdevs/concrete5,MichaelMaar/concrete5,TimDix/concrete5,MichaelMaar/concrete5,matt9mg/concrete5,MichaelMaar/concrete5 | ---
+++
@@ -6,12 +6,12 @@
}
try {
- var rimraf = require('rimraf'),
+ var shell = require('shelljs'),
fs = require('fs'),
download = require('download'),
path = "./release";
- rimraf.sync(path);
+ shell.rm('-rf', path);
fs.mkdir(path);
// Download archive from git |
602adb639f55da9ee6a9c16f5c0fec0e4e10821f | assets/debug.js | assets/debug.js | window.onerror = function(message, url, line) {
$.ajax('/api/Error', {
data: {
message: message,
url: url,
line: line
}
});
};
| window.onerror = function(message, url, line) {
// Don't attempt to handle non-standard errors (e.g. failed
// HTTP request via jQuery).
if (typeof message !== 'string') return;
$.ajax('/api/Error', {
data: {
message: message,
url: url,
line: line
}
});
};
| Fix for failure to serialize jQuery event object. | Fix for failure to serialize jQuery event object.
| JavaScript | bsd-3-clause | developmentseed/bones,Wiredcraft/bones,developmentseed/bones,Wiredcraft/bones | ---
+++
@@ -1,4 +1,7 @@
window.onerror = function(message, url, line) {
+ // Don't attempt to handle non-standard errors (e.g. failed
+ // HTTP request via jQuery).
+ if (typeof message !== 'string') return;
$.ajax('/api/Error', {
data: {
message: message, |
3a09cec10086b36ad297b31efdb3575bbc1163ee | mark_as_read.js | mark_as_read.js | HNSpecial.settings.registerModule("mark_as_read", function () {
function editLinks() {
var subtexts = _.toArray(document.getElementsByClassName("subtext"));
subtexts.forEach(function (subtext) {
if (!subtext.getAttribute("data-hnspecial-mark-as-read")) {
subtext.setAttribute("data-hnspecial-mark-as-read", "true");
// Create the Mark as read "button"
var button = _.createElement("span", {
classes: ["hnspecial-mark-as-read-button"],
content: "✔" // tick symbol
});
// Add the click listener
button.addEventListener("click", function (e) {
// Wow, that escalated quickly
var url = e.target.parentElement.parentElement.previousSibling.childNodes[2].children[0].href;
chrome.extension.sendRequest({
module: "mark_as_read",
action: "toggle",
params: {
url: url
}
});
});
// Insert the button into the page
subtext.insertBefore(button, subtext.children[0]);
}
});
}
// Run it
editLinks();
// Subscribe to the event emitted when new links are present
HNSpecial.settings.subscribe("new links", editLinks);
});
| HNSpecial.settings.registerModule("mark_as_read", function () {
function editLinks() {
var subtexts = _.toArray(document.getElementsByClassName("subtext"));
subtexts.forEach(function (subtext) {
if (!subtext.getAttribute("data-hnspecial-mark-as-read")) {
subtext.setAttribute("data-hnspecial-mark-as-read", "true");
// Create the Mark as read "button"
var button = _.createElement("span", {
classes: ["hnspecial-mark-as-read-button"],
content: "✔" // tick symbol
});
// Add the click listener
button.addEventListener("click", function (e) {
// Well, that escalated quickly
var url = e.target.parentElement.parentElement.previousSibling.childNodes[2].children[0].href;
chrome.extension.sendRequest({
module: "mark_as_read",
action: "toggle",
params: {
url: url
}
});
});
// Insert the button into the page
subtext.insertBefore(button, subtext.childNodes[0]);
}
});
}
// Run it
editLinks();
// Subscribe to the event emitted when new links are present
HNSpecial.settings.subscribe("new links", editLinks);
});
| Make sure button is before all other children | Make sure button is before all other children
| JavaScript | mit | lieuwex/hn-special,gabrielecirulli/hn-special,gabrielecirulli/hn-special,benoror/hn-special,lieuwex/hn-special,lieuwex/hn-special,benoror/hn-special,gabrielecirulli/hn-special,benoror/hn-special,kislakiruben/hn-special,kislakiruben/hn-special,kislakiruben/hn-special | ---
+++
@@ -14,7 +14,7 @@
// Add the click listener
button.addEventListener("click", function (e) {
- // Wow, that escalated quickly
+ // Well, that escalated quickly
var url = e.target.parentElement.parentElement.previousSibling.childNodes[2].children[0].href;
chrome.extension.sendRequest({
@@ -27,7 +27,7 @@
});
// Insert the button into the page
- subtext.insertBefore(button, subtext.children[0]);
+ subtext.insertBefore(button, subtext.childNodes[0]);
}
});
} |
c86593d654f2852caad6620510069c63191c3f04 | app/index.js | app/index.js | var peer = require('./peer');
var textOT = require('ottypes').text
var gulf = require('gulf');
var bindEditor = require('gulf-textarea');
var textarea = document.querySelector('textarea#doc');
var textareaDoc = bindEditor(textarea);
var text = 'hello';
var path = 'chat.sock';
// var transport = require('./transports/socket')(path);
// var transport = require('./transports/mdns')({ port: 4321, name: 'nybblr' });
var transport = require('./transports/webrtc')();
peer(transport).then(stream => {
console.log('started');
console.log(stream.server ? 'master' : 'slave');
window.stream = stream;
var textareaMaster = textareaDoc.masterLink();
if (stream.server) {
// master
gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, doc) => {
var slave1 = doc.slaveLink();
stream.pipe(slave1).pipe(stream);
var slave2 = doc.slaveLink();
textareaMaster.pipe(slave2).pipe(textareaMaster);
});
} else {
// slave
textareaMaster.pipe(stream).pipe(textareaMaster);
}
});
| var peer = require('./peer');
var textOT = require('ottypes').text
var gulf = require('gulf');
var text = 'hello';
var doc = require('gulf-textarea')(
document.querySelector('textarea#doc')
);
var path = 'chat.sock';
// var transport = require('./transports/socket')(path);
// var transport = require('./transports/mdns')({ port: 4321, name: 'nybblr' });
var transport = require('./transports/webrtc')();
peer(transport).then(stream => {
console.log('started');
console.log(stream.server ? 'master' : 'slave');
window.stream = stream;
var textareaMaster = doc.masterLink();
if (stream.server) {
// master
gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, master) => {
var slave1 = master.slaveLink();
stream.pipe(slave1).pipe(stream);
var slave2 = master.slaveLink();
textareaMaster.pipe(slave2).pipe(textareaMaster);
});
} else {
// slave
textareaMaster.pipe(stream).pipe(textareaMaster);
}
});
| Tidy doc representation into swappable one-liner. | Tidy doc representation into swappable one-liner.
| JavaScript | cc0-1.0 | nybblr/p2p-experiments,nybblr/p2p-experiments | ---
+++
@@ -2,10 +2,11 @@
var textOT = require('ottypes').text
var gulf = require('gulf');
-var bindEditor = require('gulf-textarea');
-var textarea = document.querySelector('textarea#doc');
-var textareaDoc = bindEditor(textarea);
var text = 'hello';
+
+var doc = require('gulf-textarea')(
+ document.querySelector('textarea#doc')
+);
var path = 'chat.sock';
// var transport = require('./transports/socket')(path);
@@ -17,15 +18,15 @@
console.log(stream.server ? 'master' : 'slave');
window.stream = stream;
- var textareaMaster = textareaDoc.masterLink();
+ var textareaMaster = doc.masterLink();
if (stream.server) {
// master
- gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, doc) => {
- var slave1 = doc.slaveLink();
+ gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, master) => {
+ var slave1 = master.slaveLink();
stream.pipe(slave1).pipe(stream);
- var slave2 = doc.slaveLink();
+ var slave2 = master.slaveLink();
textareaMaster.pipe(slave2).pipe(textareaMaster);
});
} else { |
dc79c6bdd3bae0ed3aa5a5663a55d574ab18379d | app/index.js | app/index.js | import 'babel-core/polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { ReduxRouter } from 'redux-router';
import Immutable from 'seamless-immutable';
import rootReducer from 'reducers/index';
import configureStore from 'store/configureStore';
import 'assets/styles/app.less';
const initialStoreState = createStore(rootReducer, {}).getState();
const initialState = window.__INITIAL_STATE__;
const finalState = Immutable(initialStoreState).merge(initialState, { deep: true });
const store = configureStore(finalState);
render(
<Provider store={store}>
<ReduxRouter
components={[]}
location={{}}
params={{}}
routes={[]}
/>
</Provider>,
document.getElementById('root')
);
if (__DEVTOOLS__) {
require('./createDevToolsWindow')(store);
}
| import 'babel-core/polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { ReduxRouter } from 'redux-router';
import Immutable from 'seamless-immutable';
import rootReducer from 'reducers/index';
import configureStore from 'store/configureStore';
import 'assets/styles/app.less';
const initialStoreState = createStore(rootReducer, {}).getState();
const initialState = window.__INITIAL_STATE__;
const finalState = Immutable(initialStoreState).merge(initialState, { deep: true });
const store = configureStore(finalState);
render(
<Provider store={store}>
<ReduxRouter
components={[]}
location={{}}
params={{}}
routes={[]}
/>
</Provider>,
document.getElementById('root')
);
if (__DEVTOOLS__) {
require('./createDevToolsWindow')(store);
}
// Fix for IE
if (!window.location.origin) {
window.location.origin = (
window.location.protocol + '//' + window.location.hostname + (
window.location.port ? ':' + window.location.port : ''
)
);
}
| Fix logout link on IE | Fix logout link on IE
Closes #213.
| JavaScript | mit | fastmonkeys/respa-ui | ---
+++
@@ -32,3 +32,12 @@
if (__DEVTOOLS__) {
require('./createDevToolsWindow')(store);
}
+
+// Fix for IE
+if (!window.location.origin) {
+ window.location.origin = (
+ window.location.protocol + '//' + window.location.hostname + (
+ window.location.port ? ':' + window.location.port : ''
+ )
+ );
+} |
6dc0dabebb1ce6bf419cbb53d83c42b017c467a6 | src/components/datepicker/utils.js | src/components/datepicker/utils.js | import { DateUtils } from 'react-day-picker/lib/src/index';
export const convertModifiersToClassnames = (modifiers, theme) => {
if (!modifiers) {
return {};
}
return Object.keys(modifiers).reduce((convertedModifiers, key) => {
return {
...convertedModifiers,
[theme[key]]: modifiers[key],
};
}, {});
};
export const isSelectingFirstDay = (from, to, day) => {
const isBeforeFirstDay = from && DateUtils.isDayBefore(day, from);
const isRangeSelected = from && to;
return !from || isBeforeFirstDay || isRangeSelected;
};
| import { DateUtils } from 'react-day-picker/lib/src/index';
import { DateTime } from 'luxon';
export const convertModifiersToClassnames = (modifiers, theme) => {
if (!modifiers) {
return {};
}
return Object.keys(modifiers).reduce((convertedModifiers, key) => {
return {
...convertedModifiers,
[theme[key]]: modifiers[key],
};
}, {});
};
export const isSelectingFirstDay = (from, to, day) => {
const isBeforeFirstDay = from && DateUtils.isDayBefore(day, from);
const isRangeSelected = from && to;
return !from || isBeforeFirstDay || isRangeSelected;
};
export function JSDateToLocaleString(date, locale, format = DateTime.DATE_SHORT) {
return DateTime.fromJSDate(date)
.setLocale(locale)
.toLocaleString(format);
}
| Add util function to convert a JS date to locale string | Add util function to convert a JS date to locale string
| JavaScript | mit | teamleadercrm/teamleader-ui | ---
+++
@@ -1,4 +1,5 @@
import { DateUtils } from 'react-day-picker/lib/src/index';
+import { DateTime } from 'luxon';
export const convertModifiersToClassnames = (modifiers, theme) => {
if (!modifiers) {
@@ -18,3 +19,9 @@
const isRangeSelected = from && to;
return !from || isBeforeFirstDay || isRangeSelected;
};
+
+export function JSDateToLocaleString(date, locale, format = DateTime.DATE_SHORT) {
+ return DateTime.fromJSDate(date)
+ .setLocale(locale)
+ .toLocaleString(format);
+} |
30c2850e9593738f2059c4c401ac75fd7b2c87fe | src/js/route.js | src/js/route.js | var route = function(name, params = {}, absolute = true) {
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri,
paramsArrayKey = 0;
return url.replace(
/\{([^}]+)\}/gi,
function (tag) {
var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, '');
paramsArrayKey++;
if (params[key] === undefined) {
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
}
return params[key];
}
);
}
if (typeof exports !== 'undefined'){ exports.route = route }
| var route = function(name, params = {}, absolute = true) {
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri,
params = typeof params !== 'object' ? [params] : params,
paramsArrayKey = 0;
return url.replace(
/\{([^}]+)\}/gi,
function (tag) {
var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, '');
paramsArrayKey++;
if (params[key] === undefined) {
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
}
return params[key];
}
);
}
if (typeof exports !== 'undefined'){ exports.route = route }
| Add support for single param instead of array/object. | Add support for single param instead of array/object.
| JavaScript | mit | tightenco/ziggy,tightenco/ziggy | ---
+++
@@ -1,6 +1,7 @@
var route = function(name, params = {}, absolute = true) {
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri,
+ params = typeof params !== 'object' ? [params] : params,
paramsArrayKey = 0;
return url.replace( |
72c5934e1f5fde40ef8cdae61b205ebd91bddd3c | website/src/app/project/experiments/experiment/experiment.model.js | website/src/app/project/experiments/experiment/experiment.model.js | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
| export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
this.done = false;
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
| Add done flag to experiment. | Add done flag to experiment.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -39,6 +39,7 @@
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
+ this.done = false;
this.steps = [];
}
|
ba39cf7dbc7ec530d0e9556bd819f01ae97f73f3 | src/helpers/collection/sort.js | src/helpers/collection/sort.js |
exports.sort = function (Handlebars) {
return function (array, field, options) {
if (arguments.length === 1) {
throw new Error('Handlebars Helper "sort" needs 1 parameter');
}
options = arguments[arguments.length - 1];
if (arguments.length === 2) {
field = undefined;
}
var results;
if (field === undefined) {
results = array.sort();
} else {
results = array.sort(function (a, b) {
return a[field] > b[field];
});
}
if (!options.fn) {
return results;
} else {
if (results.length) {
var data = Handlebars.createFrame(options.data);
return results.map(function (result, i) {
data.index = i;
data.first = (i === 0);
data.last = (i === results.length - 1);
return options.fn(result, {data: data});
}).join('');
} else {
return options.inverse(this);
}
}
};
};
|
exports.sort = function (Handlebars) {
return function (input, key, options) {
if (arguments.length === 1) {
throw new Error('Handlebars Helper "sort" needs 1 parameter');
}
options = arguments[arguments.length - 1];
if (arguments.length === 2) {
key = undefined;
}
var results = input.concat();
if (key === undefined) {
results.sort();
} else {
results.sort(function (a, b) {
if (typeof a !== 'object' && typeof b !== 'object') return 0;
if (typeof a !== 'object') return -1;
if (typeof b !== 'object') return 1;
return a[key] > b[key];
});
}
if (!options.fn) {
return results;
} else {
if (results.length) {
var data = Handlebars.createFrame(options.data);
return results.map(function (result, i) {
data.index = i;
data.first = (i === 0);
data.last = (i === results.length - 1);
return options.fn(result, {data: data});
}).join('');
} else {
return options.inverse(this);
}
}
};
};
| Sort by key now confirms both inputs are objects before comparing keys. | Sort by key now confirms both inputs are objects before comparing keys.
| JavaScript | mit | ChiperSoft/HandlebarsHelperHoard,ChiperSoft/HandlebarsHelperHoard | ---
+++
@@ -1,6 +1,6 @@
exports.sort = function (Handlebars) {
- return function (array, field, options) {
+ return function (input, key, options) {
if (arguments.length === 1) {
throw new Error('Handlebars Helper "sort" needs 1 parameter');
}
@@ -8,15 +8,18 @@
options = arguments[arguments.length - 1];
if (arguments.length === 2) {
- field = undefined;
+ key = undefined;
}
- var results;
- if (field === undefined) {
- results = array.sort();
+ var results = input.concat();
+ if (key === undefined) {
+ results.sort();
} else {
- results = array.sort(function (a, b) {
- return a[field] > b[field];
+ results.sort(function (a, b) {
+ if (typeof a !== 'object' && typeof b !== 'object') return 0;
+ if (typeof a !== 'object') return -1;
+ if (typeof b !== 'object') return 1;
+ return a[key] > b[key];
});
}
|
ec7fa504176d692b3425a9954114189e6428c03e | src/js/ui/counter-indicator.js | src/js/ui/counter-indicator.js | export const counterIndicator = {
name: 'counter',
order: 5,
onInit: (counterElement, pswp) => {
pswp.on('change', () => {
counterElement.innerHTML = (pswp.currIndex + 1)
+ pswp.options.indexIndicatorSep
+ pswp.getNumItems();
});
}
};
| export const counterIndicator = {
name: 'counter',
order: 5,
onInit: (counterElement, pswp) => {
pswp.on('change', () => {
counterElement.innerText = (pswp.currIndex + 1)
+ pswp.options.indexIndicatorSep
+ pswp.getNumItems();
});
}
};
| Drop support of HTML for indexIndicatorSep option | Drop support of HTML for indexIndicatorSep option
| JavaScript | mit | dimsemenov/PhotoSwipe,dimsemenov/PhotoSwipe | ---
+++
@@ -3,7 +3,7 @@
order: 5,
onInit: (counterElement, pswp) => {
pswp.on('change', () => {
- counterElement.innerHTML = (pswp.currIndex + 1)
+ counterElement.innerText = (pswp.currIndex + 1)
+ pswp.options.indexIndicatorSep
+ pswp.getNumItems();
}); |
90405067d41afe85eaaa7d9822f40f5ec74b7881 | spring-boot-admin-server-ui/modules/applications/services/applicationViews.js | spring-boot-admin-server-ui/modules/applications/services/applicationViews.js | /*
* Copyright 2014 the original author or authors.
*
* 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.
*/
'use strict';
module.exports = function ($state, $q) {
'ngInject';
var views = [];
this.register = function (view) {
views.push(view);
};
this.getApplicationViews = function (application) {
var applicationViews = [];
views.forEach(function (view) {
$q.when(!view.show || view.show(application)).then(function (result) {
if (result) {
view.href = $state.href(view.state, {
id: application.id
});
applicationViews.push(view);
applicationViews.sort(function (v1, v2) {
return (v1.order || 0) - (v2.order || 0);
});
}
});
});
return applicationViews;
};
};
| /*
* Copyright 2014 the original author or authors.
*
* 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.
*/
'use strict';
var angular = require('angular');
module.exports = function ($state, $q) {
'ngInject';
var views = [];
this.register = function (view) {
views.push(view);
};
this.getApplicationViews = function (application) {
var applicationViews = [];
views.forEach(function (view) {
$q.when(!view.show || view.show(application)).then(function (result) {
if (result) {
var appView = angular.copy(view);
appView.href = $state.href(view.state, {
id: application.id
});
applicationViews.push(appView);
applicationViews.sort(function (v1, v2) {
return (v1.order || 0) - (v2.order || 0);
});
}
});
});
return applicationViews;
};
};
| Fix wrong links when listing multiple apps | Fix wrong links when listing multiple apps
| JavaScript | apache-2.0 | codecentric/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,joshiste/spring-boot-admin,codecentric/spring-boot-admin,codecentric/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,librucha/spring-boot-admin | ---
+++
@@ -15,6 +15,7 @@
*/
'use strict';
+var angular = require('angular');
module.exports = function ($state, $q) {
'ngInject';
@@ -29,18 +30,18 @@
views.forEach(function (view) {
$q.when(!view.show || view.show(application)).then(function (result) {
if (result) {
- view.href = $state.href(view.state, {
+ var appView = angular.copy(view);
+ appView.href = $state.href(view.state, {
id: application.id
});
- applicationViews.push(view);
+ applicationViews.push(appView);
applicationViews.sort(function (v1, v2) {
return (v1.order || 0) - (v2.order || 0);
});
}
});
});
-
return applicationViews;
};
}; |
c3b3b55bcd208f66a2a6e85f1b97d822d815e803 | schema/image/proxies/index.js | schema/image/proxies/index.js | module.exports = function() {
return require('./embedly').apply(null, arguments);
};
| const { RESIZING_SERVICE } = process.env;
module.exports = function() {
if (RESIZING_SERVICE === 'gemini') {
return require('./gemini').apply(null, arguments);
} else {
return require('./embedly').apply(null, arguments);
}
};
| Configure using an ENV variable | Configure using an ENV variable
| JavaScript | mit | craigspaeth/metaphysics,mzikherman/metaphysics-1,craigspaeth/metaphysics,mzikherman/metaphysics-1,1aurabrown/metaphysics,artsy/metaphysics,broskoski/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics,artsy/metaphysics | ---
+++
@@ -1,3 +1,9 @@
+const { RESIZING_SERVICE } = process.env;
+
module.exports = function() {
- return require('./embedly').apply(null, arguments);
+ if (RESIZING_SERVICE === 'gemini') {
+ return require('./gemini').apply(null, arguments);
+ } else {
+ return require('./embedly').apply(null, arguments);
+ }
}; |
fd1b91a2cc219d27318d7b72a213a41c55fd1859 | dataviva/static/js/modules/help.js | dataviva/static/js/modules/help.js | $('.sidebar a').on('click', function(){
$('.sidebar a').attr('class','');
$(this).toggleClass('active');
}); | $('.sidebar a').on('click', function(){
$('.sidebar a').attr('class','');
$(this).toggleClass('active');
});
$("#home .col-md-6 > .panel-heading > h2 a").on('click', function(){
$('.sidebar a').attr('class','');
$('#sidebar_' + $(this).parent().parent()[0].id).toggleClass('active');
}); | Add js funtion that maps tab-content to sidebar-menu. | Add js funtion that maps tab-content to sidebar-menu.
| JavaScript | mit | DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site | ---
+++
@@ -2,3 +2,9 @@
$('.sidebar a').attr('class','');
$(this).toggleClass('active');
});
+
+
+$("#home .col-md-6 > .panel-heading > h2 a").on('click', function(){
+ $('.sidebar a').attr('class','');
+ $('#sidebar_' + $(this).parent().parent()[0].id).toggleClass('active');
+}); |
6055bc4109f4ccc582095f912bf68fb796e6d63e | public/js/chrome/toppanel.js | public/js/chrome/toppanel.js | (function () {
/*global jsbin, $, $body*/
'use strict';
if (jsbin.settings.gui === undefined) {
jsbin.settings.gui = {};
}
if (jsbin.settings.gui.toppanel === undefined) {
jsbin.settings.gui.toppanel = true;
}
var removeToppanel = function() {
$body.addClass('toppanel-close');
$body.removeClass('toppanel');
};
var showToppanel = function() {
$body.removeClass('toppanel-close');
$body.addClass('toppanel');
};
// to remove
var goSlow = function(e) {
$body.removeClass('toppanel-slow');
if (e.shiftKey) {
$body.addClass('toppanel-slow');
}
};
$('.toppanel-hide').click(function(event) {
event.preventDefault();
goSlow(event);
jsbin.settings.gui.toppanel = false;
removeToppanel();
});
$('.toppanel-logo').click(function(event) {
event.preventDefault();
goSlow(event);
jsbin.settings.gui.toppanel = true;
showToppanel();
});
$document.keydown(function (event) {
if (event.which == 27) {
if ($body.hasClass('toppanel')) {
jsbin.settings.gui.toppanel = false;
removeToppanel();
}
}
});
}()); | (function () {
/*global jsbin, $, $body, $document*/
'use strict';
if (jsbin.settings.gui === undefined) {
jsbin.settings.gui = {};
}
if (jsbin.settings.gui.toppanel === undefined) {
jsbin.settings.gui.toppanel = true;
localStorage.setItem('settings', JSON.stringify(jsbin.settings));
}
var removeToppanel = function() {
jsbin.settings.gui.toppanel = false;
localStorage.setItem('settings', JSON.stringify(jsbin.settings));
$body.addClass('toppanel-close');
$body.removeClass('toppanel');
};
var showToppanel = function() {
jsbin.settings.gui.toppanel = true;
localStorage.setItem('settings', JSON.stringify(jsbin.settings));
$body.removeClass('toppanel-close');
$body.addClass('toppanel');
};
// to remove
var goSlow = function(e) {
$body.removeClass('toppanel-slow');
if (e.shiftKey) {
$body.addClass('toppanel-slow');
}
};
$('.toppanel-hide').click(function(event) {
event.preventDefault();
goSlow(event);
removeToppanel();
});
$('.toppanel-logo').click(function(event) {
event.preventDefault();
goSlow(event);
showToppanel();
});
$document.keydown(function (event) {
if (event.which == 27) {
if ($body.hasClass('toppanel')) {
removeToppanel();
}
}
});
}()); | Save the state in localStorage | Save the state in localStorage
| JavaScript | mit | IvanSanchez/jsbin,eggheadio/jsbin,yohanboniface/jsbin,jsbin/jsbin,vipulnsward/jsbin,KenPowers/jsbin,yize/jsbin,thsunmy/jsbin,jamez14/jsbin,martinvd/jsbin,ilyes14/jsbin,svacha/jsbin,remotty/jsbin,yize/jsbin,roman01la/jsbin,kirjs/jsbin,IvanSanchez/jsbin,yohanboniface/jsbin,mlucool/jsbin,kirjs/jsbin,filamentgroup/jsbin,minwe/jsbin,jamez14/jsbin,AverageMarcus/jsbin,mingzeke/jsbin,jasonsanjose/jsbin-app,francoisp/jsbin,thsunmy/jsbin,arcseldon/jsbin,fgrillo21/NPA-Exam,IveWong/jsbin,dennishu001/jsbin,dedalik/jsbin,mlucool/jsbin,pandoraui/jsbin,francoisp/jsbin,simonThiele/jsbin,ctide/jsbin,late-warrior/jsbin,saikota/jsbin,knpwrs/jsbin,blesh/jsbin,mingzeke/jsbin,HeroicEric/jsbin,saikota/jsbin,ctide/jsbin,mcanthony/jsbin,dedalik/jsbin,eggheadio/jsbin,johnmichel/jsbin,IveWong/jsbin,minwe/jsbin,fgrillo21/NPA-Exam,jwdallas/jsbin,juliankrispel/jsbin,y3sh/jsbin-fork,carolineartz/jsbin,vipulnsward/jsbin,roman01la/jsbin,ilyes14/jsbin,KenPowers/jsbin,juliankrispel/jsbin,simonThiele/jsbin,kentcdodds/jsbin,jwdallas/jsbin,knpwrs/jsbin,kentcdodds/jsbin,fend-classroom/jsbin,y3sh/jsbin-fork,johnmichel/jsbin,fend-classroom/jsbin,dhval/jsbin,KenPowers/jsbin,svacha/jsbin,mdo/jsbin,dhval/jsbin,late-warrior/jsbin,dennishu001/jsbin,jsbin/jsbin,AverageMarcus/jsbin,martinvd/jsbin,Freeformers/jsbin,peterblazejewicz/jsbin,carolineartz/jsbin,arcseldon/jsbin,HeroicEric/jsbin,filamentgroup/jsbin,Hamcha/jsbin,Hamcha/jsbin,mcanthony/jsbin,jasonsanjose/jsbin-app,digideskio/jsbin,peterblazejewicz/jsbin,knpwrs/jsbin,Freeformers/jsbin,pandoraui/jsbin,digideskio/jsbin | ---
+++
@@ -1,5 +1,5 @@
(function () {
- /*global jsbin, $, $body*/
+ /*global jsbin, $, $body, $document*/
'use strict';
if (jsbin.settings.gui === undefined) {
@@ -7,14 +7,19 @@
}
if (jsbin.settings.gui.toppanel === undefined) {
jsbin.settings.gui.toppanel = true;
+ localStorage.setItem('settings', JSON.stringify(jsbin.settings));
}
var removeToppanel = function() {
+ jsbin.settings.gui.toppanel = false;
+ localStorage.setItem('settings', JSON.stringify(jsbin.settings));
$body.addClass('toppanel-close');
$body.removeClass('toppanel');
};
var showToppanel = function() {
+ jsbin.settings.gui.toppanel = true;
+ localStorage.setItem('settings', JSON.stringify(jsbin.settings));
$body.removeClass('toppanel-close');
$body.addClass('toppanel');
};
@@ -30,19 +35,16 @@
$('.toppanel-hide').click(function(event) {
event.preventDefault();
goSlow(event);
- jsbin.settings.gui.toppanel = false;
removeToppanel();
});
$('.toppanel-logo').click(function(event) {
event.preventDefault();
goSlow(event);
- jsbin.settings.gui.toppanel = true;
showToppanel();
});
$document.keydown(function (event) {
if (event.which == 27) {
if ($body.hasClass('toppanel')) {
- jsbin.settings.gui.toppanel = false;
removeToppanel();
}
} |
0a4fba655f4030f0b4b5d244416510086c0ae419 | public/main/utils/updates.js | public/main/utils/updates.js | define([
"Underscore",
"yapp/yapp",
"vendors/socket.io"
], function(_, yapp, io) {
var logging = yapp.Logger.addNamespace("updates");
var Updates = new (yapp.Class.extend({
/* Constructor */
initialize: function() {
this.url = [window.location.protocol, '//', window.location.host].join('');
logging.log("Connexion to "+this.url);
this.socket = io.connect(this.url);
// Video streaming stats
this.socket.on('stats', function(data) {
//logging.log("streaming stats ", data);
this.trigger("streaming:stats", data);
});
// Remote control connected
this.socket.on('remote', _.bind(function() {
logging.log("remote is connected");
this.trigger("remote:start");
}, this));
// Touch input from remote
this.socket.on('remote_input', _.bind(function(data) {
logging.log("remote input ", data);
this.trigger("remote:input", data);
}, this));
// Search from remote
this.socket.on('remote_search', _.bind(function(q) {
logging.log("remote search ", q);
this.trigger("remote:search", q);
yapp.History.navigate("search/:q", {
"q": q
});
}, this));
// Connexion error
this.socket.on('error', _.bind(function(data) {
logging.error("error in socket.io")
}, this));
return this;
},
}));
return Updates;
}); | define([
"Underscore",
"yapp/yapp",
"vendors/socket.io"
], function(_, yapp, io) {
var logging = yapp.Logger.addNamespace("updates");
var Updates = new (yapp.Class.extend({
/* Constructor */
initialize: function() {
this.url = [window.location.protocol, '//', window.location.host].join('');
logging.log("Connexion to "+this.url);
this.socket = io.connect(this.url);
// Video streaming stats
this.socket.on('stats', _.bind(function(data) {
//logging.log("streaming stats ", data);
this.trigger("streaming:stats", data);
}, this));
// Remote control connected
this.socket.on('remote', _.bind(function() {
logging.log("remote is connected");
this.trigger("remote:start");
}, this));
// Touch input from remote
this.socket.on('remote_input', _.bind(function(data) {
logging.log("remote input ", data);
this.trigger("remote:input", data);
}, this));
// Search from remote
this.socket.on('remote_search', _.bind(function(q) {
logging.log("remote search ", q);
this.trigger("remote:search", q);
yapp.History.navigate("search/:q", {
"q": q
});
}, this));
// Connexion error
this.socket.on('error', _.bind(function(data) {
logging.error("error in socket.io")
}, this));
return this;
},
}));
return Updates;
}); | Correct error in client for streaming | Correct error in client for streaming
| JavaScript | apache-2.0 | mafintosh/tv.js,thefkboss/tv.js,SamyPesse/tv.js,thefkboss/tv.js,mafintosh/tv.js,SamyPesse/tv.js,thefkboss/tv.js | ---
+++
@@ -12,10 +12,10 @@
this.socket = io.connect(this.url);
// Video streaming stats
- this.socket.on('stats', function(data) {
+ this.socket.on('stats', _.bind(function(data) {
//logging.log("streaming stats ", data);
this.trigger("streaming:stats", data);
- });
+ }, this));
// Remote control connected
this.socket.on('remote', _.bind(function() { |
15607d784bd426fa22789beaf42b6625e0c606c0 | src/chart/candlestick/candlestickVisual.js | src/chart/candlestick/candlestickVisual.js | define(function (require) {
var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor'];
var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0'];
var positiveColorQuery = ['itemStyle', 'normal', 'color'];
var negativeColorQuery = ['itemStyle', 'normal', 'color0'];
return function (ecModel, api) {
ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
var data = seriesModel.getData();
data.setVisual({
legendSymbol: 'roundRect'
});
// Only visible series has each data be visual encoded
if (!ecModel.isSeriesFiltered(seriesModel)) {
data.each(function (idx) {
var itemModel = data.getItemModel(idx);
var sign = data.getItemLayout(idx).sign;
data.setItemVisual(
idx,
{
color: itemModel.get(
sign > 0 ? positiveColorQuery : negativeColorQuery
),
borderColor: itemModel.get(
sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
)
}
);
});
}
});
};
}); | define(function (require) {
var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor'];
var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0'];
var positiveColorQuery = ['itemStyle', 'normal', 'color'];
var negativeColorQuery = ['itemStyle', 'normal', 'color0'];
return function (ecModel, api) {
ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
var data = seriesModel.getData();
data.setVisual({
legendSymbol: 'roundRect'
});
// Only visible series has each data be visual encoded
if (!ecModel.isSeriesFiltered(seriesModel)) {
data.each(function (idx) {
var itemModel = data.getItemModel(idx);
var openVal = data.get('open', idx);
var closeVal = data.get('close', idx);
var sign = openVal > closeVal ? -1 : openVal < closeVal ? 1 : 0;
data.setItemVisual(
idx,
{
color: itemModel.get(
sign > 0 ? positiveColorQuery : negativeColorQuery
),
borderColor: itemModel.get(
sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
)
}
);
});
}
});
};
}); | Remove layout dependency in candlestick visual | Remove layout dependency in candlestick visual
| JavaScript | apache-2.0 | hexj/echarts,ecomfe/echarts,ecomfe/echarts,apache/incubator-echarts,chenfwind/echarts,hexj/echarts,100star/echarts,chenfwind/echarts,hexj/echarts,starlkj/echarts,starlkj/echarts,starlkj/echarts,apache/incubator-echarts,100star/echarts | ---
+++
@@ -19,7 +19,9 @@
if (!ecModel.isSeriesFiltered(seriesModel)) {
data.each(function (idx) {
var itemModel = data.getItemModel(idx);
- var sign = data.getItemLayout(idx).sign;
+ var openVal = data.get('open', idx);
+ var closeVal = data.get('close', idx);
+ var sign = openVal > closeVal ? -1 : openVal < closeVal ? 1 : 0;
data.setItemVisual(
idx, |
5a98f2a4874d47da9e05a56eae3018e911fc30f1 | src/components/demos/DigitalLines/index.js | src/components/demos/DigitalLines/index.js | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes } from 'react';
class DigitalLines {
static propTypes = {
};
canvasRender() {
};
componentDidMount() {
// Get a reference to the canvas object
var canvas = document.getElementById('digitalLinesCanvas');
// Create an empty project and a view for the canvas:
paper.setup(canvas);
// Create a Paper.js Path to draw a line into it:
var path = new paper.Path();
// Give the stroke a color
path.strokeColor = 'black';
var start = new paper.Point(100, 100);
// Move to start and draw a line from there
path.moveTo(start);
// Note that the plus operator on Point objects does not work
// in JavaScript. Instead, we need to call the add() function:
path.lineTo(start.add([ 200, -50 ]));
// Draw the view now:
paper.view.draw();
};
componentWillUpdate() {
};
render() {
return (
<div className="DigitalLines">
Hello World!
<canvas width="800" height="400" id="digitalLinesCanvas" />
</div>
);
}
}
export default {
name: 'Digital Lines',
key: 'digitalLines',
author: 'Josh',
technologies: [],
component: DigitalLines
}; | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes } from 'react';
class Line {
constructor() {
try {
this.path = new paper.Path();
this.path.fillColor = undefined;
this.path.strokeColor = 'green';
this.path.strokeWidth = 2;
// Left side
var cur = new paper.Point(0, Math.random() * 500);
this.path.moveTo(cur);
while (cur.x < 800)
{
cur = cur.add(new paper.Point(Math.random() * 50 + 25, Math.random() * 50 - 25));
this.path.lineTo(cur);
}
this.path.smooth();
}catch (e) {
console.log(e);
};
}
};
class DigitalLines {
static propTypes = {
};
canvasRender() {
};
componentDidMount() {
// Get a reference to the canvas object
var canvas = document.getElementById('digitalLinesCanvas'),
lines = [];
// Create an empty project and a view for the canvas:
paper.setup(canvas);
for (var i = 0; i < 10; i++)
lines.push(new Line());
path.view.onFrame = function (event) {
};
// Draw the view now:
paper.view.draw();
};
componentWillUpdate() {
};
render() {
return (
<div className="DigitalLines">
Hello World!
<canvas width="800" height="400" id="digitalLinesCanvas" />
</div>
);
}
}
export default {
name: 'Digital Lines',
key: 'digitalLines',
author: 'Josh',
technologies: [],
component: DigitalLines
}; | Update to DigitalLines. Taking a slight mental transition to learn about Bezier Curves. | Update to DigitalLines. Taking a slight mental transition to learn about Bezier Curves.
| JavaScript | mit | jung-digital/jd-demos,jung-digital/jd-demos | ---
+++
@@ -2,7 +2,30 @@
import React, { PropTypes } from 'react';
+class Line {
+ constructor() {
+ try {
+ this.path = new paper.Path();
+ this.path.fillColor = undefined;
+ this.path.strokeColor = 'green';
+ this.path.strokeWidth = 2;
+ // Left side
+ var cur = new paper.Point(0, Math.random() * 500);
+ this.path.moveTo(cur);
+
+ while (cur.x < 800)
+ {
+ cur = cur.add(new paper.Point(Math.random() * 50 + 25, Math.random() * 50 - 25));
+ this.path.lineTo(cur);
+ }
+
+ this.path.smooth();
+ }catch (e) {
+ console.log(e);
+ };
+ }
+};
class DigitalLines {
@@ -15,24 +38,20 @@
componentDidMount() {
// Get a reference to the canvas object
- var canvas = document.getElementById('digitalLinesCanvas');
+ var canvas = document.getElementById('digitalLinesCanvas'),
+ lines = [];
// Create an empty project and a view for the canvas:
paper.setup(canvas);
- // Create a Paper.js Path to draw a line into it:
- var path = new paper.Path();
+ for (var i = 0; i < 10; i++)
+ lines.push(new Line());
- // Give the stroke a color
- path.strokeColor = 'black';
- var start = new paper.Point(100, 100);
+
- // Move to start and draw a line from there
- path.moveTo(start);
+ path.view.onFrame = function (event) {
- // Note that the plus operator on Point objects does not work
- // in JavaScript. Instead, we need to call the add() function:
- path.lineTo(start.add([ 200, -50 ]));
+ };
// Draw the view now:
paper.view.draw(); |
c951d161be8d2faf6e497d80e69998aa49a445bd | desktop/tests/database.spec.js | desktop/tests/database.spec.js | const assert = require('assert');
const parse = require('../app/shared/database/parse');
describe('database', () => {
describe('parse.js', () => {
const testQuery = 'Learn something! @3+2w !';
it('should return correct task text', () => {
assert(parse(testQuery).text === 'Learn something!');
});
it('should return correct starting point', () => {
assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000);
});
it('should return correct ending point', () => {
assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000);
});
it('should return correct importance', () => {
assert(parse(testQuery).importance === 2);
});
it('should return correct status', () => {
assert(parse(testQuery).status === 0);
});
});
});
| const assert = require('assert');
const parse = require('../app/shared/database/parse');
describe('database', () => {
describe('parse.js', () => {
const testQuery = 'Learn something! @3+2w !';
it('should return task text', () => {
assert(parse(testQuery).text === 'Learn something!');
});
it('should return starting point', () => {
assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000);
});
it('should return ending point', () => {
assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000);
});
it('should return importance', () => {
assert(parse(testQuery).importance === 2);
});
it('should return status', () => {
assert(parse(testQuery).status === 0);
});
});
});
| Remove "correct" word from test titles | Remove "correct" word from test titles
| JavaScript | mit | mkermani144/wanna,mkermani144/wanna | ---
+++
@@ -4,19 +4,19 @@
describe('database', () => {
describe('parse.js', () => {
const testQuery = 'Learn something! @3+2w !';
- it('should return correct task text', () => {
+ it('should return task text', () => {
assert(parse(testQuery).text === 'Learn something!');
});
- it('should return correct starting point', () => {
+ it('should return starting point', () => {
assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000);
});
- it('should return correct ending point', () => {
+ it('should return ending point', () => {
assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000);
});
- it('should return correct importance', () => {
+ it('should return importance', () => {
assert(parse(testQuery).importance === 2);
});
- it('should return correct status', () => {
+ it('should return status', () => {
assert(parse(testQuery).status === 0);
});
}); |
b1f3c2110910665038b5d4738d225009b21530f1 | plugins/knowyourmeme.js | plugins/knowyourmeme.js | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Know Your Meme',
version:'0.1',
prepareImgLinks:function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'a img.small',
'/small/',
'/original/'
);
callback($(res));
}
});
| var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Know Your Meme',
version:'0.2',
prepareImgLinks:function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'a img.small',
'/small/',
'/original/'
);
hoverZoom.urlReplace(res,
'img[src]',
['/list/', '/masonry/', '/medium/', '/newsfeed/', '/tiny/'],
['/original/', '/original/', '/original/', '/original/', '/original/']
);
callback($(res), this.name);
}
});
| Update for plug-in : KnowYourMeme | Update for plug-in : KnowYourMeme
| JavaScript | mit | extesy/hoverzoom,extesy/hoverzoom | ---
+++
@@ -1,14 +1,22 @@
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Know Your Meme',
- version:'0.1',
+ version:'0.2',
prepareImgLinks:function (callback) {
var res = [];
+
hoverZoom.urlReplace(res,
'a img.small',
'/small/',
'/original/'
);
- callback($(res));
+
+ hoverZoom.urlReplace(res,
+ 'img[src]',
+ ['/list/', '/masonry/', '/medium/', '/newsfeed/', '/tiny/'],
+ ['/original/', '/original/', '/original/', '/original/', '/original/']
+ );
+
+ callback($(res), this.name);
}
}); |
7b52bf19eda8d52be5ae8db7fb1d1544912e1794 | client/index.js | client/index.js | var document = require('global/document');
var value = require('observ');
var struct = require('observ-struct');
var Delegator = require('dom-delegator');
var mainLoop = require('main-loop');
var h = require('virtual-hyperscript');
var MultipleEvent = require('geval/multiple');
var changeEvent = require('value-event/change');
var courses = require('./catalog');
var state = struct({
query: value(''),
events: MultipleEvent(['change'])
});
state.events.change(function(data) {
state.query.set(data.query);
});
Delegator();
var loop = mainLoop(state(), render);
document.body.appendChild(loop.target);
state(loop.update);
function render(state) {
var results = courses.filter(function(course) {
return course.name.toLowerCase().indexOf(state.query) >= 0
|| course.code.toLowerCase().indexOf(state.query) >= 0;
});
var ret = [];
var inputField = h('input', {
type: 'text',
name: 'query',
value: String(state.query),
'ev-event': changeEvent(state.events.change),
autofocus: true
});
results.forEach(function(course) {
ret.push(h('li', [
h('h3', [
h('span.code', course.code),
h('span', ' ' + course.name)
]),
h('p', course.description)
]));
});
return h('div', [
inputField,
h('ul', ret)
]);
} | var document = require('global/document');
var value = require('observ');
var struct = require('observ-struct');
var Delegator = require('dom-delegator');
var mainLoop = require('main-loop');
var h = require('virtual-hyperscript');
var MultipleEvent = require('geval/multiple');
var changeEvent = require('value-event/change');
var courses = require('./catalog');
var state = struct({
query: value(''),
events: MultipleEvent(['change'])
});
state.events.change(function(data) {
state.query.set(data.query);
});
Delegator();
var loop = mainLoop(state(), render);
document.body.appendChild(loop.target);
state(loop.update);
function render(state) {
var results = courses.filter(function(course) {
return course.name.toLowerCase().indexOf(state.query) >= 0
|| course.code.toLowerCase().indexOf(state.query) >= 0;
});
var ret = [];
var inputField = h('input', {
type: 'search',
name: 'query',
value: String(state.query),
'ev-event': changeEvent(state.events.change),
autofocus: true
});
results.forEach(function(course) {
ret.push(h('li', [
h('h3', [
h('span.code', course.code),
h('span', ' ' + course.name)
]),
h('p', course.description)
]));
});
return h('div', [
inputField,
h('ul', ret)
]);
} | Change search field type to "search" | Change search field type to "search"
This is like "text" except that a little "x" button appears so that one can
easily clear the field. Also, on mobile browsers, the action button on the
keyboard will display "Search" instead of just "Go".
Old browsers will gracefully fallback to "text" anyways, so this is a
progressive enchancement.
| JavaScript | mit | KenanY/course-search,KenanY/course-search | ---
+++
@@ -32,7 +32,7 @@
var ret = [];
var inputField = h('input', {
- type: 'text',
+ type: 'search',
name: 'query',
value: String(state.query),
'ev-event': changeEvent(state.events.change), |
4177d6050ef41c70dc25a34ee32e43984e77f461 | visualizer/index.js | visualizer/index.js | 'use strict'
const fg = require('d3-fg')
const render = require('nanohtml')
const morphdom = require('morphdom')
const debounce = require('debounce')
const createActions = require('./actions')
const createState = require('./state')
const graph = require('./cmp/graph')(render)
const ui = require('./cmp/ui')(render)
module.exports = function (trees, opts) {
opts = opts || {}
const { kernelTracing } = opts
const exclude = new Set(['cpp', 'regexp', 'v8', 'native', 'init'])
const chart = graph()
const tree = trees.unmerged // default view
const categorizer = !kernelTracing && graph.v8cats
const flamegraph = fg({
categorizer,
tree,
exclude: Array.from(exclude),
element: chart
})
const { colors } = flamegraph
window.addEventListener('resize', debounce(() => {
const width = document.body.clientWidth * 0.89
flamegraph.width(width).update()
chart.querySelector('svg').setAttribute('width', width)
}, 150))
const state = createState({colors, trees, exclude, kernelTracing, title: opts.title})
const actions = createActions({flamegraph, state}, (state) => {
morphdom(iface, ui({state, actions}))
})
const iface = ui({state, actions})
document.body.appendChild(chart)
document.body.appendChild(iface)
}
| 'use strict'
const fg = require('d3-fg')
const render = require('nanohtml')
const morphdom = require('morphdom')
const debounce = require('debounce')
const createActions = require('./actions')
const createState = require('./state')
const graph = require('./cmp/graph')(render)
const ui = require('./cmp/ui')(render)
module.exports = function (trees, opts) {
opts = opts || {}
const { kernelTracing } = opts
const exclude = new Set(['cpp', 'regexp', 'v8', 'native', 'init'])
const chart = graph()
const tree = trees.unmerged // default view
const categorizer = !kernelTracing && graph.v8cats
const flamegraph = fg({
categorizer,
tree,
exclude: Array.from(exclude),
element: chart,
topOffset: 55
})
const { colors } = flamegraph
window.addEventListener('resize', debounce(() => {
const width = document.body.clientWidth * 0.89
flamegraph.width(width).update()
chart.querySelector('svg').setAttribute('width', width)
}, 150))
const state = createState({colors, trees, exclude, kernelTracing, title: opts.title})
const actions = createActions({flamegraph, state}, (state) => {
morphdom(iface, ui({state, actions}))
})
const iface = ui({state, actions})
document.body.appendChild(chart)
document.body.appendChild(iface)
}
| Add top offset to prevent top bar from cropping the top stack | Add top offset to prevent top bar from cropping the top stack
| JavaScript | mit | davidmarkclements/0x | ---
+++
@@ -20,7 +20,8 @@
categorizer,
tree,
exclude: Array.from(exclude),
- element: chart
+ element: chart,
+ topOffset: 55
})
const { colors } = flamegraph
|
e9bd0c16bda4221a420a9206c239e06b44a5911f | addon/index.js | addon/index.js | import Ember from 'ember';
Ember.deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, {
id: "ember-getowner-polyfill.import"
});
export default Ember.getOwner;
| import Ember from 'ember';
Ember.deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, {
id: "ember-getowner-polyfill.import",
until: '3.0.0'
});
export default Ember.getOwner;
| Add option.until to prevent extra deprecation | Add option.until to prevent extra deprecation | JavaScript | mit | rwjblue/ember-getowner-polyfill,rwjblue/ember-getowner-polyfill | ---
+++
@@ -1,7 +1,8 @@
import Ember from 'ember';
Ember.deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, {
- id: "ember-getowner-polyfill.import"
+ id: "ember-getowner-polyfill.import",
+ until: '3.0.0'
});
export default Ember.getOwner; |
5ddc15870172cabe4a362fa338dd804f6b1264e2 | src/components/Media/Media.js | src/components/Media/Media.js | import React from 'react';
import classnames from 'classnames';
const Media = (props) => {
const children = props.children;
return (
<div className={classnames('ui-media')}>
{children}
</div>
);
};
Media.propTypes = {
children: React.PropTypes.node,
};
export default Media;
| import React from 'react';
import classnames from 'classnames';
const Media = ({ compact, children }) => {
const className = classnames('ui-media', {
'ui-media-compact': compact,
});
return (
<div className={className}>
{children}
</div>
);
};
Media.propTypes = {
children: React.PropTypes.node,
compact: React.PropTypes.bool,
};
Media.defaultProps = {
compact: false,
children: null,
};
export default Media;
| Introduce compact prop for media component | Introduce compact prop for media component
| JavaScript | mit | wundery/wundery-ui-react,wundery/wundery-ui-react | ---
+++
@@ -1,11 +1,13 @@
import React from 'react';
import classnames from 'classnames';
-const Media = (props) => {
- const children = props.children;
+const Media = ({ compact, children }) => {
+ const className = classnames('ui-media', {
+ 'ui-media-compact': compact,
+ });
return (
- <div className={classnames('ui-media')}>
+ <div className={className}>
{children}
</div>
);
@@ -13,6 +15,12 @@
Media.propTypes = {
children: React.PropTypes.node,
+ compact: React.PropTypes.bool,
+};
+
+Media.defaultProps = {
+ compact: false,
+ children: null,
};
export default Media; |
85367a62999ef6be0e34556cd71d54871c98dc19 | worker/index.js | worker/index.js | 'use strict';
const config = require('config');
const logger = require('../modules').logger;
const rollbarHelper = require('../modules').rollbarHelper;
const invalidator = require('./invalidator');
const opendata = require('./opendata');
function shutdown() {
logger.info('[WORKER] Ending');
setTimeout(process.exit, config.worker.exit_timeout);
}
if (!module.parent) {
require('../modules').mongooseHelper.connect()
.then(() => rollbarHelper.init())
.then(() => {
invalidator.start();
opendata.start();
logger.info('[WORKER] Started');
})
.catch(err => {
logger.error(err, '[WORKER] Uncaught error');
rollbarHelper.rollbar.handleError(err, '[WORKER] Uncaught exception');
shutdown();
});
process.on('SIGTERM', shutdown);
}
module.exports = {
opendata
};
| 'use strict';
const config = require('config');
const logger = require('../modules').logger;
const mongooseHelper = require('../modules').mongooseHelper;
const rollbarHelper = require('../modules').rollbarHelper;
const invalidator = require('./invalidator');
const opendata = require('./opendata');
function shutdown() {
logger.info('[WORKER] Ending');
setTimeout(process.exit, config.worker.exit_timeout);
}
if (!module.parent) {
rollbarHelper.init()
.then(() => mongooseHelper.connect())
.then(() => {
invalidator.start();
opendata.start();
logger.info('[WORKER] Started');
})
.catch(err => {
logger.error(err, '[WORKER] Uncaught error');
rollbarHelper.rollbar.handleError(err, '[WORKER] Uncaught exception');
shutdown();
});
process.on('SIGTERM', shutdown);
}
module.exports = {
opendata
};
| Initialize rollbar before mongoose in worker | Initialize rollbar before mongoose in worker
| JavaScript | mit | carparker/carparker-server | ---
+++
@@ -2,6 +2,7 @@
const config = require('config');
const logger = require('../modules').logger;
+const mongooseHelper = require('../modules').mongooseHelper;
const rollbarHelper = require('../modules').rollbarHelper;
const invalidator = require('./invalidator');
@@ -13,8 +14,8 @@
}
if (!module.parent) {
- require('../modules').mongooseHelper.connect()
- .then(() => rollbarHelper.init())
+ rollbarHelper.init()
+ .then(() => mongooseHelper.connect())
.then(() => {
invalidator.start();
opendata.start(); |
49bd3bf427f57fa65a9b04bcbb5af9d654258120 | providers/providers.js | providers/providers.js | var path = require('path');
var _ = require('underscore')._;
module.exports = function(app, settings) {
var providers = {};
for (var p in settings.providers) {
// TODO :express better
providers[p] = require('./' + path.join(p, 'index'))(app, settings);
}
app.get('/provider', function(req, res) {
res.send({
status: true,
provider: _.keys(settings.providers)
});
});
app.get('/provider/:provider', function(req, res) {
if (providers[req.params.provider]) {
providers[req.params.provider].objects(function(objects) {
res.send(objects);
});
}
else {
// @TODO: better error handling here.
// Currently allows graceful downgrade of missing S3 information
// but ideally client side JS would not request for the S3 provider
// at all if it is not enabled.
res.send([]);
}
});
};
| var path = require('path');
var _ = require('underscore')._;
module.exports = function(app, settings) {
var providers = {};
for (var p in settings.providers) {
// TODO :express better
providers[p] = require('./' + path.join(p, 'index'))(app, settings);
}
app.get('/provider', function(req, res) {
res.send({
status: true,
provider: _.keys(settings.providers)
});
});
/**
* This endpoint is a backbone.js collection compatible REST endpoint
* providing datasource model objects. The models provided are read-only
* and cannot be created, saved or destroyed back to the server.
*/
app.get('/provider/:provider', function(req, res) {
if (providers[req.params.provider]) {
providers[req.params.provider].objects(function(objects) {
res.send(objects);
});
}
else {
// @TODO: better error handling here.
// Currently allows graceful downgrade of missing S3 information
// but ideally client side JS would not request for the S3 provider
// at all if it is not enabled.
res.send([]);
}
});
};
| Add comment which notes that the provider endpoint is a backbone.js collection endpoint as well. | Add comment which notes that the provider endpoint is a backbone.js collection endpoint as well.
| JavaScript | bsd-3-clause | nyimbi/tilemill,mbrukman/tilemill,mbrukman/tilemill,isaacs/tilemill,mbrukman/tilemill,MappingKat/tilemill,paulovieira/tilemill-clima,Zhao-Qi/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,mbrukman/tilemill,paulovieira/tilemill-clima,nyimbi/tilemill,MappingKat/tilemill,makinacorpus/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,isaacs/tilemill,mbrukman/tilemill,tilemill-project/tilemill,tizzybec/tilemill,makinacorpus/tilemill,MappingKat/tilemill,MappingKat/tilemill,florianf/tileoven,Zhao-Qi/tilemill,tizzybec/tilemill,tilemill-project/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,tizzybec/tilemill,fxtentacle/tilemill,fxtentacle/tilemill,paulovieira/tilemill-clima,Zhao-Qi/tilemill,Zhao-Qi/tilemill,fxtentacle/tilemill,Zhao-Qi/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,nyimbi/tilemill,fxtentacle/tilemill,isaacs/tilemill,nyimbi/tilemill,tizzybec/tilemill,paulovieira/tilemill-clima,tilemill-project/tilemill,tizzybec/tilemill,florianf/tileoven,nyimbi/tilemill,paulovieira/tilemill-clima,florianf/tileoven,fxtentacle/tilemill,MappingKat/tilemill | ---
+++
@@ -13,6 +13,11 @@
provider: _.keys(settings.providers)
});
});
+ /**
+ * This endpoint is a backbone.js collection compatible REST endpoint
+ * providing datasource model objects. The models provided are read-only
+ * and cannot be created, saved or destroyed back to the server.
+ */
app.get('/provider/:provider', function(req, res) {
if (providers[req.params.provider]) {
providers[req.params.provider].objects(function(objects) { |
a37853c97ad9850e6bae0adf254399b3d6d29424 | src/suspense.js | src/suspense.js | import { Component } from './component';
import { createElement } from './create-element';
// having a "custom class" here saves 50bytes gzipped
export function s(props) {}
s.prototype = new Component();
s.prototype._childDidSuspend = function(e) {
this.setState({ _loading: true });
const cb = () => { this.setState({ _loading: false }); };
// Suspense ignores errors thrown in Promises as this should be handled by user land code
e.then(cb, cb);
};
s.prototype.render = function(props, state) {
return state._loading ? props.fallback : props.children;
};
// exporting s as Suspense instead of naming the class iself Suspense saves 4 bytes gzipped
// TODO: does this add the need of a displayName?
export const Suspense = s;
export function lazy(loader) {
let prom;
let component;
let error;
return function L(props) {
if (!prom) {
prom = loader();
prom.then(
({ default: c }) => { component = c; },
e => error = e,
);
}
if (error) {
throw error;
}
if (!component) {
throw prom;
}
return createElement(component, props);
};
} | import { Component } from './component';
import { createElement } from './create-element';
// having a "custom class" here saves 50bytes gzipped
export function s(props) {}
s.prototype = new Component();
/**
* @param {Promise} promise The thrown promise
*/
s.prototype._childDidSuspend = function(promise) {
this.setState({ _loading: true });
const cb = () => { this.setState({ _loading: false }); };
// Suspense ignores errors thrown in Promises as this should be handled by user land code
promise.then(cb, cb);
};
s.prototype.render = function(props, state) {
return state._loading ? props.fallback : props.children;
};
// exporting s as Suspense instead of naming the class iself Suspense saves 4 bytes gzipped
// TODO: does this add the need of a displayName?
export const Suspense = s;
export function lazy(loader) {
let prom;
let component;
let error;
return function L(props) {
if (!prom) {
prom = loader();
prom.then(
({ default: c }) => { component = c; },
e => error = e,
);
}
if (error) {
throw error;
}
if (!component) {
throw prom;
}
return createElement(component, props);
};
} | Add some jsdoc to _childDidSuspend | Add some jsdoc to _childDidSuspend
| JavaScript | mit | developit/preact,developit/preact | ---
+++
@@ -4,13 +4,18 @@
// having a "custom class" here saves 50bytes gzipped
export function s(props) {}
s.prototype = new Component();
-s.prototype._childDidSuspend = function(e) {
+
+/**
+ * @param {Promise} promise The thrown promise
+ */
+s.prototype._childDidSuspend = function(promise) {
this.setState({ _loading: true });
const cb = () => { this.setState({ _loading: false }); };
// Suspense ignores errors thrown in Promises as this should be handled by user land code
- e.then(cb, cb);
+ promise.then(cb, cb);
};
+
s.prototype.render = function(props, state) {
return state._loading ? props.fallback : props.children;
}; |
bf79820c7a37188c9e66c912eb9a66ad45ecc7ad | app/javascript/app/pages/sectors-agriculture/sectors-agricuture-selectors.js | app/javascript/app/pages/sectors-agriculture/sectors-agricuture-selectors.js | import { createSelector } from 'reselect';
// import omit from 'lodash/omit';
// import qs from 'query-string';
const getSections = routeData => routeData.route.sections || null;
// const getSearch = routeData => routeData.location.search || null;
// const getHash = routeData => routeData.hash || null;
// const getRoutes = routeData => routeData.route.routes || null;
export const getAnchorLinks = createSelector([getSections], sections =>
sections.filter(route => route.anchor).map(route => ({
label: route.label,
path: route.path,
hash: route.hash,
component: route.component
}))
);
// export const getRouteLinks = createSelector(
// [getRoutes, getHash, getSearch],
// (routes, hash, search) =>
// routes &&
// routes.filter(r => r.anchor).map(route => ({
// label: route.label,
// path: route.path,
// search: qs.stringify(omit(qs.parse(search), 'search')), // we want to reset the search on tabs change
// hash
// }))
// );
export default {
getAnchorLinks
// getRouteLinks
};
| import { createSelector } from 'reselect';
const getSections = routeData => routeData.route.sections || null;
export const getAnchorLinks = createSelector([getSections], sections =>
sections.filter(route => route.anchor).map(route => ({
label: route.label,
path: route.path,
hash: route.hash,
component: route.component
}))
);
export default {
getAnchorLinks
};
| Remove commented code from agriculture selectors | Remove commented code from agriculture selectors
| JavaScript | mit | Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch | ---
+++
@@ -1,11 +1,6 @@
import { createSelector } from 'reselect';
-// import omit from 'lodash/omit';
-// import qs from 'query-string';
const getSections = routeData => routeData.route.sections || null;
-// const getSearch = routeData => routeData.location.search || null;
-// const getHash = routeData => routeData.hash || null;
-// const getRoutes = routeData => routeData.route.routes || null;
export const getAnchorLinks = createSelector([getSections], sections =>
sections.filter(route => route.anchor).map(route => ({
@@ -16,19 +11,6 @@
}))
);
-// export const getRouteLinks = createSelector(
-// [getRoutes, getHash, getSearch],
-// (routes, hash, search) =>
-// routes &&
-// routes.filter(r => r.anchor).map(route => ({
-// label: route.label,
-// path: route.path,
-// search: qs.stringify(omit(qs.parse(search), 'search')), // we want to reset the search on tabs change
-// hash
-// }))
-// );
-
export default {
getAnchorLinks
- // getRouteLinks
}; |
ed3c72146dad8baa293755c8732f3ad0ef9581f2 | eloquent_js/chapter11/ch11_ex02.js | eloquent_js/chapter11/ch11_ex02.js | function Promise_all(promises) {
return new Promise((resolve, reject) => {
let ctr = promises.length;
let resArray = [];
if (ctr === 0) resolve(resArray);
for (let idx = 0; idx < promises.length; ++idx) {
promises[idx].then(result => {
resArray[idx] = result;
--ctr;
if (ctr === 0) resolve(resArray);
}, reject);
}
});
}
| function Promise_all(promises) {
return new Promise((resolve, reject) => {
let result = [];
let unresolved = promises.length;
if (unresolved == 0) resolve(result);
for (let i = 0; i < promises.length; ++i) {
promises[i]
.then(value => {
result[i] = value;
--unresolved;
if (unresolved == 0) resolve(result);
})
.catch(error => reject(error));
}
});
}
| Add chapter 11, exercise 2 | Add chapter 11, exercise 2
| JavaScript | mit | bewuethr/ctci | ---
+++
@@ -1,14 +1,17 @@
function Promise_all(promises) {
- return new Promise((resolve, reject) => {
- let ctr = promises.length;
- let resArray = [];
- if (ctr === 0) resolve(resArray);
- for (let idx = 0; idx < promises.length; ++idx) {
- promises[idx].then(result => {
- resArray[idx] = result;
- --ctr;
- if (ctr === 0) resolve(resArray);
- }, reject);
- }
- });
+ return new Promise((resolve, reject) => {
+ let result = [];
+ let unresolved = promises.length;
+ if (unresolved == 0) resolve(result);
+
+ for (let i = 0; i < promises.length; ++i) {
+ promises[i]
+ .then(value => {
+ result[i] = value;
+ --unresolved;
+ if (unresolved == 0) resolve(result);
+ })
+ .catch(error => reject(error));
+ }
+ });
} |
334795d1f6a881f9377bb9c436641a422431153f | modules/cloud-portal-server/src/main/resources/public/static/dist/js/portal.js | modules/cloud-portal-server/src/main/resources/public/static/dist/js/portal.js | $(function() {
$("form :button").each(function(){
var button = $(this);
if ($(button).attr('id') == 'cancel') {
$(button).click(function(e){
e.preventDefault();
history.back();
});
}
else {
$(button).click(function(e){
var buttonId = $(button).attr('id');
if (typeof buttonId !== 'undefined') {
e.preventDefault();
var form = $(this).closest('form');
var originalActionUrl = $(form).attr('action');
if ($(form).valid()) {
if (buttonId == "plan" || buttonId == "apply") {
$('#myModal').modal('toggle');
}
var submit = true;
if (buttonId.startsWith('delete')) {
submit = confirm('Do you really want to delete this item?');
if (submit) {
$('#myModal').modal('toggle');
}
}
if (submit) {
$(form).attr('action', originalActionUrl + "/" + buttonId);
$(form).submit();
$(form).attr('action', originalActionUrl);
}
}
}
});
}
});
$('#datatable').DataTable({
responsive: true,
order: [[ 0, 'desc' ]]
});
}); | $(function() {
$("form :button").each(function(){
var button = $(this);
if ($(button).attr('id') == 'cancel') {
$(button).click(function(e){
e.preventDefault();
history.back();
});
}
else {
$(button).click(function(e){
var buttonId = $(button).attr('id');
if (typeof buttonId !== 'undefined') {
e.preventDefault();
var form = $(this).closest('form');
var originalActionUrl = $(form).attr('action');
if ($(form).valid()) {
if (buttonId == "plan" || buttonId == "apply") {
$('#myModal').modal('toggle');
}
var submit = true;
if (buttonId.startsWith('delete')) {
submit = confirm('Do you really want to delete this item?');
if (submit) {
$('#myModal').modal('toggle');
}
}
if (submit) {
$(form).attr('action', originalActionUrl + "/" + buttonId);
$(form).submit();
$(form).attr('action', originalActionUrl);
}
}
}
});
}
});
$('#datatable').DataTable({
responsive: true,
order: [[ 0, 'asc' ]]
});
}); | Fix for vm list ordering | Fix for vm list ordering | JavaScript | mit | chrisipa/cloud-portal,chrisipa/cloud-portal,chrisipa/cloud-portal | ---
+++
@@ -49,6 +49,6 @@
$('#datatable').DataTable({
responsive: true,
- order: [[ 0, 'desc' ]]
+ order: [[ 0, 'asc' ]]
});
}); |
ea768085c12ef4ea8551510bd3ab606a61115967 | get-file.js | get-file.js | var fs = require('fs');
var path = require('path');
var md = require('cli-md');
module.exports = function (filepath) {
return md(fs.readFileSync(filepath, 'utf8'))
.replace(/'/g, "'")
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '<');
}; | var fs = require('fs');
var path = require('path');
var md = require('cli-md');
module.exports = function (filepath) {
return md(fs.readFileSync(filepath, 'utf8'))
.replace(/'/g, "'")
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '<');
};
| Fix greate/less than HTML entity in problem description | Fix greate/less than HTML entity in problem description
| JavaScript | mit | soujiro27/javascripting,ubergrafik/javascripting,SomeoneWeird/javascripting,jaredhensley/javascripting,d9magai/javascripting,montogeek/javascripting,liyuqi/javascripting,nodeschool-no/javascripting,braday/javascripting,michaelgrilo/javascripting,RichardLitt/javascripting,barberboy/javascripting,agrimm/javascripting,ymote/javascripting,ipelekhan/javascripting,CLAV1ER/javascripting,LindsayElia/javascripting,ledsun/javascripting,victorperin/javascripting,aijiekj/javascripting,he11yeah/javascripting,Aalisha/javascripting,samilokan/javascripting,gcbeyond/javascripting,marocchino/javascripting,thenaughtychild/javascripting,sethvincent/javascripting,NgaNguyenDuy/javascripting,a0viedo/javascripting,claudiopro/javascripting,MatthewDiana/javascripting | |
c4bb41471441da921da9c2dc9515e662619fef5b | public/javascripts/checker.js | public/javascripts/checker.js | var socket = io.connect('/');
var waitMilliSec = 1000;
var oldJavaCode = '';
var oldClassName = '';
socket.on('byte_code', function(data) {
$('#output_bc').val(data.code);
});
socket.on('wrong', function(data) {
$('#output_bc').val(data.err);
});
$(function() {
var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), {
mode: 'clike',
lineNumbers: true
});
var idleIntervalId = setInterval(function() {
newJavaCode = inputJavaCM.getValue();
newClassName = $('#class_name').val();
checkDiff(newJavaCode, newClassName);
} , waitMilliSec);
function checkDiff(newJavaCode, newClassName) {
if((newJavaCode != oldJavaCode) || (newClassName != oldClassName)) {
socket.emit('code_sent', {
code: newJavaCode,
className: newClassName
});
oldJavaCode = newJavaCode;
oldClassName = newClassName;
}
}
});
| var socket = io.connect('/');
var waitMilliSec = 1000;
var oldJavaCode = '';
var oldClassName = '';
var outputBcCM;
socket.on('byte_code', function(data) {
outputBcCM.setValue(data.code);
});
socket.on('wrong', function(data) {
outputBcCM.setValue(data.err);
});
$(function() {
var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), {
mode: 'clike',
lineNumbers: true
});
outputBcCM = CodeMirror.fromTextArea(document.getElementById('output_bc'), {
mode: 'clike',
lineNumbers: true
});
var idleIntervalId = setInterval(function() {
newJavaCode = inputJavaCM.getValue();
newClassName = $('#class_name').val();
checkDiff(newJavaCode, newClassName);
} , waitMilliSec);
function checkDiff(newJavaCode, newClassName) {
if((newJavaCode != oldJavaCode) || (newClassName != oldClassName)) {
socket.emit('code_sent', {
code: newJavaCode,
className: newClassName
});
oldJavaCode = newJavaCode;
oldClassName = newClassName;
}
}
});
| Apply CodeMirror to output textarea. | Apply CodeMirror to output textarea.
| JavaScript | mit | Java2ByteCode/InstantBytecode,Java2ByteCode/InstantBytecode | ---
+++
@@ -2,18 +2,22 @@
var waitMilliSec = 1000;
var oldJavaCode = '';
var oldClassName = '';
-
+var outputBcCM;
socket.on('byte_code', function(data) {
- $('#output_bc').val(data.code);
+ outputBcCM.setValue(data.code);
});
socket.on('wrong', function(data) {
- $('#output_bc').val(data.err);
+ outputBcCM.setValue(data.err);
});
$(function() {
var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), {
+ mode: 'clike',
+ lineNumbers: true
+ });
+ outputBcCM = CodeMirror.fromTextArea(document.getElementById('output_bc'), {
mode: 'clike',
lineNumbers: true
}); |
4690efb9543e0fffc11c5330dc93c75482c3e9b5 | kolibri/plugins/coach/assets/src/state/mutations/lessonsMutations.js | kolibri/plugins/coach/assets/src/state/mutations/lessonsMutations.js | export function SET_CLASS_LESSONS(state, lessons) {
state.pageState.lessons = lessons;
}
export function SET_CURRENT_LESSON(state, lesson) {
state.pageState.currentLesson = lesson;
}
export function SET_LEARNER_GROUPS(state, learnerGroups) {
state.pageState.learnerGroups = learnerGroups;
}
| export function SET_CLASS_LESSONS(state, lessons) {
state.pageState.lessons = lessons;
}
export function SET_CURRENT_LESSON(state, lesson) {
state.pageState.currentLesson = { ...lesson };
}
export function SET_LEARNER_GROUPS(state, learnerGroups) {
state.pageState.learnerGroups = learnerGroups;
}
| Make copy before setting current lesson | Make copy before setting current lesson
| JavaScript | mit | DXCanas/kolibri,christianmemije/kolibri,benjaoming/kolibri,christianmemije/kolibri,DXCanas/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,jonboiser/kolibri,indirectlylit/kolibri,jonboiser/kolibri,indirectlylit/kolibri,benjaoming/kolibri,lyw07/kolibri,DXCanas/kolibri,benjaoming/kolibri,christianmemije/kolibri,indirectlylit/kolibri,christianmemije/kolibri,benjaoming/kolibri,learningequality/kolibri,learningequality/kolibri,lyw07/kolibri,learningequality/kolibri,mrpau/kolibri,DXCanas/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,jonboiser/kolibri,lyw07/kolibri,jonboiser/kolibri | ---
+++
@@ -3,7 +3,7 @@
}
export function SET_CURRENT_LESSON(state, lesson) {
- state.pageState.currentLesson = lesson;
+ state.pageState.currentLesson = { ...lesson };
}
export function SET_LEARNER_GROUPS(state, learnerGroups) { |
d6da2ba83bb7dbcdaa73f4df45927a50fe8f8e15 | backend/Log.js | backend/Log.js | var Log = require("log4js");
var Utils = require("./Utils");
Log.configure({
"replaceConsole": true,
"appenders": process.env.DEBUG ? [{"type": "console"}] :
[
{
"type": "console"
},
{
"type": "logLevelFilter",
"level": "ERROR",
"appender": {
"type": "smtp",
"recipients": process.env.EMAIL,
"sender": "info@ideacolorthemes.org",
"sendInterval": process.env.LOG_EMAIL_INTERVAL || 30,
"transport": "SMTP",
"SMTP": Utils.getEmailConfig()
}
}
]
});
module.exports = Log.getLogger();
| var Log = require("log4js");
var Utils = require("./Utils");
Log.configure({
"replaceConsole": true,
"appenders": process.env.DEBUG ? [{"type": "console"}] :
[
{
"type": "console"
},
{
"type": "logLevelFilter",
"level": "ERROR",
"appender": {
"type": "smtp",
"recipients": process.env.EMAIL,
"sender": process.env.EMAIL,
"sendInterval": process.env.LOG_EMAIL_INTERVAL || 30,
"transport": "SMTP",
"SMTP": Utils.getEmailConfig()
}
}
]
});
module.exports = Log.getLogger();
| Fix for error reporting email | Fix for error reporting email
| JavaScript | mit | y-a-r-g/color-themes,y-a-r-g/color-themes | ---
+++
@@ -14,7 +14,7 @@
"appender": {
"type": "smtp",
"recipients": process.env.EMAIL,
- "sender": "info@ideacolorthemes.org",
+ "sender": process.env.EMAIL,
"sendInterval": process.env.LOG_EMAIL_INTERVAL || 30,
"transport": "SMTP",
"SMTP": Utils.getEmailConfig() |
d3d7932eb1c067b2a403e0260c87192940565964 | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
gulp.task('mock-server', function() {
nodemon({
script: 'server.js'
, ext: 'js json'
, env: { 'NODE_ENV': 'development' }
})
});
| var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
gulp.task('default', function() {
nodemon({
script: 'server.js'
, ext: 'js json'
, env: { 'NODE_ENV': 'development' }
})
});
| Set gulp task as default | Set gulp task as default
| JavaScript | mit | isuru88/lazymine-mock-server | ---
+++
@@ -1,7 +1,7 @@
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
-gulp.task('mock-server', function() {
+gulp.task('default', function() {
nodemon({
script: 'server.js'
, ext: 'js json' |
9765f97a3c71483ef3793b7990ec73b6909edc9c | gulpfile.js | gulpfile.js | var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
//mix.less('');
mix.copy(
'./public/js/libs/semantic/dist/themes',
'public/css/themes'
);
mix.styles([
'./public/js/libs/semantic/dist/semantic.min.css'
],
'public/css/nestor.css');
// mix.scripts([
// './resources/assets/bower/jquery/dist/jquery.js',
// './resources/assets/bower/bootstrap-sass-official/assets/javascripts/bootstrap.min.js'
// ],
// 'public/js/nestor.js');
});
| var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
//mix.less('');
mix.copy(
'./public/js/libs/semantic/dist/themes',
'./public/css/themes'
);
mix.styles([
'./public/js/libs/semantic/dist/semantic.min.css'
],
'public/css/nestor.css');
// mix.scripts([
// './resources/assets/bower/jquery/dist/jquery.js',
// './resources/assets/bower/bootstrap-sass-official/assets/javascripts/bootstrap.min.js'
// ],
// 'public/js/nestor.js');
});
| Use same syntax for all assets | Use same syntax for all assets
| JavaScript | mit | nestor-qa/nestor,kinow/nestor,kinow/nestor,nestor-qa/nestor,nestor-qa/nestor,nestor-qa/nestor,kinow/nestor,kinow/nestor | ---
+++
@@ -14,10 +14,10 @@
elixir(function(mix) {
mix.sass('app.scss');
//mix.less('');
-
+
mix.copy(
'./public/js/libs/semantic/dist/themes',
- 'public/css/themes'
+ './public/css/themes'
);
mix.styles([
@@ -28,6 +28,6 @@
// mix.scripts([
// './resources/assets/bower/jquery/dist/jquery.js',
// './resources/assets/bower/bootstrap-sass-official/assets/javascripts/bootstrap.min.js'
- // ],
+ // ],
// 'public/js/nestor.js');
}); |
e1fb651837436053b24b9198a5d62ba869090297 | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var uglify = require('gulp-uglify');
gulp.task('default', function() {
gulp.src('lib/fs.js')
.pipe(uglify())
.pipe(gulp.dest('build'));
}); | var gulp = require('gulp');
var uglify = require('gulp-uglify');
var babel = require('gulp-babel');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
gulp.task('default', function() {
gulp.src('src/fs.js')
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(uglify())
.pipe(rename('fs.min.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
}); | Update default task for compile prod code | 1.2.2: Update default task for compile prod code
| JavaScript | mit | wangpin34/fs-h5,wangpin34/fs-h5 | ---
+++
@@ -1,8 +1,15 @@
var gulp = require('gulp');
var uglify = require('gulp-uglify');
+var babel = require('gulp-babel');
+var sourcemaps = require('gulp-sourcemaps');
+var rename = require('gulp-rename');
gulp.task('default', function() {
- gulp.src('lib/fs.js')
+ gulp.src('src/fs.js')
+ .pipe(sourcemaps.init())
+ .pipe(babel())
.pipe(uglify())
- .pipe(gulp.dest('build'));
+ .pipe(rename('fs.min.js'))
+ .pipe(sourcemaps.write('.'))
+ .pipe(gulp.dest('dist'));
}); |
2e8ab65088ba8acd7ddda01e4cfc5ba0f0fcdc1a | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp')
, jshint = require('gulp-jshint')
, nodemon = require('gulp-nodemon')
, paths
;
paths = {
projectScripts: ['./bin/www', '**/*.js', '!node_modules/**', '!public/**']
};
gulp.task('default', ['develop'], function () {
});
gulp.task('develop', function () {
nodemon({ script: 'bin/www', ext: 'js' })
.on('change', ['lint'])
.on('restart', function () {
console.log('Restared!');
});
});
gulp.task('lint', function () {
gulp.src(paths.projectScripts)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
| 'use strict';
var gulp = require('gulp')
, jshint = require('gulp-jshint')
, nodemon = require('gulp-nodemon')
, paths
;
paths = {
projectScripts: ['./bin/www', '**/*.js', '!node_modules/**', '!public/**']
};
gulp.task('default', ['develop'], function () {
});
gulp.task('develop', function () {
nodemon({ script: 'bin/www', ext: 'js' })
.on('change', ['hint'])
.on('restart', function () {
console.log('Restared!');
});
});
gulp.task('hint', function () {
gulp.src(paths.projectScripts)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
| Rename lint task to hint | Rename lint task to hint
| JavaScript | mit | Hilzu/SecureChat | ---
+++
@@ -15,13 +15,13 @@
gulp.task('develop', function () {
nodemon({ script: 'bin/www', ext: 'js' })
- .on('change', ['lint'])
+ .on('change', ['hint'])
.on('restart', function () {
console.log('Restared!');
});
});
-gulp.task('lint', function () {
+gulp.task('hint', function () {
gulp.src(paths.projectScripts)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish')); |
83cc95b851a39cd3952fa105272a750e0a147dee | addons/notes/src/__tests__/index.js | addons/notes/src/__tests__/index.js | import addons from '@storybook/addons';
import { withNotes } from '..';
jest.mock('@storybook/addons');
describe('Storybook Addon Notes', () => {
it('should inject info', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
const context = {};
const decoratedStory = withNotes('hello')(getStory);
decoratedStory(context);
expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello');
expect(getStory).toHaveBeenCalledWith(context);
});
});
| import addons from '@storybook/addons';
import { withNotes } from '..';
jest.mock('@storybook/addons');
describe('Storybook Addon Notes', () => {
it('should inject text from `notes` parameter', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
const context = { parameters: { notes: 'hello' } };
withNotes(getStory, context);
expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello');
expect(getStory).toHaveBeenCalledWith(context);
});
it('should inject markdown from `notes.markdown` parameter', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
const context = { parameters: { notes: { markdown: '# hello' } } };
withNotes(getStory, context);
expect(channel.emit).toHaveBeenCalledWith(
'storybook/notes/add_notes',
expect.stringContaining('<h1 id="hello">hello</h1>')
);
expect(getStory).toHaveBeenCalledWith(context);
});
it('should inject info (deprecated API)', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
const context = { parameters: {} };
const decoratedStory = withNotes('hello')(getStory);
decoratedStory(context);
expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello');
expect(getStory).toHaveBeenCalledWith(context);
});
});
| Update tests with new API | Update tests with new API
| JavaScript | mit | rhalff/storybook,storybooks/react-storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,rhalff/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,rhalff/storybook | ---
+++
@@ -4,12 +4,39 @@
jest.mock('@storybook/addons');
describe('Storybook Addon Notes', () => {
- it('should inject info', () => {
+ it('should inject text from `notes` parameter', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
- const context = {};
+ const context = { parameters: { notes: 'hello' } };
+
+ withNotes(getStory, context);
+ expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello');
+ expect(getStory).toHaveBeenCalledWith(context);
+ });
+
+ it('should inject markdown from `notes.markdown` parameter', () => {
+ const channel = { emit: jest.fn() };
+ addons.getChannel.mockReturnValue(channel);
+
+ const getStory = jest.fn();
+ const context = { parameters: { notes: { markdown: '# hello' } } };
+
+ withNotes(getStory, context);
+ expect(channel.emit).toHaveBeenCalledWith(
+ 'storybook/notes/add_notes',
+ expect.stringContaining('<h1 id="hello">hello</h1>')
+ );
+ expect(getStory).toHaveBeenCalledWith(context);
+ });
+
+ it('should inject info (deprecated API)', () => {
+ const channel = { emit: jest.fn() };
+ addons.getChannel.mockReturnValue(channel);
+
+ const getStory = jest.fn();
+ const context = { parameters: {} };
const decoratedStory = withNotes('hello')(getStory);
decoratedStory(context); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.