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 |
|---|---|---|---|---|---|---|---|---|---|---|
18dba001d139a01cfc8a52b9122dd821c72139d7 | backend/app/assets/javascripts/spree/backend/user_picker.js | backend/app/assets/javascripts/spree/backend/user_picker.js | $.fn.userAutocomplete = function () {
'use strict';
function formatUser(user) {
return Select2.util.escapeMarkup(user.email);
}
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
$.get(Spree.routes.users_api, {
ids: element.val()
}, function (data) {
callback(data.users);
});
},
ajax: {
url: Spree.routes.users_api,
datatype: 'json',
params: { "headers": { "X-Spree-Token": Spree.api_key } },
data: function (term) {
return {
m: 'or',
email_start: term,
addresses_firstname_start: term,
addresses_lastname_start: term
};
},
results: function (data) {
return {
results: data.users,
more: data.current_page < data.pages
};
}
},
formatResult: formatUser,
formatSelection: formatUser
});
};
$(document).ready(function () {
$('.user_picker').userAutocomplete();
});
| $.fn.userAutocomplete = function () {
'use strict';
function formatUser(user) {
return Select2.util.escapeMarkup(user.email);
}
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
Spree.ajax({
url: Spree.routes.users_api,
data: {
ids: element.val()
},
success: function(data) {
callback(data.users);
}
});
},
ajax: {
url: Spree.routes.users_api,
datatype: 'json',
params: { "headers": { "X-Spree-Token": Spree.api_key } },
data: function (term) {
return {
m: 'or',
email_start: term,
addresses_firstname_start: term,
addresses_lastname_start: term
};
},
results: function (data) {
return {
results: data.users,
more: data.current_page < data.pages
};
}
},
formatResult: formatUser,
formatSelection: formatUser
});
};
$(document).ready(function () {
$('.user_picker').userAutocomplete();
});
| Fix user picker's select2 initial selection | Fix user picker's select2 initial selection
- was failing because of missing token: `Spree.api_key`
- going through the Spree.ajax automatically adds the `api_key`
| JavaScript | bsd-3-clause | jordan-brough/solidus,Arpsara/solidus,jordan-brough/solidus,pervino/solidus,pervino/solidus,Arpsara/solidus,Arpsara/solidus,jordan-brough/solidus,pervino/solidus,Arpsara/solidus,pervino/solidus,jordan-brough/solidus | ---
+++
@@ -9,10 +9,14 @@
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
- $.get(Spree.routes.users_api, {
- ids: element.val()
- }, function (data) {
- callback(data.users);
+ Spree.ajax({
+ url: Spree.routes.users_api,
+ data: {
+ ids: element.val()
+ },
+ success: function(data) {
+ callback(data.users);
+ }
});
},
ajax: { |
d5c4c7b0e48c736abf56022be40ba962cea78d9b | Resources/public/scripts/date-time-pickers-init.js | Resources/public/scripts/date-time-pickers-init.js | $(document).ready(function () {
var locale = 'en' !== LOCALE ? LOCALE : '';
var options = $.extend({}, $.datepicker.regional[locale], $.timepicker.regional[locale], {
dateFormat: 'dd.mm.yy'
});
var init;
(init = function () {
$('input.date').datepicker(options);
$('input.datetime').datetimepicker(options);
$('input.time').timepicker(options);
})();
$(document).bind('ajaxSuccess', init);
});
| $(document).ready(function () {
var locale = 'en' !== LOCALE ? LOCALE : '';
var options = $.extend({}, $.datepicker.regional[locale], $.timepicker.regional[locale], {
dateFormat: 'dd.mm.yy'
});
var init;
(init = function () {
['date', 'datetime', 'time'].map(function (type) {
$('input.' + type)[type + 'picker'](options);
});
})();
$(document).bind('ajaxSuccess', init);
});
| Simplify date time pickers init JS. | Simplify date time pickers init JS.
| JavaScript | mit | DarvinStudio/DarvinAdminBundle,DarvinStudio/DarvinAdminBundle,DarvinStudio/DarvinAdminBundle | ---
+++
@@ -6,9 +6,9 @@
var init;
(init = function () {
- $('input.date').datepicker(options);
- $('input.datetime').datetimepicker(options);
- $('input.time').timepicker(options);
+ ['date', 'datetime', 'time'].map(function (type) {
+ $('input.' + type)[type + 'picker'](options);
+ });
})();
$(document).bind('ajaxSuccess', init); |
1c8f5cc3126258472e9e80928f9cb9f9ac358899 | objects/barrier.js | objects/barrier.js | 'use strict';
const audioUtil = require('../utils/audio');
const PhysicsSprite = require('./physics-sprite');
class Barrier extends PhysicsSprite {
constructor(game, x, y) {
super(game, x, y, 'barrier', 2, true);
this.animations.add('up', [ 2, 1, 0 ], 10, false);
this.animations.add('down', [ 0, 1, 2 ], 10, false);
this.introSfx = audioUtil.addSfx(
game, 'barrier', game.rnd.integerInRange(0, 2)
);
}
playIntro() {
this.animations.play('up');
this.introSfx.play();
}
playOutro() {
this.animations.play('down');
}
}
module.exports = Barrier;
| 'use strict';
const audioUtil = require('../utils/audio');
const PhysicsSprite = require('./physics-sprite');
class Barrier extends PhysicsSprite {
constructor(game, x, y) {
super(game, x, y, 'barrier', 2, true);
this.animations.add('up', [ 2, 1, 0 ], 10, false);
this.animations.add('down', [ 0, 1, 2 ], 10, false);
this.introSfx = audioUtil.addSfx('barrier', game.rnd.integerInRange(0, 2));
}
playIntro() {
this.animations.play('up');
this.introSfx.play();
}
playOutro() {
this.animations.play('down');
}
}
module.exports = Barrier;
| Fix the call to addSfx broken by the signature change | Fix the call to addSfx broken by the signature change
| JavaScript | mit | to-the-end/to-the-end,to-the-end/to-the-end | ---
+++
@@ -11,9 +11,7 @@
this.animations.add('up', [ 2, 1, 0 ], 10, false);
this.animations.add('down', [ 0, 1, 2 ], 10, false);
- this.introSfx = audioUtil.addSfx(
- game, 'barrier', game.rnd.integerInRange(0, 2)
- );
+ this.introSfx = audioUtil.addSfx('barrier', game.rnd.integerInRange(0, 2));
}
playIntro() { |
2f1a55fa66279b8f15d9fa3b5c2c6d3056b2a3bd | ghost/admin/views/posts.js | ghost/admin/views/posts.js | import {mobileQuery, responsiveAction} from 'ghost/utils/mobile';
var PostsView = Ember.View.extend({
target: Ember.computed.alias('controller'),
classNames: ['content-view-container'],
tagName: 'section',
mobileInteractions: function () {
Ember.run.scheduleOnce('afterRender', this, function () {
var self = this;
$(window).resize(function () {
if (!mobileQuery.matches) {
self.send('resetContentPreview');
}
});
// ### Show content preview when swiping left on content list
$('.manage').on('click', '.content-list ol li', function (event) {
responsiveAction(event, '(max-width: 800px)', function () {
self.send('showContentPreview');
});
});
// ### Hide content preview
$('.manage').on('click', '.content-preview .button-back', function (event) {
responsiveAction(event, '(max-width: 800px)', function () {
self.send('hideContentPreview');
});
});
});
}.on('didInsertElement'),
});
export default PostsView;
| import {mobileQuery, responsiveAction} from 'ghost/utils/mobile';
var PostsView = Ember.View.extend({
target: Ember.computed.alias('controller'),
classNames: ['content-view-container'],
tagName: 'section',
mobileInteractions: function () {
Ember.run.scheduleOnce('afterRender', this, function () {
var self = this;
$(window).resize(function () {
if (!mobileQuery.matches) {
self.send('resetContentPreview');
}
});
// ### Show content preview when swiping left on content list
$('.manage').on('click', '.content-list ol li', function (event) {
responsiveAction(event, '(max-width: 800px)', function () {
self.send('showContentPreview');
});
});
// ### Hide content preview
$('.manage').on('click', '.content-preview .button-back', function (event) {
responsiveAction(event, '(max-width: 800px)', function () {
self.send('hideContentPreview');
});
});
$('[data-off-canvas]').attr('href', this.get('controller.ghostPaths.blogRoot'));
});
}.on('didInsertElement'),
});
export default PostsView;
| Fix Ghost icon is not clickable | Fix Ghost icon is not clickable
closes #3623
- Initialization of the link was done on login page where the ‚burger‘
did not exist.
- initialization in application needs to be done to make it work on
refresh
| JavaScript | mit | TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost | ---
+++
@@ -28,6 +28,7 @@
self.send('hideContentPreview');
});
});
+ $('[data-off-canvas]').attr('href', this.get('controller.ghostPaths.blogRoot'));
});
}.on('didInsertElement'),
}); |
a707671862e95b88c827f835187c1d3f96f899bd | test/system/bootcode-size.test.js | test/system/bootcode-size.test.js | const fs = require('fs'),
path = require('path'),
CACHE_DIR = path.join(__dirname, '/../../.cache'),
THRESHOLD = 3.4 * 1024 * 1024; // 3.4 MB
describe('bootcode size', function () {
this.timeout(60 * 1000);
it('should not exceed the threshold', function (done) {
fs.readdir(CACHE_DIR, function (err, files) {
if (err) { return done(err); }
files.forEach(function (file) {
var size = fs.statSync(CACHE_DIR + '/' + file).size;
expect(size, (file + ' threshold exceeded')).to.be.below(THRESHOLD);
});
done();
});
});
});
| const fs = require('fs'),
path = require('path'),
CACHE_DIR = path.join(__dirname, '/../../.cache'),
THRESHOLD = 4 * 1024 * 1024; // 4 MB
describe('bootcode size', function () {
this.timeout(60 * 1000);
it('should not exceed the threshold', function (done) {
fs.readdir(CACHE_DIR, function (err, files) {
if (err) { return done(err); }
files.forEach(function (file) {
var size = fs.statSync(CACHE_DIR + '/' + file).size;
expect(size, (file + ' threshold exceeded')).to.be.below(THRESHOLD);
});
done();
});
});
});
| Update bootcode threshold to 4 MB | Update bootcode threshold to 4 MB
| JavaScript | apache-2.0 | postmanlabs/postman-sandbox | ---
+++
@@ -1,7 +1,7 @@
const fs = require('fs'),
path = require('path'),
CACHE_DIR = path.join(__dirname, '/../../.cache'),
- THRESHOLD = 3.4 * 1024 * 1024; // 3.4 MB
+ THRESHOLD = 4 * 1024 * 1024; // 4 MB
describe('bootcode size', function () {
this.timeout(60 * 1000); |
100f84cc123ea99b366e314d15e534eb50912fde | backend/server/model-loader.js | backend/server/model-loader.js | module.exports = function modelLoader(isParent) {
'use strict';
if (isParent || process.env.MCTEST) {
console.log('using mocks/model');
return require('./mocks/model');
}
let ropts = {
db: 'materialscommons',
port: 30815
};
let r = require('rethinkdbdash')(ropts);
return require('./db/model')(r);
};
| module.exports = function modelLoader(isParent) {
'use strict';
if (isParent || process.env.MCTEST) {
return require('./mocks/model');
}
let ropts = {
db: process.env.MCDB || 'materialscommons',
port: process.env.MCPORT || 30815
};
let r = require('rethinkdbdash')(ropts);
return require('./db/model')(r);
};
| Add environment variables for testing, database and database server port. | Add environment variables for testing, database and database server port.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -2,13 +2,12 @@
'use strict';
if (isParent || process.env.MCTEST) {
- console.log('using mocks/model');
return require('./mocks/model');
}
let ropts = {
- db: 'materialscommons',
- port: 30815
+ db: process.env.MCDB || 'materialscommons',
+ port: process.env.MCPORT || 30815
};
let r = require('rethinkdbdash')(ropts); |
27c448c3672b174df3dcfa3cff1e29f85983b2b3 | app/helpers/register-helpers/helper-config.js | app/helpers/register-helpers/helper-config.js | var ConfigBuilder = require('../builders/ConfigBuilder');
module.exports.register = function(Handlebars, options) {
options = options || {};
var helpers = {
helper_config: function(key) {
var config = new ConfigBuilder().build();
return config.get(key);
}
};
for (var helper in helpers) {
if (helpers.hasOwnProperty(helper)) {
Handlebars.registerHelper(helper, helpers[helper]);
}
}
} | var ConfigBuilder = require('../builders/ConfigBuilder');
module.exports.register = function(Handlebars, options) {
options = options || {};
var helperName = 'helper_config';
function validateArguments(arguments) {
if (arguments.length < 2) {
throw new ReferenceError(`${helperName}: config key must be passed from template; nothing was passed`);
}
if (arguments.length === 2 && typeof arguments[0] != 'string') {
var argType = typeof arguments[0];
throw new TypeError(`${helperName}: config key must be a string when passed from template; ${argType} was passed`);
}
}
var helpers = {
[helperName]: function(key, options) {
validateArguments(arguments);
var config = new ConfigBuilder({helperName: helperName}).build();
return config.get(key);
}
};
for (var helper in helpers) {
if (helpers.hasOwnProperty(helper)) {
Handlebars.registerHelper(helper, helpers[helper]);
}
}
} | Validate arguments passed from template to helper_config | Validate arguments passed from template to helper_config
| JavaScript | mit | oksana-khristenko/assemble-starter,oksana-khristenko/assemble-starter | ---
+++
@@ -3,9 +3,23 @@
module.exports.register = function(Handlebars, options) {
options = options || {};
+ var helperName = 'helper_config';
+
+ function validateArguments(arguments) {
+ if (arguments.length < 2) {
+ throw new ReferenceError(`${helperName}: config key must be passed from template; nothing was passed`);
+ }
+ if (arguments.length === 2 && typeof arguments[0] != 'string') {
+ var argType = typeof arguments[0];
+ throw new TypeError(`${helperName}: config key must be a string when passed from template; ${argType} was passed`);
+ }
+ }
+
var helpers = {
- helper_config: function(key) {
- var config = new ConfigBuilder().build();
+ [helperName]: function(key, options) {
+ validateArguments(arguments);
+
+ var config = new ConfigBuilder({helperName: helperName}).build();
return config.get(key);
}
}; |
c6b618f37cb48bcde0d858d0e0627ac734a9970f | static/js/settings.js | static/js/settings.js | /****************************************************************************
#
# This file is part of the Vilfredo Client.
#
# Copyright © 2009-2014 Pietro Speroni di Fenizio / Derek Paterson.
#
# VilfredoReloadedCore is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation version 3 of the License.
#
# VilfredoReloadedCore is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
# for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with VilfredoReloadedCore. If not, see <http://www.gnu.org/licenses/>.
#
****************************************************************************/
var VILFREDO_URL = 'http://0.0.0.0:8080';
var API_VERSION = 'v1';
var ALGORITHM_VERSION = 1;
// Don't edit below
//
var VILFREDO_API = VILFREDO_URL + '/api/' + API_VERSION;
var STATIC_FILES = VILFREDO_URL + '/static';
var Q_READ = 0x1
var Q_VOTE = 0x2
var Q_PROPOSE = 0x4
var Q_INVITE = 0x8
| /****************************************************************************
#
# This file is part of the Vilfredo Client.
#
# Copyright © 2009-2014 Pietro Speroni di Fenizio / Derek Paterson.
#
# VilfredoReloadedCore is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation version 3 of the License.
#
# VilfredoReloadedCore is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
# for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with VilfredoReloadedCore. If not, see <http://www.gnu.org/licenses/>.
#
****************************************************************************/
var VILFREDO_URL = 'http://0.0.0.0:8080';
var API_VERSION = 'v1';
var ALGORITHM_VERSION = 1;
// radius of circle representing a vote
var radius = 10;
// Don't edit below
//
var VILFREDO_API = VILFREDO_URL + '/api/' + API_VERSION;
var STATIC_FILES = VILFREDO_URL + '/static';
var Q_READ = 0x1
var Q_VOTE = 0x2
var Q_PROPOSE = 0x4
var Q_INVITE = 0x8
| Add setting for vote radius | Add setting for vote radius
| JavaScript | agpl-3.0 | fairdemocracy/vilfredo-client,fairdemocracy/vilfredo-client,fairdemocracy/vilfredo-client,fairdemocracy/vilfredo-client | ---
+++
@@ -23,6 +23,9 @@
var ALGORITHM_VERSION = 1;
+// radius of circle representing a vote
+var radius = 10;
+
// Don't edit below
//
var VILFREDO_API = VILFREDO_URL + '/api/' + API_VERSION; |
76c698424bcfaa28a0de3b78779595f51ec9a63f | source/icsm/toolbar/toolbar.js | source/icsm/toolbar/toolbar.js | /*!
* Copyright 2015 Geoscience Australia (http://www.ga.gov.au/copyright.html)
*/
(function(angular) {
'use strict';
angular.module("icsm.toolbar", [])
.directive("icsmToolbar", [function() {
return {
controller: 'toolbarLinksCtrl'
};
}])
/**
* Override the default mars tool bar row so that a different implementation of the toolbar can be used.
*/
.directive('icsmToolbarRow', [function() {
return {
scope:{
map:"="
},
restrict:'AE',
templateUrl:'icsm/toolbar/toolbar.html'
};
}])
.directive('icsmToolbarInfo', [function() {
return {
templateUrl: 'radwaste/toolbar/toolbarInfo.html'
};
}])
.controller("toolbarLinksCtrl", ["$scope", "configService", function($scope, configService) {
var self = this;
configService.getConfig().then(function(config) {
self.links = config.toolbarLinks;
});
$scope.item = "";
$scope.toggleItem = function(item) {
$scope.item = ($scope.item == item) ? "" : item;
};
}]);
})(angular); | /*!
* Copyright 2015 Geoscience Australia (http://www.ga.gov.au/copyright.html)
*/
(function(angular) {
'use strict';
angular.module("icsm.toolbar", [])
.directive("icsmToolbar", [function() {
return {
controller: 'toolbarLinksCtrl'
};
}])
/**
* Override the default mars tool bar row so that a different implementation of the toolbar can be used.
*/
.directive('icsmToolbarRow', [function() {
return {
scope:{
map:"="
},
restrict:'AE',
templateUrl:'icsm/toolbar/toolbar.html'
};
}])
.directive('icsmToolbarInfo', [function() {
return {
templateUrl: 'radwaste/toolbar/toolbarInfo.html'
};
}])
.controller("toolbarLinksCtrl", ["$scope", "configService", function($scope, configService) {
var self = this;
configService.getConfig().then(function(config) {
self.links = config.toolbarLinks;
});
$scope.item = "";
$scope.toggleItem = function(item) {
$scope.item = ($scope.item === item) ? "" : item;
};
}]);
})(angular); | Implement eslint suggestion around equals comparison | Implement eslint suggestion around equals comparison
| JavaScript | apache-2.0 | Tomella/fsdf-elvis,Tomella/fsdf-elvis,Tomella/fsdf-elvis | ---
+++
@@ -43,7 +43,7 @@
$scope.item = "";
$scope.toggleItem = function(item) {
- $scope.item = ($scope.item == item) ? "" : item;
+ $scope.item = ($scope.item === item) ? "" : item;
};
}]); |
40bad4868b572bf0753cdc7bcc7b9a856f2f6bda | render.js | render.js | var page = require('webpage').create(),
system = require('system'),
fs = require('fs');
var userAgent = "Grabshot"
var url = system.args[1];
var format = system.args[2] || "PNG"
page.viewportSize = {
width: 1280
// height: ...
}
function render() {
result = {
title: page.evaluate(function() { return document.title }),
imageData: page.renderBase64(format),
format: format
}
console.log(JSON.stringify(result))
phantom.exit();
}
page.onError = phantom.onError = function() {
console.log("PhantomJS error :(");
phantom.exit(1);
};
page.onLoadFinished = function (status) {
if (status !== 'success') {
phantom.exit(1);
}
setTimeout(render, 50);
}
page.open(url);
| var page = require('webpage').create(),
system = require('system'),
fs = require('fs');
var userAgent = "Grabshot"
var url = system.args[1];
var format = system.args[2] || "PNG"
page.viewportSize = {
width: 1280
// height: ...
}
function render() {
result = {
title: page.evaluate(function() { return document.title }),
imageData: page.renderBase64(format),
format: format
}
console.log(JSON.stringify(result))
phantom.exit();
}
page.onError = phantom.onError = function() {
console.log("PhantomJS error :(");
phantom.exit(1);
};
page.onLoadFinished = function (status) {
if (status !== 'success') {
phantom.exit(1);
}
setTimeout(render, 300);
}
page.open(url);
| Increase timeout to give time for loading transitions to complete | Increase timeout to give time for loading transitions to complete
TODO: Use JavaScript to try to predict when loading is done...
| JavaScript | mit | bjeanes/grabshot,bjeanes/grabshot | ---
+++
@@ -33,7 +33,7 @@
phantom.exit(1);
}
- setTimeout(render, 50);
+ setTimeout(render, 300);
}
page.open(url); |
ba8d433ab2cccdfa652e45494543428c093a85ce | app/javascript/gobierto_participation/modules/application.js | app/javascript/gobierto_participation/modules/application.js | function currentLocationMatches(action_path) {
return $("body.gobierto_participation_" + action_path).length > 0
}
$(document).on('turbolinks:load', function() {
// Toggle description for Process#show stages diagram
$('.toggle_description').click(function() {
$(this).parents('.timeline_row').toggleClass('toggled');
$(this).find('.fa').toggleClass('fa-caret-right fa-caret-down');
$(this).siblings('.description').toggle();
});
$.fn.extend({
toggleText: function(a, b){
return this.text(this.text() == b ? a : b);
}
});
$('.button_toggle').on('click', function() {
$('.button.hidden').toggleClass('hidden');
})
if (currentLocationMatches("processes_poll_answers_new")) {
window.GobiertoParticipation.process_polls_controller.show();
} else if (currentLocationMatches("processes_show")) {
window.GobiertoParticipation.processes_controller.show();
}
// fix this to be only in the home
window.GobiertoParticipation.poll_teaser_controller.show();
});
| function currentLocationMatches(action_path) {
return $("body.gobierto_participation_" + action_path).length > 0
}
$(document).on('turbolinks:load', function() {
// Toggle description for Process#show stages diagram
$('.toggle_description').click(function() {
$(this).parents('.timeline_row').toggleClass('toggled');
$(this).find('.fa').toggleClass('fa-caret-right fa-caret-down');
$(this).siblings('.description').toggle();
});
$.fn.extend({
toggleText: function(a, b){
return this.text(this.text() == b ? a : b);
}
});
$('.button_toggle').on('click', function() {
$('.button.hidden').toggleClass('hidden');
})
if (currentLocationMatches("processes_poll_answers_new")) {
window.GobiertoParticipation.process_polls_controller.show();
} else if (currentLocationMatches("processes_show")) {
window.GobiertoParticipation.processes_controller.show();
}
// fix this to be only in the home
window.GobiertoParticipation.poll_teaser_controller.show();
// Add active class to menu
$('nav a[href="' + window.location.pathname + '"]').parent().addClass('active');
});
| Add active class in participation navigation menu using JS | Add active class in participation navigation menu using JS
| JavaScript | agpl-3.0 | PopulateTools/gobierto-dev,PopulateTools/gobierto,PopulateTools/gobierto,PopulateTools/gobierto,PopulateTools/gobierto,PopulateTools/gobierto-dev,PopulateTools/gobierto-dev,PopulateTools/gobierto-dev | ---
+++
@@ -30,4 +30,7 @@
// fix this to be only in the home
window.GobiertoParticipation.poll_teaser_controller.show();
+
+ // Add active class to menu
+ $('nav a[href="' + window.location.pathname + '"]').parent().addClass('active');
}); |
3c9c39915271ff611c7dbcacddde379c78301303 | src/client/reducers/StatusReducer.js | src/client/reducers/StatusReducer.js | import initialState from './initialState';
import {
LOGO_SPIN_STARTED,
LOGO_SPIN_ENDED,
PAGE_SCROLL_STARTED,
PAGE_SCROLL_ENDED,
APP_INIT,
STATUS_UPDATE,
PROVIDER_CHANGE,
BOARD_CHANGE,
SCROLL_HEADER,
THREAD_REQUESTED,
BOARD_REQUESTED,
} from '../constants';
export default function (state = initialState.status, action) {
switch (action.type) {
// case APP_INIT:
// return Object.assign({}, state, {
// isMainPage: true
// })
case PAGE_SCROLL_STARTED:
return Object.assign({}, state, {
isScrolling: true,
currentPage: action.payload
})
case PAGE_SCROLL_ENDED:
return Object.assign({}, state, {
isScrolling: false,
currentPage: action.payload
})
case SCROLL_HEADER:
return Object.assign({}, state, {
isHeaderVisible: action.payload
})
case PROVIDER_CHANGE:
return Object.assign({}, state, {
provider: action.payload
})
case BOARD_REQUESTED:
return Object.assign({}, state, {
boardID: action.payload
})
case THREAD_REQUESTED:
return Object.assign({}, state, {
threadID: action.payload
})
case STATUS_UPDATE:
return Object.assign({}, state, {
statusMessage: action.payload
})
default:
return state
}
}
| import initialState from './initialState';
import {
LOGO_SPIN_STARTED,
LOGO_SPIN_ENDED,
PAGE_SCROLL_STARTED,
PAGE_SCROLL_ENDED,
APP_INIT,
STATUS_UPDATE,
PROVIDER_CHANGE,
BOARD_CHANGE,
SCROLL_HEADER,
THREAD_REQUESTED,
THREAD_DESTROYED,
BOARD_REQUESTED,
BOARD_DESTROYED,
} from '../constants';
export default function (state = initialState.status, action) {
switch (action.type) {
// case APP_INIT:
// return Object.assign({}, state, {
// isMainPage: true
// })
case PAGE_SCROLL_STARTED:
return Object.assign({}, state, {
isScrolling: true,
currentPage: action.payload
})
case PAGE_SCROLL_ENDED:
return Object.assign({}, state, {
isScrolling: false,
currentPage: action.payload
})
case SCROLL_HEADER:
return Object.assign({}, state, {
isHeaderVisible: action.payload
})
case PROVIDER_CHANGE:
return Object.assign({}, state, {
provider: action.payload
})
case BOARD_REQUESTED:
return Object.assign({}, state, {
boardID: action.payload
})
case THREAD_REQUESTED:
return Object.assign({}, state, {
threadID: action.payload
})
case STATUS_UPDATE:
return Object.assign({}, state, {
alertMessage: action.payload
})
case THREAD_DESTROYED:
return Object.assign({}, state, {
threadID: null
})
case BOARD_DESTROYED:
return Object.assign({}, state, {
boardID: null
})
default:
return state
}
}
| Add reducer cases for thread/board destroyed | Add reducer cases for thread/board destroyed
| JavaScript | mit | AdamSalma/Lurka,AdamSalma/Lurka | ---
+++
@@ -12,7 +12,10 @@
SCROLL_HEADER,
THREAD_REQUESTED,
+ THREAD_DESTROYED,
+
BOARD_REQUESTED,
+ BOARD_DESTROYED,
} from '../constants';
export default function (state = initialState.status, action) {
@@ -57,7 +60,17 @@
case STATUS_UPDATE:
return Object.assign({}, state, {
- statusMessage: action.payload
+ alertMessage: action.payload
+ })
+
+ case THREAD_DESTROYED:
+ return Object.assign({}, state, {
+ threadID: null
+ })
+
+ case BOARD_DESTROYED:
+ return Object.assign({}, state, {
+ boardID: null
})
default: |
d6328b1e65daf111720f76b70f6d469a91a96335 | pointergestures.js | pointergestures.js | /*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* @module PointerGestures
*/
(function() {
var thisFile = 'pointergestures.js';
var scopeName = 'PointerGestures';
var modules = [
'src/PointerGestureEvent.js',
'src/initialize.js',
'src/sidetable.js',
'src/pointermap.js',
'src/dispatcher.js',
'src/hold.js',
'src/track.js',
'src/flick.js',
'src/tap.js'
];
window[scopeName] = {
entryPointName: thisFile,
modules: modules
};
var script = document.querySelector('script[src $= "' + thisFile + '"]');
var src = script.attributes.src.value;
var basePath = src.slice(0, src.indexOf(thisFile));
if (!window.PointerEventPolyfill) {
document.write('<script src="' + basePath + '../PointerEvents/pointerevents.js"></script>');
}
if (!window.Loader) {
var path = basePath + 'tools/loader/loader.js';
document.write('<script src="' + path + '"></script>');
}
document.write('<script>Loader.load("' + scopeName + '")</script>');
})();
| /*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* @module PointerGestures
*/
(function() {
var thisFile = 'pointergestures.js';
var scopeName = 'PointerGestures';
var modules = [
'src/PointerGestureEvent.js',
'src/initialize.js',
'src/sidetable.js',
'src/pointermap.js',
'src/dispatcher.js',
'src/hold.js',
'src/track.js',
'src/flick.js',
'src/tap.js'
];
window[scopeName] = {
entryPointName: thisFile,
modules: modules
};
var script = document.querySelector('script[src $= "' + thisFile + '"]');
var src = script.attributes.src.value;
var basePath = src.slice(0, src.indexOf(thisFile));
if (!window.PointerEvent) {
document.write('<script src="' + basePath + '../PointerEvents/pointerevents.js"></script>');
}
if (!window.Loader) {
var path = basePath + 'tools/loader/loader.js';
document.write('<script src="' + path + '"></script>');
}
document.write('<script>Loader.load("' + scopeName + '")</script>');
})();
| Use PointerEvent to be check for loading PointerEvents polyfill | Use PointerEvent to be check for loading PointerEvents polyfill
| JavaScript | bsd-3-clause | Polymer/PointerGestures | ---
+++
@@ -30,7 +30,7 @@
var src = script.attributes.src.value;
var basePath = src.slice(0, src.indexOf(thisFile));
- if (!window.PointerEventPolyfill) {
+ if (!window.PointerEvent) {
document.write('<script src="' + basePath + '../PointerEvents/pointerevents.js"></script>');
}
|
3495b9e94ffb9dc03bf6c3699f9484343829171c | test/highlightAuto.js | test/highlightAuto.js | 'use strict';
var fs = require('fs');
var hljs = require('../build');
var path = require('path');
var utility = require('./utility');
function testAutoDetection(language) {
it('should be detected as ' + language, function() {
var languagePath = utility.buildPath('detect', language),
examples = fs.readdirSync(languagePath);
examples.forEach(function(example) {
var filename = path.join(languagePath, example),
content = fs.readFileSync(filename, 'utf-8'),
expected = language,
actual = hljs.highlightAuto(content).language;
actual.should.equal(expected);
});
});
}
describe('hljs', function() {
describe('.highlightAuto', function() {
var languages = utility.languagesList();
languages.forEach(testAutoDetection);
});
});
| 'use strict';
var fs = require('fs');
var hljs = require('../build');
var path = require('path');
var utility = require('./utility');
function testAutoDetection(language) {
it('should be detected as ' + language, function() {
var languagePath = utility.buildPath('detect', language),
examples = fs.readdirSync(languagePath);
examples.forEach(function(example) {
var filename = path.join(languagePath, example),
content = fs.readFileSync(filename, 'utf-8'),
expected = language,
actual = hljs.highlightAuto(content).language;
actual.should.equal(expected);
});
});
}
describe('hljs', function() {
describe('.highlightAuto', function() {
var languages = hljs.listLanguages();
languages.forEach(testAutoDetection);
});
});
| Use hljs.listLanguages for auto-detection tests | Use hljs.listLanguages for auto-detection tests
| JavaScript | bsd-3-clause | snegovick/highlight.js,iOctocat/highlight.js,dYale/highlight.js,dbkaplun/highlight.js,kevinrodbe/highlight.js,dirkk/highlight.js,abhishekgahlot/highlight.js,kevinrodbe/highlight.js,daimor/highlight.js,Ajunboys/highlight.js,cicorias/highlight.js,isagalaev/highlight.js,xing-zhi/highlight.js,yxxme/highlight.js,STRML/highlight.js,daimor/highlight.js,rla/highlight.js,J2TeaM/highlight.js,bogachev-pa/highlight.js,christoffer/highlight.js,StanislawSwierc/highlight.js,robconery/highlight.js,Delermando/highlight.js,Sannis/highlight.js,carlokok/highlight.js,taoger/highlight.js,kayyyy/highlight.js,highlightjs/highlight.js,drmohundro/highlight.js,krig/highlight.js,robconery/highlight.js,gitterHQ/highlight.js,brennced/highlight.js,brennced/highlight.js,alvarotrigo/highlight.js,drmohundro/highlight.js,kayyyy/highlight.js,dublebuble/highlight.js,zachaysan/highlight.js,yxxme/highlight.js,snegovick/highlight.js,1st1/highlight.js,liang42hao/highlight.js,aurusov/highlight.js,ilovezy/highlight.js,xing-zhi/highlight.js,kba/highlight.js,1st1/highlight.js,dx285/highlight.js,Ajunboys/highlight.js,abhishekgahlot/highlight.js,martijnrusschen/highlight.js,Aaron1992/highlight.js,tenbits/highlight.js,teambition/highlight.js,adam-lynch/highlight.js,adjohnson916/highlight.js,weiyibin/highlight.js,Aaron1992/highlight.js,JoshTheGeek-graveyard/highlight.js,axter/highlight.js,tenbits/highlight.js,adjohnson916/highlight.js,axter/highlight.js,palmin/highlight.js,alex-zhang/highlight.js,ysbaddaden/highlight.js,dYale/highlight.js,iOctocat/highlight.js,lizhil/highlight.js,highlightjs/highlight.js,lizhil/highlight.js,VoldemarLeGrand/highlight.js,Aaron1992/highlight.js,adjohnson916/highlight.js,krig/highlight.js,iOctocat/highlight.js,devmario/highlight.js,bluepichu/highlight.js,CausalityLtd/highlight.js,liang42hao/highlight.js,adam-lynch/highlight.js,yxxme/highlight.js,tenbits/highlight.js,lead-auth/highlight.js,kba/highlight.js,Ankirama/highlight.js,StanislawSwierc/highlight.js,delebash/highlight.js,jean/highlight.js,STRML/highlight.js,cicorias/highlight.js,taoger/highlight.js,teambition/highlight.js,ilovezy/highlight.js,bogachev-pa/highlight.js,CausalityLtd/highlight.js,dYale/highlight.js,ysbaddaden/highlight.js,sourrust/highlight.js,ponylang/highlight.js,0x7fffffff/highlight.js,dublebuble/highlight.js,dirkk/highlight.js,aurusov/highlight.js,robconery/highlight.js,VoldemarLeGrand/highlight.js,ponylang/highlight.js,zachaysan/highlight.js,VoldemarLeGrand/highlight.js,Ajunboys/highlight.js,MakeNowJust/highlight.js,Sannis/highlight.js,cicorias/highlight.js,dx285/highlight.js,palmin/highlight.js,Amrit01/highlight.js,MakeNowJust/highlight.js,liang42hao/highlight.js,snegovick/highlight.js,bluepichu/highlight.js,highlightjs/highlight.js,devmario/highlight.js,SibuStephen/highlight.js,alex-zhang/highlight.js,0x7fffffff/highlight.js,palmin/highlight.js,dirkk/highlight.js,aristidesstaffieri/highlight.js,J2TeaM/highlight.js,sourrust/highlight.js,dublebuble/highlight.js,0x7fffffff/highlight.js,christoffer/highlight.js,kba/highlight.js,delebash/highlight.js,sourrust/highlight.js,STRML/highlight.js,jean/highlight.js,martijnrusschen/highlight.js,rla/highlight.js,brennced/highlight.js,JoshTheGeek-graveyard/highlight.js,teambition/highlight.js,1st1/highlight.js,krig/highlight.js,SibuStephen/highlight.js,carlokok/highlight.js,ehornbostel/highlight.js,ehornbostel/highlight.js,ysbaddaden/highlight.js,kayyyy/highlight.js,jean/highlight.js,Delermando/highlight.js,kevinrodbe/highlight.js,highlightjs/highlight.js,aurusov/highlight.js,SibuStephen/highlight.js,carlokok/highlight.js,isagalaev/highlight.js,Amrit01/highlight.js,taoger/highlight.js,dbkaplun/highlight.js,ilovezy/highlight.js,xing-zhi/highlight.js,weiyibin/highlight.js,gitterHQ/highlight.js,lizhil/highlight.js,alex-zhang/highlight.js,Ankirama/highlight.js,martijnrusschen/highlight.js,aristidesstaffieri/highlight.js,alvarotrigo/highlight.js,MakeNowJust/highlight.js,CausalityLtd/highlight.js,Amrit01/highlight.js,ehornbostel/highlight.js,bogachev-pa/highlight.js,aristidesstaffieri/highlight.js,Sannis/highlight.js,Delermando/highlight.js,axter/highlight.js,carlokok/highlight.js,dbkaplun/highlight.js,dx285/highlight.js,daimor/highlight.js,weiyibin/highlight.js,ponylang/highlight.js,Ankirama/highlight.js,devmario/highlight.js,delebash/highlight.js,christoffer/highlight.js,abhishekgahlot/highlight.js,J2TeaM/highlight.js,bluepichu/highlight.js,zachaysan/highlight.js,adam-lynch/highlight.js | ---
+++
@@ -24,7 +24,7 @@
describe('hljs', function() {
describe('.highlightAuto', function() {
- var languages = utility.languagesList();
+ var languages = hljs.listLanguages();
languages.forEach(testAutoDetection);
}); |
3248f52485a8cf44788a070744378f4e421b1529 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .
$(function(){ $(document).foundation(); });
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require foundation
//= require turbolinks
//= require_tree .
| Remove code from Application.js to remedy errors seen in browser console | Remove code from Application.js to remedy errors seen in browser console
| JavaScript | mit | TerrenceLJones/not-bored-tonight,TerrenceLJones/not-bored-tonight | ---
+++
@@ -11,8 +11,6 @@
// about supported directives.
//
//= require jquery
-//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .
-$(function(){ $(document).foundation(); }); |
83322ef4a60598c58adedcec4240f83e659d5349 | app/controllers/abstractController.js | app/controllers/abstractController.js | core.controller('AbstractController', function ($scope, StorageService) {
$scope.isAssumed = function() {
return StorageService.get("assumed");
};
$scope.isAssuming = function() {
return StorageService.get("assuming");
};
$scope.isAnonymous = function() {
return (sessionStorage.role == "ROLE_ANONYMOUS");
};
$scope.isUser = function() {
return (sessionStorage.role == "ROLE_USER");
};
$scope.isAnnotator = function() {
return (sessionStorage.role == "ROLE_ANNOTATOR");
};
$scope.isManager = function() {
return (sessionStorage.role == "ROLE_MANAGER");
};
$scope.isAdmin = function() {
return (sessionStorage.role == "ROLE_ADMIN");
};
});
| core.controller('AbstractController', function ($scope, StorageService) {
$scope.storage = StorageService;
$scope.isAssumed = function() {
return StorageService.get("assumed");
};
$scope.isAssuming = function() {
return StorageService.get("assuming");
};
$scope.isAnonymous = function() {
return (sessionStorage.role == "ROLE_ANONYMOUS");
};
$scope.isUser = function() {
return (sessionStorage.role == "ROLE_USER");
};
$scope.isAnnotator = function() {
return (sessionStorage.role == "ROLE_ANNOTATOR");
};
$scope.isManager = function() {
return (sessionStorage.role == "ROLE_MANAGER");
};
$scope.isAdmin = function() {
return (sessionStorage.role == "ROLE_ADMIN");
};
});
| Put storage service on scope for abstract controller. | Put storage service on scope for abstract controller.
| JavaScript | mit | TAMULib/Weaver-UI-Core,TAMULib/Weaver-UI-Core | ---
+++
@@ -1,4 +1,6 @@
core.controller('AbstractController', function ($scope, StorageService) {
+
+ $scope.storage = StorageService;
$scope.isAssumed = function() {
return StorageService.get("assumed"); |
ba555027b6ce0815cc3960d31d1bd56fbf8c04a3 | client/components/Dashboard.js | client/components/Dashboard.js | import React, { Component } from 'react'
import Affirmations from './analytics/Affirmations'
export default class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
data: {
url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/98887/d3pack-flare-short.json',
elementDelay: 100
},
startDelay: 2000
};
}
componentDidMount() {
console.log('rendering');
}
render() {
var style = {
width: '100%',
height: '100%'
};
return (
<div style={style}>
<Affirmations
startDelay={this.state.startDelay}
elementDelay={this.state.data.elementDelay}
json={this.state.data.url}
/>
</div>
)
}
} | import React, { Component } from 'react'
import Circles from './analytics/Circles'
export default class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
data: {
url: './data/sample.json',
elementDelay: 100
},
startDelay: 2000
};
}
componentDidMount() {
console.log('rendering');
}
render() {
return (
<div className="dashboard-container">
<Circles
startDelay={this.state.startDelay}
elementDelay={this.state.data.elementDelay}
json={this.state.data.url}
/>
</div>
)
}
} | Update for circles and new sample data | Update for circles and new sample data
| JavaScript | mit | scrumptiousAmpersand/journey,scrumptiousAmpersand/journey | ---
+++
@@ -1,12 +1,12 @@
import React, { Component } from 'react'
-import Affirmations from './analytics/Affirmations'
+import Circles from './analytics/Circles'
export default class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
data: {
- url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/98887/d3pack-flare-short.json',
+ url: './data/sample.json',
elementDelay: 100
},
startDelay: 2000
@@ -16,13 +16,9 @@
console.log('rendering');
}
render() {
- var style = {
- width: '100%',
- height: '100%'
- };
return (
- <div style={style}>
- <Affirmations
+ <div className="dashboard-container">
+ <Circles
startDelay={this.state.startDelay}
elementDelay={this.state.data.elementDelay}
json={this.state.data.url} |
24317f5dc7b9e2e363e9424bdbcdb007e9704908 | src/types/Config.js | src/types/Config.js | // @flow
export type Config = {
disabledPages: string[],
showUserDomainInput: boolean,
defaultUserDomain: string,
showOpenstackCurrentUserSwitch: boolean,
useBarbicanSecrets: boolean,
requestPollTimeout: number,
sourceOptionsProviders: string[],
instancesListBackgroundLoading: { default: number, [string]: number },
sourceProvidersWithExtraOptions: Array<string | { name: string, envRequiredFields: string[] }>,
destinationProvidersWithExtraOptions: Array<string | { name: string, envRequiredFields: string[] }>,
providerSortPriority: { [providerName: string]: number }
hiddenUsers: string[],
}
| // @flow
export type Config = {
disabledPages: string[],
showUserDomainInput: boolean,
defaultUserDomain: string,
showOpenstackCurrentUserSwitch: boolean,
useBarbicanSecrets: boolean,
requestPollTimeout: number,
sourceOptionsProviders: string[],
instancesListBackgroundLoading: { default: number, [string]: number },
sourceProvidersWithExtraOptions: Array<string | { name: string, envRequiredFields: string[] }>,
destinationProvidersWithExtraOptions: Array<string | { name: string, envRequiredFields: string[] }>,
providerSortPriority: { [providerName: string]: number },
hiddenUsers: string[],
}
| Add missing comma to type file | Add missing comma to type file
| JavaScript | agpl-3.0 | aznashwan/coriolis-web,aznashwan/coriolis-web | ---
+++
@@ -11,6 +11,6 @@
instancesListBackgroundLoading: { default: number, [string]: number },
sourceProvidersWithExtraOptions: Array<string | { name: string, envRequiredFields: string[] }>,
destinationProvidersWithExtraOptions: Array<string | { name: string, envRequiredFields: string[] }>,
- providerSortPriority: { [providerName: string]: number }
+ providerSortPriority: { [providerName: string]: number },
hiddenUsers: string[],
} |
03ee8adc1cf7bde21e52386e72bc4a663d6834f3 | script.js | script.js | $('body').scrollspy({ target: '#side-menu' , offset : 10});
var disableEvent = function(e) {
e.preventDefault();
};
$('a[href="#"]').click(disableEvent);
$('button[type="submit"]').click(disableEvent);
// Initialize popovers
$('[data-toggle="popover"]').popover();
$('#openGithub').click(function(e){
e.preventDefault();
window.location = "https://github.com/caneruguz/osf-style";
});
| $('body').scrollspy({ target: '#side-menu' , offset : 10});
var disableEvent = function(e) {
e.preventDefault();
};
$('a[href="#"]').click(disableEvent);
$('button[type="submit"]').click(disableEvent);
// Initialize popovers
$('[data-toggle="popover"]').popover();
$('#openGithub').click(function(e){
e.preventDefault();
window.location = "https://github.com/caneruguz/osf-style";
});
$('[data-toggle="tooltip"]').tooltip();
| Fix commit mistake with tooltip | Fix commit mistake with tooltip
| JavaScript | apache-2.0 | CenterForOpenScience/osf-style,CenterForOpenScience/osf-style | ---
+++
@@ -11,3 +11,4 @@
e.preventDefault();
window.location = "https://github.com/caneruguz/osf-style";
});
+$('[data-toggle="tooltip"]').tooltip(); |
0915cc2024564c1ee79f9695c82eda8adb1f9980 | src/vibrant.directive.js | src/vibrant.directive.js | angular
.module('ngVibrant')
.directive('vibrant', vibrant);
function vibrant($vibrant) {
var directive = {
restrict: 'AE',
scope: {
model: '=ngModel', //Model
url: '@?',
swatch: '@?',
quality: '@?',
colors: '@?'
},
link: link
};
return directive;
function link(scope, element, attrs) {
scope.model = [];
if (angular.isUndefined(attrs.quality)) {
attrs.quality = $vibrant.getDefaultQuality();
}
if (angular.isUndefined(attrs.colors)) {
attrs.colors = $vibrant.getDefaultColors();
}
if (angular.isDefined(attrs.url)) {
$vibrant.get(attrs.url).then(function(swatches) {
scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
});
}else {
element.on('load', function() {
var swatches = $vibrant(element[0], attrs.colors, attrs.quality);
scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
});
}
}
}
| angular
.module('ngVibrant')
.directive('vibrant', vibrant);
function vibrant($vibrant) {
var directive = {
restrict: 'AE',
scope: {
model: '=ngModel', //Model
url: '@?',
swatch: '@?',
quality: '@?',
colors: '@?'
},
link: link
};
return directive;
function link(scope, element, attrs) {
scope.model = [];
if (angular.isUndefined(attrs.quality)) {
attrs.quality = $vibrant.getDefaultQuality();
}
if (angular.isUndefined(attrs.colors)) {
attrs.colors = $vibrant.getDefaultColors();
}
if (angular.isDefined(attrs.url)) {
$vibrant.get(attrs.url, attrs.colors, attrs.quality).then(function(swatches) {
scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
});
}else {
element.on('load', function() {
var swatches = $vibrant(element[0], attrs.colors, attrs.quality);
scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
});
}
}
}
| Use colors and quality attributes on manual image fetching | Use colors and quality attributes on manual image fetching
| JavaScript | apache-2.0 | maxjoehnk/ngVibrant | ---
+++
@@ -26,7 +26,7 @@
attrs.colors = $vibrant.getDefaultColors();
}
if (angular.isDefined(attrs.url)) {
- $vibrant.get(attrs.url).then(function(swatches) {
+ $vibrant.get(attrs.url, attrs.colors, attrs.quality).then(function(swatches) {
scope.model = angular.isDefined(attrs.swatch) ? swatches[attrs.swatch] : swatches;
});
}else { |
2a1b7b1b0b9706dba23e45703b996bba616018e3 | static/service-worker.js | static/service-worker.js | const cacheName = 'cache-v4'
const precacheResources = [
'/',
'/posts/',
'index.html',
'/bundle.min.js',
'/main.min.css',
'/fonts/Inter-UI-Bold.woff',
'/fonts/Inter-UI-Medium.woff',
'/fonts/Inter-UI-Medium.woff2',
'/fonts/Inter-UI-Italic.woff',
'/fonts/Inter-UI-Regular.woff',
'/fonts/Inter-UI-Italic.woff2',
'/fonts/Inter-UI-MediumItalic.woff2',
'/fonts/Inter-UI-MediumItalic.woff',
'/fonts/Inter-UI-BoldItalic.woff',
'/fonts/Inter-UI-Regular.woff2',
'/fonts/Inter-UI-Bold.woff2',
'/fonts/Inter-UI-BoldItalic.woff2',
'/static/fonts/icomoon.eot',
'/static/fonts/icomoon.svg',
'/static/fonts/icomoon.ttf',
'/static/fonts/icomoon.woff',
'/posts/how-to-get-involved-in-open-source/index.html',
'/posts/i-m-gonna-blog/index.html',
'/posts/tools-for-effective-rust-development/index.html',
'/posts/understanding-and-resolving-selinux-denials-on-android/index.html',
'/posts/teaching-kotlin-kotlin-for-android-java-developers/index.html',
'/posts/teaching-kotlin-classes-and-objects/index.html',
'/posts/teaching-kotlin-variables/index.html'
]
self.addEventListener('install', event => {
event.waitUntil(
caches.open(cacheName).then(cache => {
return cache.addAll(precacheResources)
})
)
})
self.addEventListener('activate', event => {
var cacheKeeplist = [cacheName]
event.waitUntil(
caches
.keys()
.then(keyList => {
return Promise.all(
keyList.map(key => {
if (cacheKeeplist.indexOf(key) === -1) {
return caches.delete(key)
}
})
)
})
.then(self.clients.claim())
)
})
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse
}
return fetch(event.request)
})
)
})
| self.addEventListener('activate', event => {
event.waitUntil(
caches
.keys()
.then(keyList => {
return Promise.all(
keyList.map(key => {
return caches.delete(key)
})
)
})
.then(self.clients.claim())
)
})
navigator.serviceWorker.getRegistrations().then(registrations => {
registrations.forEach(registration => {
registration.unregister()
})
})
| Stop caching things and remove existing service worker registrations | Stop caching things and remove existing service worker registrations
Signed-off-by: Harsh Shandilya <c6ff3190142d3f8560caed342b4d93721fe8dacf@gmail.com>
| JavaScript | mit | MSF-Jarvis/msf-jarvis.github.io | ---
+++
@@ -1,54 +1,11 @@
-const cacheName = 'cache-v4'
-const precacheResources = [
- '/',
- '/posts/',
- 'index.html',
- '/bundle.min.js',
- '/main.min.css',
- '/fonts/Inter-UI-Bold.woff',
- '/fonts/Inter-UI-Medium.woff',
- '/fonts/Inter-UI-Medium.woff2',
- '/fonts/Inter-UI-Italic.woff',
- '/fonts/Inter-UI-Regular.woff',
- '/fonts/Inter-UI-Italic.woff2',
- '/fonts/Inter-UI-MediumItalic.woff2',
- '/fonts/Inter-UI-MediumItalic.woff',
- '/fonts/Inter-UI-BoldItalic.woff',
- '/fonts/Inter-UI-Regular.woff2',
- '/fonts/Inter-UI-Bold.woff2',
- '/fonts/Inter-UI-BoldItalic.woff2',
- '/static/fonts/icomoon.eot',
- '/static/fonts/icomoon.svg',
- '/static/fonts/icomoon.ttf',
- '/static/fonts/icomoon.woff',
- '/posts/how-to-get-involved-in-open-source/index.html',
- '/posts/i-m-gonna-blog/index.html',
- '/posts/tools-for-effective-rust-development/index.html',
- '/posts/understanding-and-resolving-selinux-denials-on-android/index.html',
- '/posts/teaching-kotlin-kotlin-for-android-java-developers/index.html',
- '/posts/teaching-kotlin-classes-and-objects/index.html',
- '/posts/teaching-kotlin-variables/index.html'
-]
-
-self.addEventListener('install', event => {
- event.waitUntil(
- caches.open(cacheName).then(cache => {
- return cache.addAll(precacheResources)
- })
- )
-})
-
self.addEventListener('activate', event => {
- var cacheKeeplist = [cacheName]
event.waitUntil(
caches
.keys()
.then(keyList => {
return Promise.all(
keyList.map(key => {
- if (cacheKeeplist.indexOf(key) === -1) {
- return caches.delete(key)
- }
+ return caches.delete(key)
})
)
})
@@ -56,13 +13,8 @@
)
})
-self.addEventListener('fetch', event => {
- event.respondWith(
- caches.match(event.request).then(cachedResponse => {
- if (cachedResponse) {
- return cachedResponse
- }
- return fetch(event.request)
- })
- )
+navigator.serviceWorker.getRegistrations().then(registrations => {
+ registrations.forEach(registration => {
+ registration.unregister()
+ })
}) |
d250bb1ac822aa7beb8a3602698001559c7e7c83 | karma.conf.js | karma.conf.js | module.exports = function (config) {
config.set({
port: 9876,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
colors: true,
plugins: [
'karma-jasmine',
'karma-sinon',
'karma-spec-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-browserify',
'karma-sourcemap-loader'
],
browsers: process.env.CI === true ? ['PhantomJS'] : [],
frameworks: ['jasmine', 'sinon', 'browserify'],
reporters: ['spec'],
files: [
'spec/helpers/**/*.coffee',
'spec/**/*-behavior.coffee',
'spec/**/*-spec.coffee'
],
preprocessors: {
'src/**/*.coffee': ['browserify', 'sourcemap'],
'spec/**/*.coffee': ['browserify', 'sourcemap']
},
browserify: {
extensions: ['.coffee'],
transform: ['coffeeify'],
watch: true,
debug: true
}
});
};
| module.exports = function (config) {
config.set({
port: 9876,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
colors: true,
plugins: [
'karma-jasmine',
'karma-sinon',
'karma-spec-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-browserify',
'karma-sourcemap-loader'
],
browsers: ['PhantomJS'],
frameworks: ['jasmine', 'sinon', 'browserify'],
reporters: ['spec'],
files: [
'spec/helpers/**/*.coffee',
'spec/**/*-behavior.coffee',
'spec/**/*-spec.coffee'
],
preprocessors: {
'src/**/*.coffee': ['browserify', 'sourcemap'],
'spec/**/*.coffee': ['browserify', 'sourcemap']
},
browserify: {
extensions: ['.coffee'],
transform: ['coffeeify'],
watch: true,
debug: true
}
});
};
| Revert "Conditionally set browser for karma" | Revert "Conditionally set browser for karma"
This reverts commit 9f43fe898e74a0541430a06532ba8b504796af6c.
| JavaScript | mit | mavenlink/brainstem-js | ---
+++
@@ -20,7 +20,7 @@
'karma-sourcemap-loader'
],
- browsers: process.env.CI === true ? ['PhantomJS'] : [],
+ browsers: ['PhantomJS'],
frameworks: ['jasmine', 'sinon', 'browserify'],
|
f0117c0242844550f6aed2dc1b706c0ffb44c769 | src/cli/require-qunit.js | src/cli/require-qunit.js | // Depending on the exact usage, QUnit could be in one of several places, this
// function handles finding it.
module.exports = function requireQUnit( resolve = require.resolve ) {
try {
// First we attempt to find QUnit relative to the current working directory.
const localQUnitPath = resolve( "qunit", { paths: [ process.cwd() ] } );
delete require.cache[ localQUnitPath ];
return require( localQUnitPath );
} catch ( e ) {
try {
// Second, we use the globally installed QUnit
delete require.cache[ resolve( "../../qunit/qunit" ) ];
// eslint-disable-next-line node/no-missing-require, node/no-unpublished-require
return require( "../../qunit/qunit" );
} catch ( e ) {
if ( e.code === "MODULE_NOT_FOUND" ) {
// Finally, we use the local development version of QUnit
delete require.cache[ resolve( "../../dist/qunit" ) ];
// eslint-disable-next-line node/no-missing-require, node/no-unpublished-require
return require( "../../dist/qunit" );
}
throw e;
}
}
};
| // Depending on the exact usage, QUnit could be in one of several places, this
// function handles finding it.
module.exports = function requireQUnit( resolve = require.resolve ) {
try {
// First we attempt to find QUnit relative to the current working directory.
const localQUnitPath = resolve( "qunit", {
// Support: Node 10. Explicitly check "node_modules" to avoid a bug.
// Fixed in Node 12+. See https://github.com/nodejs/node/issues/35367.
paths: [ process.cwd() + "/node_modules", process.cwd() ]
} );
delete require.cache[ localQUnitPath ];
return require( localQUnitPath );
} catch ( e ) {
try {
// Second, we use the globally installed QUnit
delete require.cache[ resolve( "../../qunit/qunit" ) ];
// eslint-disable-next-line node/no-missing-require, node/no-unpublished-require
return require( "../../qunit/qunit" );
} catch ( e ) {
if ( e.code === "MODULE_NOT_FOUND" ) {
// Finally, we use the local development version of QUnit
delete require.cache[ resolve( "../../dist/qunit" ) ];
// eslint-disable-next-line node/no-missing-require, node/no-unpublished-require
return require( "../../dist/qunit" );
}
throw e;
}
}
};
| Fix 'qunit' require error on Node 10 if qunit.json exists | CLI: Fix 'qunit' require error on Node 10 if qunit.json exists
If the project using QUnit has a local qunit.json file in the
repository root, then the CLI was unable to find the 'qunit'
package. Instead, it first found a local 'qunit.json' file.
This affected an ESLint plugin with a 'qunit' preset file.
This bug was fixed in Node 12, and thus only affects Node 10 for us.
The bug is also specific to require.resolve(). Regular use of
require() was not affected and always correctly found the
local package. (A local file would only be considered if the
require started with dot-slash like `./qunit`.)
Ref https://github.com/nodejs/node/issues/35367.
Fixes https://github.com/qunitjs/qunit/issues/1484.
| JavaScript | mit | qunitjs/qunit,qunitjs/qunit | ---
+++
@@ -4,7 +4,12 @@
try {
// First we attempt to find QUnit relative to the current working directory.
- const localQUnitPath = resolve( "qunit", { paths: [ process.cwd() ] } );
+ const localQUnitPath = resolve( "qunit", {
+
+ // Support: Node 10. Explicitly check "node_modules" to avoid a bug.
+ // Fixed in Node 12+. See https://github.com/nodejs/node/issues/35367.
+ paths: [ process.cwd() + "/node_modules", process.cwd() ]
+ } );
delete require.cache[ localQUnitPath ];
return require( localQUnitPath );
} catch ( e ) { |
a27021ff9d42fbe10e8d5107387dbaafab96e654 | lib/router.js | lib/router.js | Router.configure({
layoutTemplate : 'layout',
loadingTemplate : 'loading',
notFoundTemplate : 'notFound'
// waitOn : function () {
// return Meteor.subscribe('posts');
// }
});
Router.route('/', {name : 'landing'});
Router.route('/goalsettings', {name : 'showGoals'});
Router.route('/crylevel', {name : 'cryLevel'});
Router.route('/posts/:_id', {
name : 'postPage',
data : function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/posts/:_id/edit', {
name : 'postEdit',
data : function () {
return Posts.findOne(this.params._id);
}
})
Router.route('/submit', {name : 'postSubmit'})
var requireLogin = function () {
if (!Meteor.userId()) {
if (Meteor.loggingIn()) {
this.render('loadingTemplate');
} else {
Router.go('landing');
}
this.stop();
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', {only : 'postPage'});
Router.onBeforeAction(requireLogin, {except : 'landing'}); | Router.configure({
layoutTemplate : 'layout',
loadingTemplate : 'loading',
notFoundTemplate : 'notFound'
// waitOn : function () {
// return Meteor.subscribe('posts');
// }
});
Router.route('/', {name : 'landing'});
Router.route('/goal-settings', {name : 'showGoals'});
Router.route('/cry-level', {name : 'cryLevel'});
Router.route('/posts/:_id', {
name : 'postPage',
data : function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/posts/:_id/edit', {
name : 'postEdit',
data : function () {
return Posts.findOne(this.params._id);
}
})
Router.route('/submit', {name : 'postSubmit'})
var requireLogin = function () {
if (!Meteor.userId()) {
if (Meteor.loggingIn()) {
this.render('loadingTemplate');
} else {
Router.go('landing');
}
this.stop();
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', {only : 'postPage'});
Router.onBeforeAction(requireLogin, {except : 'landing'}); | Add dashes to route paths | Add dashes to route paths
| JavaScript | mit | JohnathanWeisner/man_tears,JohnathanWeisner/man_tears | ---
+++
@@ -8,8 +8,8 @@
});
Router.route('/', {name : 'landing'});
-Router.route('/goalsettings', {name : 'showGoals'});
-Router.route('/crylevel', {name : 'cryLevel'});
+Router.route('/goal-settings', {name : 'showGoals'});
+Router.route('/cry-level', {name : 'cryLevel'});
Router.route('/posts/:_id', {
name : 'postPage', |
cac8899b7ff10268146c9d150faa94f5126284de | lib/server.js | lib/server.js | Counter = function (name, cursor, interval) {
this.name = name;
this.cursor = cursor;
this.interval = interval || 1000 * 10;
this._collectionName = 'counters-collection';
}
// every cursor must provide a collection name via this method
Counter.prototype._getCollectionName = function() {
return "counter-" + this.name;
};
// the api to publish
Counter.prototype._publishCursor = function(sub) {
var self = this;
var count = self.cursor.count();
sub.added(self._collectionName, self.name, {count: count});
var handler = Meteor.setInterval(function() {
var count = self.cursor.count();
sub.changed(self._collectionName, self.name, {count: count});
}, this.interval);
sub.onStop(function() {
Meteor.clearTimeout(handler);
});
};
| Counter = function (name, cursor, interval) {
this.name = name;
this.cursor = cursor;
this.interval = interval || 1000 * 10;
this._collectionName = 'counters-collection';
}
// every cursor must provide a collection name via this method
Counter.prototype._getCollectionName = function() {
return "counter-" + this.name;
};
// the api to publish
Counter.prototype._publishCursor = function(sub) {
var self = this;
var count = self.cursor.count();
sub.added(self._collectionName, self.name, {count: count});
var handler = Meteor.setInterval(function() {
var count = self.cursor.count();
sub.changed(self._collectionName, self.name, {count: count});
}, this.interval);
sub.onStop(function() {
Meteor.clearTimeout(handler);
});
return {
stop: sub.onStop.bind(sub)
}
};
| Make _publishCursor return a handle with a stop method | Make _publishCursor return a handle with a stop method
| JavaScript | mit | nate-strauser/meteor-publish-performant-counts | ---
+++
@@ -24,5 +24,9 @@
sub.onStop(function() {
Meteor.clearTimeout(handler);
});
+
+ return {
+ stop: sub.onStop.bind(sub)
+ }
};
|
aae8f83338ed69a28e8c8279e738857b13364841 | examples/walk-history.js | examples/walk-history.js | var nodegit = require("../"),
path = require("path");
// This code walks the history of the master branch and prints results
// that look very similar to calling `git log` from the command line
nodegit.Repository.open(path.resolve(__dirname, "../.git"))
.then(function(repo) {
return repo.getMasterCommit();
})
.then(function(firstCommitOnMaster){
// History returns an event.
var history = firstCommitOnMaster.history(nodegit.Revwalk.SORT.Time);
// History emits "commit" event for each commit in the branch's history
history.on("commit", function(commit) {
console.log("commit " + commit.sha());
console.log("Author:", commit.author().name() +
" <" + commit.author().email() + ">");
console.log("Date:", commit.date());
console.log("\n " + commit.message());
});
// Don't forget to call `start()`!
history.start();
})
.done();
| var nodegit = require("../"),
path = require("path");
// This code walks the history of the master branch and prints results
// that look very similar to calling `git log` from the command line
nodegit.Repository.open(path.resolve(__dirname, "../.git"))
.then(function(repo) {
return repo.getMasterCommit();
})
.then(function(firstCommitOnMaster){
// History returns an event.
var history = firstCommitOnMaster.history(nodegit.Revwalk.SORT.TIME);
// History emits "commit" event for each commit in the branch's history
history.on("commit", function(commit) {
console.log("commit " + commit.sha());
console.log("Author:", commit.author().name() +
" <" + commit.author().email() + ">");
console.log("Date:", commit.date());
console.log("\n " + commit.message());
});
// Don't forget to call `start()`!
history.start();
})
.done();
| Fix incorrect api usage, not Time rather TIME | Fix incorrect api usage, not Time rather TIME | JavaScript | mit | nodegit/nodegit,nodegit/nodegit,nodegit/nodegit,nodegit/nodegit,jmurzy/nodegit,jmurzy/nodegit,jmurzy/nodegit,jmurzy/nodegit,jmurzy/nodegit,nodegit/nodegit | ---
+++
@@ -10,7 +10,7 @@
})
.then(function(firstCommitOnMaster){
// History returns an event.
- var history = firstCommitOnMaster.history(nodegit.Revwalk.SORT.Time);
+ var history = firstCommitOnMaster.history(nodegit.Revwalk.SORT.TIME);
// History emits "commit" event for each commit in the branch's history
history.on("commit", function(commit) { |
a76bbc0d7afe1136b8768ef0aadc57024fa88d55 | test/mithril.withAttr.js | test/mithril.withAttr.js | describe("m.withAttr()", function () {
"use strict"
it("calls the handler with the right value/context without callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy).call(object, {currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
it("calls the handler with the right value/context with callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy, object)({currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("Bfoo")
})
})
| describe("m.withAttr()", function () {
"use strict"
it("calls the handler with the right value/context without callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy).call(object, {currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
it("calls the handler with the right value/context with callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy, object)({currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
})
| Fix the test of the new suite | Fix the test of the new suite
| JavaScript | mit | tivac/mithril.js,MithrilJS/mithril.js,lhorie/mithril.js,impinball/mithril.js,barneycarroll/mithril.js,pygy/mithril.js,pygy/mithril.js,impinball/mithril.js,MithrilJS/mithril.js,barneycarroll/mithril.js,lhorie/mithril.js,tivac/mithril.js | ---
+++
@@ -12,6 +12,6 @@
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy, object)({currentTarget: {test: "foo"}})
- expect(spy).to.be.calledOn(object).and.calledWith("Bfoo")
+ expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
}) |
e1a896d31ace67e33986b78b04f9fab50536dddb | extensions/API/Client.js | extensions/API/Client.js | let origBot, origGuild;
// A dummy message object so ESLint doesn't complain
class Message {}
class Client {
constructor(bot, guild) {
origBot = bot;
origGuild = guild;
}
get guilds() {
return origBot.guilds.size
}
get users() {
return origBot.users.size
}
waitForMessage(authorId, channelId, timeout, check) {
if (!authorId || !channelId) return Promise.reject("Missing author/channel ID");
if (!check || typeof check !== "function") check = () => true;
let c = msg => {
if (msg.author.id == authorId && msg.channel.id == channelId
&& msg.channel.guild && msg.channel.guild.id == origGuild.id
&& check()) return true;
else return false;
};
origBot.waitForEvent("messageCreate", timeout, c)
.then((eventReturn) => new Message(eventReturn[0]));
}
}
module.exports = Client; | let origBot, origGuild;
// A dummy message object so ESLint doesn't complain
class Message {}
class Client {
constructor(bot, guild) {
origBot = bot;
origGuild = guild;
// TODO: sandboxed user
// this.user = bot.user
// TODO: sandboxed guild
// this.currentGuild = guild;
}
get guilds() {
return origBot.guilds.size;
}
get users() {
return origBot.users.size;
}
waitForMessage(authorId, channelId, timeout, check) {
if (!authorId || !channelId) return Promise.reject("Missing author/channel ID");
if (!check || typeof check !== "function") check = () => true;
let c = msg => {
if (msg.author.id == authorId && msg.channel.id == channelId
&& msg.channel.guild && msg.channel.guild.id == origGuild.id
&& check()) return true;
else return false;
};
origBot.waitForEvent("messageCreate", timeout, c)
.then((eventReturn) => new Message(eventReturn[0]));
}
}
module.exports = Client; | Add new properties, to be sandboxed | Add new properties, to be sandboxed
| JavaScript | mit | TTtie/TTtie-Bot,TTtie/TTtie-Bot,TTtie/TTtie-Bot | ---
+++
@@ -5,14 +5,18 @@
constructor(bot, guild) {
origBot = bot;
origGuild = guild;
+ // TODO: sandboxed user
+ // this.user = bot.user
+ // TODO: sandboxed guild
+ // this.currentGuild = guild;
}
get guilds() {
- return origBot.guilds.size
+ return origBot.guilds.size;
}
get users() {
- return origBot.users.size
+ return origBot.users.size;
}
waitForMessage(authorId, channelId, timeout, check) { |
afdd27cc9e852d2aa4c311a67635cc6ffa55455b | test/unit/icon-toggle.js | test/unit/icon-toggle.js |
describe('icon-toggle tests', function () {
it('Should have MaterialIconToggle globally available', function () {
expect(MaterialIconToggle).to.be.a('function');
});
it('Should be upgraded to a MaterialIconToggle successfully', function () {
var el = document.createElement('div');
el.innerHTML = '<input type="checkbox" class="wsk-icon-toggle__input">';
componentHandler.upgradeElement(el, 'MaterialIconToggle');
var upgraded = el.getAttribute('data-upgraded');
expect(upgraded).to.contain('MaterialIconToggle');
});
});
|
describe('icon-toggle tests', function () {
it('Should have MaterialIconToggle globally available', function () {
expect(MaterialIconToggle).to.be.a('function');
});
it('Should be upgraded to a MaterialIconToggle successfully', function () {
var el = document.createElement('div');
el.innerHTML = '<input type="checkbox" class="wsk-icon-toggle__input">';
componentHandler.upgradeElement(el, 'MaterialIconToggle');
expect($(el)).to.have.data('upgraded', ',MaterialIconToggle');
});
});
| Update MaterialIconToggle unit test with chai-jquery | Update MaterialIconToggle unit test with chai-jquery
| JavaScript | apache-2.0 | hassanabidpk/material-design-lite,yonjar/material-design-lite,LuanNg/material-design-lite,coraxster/material-design-lite,hebbet/material-design-lite,snice/material-design-lite,i9-Technologies/material-design-lite,craicoverflow/material-design-lite,Saber-Kurama/material-design-lite,pedroha/material-design-lite,it-andy-hou/material-design-lite,AliMD/material-design-lite,lahmizzar/material-design-lite,AntonGulkevich/material-design-lite,andyyou/material-design-lite,kidGodzilla/material-design-lite,hcxiong/material-design-lite,ananthmysore/material-design-lite,craicoverflow/material-design-lite,achalv/material-design-lite,ovaskevich/material-design-lite,yinxufeng/material-design-lite,shairez/material-design-lite,victorhaggqvist/material-design-lite,nickretallack/material-design-lite,schobiwan/material-design-lite,NaveenNs123/material-design-lite,stevenliuit/material-design-lite,paulirish/material-design-lite,jvkops/material-design-lite,narendrashetty/material-design-lite,ArmendGashi/material-design-lite,paulirish/material-design-lite,innovand/material-design-lite,nandollorella/material-design-lite,stevenliuit/material-design-lite,shairez/material-design-lite,praveenscience/material-design-lite,rschmidtz/material-design-lite,two9seven/material-design-lite,hebbet/material-design-lite,hsnunes/material-design-lite,hcxiong/material-design-lite,rmccutcheon/material-design-lite,stealba/mdl,puncoz/material-design-lite,pj19060/material-design-lite,mayhem-ahmad/material-design-lite,achalv/material-design-lite,citypeople/material-design-lite,haapanen/material-design-lite,joyouscob/material-design-lite,thunsaker/material-design-lite,BrUn3y/material-design-lite,silvolu/material-design-lite,vrajakishore/material-design-lite,iamrudra/material-design-lite,mdixon47/material-design-lite,yongxu/material-design-lite,palimadra/material-design-lite,marekswiecznik/material-design-lite,fjvalencian/material-design-lite,manisoni28/material-design-lite,danbenn93/material-design-lite,lintangarief/material-design-lite,koddsson/material-design-lite,gwokudasam/material-design-lite,leeleo26/material-design-lite,NaveenNs123/material-design-lite,hobbyquaker/material-design-lite,TejaSedate/material-design-lite,serdimoa/material-design-lite,Heart2009/material-design-lite,andrect/material-design-lite,zckrs/material-design-lite,gbn972/material-design-lite,modulexcite/material-design-lite,gaurav1981/material-design-lite,Ycfx/material-design-lite,Kushmall/material-design-lite,l0rd0fwar/material-design-lite,anton-kachurin/material-components-web,manohartn/material-design-lite,Ninir/material-design-lite,ProfNandaa/material-design-lite,ojengwa/material-design-lite,ZNosX/material-design-lite,nikhil2kulkarni/material-design-lite,tornade0913/material-design-lite,erickacevedor/material-design-lite,NicolasJEngler/material-design-lite,martnga/material-design-lite,tangposmarvin/material-design-lite,ForsakenNGS/material-design-lite,milkcreation/material-design-lite,l0rd0fwar/material-design-lite,Kabele/material-design-lite,rtoya/material-design-lite,lebas/material-design-lite,jbnicolai/material-design-lite,mikepuerto/material-design-lite,milkcreation/material-design-lite,hassanabidpk/material-design-lite,palimadra/material-design-lite,udhayam/material-design-lite,pierr/material-design-lite,Messi10AP/material-design-lite,coraxster/material-design-lite,gaurav1981/material-design-lite,devbeta/material-design-lite,NaokiMiyata/material-design-lite,Jonekee/material-design-lite,zckrs/material-design-lite,icdev/material-design-lite,wendaleruan/material-design-lite,2947721120/material-design-lite,lawhump/material-design-lite,libinbensin/material-design-lite,quannt/material-design-lite,SeasonFour/material-design-lite,odin3/material-design-lite,manohartn/material-design-lite,tornade0913/material-design-lite,levonter/material-design-lite,srinivashappy/material-design-lite,Franklin-vaz/material-design-lite,yonjar/material-design-lite,andrewpetrovic/material-design-lite,tradeserve/material-design-lite,DigitalCoder/material-design-lite,Endika/material-design-lite,ctuwuzida/material-design-lite,rogerhu/material-design-lite,gabimanea/material-design-lite,nickretallack/material-design-lite,ananthmysore/material-design-lite,eidehua/material-design-lite,sindhusrao/material-design-lite,domingossantos/material-design-lite,AntonGulkevich/material-design-lite,afvieira/material-design-lite,lebas/material-design-lite,bendroid/material-design-lite,nikhil2kulkarni/material-design-lite,jahnaviancha/material-design-lite,warshanks/material-design-lite,shardul-cr7/DazlingCSS,devbeta/material-design-lite,Ubynano/material-design-lite,unya-2/material-design-lite,joyouscob/material-design-lite,alitedi/material-design-lite,ahmadhmoud/material-design-lite,suman28/material-design-lite,ovaskevich/material-design-lite,fernandoPalaciosGit/material-design-lite,fernandoPalaciosGit/material-design-lite,ObviouslyGreen/material-design-lite,jjj117/material-design-lite,rawrsome/material-design-lite,b-cuts/material-design-lite,glizer/material-design-lite,FredrikAppelros/material-design-lite,Creepypastas/material-design-lite,material-components/material-components-web,JonFerrera/material-design-lite,JacobDorman/material-design-lite,serdimoa/material-design-lite,chinovian/material-design-lite,GilFewster/material-design-lite,ThiagoGarciaAlves/material-design-lite,gwokudasam/material-design-lite,imskojs/material-design-lite,rrenwick/material-design-lite,mailtoharshit/material-design-lite,eboominathan/material-design-lite,wengqi/material-design-lite,alisterlf/material-design-lite,zeroxfire/material-design-lite,pedroha/material-design-lite,samthor/material-design-lite,afonsopacifer/material-design-lite,glebm/material-design-lite,ebulay/material-design-lite,WeRockStar/material-design-lite,vluong/material-design-lite,kamilik26/material-design-lite,two9seven/material-design-lite,urandu/material-design-lite,JonReppDoneD/google-material-design-lite,jvkops/material-design-lite,odin3/material-design-lite,sangupandi/material-design-lite,wilsson/material-design-lite,anton-kachurin/material-components-web,abhishekgahlot/material-design-lite,chaimanat/material-design-lite,ProgLan/material-design-lite,weiwei695/material-design-lite,chalermporn/material-design-lite,yongxu/material-design-lite,billychappell/material-design-lite,codeApeFromChina/material-design-lite,s4050855/material-design-lite,Kekanto/material-design-lite,Frankistan/material-design-lite,DigitalCoder/material-design-lite,sraskin/material-design-lite,thechampanurag/material-design-lite,callumlocke/material-design-lite,sindhusrao/material-design-lite,KageKirin/material-design-lite,alihalabyah/material-design-lite,urandu/material-design-lite,razchiriac/material-design-lite,warshanks/material-design-lite,marlcome/material-design-lite,fizzvr/material-design-lite,eidehua/material-design-lite,CreevDesign/material-design-lite,wendaleruan/material-design-lite,ojengwa/material-design-lite,Daiegon/material-design-lite,pierr/material-design-lite,yamingd/material-design-lite,hanachin/material-design-lite,ithinkihaveacat/material-design-lite,WritingPanda/material-design-lite,Treevil/material-design-lite,davidjahns/material-design-lite,fizzvr/material-design-lite,Zagorakiss/material-design-lite,thanhnhan2tn/material-design-lite,miragshin/material-design-lite,tangposmarvin/material-design-lite,GilFewster/material-design-lite,youknow0709/material-design-lite,BrUn3y/material-design-lite,JonFerrera/material-design-lite,google/material-design-lite,Zagorakiss/material-design-lite,xiezhe/material-design-lite,elizad/material-design-lite,ilovezy/material-design-lite,rschmidtz/material-design-lite,ThiagoGarciaAlves/material-design-lite,katchoua/material-design-lite,marekswiecznik/material-design-lite,ElvisMoVi/material-design-lite,ProfNandaa/material-design-lite,AliMD/material-design-lite,listatt/material-design-lite,Treevil/material-design-lite,b-cuts/material-design-lite,howtomake/material-design-lite,howtomake/material-design-lite,levonter/material-design-lite,nakamuraagatha/material-design-lite,eboominathan/material-design-lite,mdixon47/material-design-lite,billychappell/material-design-lite,afonsopacifer/material-design-lite,gshireesh/material-design-lite,shoony86/material-design-lite,yinxufeng/material-design-lite,tradeserve/material-design-lite,voumir/material-design-lite,dgash/material-design-lite,egobrightan/material-design-lite,ston380/material-design-lite,dgrubelic/material-design-lite,SeasonFour/material-design-lite,puncoz/material-design-lite,rtoya/material-design-lite,marlcome/material-design-lite,WebRTL/material-design-lite-rtl,elizad/material-design-lite,pauloedspinho20/material-design-lite,bendroid/material-design-lite,bruninja/material-design-lite,nakamuraagatha/material-design-lite,youknow0709/material-design-lite,ChipCastleDotCom/material-design-lite,mibcadet/material-design-lite,huoxudong125/material-design-lite,KMikhaylovCTG/material-design-lite,mlc0202/material-design-lite,tomatau/material-design-lite,udhayam/material-design-lite,thechampanurag/material-design-lite,Endika/material-design-lite,andrewpetrovic/material-design-lite,diegodsgarcia/material-design-lite,zlotas/material-design-lite,Sahariar/material-design-lite,Kabele/material-design-lite,tahaipek/material-design-lite,kenlojt/material-design-lite,glebm/material-design-lite,afvieira/material-design-lite,sejr/material-design-lite,rogerhu/material-design-lite,gs-akhan/material-design-lite,sylvesterwillis/material-design-lite,wonder-coders/material-design-lite,kwangkim/material-design-lite,stevewithington/material-design-lite,chaimanat/material-design-lite,kamilik26/material-design-lite,mweimerskirch/material-design-lite,david84/material-design-lite,scrapp-uk/material-design-lite,material-components/material-components-web,gabimanea/material-design-lite,garylgh/material-design-lite,Frankistan/material-design-lite,WritingPanda/material-design-lite,wilsson/material-design-lite,ilovezy/material-design-lite,Heart2009/material-design-lite,TejaSedate/material-design-lite,egobrightan/material-design-lite,listatt/material-design-lite,DeXterMarten/material-design-lite,lucianna/material-design-lite,tschiela/material-design-lite,ForsakenNGS/material-design-lite,alanpassos/material-design-lite,codephillip/material-design-lite,xumingjie1658/material-design-lite,sbrieuc/material-design-lite,jackielii/material-design-lite,qiujuer/material-design-lite,fchuks/material-design-lite,kidGodzilla/material-design-lite,jorgeucano/material-design-lite,Mararesliu/material-design-lite,genmacg/material-design-lite,mroell/material-design-lite,citypeople/material-design-lite,iamrudra/material-design-lite,NaokiMiyata/material-design-lite,haapanen/material-design-lite,killercup/material-design-lite,stealba/mdl,rohanthacker/material-design-lite,KMikhaylovCTG/material-design-lite,praveenscience/material-design-lite,gs-akhan/material-design-lite,chinovian/material-design-lite,jorgeucano/material-design-lite,youprofit/material-design-lite,scrapp-uk/material-design-lite,Jonekee/material-design-lite,peiche/material-design-lite,Yizhachok/material-components-web,poljeff/material-design-lite,marc-f/material-design-lite,timkrins/material-design-lite,lawhump/material-design-lite,huoxudong125/material-design-lite,ahmadhmoud/material-design-lite,rkmax/material-design-lite,qiujuer/material-design-lite,pudgereyem/material-design-lite,ElvisMoVi/material-design-lite,gxcnupt08/material-design-lite,zeroxfire/material-design-lite,ganglee/material-design-lite,dylannnn/material-design-lite,ithinkihaveacat/material-design-lite,hanachin/material-design-lite,srinivashappy/material-design-lite,tomatau/material-design-lite,ganglee/material-design-lite,lijanele/material-design-lite,koddsson/material-design-lite,leeleo26/material-design-lite,JuusoV/material-design-lite,jackielii/material-design-lite,nandollorella/material-design-lite,zlotas/material-design-lite,alitedi/material-design-lite,dMagsAndroid/material-design-lite,rrenwick/material-design-lite,samccone/material-design-lite,CreevDesign/material-design-lite,Zodiase/material-design-lite,ominux/material-design-lite,Ninir/material-design-lite,UmarMughal/material-design-lite,Creepypastas/material-design-lite,xdissent/material-design-lite,tschiela/material-design-lite,miragshin/material-design-lite,Franklin-vaz/material-design-lite,dMagsAndroid/material-design-lite,alisterlf/material-design-lite,2947721120/material-design-lite,chinasb/material-design-lite,vluong/material-design-lite,rvanmarkus/material-design-lite,samthor/material-design-lite,abhishekgahlot/material-design-lite,DCSH2O/material-design-lite,katchoua/material-design-lite,mike-north/material-design-lite,hdolinski/material-design-lite,daviddenbigh/material-design-lite,mroell/material-design-lite,samccone/material-design-lite,ryancford/material-design-lite,Ubynano/material-design-lite,imskojs/material-design-lite,jjj117/material-design-lite,Yizhachok/material-components-web,ominux/material-design-lite,razchiriac/material-design-lite,xumingjie1658/material-design-lite,poljeff/material-design-lite,jahnaviancha/material-design-lite,callumlocke/material-design-lite,material-components/material-components-web,Daiegon/material-design-lite,Kekanto/material-design-lite,pgbross/material-components-web,dylannnn/material-design-lite,daviddenbigh/material-design-lite,luisbrito/material-design-lite,sraskin/material-design-lite,StephanieMak/material-design-lite,schobiwan/material-design-lite,johannchen/material-design-lite,hsnunes/material-design-lite,rvanmarkus/material-design-lite,trendchaser4u/material-design-lite,kwangkim/material-design-lite,glizer/material-design-lite,fonai/material-design-lite,icdev/material-design-lite,DCSH2O/material-design-lite,pandoraui/material-design-lite,MuZT3/material-design-lite,francisco-filho/material-design-lite,rohanthacker/material-design-lite,Ycfx/material-design-lite,modulexcite/material-design-lite,hdolinski/material-design-lite,luisbrito/material-design-lite,bruninja/material-design-lite,basicsharp/material-design-lite,xiezhe/material-design-lite,bright-sparks/material-design-lite,tvoli/material-design-zero,chunwei/material-design-lite,wonder-coders/material-design-lite,libinbensin/material-design-lite,suman28/material-design-lite,fonai/material-design-lite,FredrikAppelros/material-design-lite,danbenn93/material-design-lite,ebulay/material-design-lite,peterblazejewicz/material-design-lite,Mannaio/javascript-course,pauloedspinho20/material-design-lite,weiwei695/material-design-lite,lucianna/material-design-lite,leomiranda92/material-design-lite,voumir/material-design-lite,lahmizzar/material-design-lite,shoony86/material-design-lite,davidjahns/material-design-lite,mike-north/material-design-lite,unya-2/material-design-lite,Victorgichohi/material-design-lite,OoNaing/material-design-lite,hairychris/material-design-lite,rawrsome/material-design-lite,andrect/material-design-lite,wengqi/material-design-lite,LuanNg/material-design-lite,mattbutlar/mattbutlar.github.io,hobbyquaker/material-design-lite,coreyaus/material-design-lite,Mannaio/javascript-course,MuZT3/material-design-lite,WebRTL/material-design-lite-rtl,fjvalencian/material-design-lite,KageKirin/material-design-lite,gbn972/material-design-lite,quannt/material-design-lite,lijanele/material-design-lite,vrajakishore/material-design-lite,jermspeaks/material-design-lite,genmacg/material-design-lite,diegodsgarcia/material-design-lite,it-andy-hou/material-design-lite,victorhaggqvist/material-design-lite,ObviouslyGreen/material-design-lite,OoNaing/material-design-lite,sejr/material-design-lite,bright-sparks/material-design-lite,manisoni28/material-design-lite,fhernandez173/material-design-lite,snice/material-design-lite,ArmendGashi/material-design-lite,cbmeeks/material-design-lite,i9-Technologies/material-design-lite,innovand/material-design-lite,vladikoff/material-design-lite,WeRockStar/material-design-lite,JacobDorman/material-design-lite,Vincent2015/material-design-lite,xdissent/material-design-lite,mweimerskirch/material-design-lite,pgbross/material-components-web,garylgh/material-design-lite,johannchen/material-design-lite,mikepuerto/material-design-lite,ryancford/material-design-lite,hairychris/material-design-lite,DeXterMarten/material-design-lite,rkmax/material-design-lite,thunsaker/material-design-lite,codephillip/material-design-lite,ctuwuzida/material-design-lite,yamingd/material-design-lite,fhernandez173/material-design-lite,Messi10AP/material-design-lite,chunwei/material-design-lite,stevewithington/material-design-lite,cbmeeks/material-design-lite,codeApeFromChina/material-design-lite,sylvesterwillis/material-design-lite,vasiliy-pdk/material-design-lite,basicsharp/material-design-lite,silvolu/material-design-lite,pandoraui/material-design-lite,tainanboy/material-design-lite,mlc0202/material-design-lite,tainanboy/material-design-lite,sangupandi/material-design-lite,timkrins/material-design-lite,EllieAdam/material-design-lite,MaxvonStein/material-design-lite,alihalabyah/material-design-lite,domingossantos/material-design-lite,peiche/material-design-lite,pudgereyem/material-design-lite,Vincent2015/material-design-lite,s4050855/material-design-lite,erickacevedor/material-design-lite,martnga/material-design-lite,Kushmall/material-design-lite,WPG/material-design-lite,tvoli/material-design-zero,ProgLan/material-design-lite,Wyvan/material-design-lite,pj19060/material-design-lite,EllieAdam/material-design-lite,ZNosX/material-design-lite,tahaipek/material-design-lite,MaxvonStein/material-design-lite,mayhem-ahmad/material-design-lite,lintangarief/material-design-lite,rmccutcheon/material-design-lite,Mararesliu/material-design-lite,gshireesh/material-design-lite,chinasb/material-design-lite,Zodiase/material-design-lite,francisco-filho/material-design-lite,mibcadet/material-design-lite,alanpassos/material-design-lite,marc-f/material-design-lite,google/material-design-lite,narendrashetty/material-design-lite,youprofit/material-design-lite,JuusoV/material-design-lite,gxcnupt08/material-design-lite,StephanieMak/material-design-lite,dgash/material-design-lite,killercup/material-design-lite,vasiliy-pdk/material-design-lite,Victorgichohi/material-design-lite,fchuks/material-design-lite,Saber-Kurama/material-design-lite,Wyvan/material-design-lite,UmarMughal/material-design-lite,sbrieuc/material-design-lite,kenlojt/material-design-lite,vladikoff/material-design-lite,jbnicolai/material-design-lite,mailtoharshit/material-design-lite,ston380/material-design-lite,jermspeaks/material-design-lite,leomiranda92/material-design-lite,WPG/material-design-lite,andyyou/material-design-lite,peterblazejewicz/material-design-lite,chalermporn/material-design-lite,dgrubelic/material-design-lite,JonReppDoneD/google-material-design-lite,ChipCastleDotCom/material-design-lite,shardul-cr7/DazlingCSS,david84/material-design-lite,Sahariar/material-design-lite,trendchaser4u/material-design-lite,NicolasJEngler/material-design-lite,coreyaus/material-design-lite,thanhnhan2tn/material-design-lite | ---
+++
@@ -9,7 +9,6 @@
var el = document.createElement('div');
el.innerHTML = '<input type="checkbox" class="wsk-icon-toggle__input">';
componentHandler.upgradeElement(el, 'MaterialIconToggle');
- var upgraded = el.getAttribute('data-upgraded');
- expect(upgraded).to.contain('MaterialIconToggle');
+ expect($(el)).to.have.data('upgraded', ',MaterialIconToggle');
});
}); |
bdd1d8705399c1c9272499a300a3bc869717ef04 | request-builder.js | request-builder.js | 'use strict';
const _ = require('underscore');
function buildSlots(slots) {
const res = {};
_.each(slots, (value, key) => {
if ( _.isString(value)) {
res[key] = {
name: key,
value: value
};
} else {
res[key] = {
name: key,
...value
};
}
});
return res;
}
function buildSession(e) {
return e ? e.sessionAttributes : {};
}
function init(options) {
let isNew = true;
// public API
const api = {
init,
build
};
function build(intentName, slots, prevEvent) {
if (!options.appId) throw String('AppId not specified. Please run events.init(appId) before building a Request');
const res = { // override more stuff later as we need
session: {
sessionId: options.sessionId,
application: {
applicationId: options.appId
},
attributes: buildSession(prevEvent),
user: {
userId: options.userId,
accessToken: options.accessToken
},
new: isNew
},
request: {
type: 'IntentRequest',
requestId: options.requestId,
locale: options.locale,
timestamp: (new Date()).toISOString(),
intent: {
name: intentName,
slots: buildSlots(slots)
}
},
version: '1.0'
};
isNew = false;
return res;
}
return api;
}
module.exports = {init};
| 'use strict';
const _ = require('underscore');
function buildSlots(slots) {
const res = {};
_.each(slots, (value, key) => {
if ( _.isString(value)) {
res[key] = {
name: key,
value: value
};
} else {
res[key] = {
...value,
name: key
};
}
});
return res;
}
function buildSession(e) {
return e ? e.sessionAttributes : {};
}
function init(options) {
let isNew = true;
// public API
const api = {
init,
build
};
function build(intentName, slots, prevEvent) {
if (!options.appId) throw String('AppId not specified. Please run events.init(appId) before building a Request');
const res = { // override more stuff later as we need
session: {
sessionId: options.sessionId,
application: {
applicationId: options.appId
},
attributes: buildSession(prevEvent),
user: {
userId: options.userId,
accessToken: options.accessToken
},
new: isNew
},
request: {
type: 'IntentRequest',
requestId: options.requestId,
locale: options.locale,
timestamp: (new Date()).toISOString(),
intent: {
name: intentName,
slots: buildSlots(slots)
}
},
version: '1.0'
};
isNew = false;
return res;
}
return api;
}
module.exports = {init};
| Make sure to keep the property 'name' | Make sure to keep the property 'name'
| JavaScript | mit | ExpediaDotCom/alexa-conversation | ---
+++
@@ -12,8 +12,8 @@
};
} else {
res[key] = {
- name: key,
- ...value
+ ...value,
+ name: key
};
}
}); |
819ba6bfb8cb4b8a329520a09c05abf276e12148 | src/buildScripts/nodeServer.js | src/buildScripts/nodeServer.js | "use strict";
/* eslint-disable no-console */
/* eslint-disable import/default */
var chalk = require('chalk');
var app = require('../app.js'); // This initializes the Express application
var config = require('../../config.js');
var port = config.port || 5000;
var server = app.listen(port, err => {
if (err) {
console.log(chalk.red(err));
} else {
console.log(chalk.green('Server listening on port'), chalk.blue(port));
}
});
module.exports = server;
| "use strict";
/* eslint-disable no-console */
/* eslint-disable import/default */
var chalk = require('chalk');
var app = require('../app.js'); // This initializes the Express application
// var config = require('../../config.js');
var port = process.env.PORT || 5000;
var server = app.listen(port, err => {
if (err) {
console.log(chalk.red(err));
} else {
console.log(chalk.green('Server listening on port'), chalk.blue(port));
}
});
module.exports = server;
| Move npm dotenv to dependencies instead of dev-dependencies | app(env): Move npm dotenv to dependencies instead of dev-dependencies
| JavaScript | mit | zklinger2000/fcc-heroku-rest-api | ---
+++
@@ -3,9 +3,9 @@
/* eslint-disable import/default */
var chalk = require('chalk');
var app = require('../app.js'); // This initializes the Express application
-var config = require('../../config.js');
+// var config = require('../../config.js');
-var port = config.port || 5000;
+var port = process.env.PORT || 5000;
var server = app.listen(port, err => {
if (err) {
console.log(chalk.red(err)); |
cd3b959d10b8ac8c8011715a7e8cd3308f366cb2 | js/scripts.js | js/scripts.js | var pingPong = function(i) {
if ((i % 3 === 0) && (i % 5 != 0)) {
return "ping";
} else if ((i % 5 === 0) && (i % 6 != 0)) {
return "pong";
} else if ((i % 3 === 0) && (i % 5 === 0)) {
return "ping pong";
} else {
return false;
}
};
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
for (var i = 1; i <= number; i += 1) {
if (i % 15 === 0) {
$('#outputList').append("<li>ping pong</li>");
} else if ((winner) && (i % 5 != 0)) {
$('#outputList').append("<li>ping</li>");
} else if ((winner) && (i % 3 != 0)) {
$('#outputList').append("<li>pong</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
| var pingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0)) {
return true;
} else {
return false;
}
};
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
for (var i = 1; i <= number; i += 1) {
if (i % 15 === 0) {
$('#outputList').append("<li>ping pong</li>");
} else if (i % 3 === 0) {
$('#outputList').append("<li>ping</li>");
} else if (i % 5 === 0) {
$('#outputList').append("<li>pong</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
| Change spec test back to true/false, rewrite loop for better clarity of changes | Change spec test back to true/false, rewrite loop for better clarity of changes
| JavaScript | mit | kcmdouglas/pingpong,kcmdouglas/pingpong | ---
+++
@@ -1,10 +1,6 @@
var pingPong = function(i) {
- if ((i % 3 === 0) && (i % 5 != 0)) {
- return "ping";
- } else if ((i % 5 === 0) && (i % 6 != 0)) {
- return "pong";
- } else if ((i % 3 === 0) && (i % 5 === 0)) {
- return "ping pong";
+ if ((i % 5 === 0) || (i % 3 === 0)) {
+ return true;
} else {
return false;
}
@@ -19,9 +15,9 @@
for (var i = 1; i <= number; i += 1) {
if (i % 15 === 0) {
$('#outputList').append("<li>ping pong</li>");
- } else if ((winner) && (i % 5 != 0)) {
+ } else if (i % 3 === 0) {
$('#outputList').append("<li>ping</li>");
- } else if ((winner) && (i % 3 != 0)) {
+ } else if (i % 5 === 0) {
$('#outputList').append("<li>pong</li>");
} else {
$('#outputList').append("<li>" + i + "</li>"); |
ef7450d5719b591b4517c9e107afe142de4246a8 | test/test-config.js | test/test-config.js | var BATCH_API_ENDPOINT = 'http://127.0.0.1:8080/api/v1/sql/job';
module.exports = {
db: {
host: 'localhost',
port: 5432,
dbname: 'analysis_api_test_db',
user: 'postgres',
pass: ''
},
batch: {
endpoint: BATCH_API_ENDPOINT,
username: 'localhost',
apiKey: 1234
}
};
| 'use strict';
var BATCH_API_ENDPOINT = 'http://127.0.0.1:8080/api/v1/sql/job';
function create (override) {
override = override || {
db: {},
batch: {}
};
override.db = override.db || {};
override.batch = override.batch || {};
return {
db: defaults(override.db, {
host: 'localhost',
port: 5432,
dbname: 'analysis_api_test_db',
user: 'postgres',
pass: ''
}),
batch: defaults(override.batch, {
endpoint: BATCH_API_ENDPOINT,
username: 'localhost',
apiKey: 1234
})
};
}
function defaults (obj, def) {
Object.keys(def).forEach(function(key) {
if (!obj.hasOwnProperty(key)) {
obj[key] = def[key];
}
});
return obj;
}
module.exports = create();
module.exports.create = create;
| Allow to create test config with overrided options | Allow to create test config with overrided options
| JavaScript | bsd-3-clause | CartoDB/camshaft | ---
+++
@@ -1,16 +1,40 @@
+'use strict';
+
var BATCH_API_ENDPOINT = 'http://127.0.0.1:8080/api/v1/sql/job';
-module.exports = {
- db: {
- host: 'localhost',
- port: 5432,
- dbname: 'analysis_api_test_db',
- user: 'postgres',
- pass: ''
- },
- batch: {
- endpoint: BATCH_API_ENDPOINT,
- username: 'localhost',
- apiKey: 1234
- }
-};
+function create (override) {
+ override = override || {
+ db: {},
+ batch: {}
+ };
+ override.db = override.db || {};
+ override.batch = override.batch || {};
+ return {
+ db: defaults(override.db, {
+ host: 'localhost',
+ port: 5432,
+ dbname: 'analysis_api_test_db',
+ user: 'postgres',
+ pass: ''
+ }),
+ batch: defaults(override.batch, {
+ endpoint: BATCH_API_ENDPOINT,
+ username: 'localhost',
+ apiKey: 1234
+ })
+ };
+}
+
+function defaults (obj, def) {
+ Object.keys(def).forEach(function(key) {
+ if (!obj.hasOwnProperty(key)) {
+ obj[key] = def[key];
+ }
+ });
+
+ return obj;
+}
+
+module.exports = create();
+
+module.exports.create = create; |
9a4c99a0f8ff0076c4803fe90d904ca4a8f8f05e | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
frameworks: ['mocha'],
browsers: ['Firefox', 'PhantomJS'],
files: [require.resolve('es5-shim'), 'build/test.js'],
reporters: ['dots']
});
if (process.env.CI && process.env.SAUCE_ACCESS_KEY) {
var customLaunchers = {
sauceLabsFirefox: {
base: 'SauceLabs',
browserName: 'firefox'
},
sauceLabsChrome: {
base: 'SauceLabs',
browserName: 'chrome'
},
sauceLabsIE11: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: 11
},
sauceLabsIE10: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: 10
},
sauceLabsIE9: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: 9
},
sauceLabsIE8: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: 8
}
};
config.set({
browsers: Object.keys(customLaunchers),
reporters: ['dots', 'saucelabs'],
captureTimeout: 120000,
sauceLabs: {
testName: 'Loud'
},
customLaunchers: customLaunchers
});
}
};
| module.exports = function(config) {
config.set({
frameworks: ['mocha'],
browsers: ['Firefox', 'PhantomJS'],
files: [require.resolve('es5-shim'), 'build/test.js'],
reporters: ['dots']
});
if (process.env.CI && process.env.SAUCE_ACCESS_KEY) {
var customLaunchers = {
sauceLabsFirefox: {
base: 'SauceLabs',
browserName: 'firefox'
},
sauceLabsChrome: {
base: 'SauceLabs',
browserName: 'chrome'
}
};
config.set({
browsers: Object.keys(customLaunchers),
reporters: ['dots', 'saucelabs'],
captureTimeout: 120000,
sauceLabs: {
testName: 'Loud'
},
customLaunchers: customLaunchers
});
}
};
| Revert "Test in Internet Explorer in SauceLabs" | Revert "Test in Internet Explorer in SauceLabs"
This reverts commit c65a817bf6dad9c9610baa00bf8d8d3143e9822e.
| JavaScript | mit | ruslansagitov/loud | ---
+++
@@ -15,26 +15,6 @@
sauceLabsChrome: {
base: 'SauceLabs',
browserName: 'chrome'
- },
- sauceLabsIE11: {
- base: 'SauceLabs',
- browserName: 'internet explorer',
- version: 11
- },
- sauceLabsIE10: {
- base: 'SauceLabs',
- browserName: 'internet explorer',
- version: 10
- },
- sauceLabsIE9: {
- base: 'SauceLabs',
- browserName: 'internet explorer',
- version: 9
- },
- sauceLabsIE8: {
- base: 'SauceLabs',
- browserName: 'internet explorer',
- version: 8
}
};
|
1a77bdfc1cd0106d2a0c9813f41c86e0ed6bd677 | frontend/src/app/users/components/detail/Record.js | frontend/src/app/users/components/detail/Record.js | import React from "react";
import moment from "moment";
class Record extends React.Component {
render() {
const {record} = this.props;
return (
<dl className="dl-horizontal">
<dt className="text-muted">Id</dt>
<dd>{record.id}</dd>
<dt className="text-muted">First Name</dt>
<dd>{record.first_name}</dd>
<dt className="text-muted">Last Name</dt>
<dd>{record.last_name}</dd>
<dt className="text-muted">Email</dt>
<dd><a href={`mailto:${record.email}`}>{record.email}</a></dd>
<dt className="text-muted">Date Joined</dt>
<dd>{moment(record.date_joined).format('dddd MMMM Do YYYY, h:mm A')}</dd>
<dt className="text-muted">Last Login</dt>
<dd>{moment(record.last_login).format('dddd MMMM Do YYYY, h:mm A')}</dd>
</dl>
);
}
}
export default Record;
| import React from "react";
import moment from "moment";
class Record extends React.Component {
render() {
const {record} = this.props;
return (
<dl className="dl-horizontal">
<dt className="text-muted">Id</dt>
<dd>{record.id}</dd>
<dt className="text-muted">First Name</dt>
<dd>{record.first_name}</dd>
<dt className="text-muted">Last Name</dt>
<dd>{record.last_name}</dd>
<dt className="text-muted">Email</dt>
<dd><a href={`mailto:${record.email}`}>{record.email}</a></dd>
<dt className="text-muted">Date Joined</dt>
<dd>{moment(record.date_joined).format('ddd. MMM. Do YYYY, h:mm A')}</dd>
<dt className="text-muted">Last Login</dt>
<dd>{moment(record.last_login).format('ddd. MMM. Do YYYY, h:mm A')}</dd>
</dl>
);
}
}
export default Record;
| Use short format when displaying dates on user record | Use short format when displaying dates on user record
| JavaScript | mit | scottwoodall/django-react-template,scottwoodall/django-react-template,scottwoodall/django-react-template | ---
+++
@@ -21,10 +21,10 @@
<dd><a href={`mailto:${record.email}`}>{record.email}</a></dd>
<dt className="text-muted">Date Joined</dt>
- <dd>{moment(record.date_joined).format('dddd MMMM Do YYYY, h:mm A')}</dd>
+ <dd>{moment(record.date_joined).format('ddd. MMM. Do YYYY, h:mm A')}</dd>
<dt className="text-muted">Last Login</dt>
- <dd>{moment(record.last_login).format('dddd MMMM Do YYYY, h:mm A')}</dd>
+ <dd>{moment(record.last_login).format('ddd. MMM. Do YYYY, h:mm A')}</dd>
</dl>
);
} |
fb92f710ead91a13d0bfa466b195e4e8ea975679 | lib/formats/json/parser.js | lib/formats/json/parser.js | var Spec02 = require("../../specs/spec_0_2.js");
const spec02 = new Spec02();
function JSONParser(_spec) {
this.spec = (_spec) ? _spec : new Spec02();
}
/**
* Level 0 of validation: is that string? is that JSON?
*/
function validate_and_parse_as_json(payload) {
var json = payload;
if(payload) {
if( (typeof payload) == "string"){
try {
json = JSON.parse(payload);
}catch(e) {
throw {message: "invalid json payload", errors: e};
}
} else if( (typeof payload) != "object"){
// anything else
throw {message: "invalid payload type, allowed are: string or object"};
}
} else {
throw {message: "null or undefined payload"};
}
return json;
}
/*
* Level 1 of validation: is that follow a spec?
*/
function validate_spec(payload, spec) {
// is that follow the spec?
spec.check(payload);
return payload;
}
JSONParser.prototype.parse = function(payload) {
// Level 0 of validation: is that string? is that JSON?
var valid0 = validate_and_parse_as_json(payload);
// Level 1 of validation: is that follow a spec?
var valid1 = validate_spec(valid0, this.spec);
return valid1;
}
module.exports = JSONParser;
| function JSONParser() {
}
/**
* Level 0 of validation: is that string? is that JSON?
*/
function validate_and_parse_as_json(payload) {
var json = payload;
if(payload) {
if( (typeof payload) == "string"){
try {
json = JSON.parse(payload);
}catch(e) {
throw {message: "invalid json payload", errors: e};
}
} else if( (typeof payload) != "object"){
// anything else
throw {message: "invalid payload type, allowed are: string or object"};
}
} else {
throw {message: "null or undefined payload"};
}
return json;
}
/*
* Level 1 of validation: is that follow a spec?
*/
function validate_spec(payload, spec) {
// is that follow the spec?
spec.check(payload);
return payload;
}
JSONParser.prototype.parse = function(payload) {
//is that string? is that JSON?
var valid = validate_and_parse_as_json(payload);
return valid;
}
module.exports = JSONParser;
| Remove the responsability of spec checking | Remove the responsability of spec checking
Signed-off-by: Fabio José <34f3a7e4e4d9fe971c99ebc4af947a5309eca653@gmail.com>
| JavaScript | apache-2.0 | cloudevents/sdk-javascript,cloudevents/sdk-javascript | ---
+++
@@ -1,9 +1,5 @@
-var Spec02 = require("../../specs/spec_0_2.js");
+function JSONParser() {
-const spec02 = new Spec02();
-
-function JSONParser(_spec) {
- this.spec = (_spec) ? _spec : new Spec02();
}
/**
@@ -45,13 +41,10 @@
JSONParser.prototype.parse = function(payload) {
- // Level 0 of validation: is that string? is that JSON?
- var valid0 = validate_and_parse_as_json(payload);
+ //is that string? is that JSON?
+ var valid = validate_and_parse_as_json(payload);
- // Level 1 of validation: is that follow a spec?
- var valid1 = validate_spec(valid0, this.spec);
-
- return valid1;
+ return valid;
}
module.exports = JSONParser; |
d04acd77fc9ac2d911bcaf36e4714ec141645371 | lib/server/routefactory.js | lib/server/routefactory.js | 'use strict';
module.exports = function RouteFactory(options) {
return ([
require('./routes/credits'),
require('./routes/debits'),
require('./routes/users'),
require('./routes/graphql'),
require('./routes/referrals')
]).map(function(Router) {
return Router({
config: options.config,
network: options.network,
storage: options.storage,
mailer: options.mailer,
contracts: options.contracts
}).getEndpointDefinitions();
}).reduce(function(set1, set2) {
return set1.concat(set2);
}, []);
};
| 'use strict';
module.exports = function RouteFactory(options) {
return ([
require('./routes/credits'),
require('./routes/debits'),
require('./routes/users'),
require('./routes/graphql'),
require('./routes/referrals'),
require('./routes/marketing')
]).map(function(Router) {
return Router({
config: options.config,
network: options.network,
storage: options.storage,
mailer: options.mailer,
contracts: options.contracts
}).getEndpointDefinitions();
}).reduce(function(set1, set2) {
return set1.concat(set2);
}, []);
};
| Add marketing route to factory | Add marketing route to factory
| JavaScript | agpl-3.0 | bryanchriswhite/billing,bryanchriswhite/billing | ---
+++
@@ -6,7 +6,8 @@
require('./routes/debits'),
require('./routes/users'),
require('./routes/graphql'),
- require('./routes/referrals')
+ require('./routes/referrals'),
+ require('./routes/marketing')
]).map(function(Router) {
return Router({
config: options.config, |
ac05b52e7fbaeef5d6e09d5552da0f4a4fe17e7f | palette/js/picker-main.js | palette/js/picker-main.js | (function( window, document, undefined ) {
'use strict';
var hslEl = document.createElement( 'div' );
hslEl.classList.add( 'hsl' );
document.body.appendChild( hslEl );
window.addEventListener( 'mousemove', function( event ) {
var x = event.pageX,
y = event.pageY;
var h = x / window.innerWidth * 360,
s = ( window.innerHeight - y ) / window.innerHeight * 100,
l = 50;
var hsl = 'hsl(' +
Math.round( h ) + ', ' +
Math.round( s ) + '%, ' +
Math.round( l ) + '%)';
document.body.style.backgroundColor = hsl;
hslEl.textContent = hsl;
});
}) ( window, document );
| (function( window, document, undefined ) {
'use strict';
function clamp( value, min, max ) {
return Math.min( Math.max( value, min ), max );
}
var hslEl = document.createElement( 'div' );
hslEl.classList.add( 'hsl' );
document.body.appendChild( hslEl );
var h = 0,
s = 50,
l = 50;
function update() {
var hsl = 'hsl(' +
Math.round( h ) + ', ' +
Math.round( s ) + '%, ' +
Math.round( l ) + '%)';
document.body.style.backgroundColor = hsl;
hslEl.textContent = hsl;
}
window.addEventListener( 'mousemove', function( event ) {
var x = event.pageX,
y = event.pageY;
h = x / window.innerWidth * 360;
s = ( window.innerHeight - y ) / window.innerHeight * 100;
update();
});
window.addEventListener( 'wheel', function( event ) {
event.preventDefault();
l = clamp( l - event.deltaY, 0, 100 );
update();
});
update();
}) ( window, document );
| Use mouse wheel to control HSL lightness. | palette[picker]: Use mouse wheel to control HSL lightness.
| JavaScript | mit | razh/experiments,razh/experiments,razh/experiments | ---
+++
@@ -1,18 +1,19 @@
(function( window, document, undefined ) {
'use strict';
+
+ function clamp( value, min, max ) {
+ return Math.min( Math.max( value, min ), max );
+ }
var hslEl = document.createElement( 'div' );
hslEl.classList.add( 'hsl' );
document.body.appendChild( hslEl );
- window.addEventListener( 'mousemove', function( event ) {
- var x = event.pageX,
- y = event.pageY;
+ var h = 0,
+ s = 50,
+ l = 50;
- var h = x / window.innerWidth * 360,
- s = ( window.innerHeight - y ) / window.innerHeight * 100,
- l = 50;
-
+ function update() {
var hsl = 'hsl(' +
Math.round( h ) + ', ' +
Math.round( s ) + '%, ' +
@@ -20,5 +21,23 @@
document.body.style.backgroundColor = hsl;
hslEl.textContent = hsl;
+ }
+
+ window.addEventListener( 'mousemove', function( event ) {
+ var x = event.pageX,
+ y = event.pageY;
+
+ h = x / window.innerWidth * 360;
+ s = ( window.innerHeight - y ) / window.innerHeight * 100;
+
+ update();
});
+
+ window.addEventListener( 'wheel', function( event ) {
+ event.preventDefault();
+ l = clamp( l - event.deltaY, 0, 100 );
+ update();
+ });
+
+ update();
}) ( window, document ); |
cd8a7f8facceddf2ffa0eae165438cfa31e8044e | lib/config.js | lib/config.js | var nconf = require('nconf')
, path = require('path');
const defaults = {
username: "",
password: "",
guardcode: "",
twofactor: "",
sentryauth: false,
sentryfile: "",
autojoin: [],
"24hour": false,
userlistwidth: 26, // 26 characters
scrollback: 1000, // 1000 lines
ghostcheck: 5*60*1000, // 5 minutes
max_reconnect: 5, // 5 attempts
reconnect_timeout: 30*1000, // 30 seconds
reconnect_long_timeout: 10*60*1000 // 10 minutes
};
function setPath(configPath) {
nconf.file(configPath);
nconf.stores.file.store =
Object.assign({}, defaults, nconf.stores.file.store);
}
setPath(path.join(__dirname, '..', 'config.json'));
module.exports = {
set: (...args) => nconf.set(...args),
get: (...args) => nconf.get(...args),
save: (...args) => nconf.save(...args),
reload: (...args) => nconf.load(...args),
getPath: () => nconf.stores.file.file,
setPath,
isValidKey: (key) => Object.keys(defaults).includes(key)
};
| var nconf = require('nconf')
, path = require('path');
const defaults = {
username: "",
password: "",
guardcode: "",
twofactor: "",
sentryauth: false,
sentryfile: "",
autojoin: [],
"24hour": false,
userlistwidth: 26, // 26 characters
scrollback: 1000, // 1000 lines
ghostcheck: 5*60*1000, // 5 minutes
max_reconnect: 5, // 5 attempts
reconnect_timeout: 30*1000, // 30 seconds
reconnect_long_timeout: 10*60*1000 // 10 minutes
};
module.exports = {
set: (...args) => nconf.set(...args),
get: (...args) => nconf.get(...args),
save: (...args) => nconf.save(...args),
reload: (...args) => nconf.load(...args),
getPath: () => nconf.stores.file.file,
setPath: (configPath) => {
nconf.file(configPath);
nconf.stores.file.store =
Object.assign({}, defaults, nconf.stores.file.store);
},
isValidKey: (key) => Object.keys(defaults).includes(key),
checkType: (key) => module.exports.isValidKey(key)
&& typeof(defaults[key])
};
module.exports.setPath(path.join(__dirname, '..', 'config.json'));
| Add checkType method and prettify code | Add checkType method and prettify code
| JavaScript | mit | rubyconn/steam-chat | ---
+++
@@ -18,20 +18,20 @@
reconnect_long_timeout: 10*60*1000 // 10 minutes
};
-function setPath(configPath) {
- nconf.file(configPath);
- nconf.stores.file.store =
- Object.assign({}, defaults, nconf.stores.file.store);
-}
-
-setPath(path.join(__dirname, '..', 'config.json'));
-
module.exports = {
set: (...args) => nconf.set(...args),
get: (...args) => nconf.get(...args),
save: (...args) => nconf.save(...args),
reload: (...args) => nconf.load(...args),
getPath: () => nconf.stores.file.file,
- setPath,
- isValidKey: (key) => Object.keys(defaults).includes(key)
+ setPath: (configPath) => {
+ nconf.file(configPath);
+ nconf.stores.file.store =
+ Object.assign({}, defaults, nconf.stores.file.store);
+ },
+ isValidKey: (key) => Object.keys(defaults).includes(key),
+ checkType: (key) => module.exports.isValidKey(key)
+ && typeof(defaults[key])
};
+
+module.exports.setPath(path.join(__dirname, '..', 'config.json')); |
4b24302999e934ad7d3cb0ad042b9d6678ed13de | bin/spider.js | bin/spider.js | #!/usr/local/bin/node
var options = {},
args = process.argv.slice( 0 ),
spider = require( "../index.js" );
args.splice( 0, 2 );
args.forEach( function( value ) {
var arg = value.match( /^(?:--)((?:[a-zA-Z])*)(?:=)((?:.)*)/ );
options[ arg[ 1 ] ] = arg[ 2 ];
});
spider( options, function( statusCode ) {
process.exit( statusCode );
} );
| #!/usr/bin/env node
var options = {},
args = process.argv.slice( 0 ),
spider = require( "../index.js" );
args.splice( 0, 2 );
args.forEach( function( value ) {
var arg = value.match( /^(?:--)((?:[a-zA-Z])*)(?:=)((?:.)*)/ );
options[ arg[ 1 ] ] = arg[ 2 ];
});
spider( options, function( statusCode ) {
process.exit( statusCode );
} );
| Fix hardcoded path to node executable | Fix hardcoded path to node executable
| JavaScript | mit | arschmitz/spider.js | ---
+++
@@ -1,4 +1,4 @@
-#!/usr/local/bin/node
+#!/usr/bin/env node
var options = {},
args = process.argv.slice( 0 ), |
9a5547d4c754d5594d2a8f64a3cb4937642e9bb1 | packages/strapi-hook-mongoose/lib/utils/index.js | packages/strapi-hook-mongoose/lib/utils/index.js | 'use strict';
/**
* Module dependencies
*/
module.exports = mongoose => {
var Decimal = require('mongoose-float').loadType(mongoose, 2);
var Float = require('mongoose-float').loadType(mongoose, 20);
return {
convertType: mongooseType => {
switch (mongooseType.toLowerCase()) {
case 'array':
return Array;
case 'boolean':
return 'Boolean';
case 'binary':
return 'Buffer';
case 'date':
case 'datetime':
case 'time':
case 'timestamp':
return Date;
case 'decimal':
return Decimal;
case 'float':
return Float;
case 'json':
return 'Mixed';
case 'biginteger':
case 'integer':
return 'Number';
case 'uuid':
return 'ObjectId';
case 'email':
case 'enumeration':
case 'password':
case 'string':
case 'text':
return 'String';
default:
}
},
};
};
| 'use strict';
/**
* Module dependencies
*/
module.exports = mongoose => {
mongoose.Schema.Types.Decimal = require('mongoose-float').loadType(mongoose, 2);
mongoose.Schema.Types.Float = require('mongoose-float').loadType(mongoose, 20);
return {
convertType: mongooseType => {
switch (mongooseType.toLowerCase()) {
case 'array':
return Array;
case 'boolean':
return 'Boolean';
case 'binary':
return 'Buffer';
case 'date':
case 'datetime':
case 'time':
case 'timestamp':
return Date;
case 'decimal':
return 'Decimal';
case 'float':
return 'Float';
case 'json':
return 'Mixed';
case 'biginteger':
case 'integer':
return 'Number';
case 'uuid':
return 'ObjectId';
case 'email':
case 'enumeration':
case 'password':
case 'string':
case 'text':
return 'String';
default:
}
},
};
};
| Fix mongoose float and decimal problems | Fix mongoose float and decimal problems
| JavaScript | mit | wistityhq/strapi,wistityhq/strapi | ---
+++
@@ -5,8 +5,8 @@
*/
module.exports = mongoose => {
- var Decimal = require('mongoose-float').loadType(mongoose, 2);
- var Float = require('mongoose-float').loadType(mongoose, 20);
+ mongoose.Schema.Types.Decimal = require('mongoose-float').loadType(mongoose, 2);
+ mongoose.Schema.Types.Float = require('mongoose-float').loadType(mongoose, 20);
return {
convertType: mongooseType => {
@@ -23,9 +23,9 @@
case 'timestamp':
return Date;
case 'decimal':
- return Decimal;
+ return 'Decimal';
case 'float':
- return Float;
+ return 'Float';
case 'json':
return 'Mixed';
case 'biginteger': |
43cd349bba9405b35b94678d03d65fe5ed7635b2 | lib/logger.js | lib/logger.js | 'use strict';
var aFrom = require('es5-ext/array/from')
, partial = require('es5-ext/function/#/partial')
, extend = require('es5-ext/object/extend-properties')
, ee = require('event-emitter')
, o;
o = ee(exports = {
init: function () {
this.msg = [];
this.passed = [];
this.errored = [];
this.failed = [];
this.started = new Date();
return this;
},
in: function (msg) {
this.msg.push(msg);
},
out: function () {
this.msg.pop();
},
log: function (type, data) {
var o = { type: type, time: new Date(), data: data, msg: aFrom(this.msg) };
this.push(o);
this[type + 'ed'].push(o);
this.emit('data', o);
},
end: function () {
this.emit('end');
}
});
o.log.partial = partial;
o.error = o.log.partial('error');
o.pass = o.log.partial('pass');
o.fail = o.log.partial('fail');
module.exports = function () {
return extend([], o).init();
};
| 'use strict';
var aFrom = require('es5-ext/array/from')
, partial = require('es5-ext/function/#/partial')
, mixin = require('es5-ext/object/mixin')
, ee = require('event-emitter')
, o;
o = ee(exports = {
init: function () {
this.msg = [];
this.passed = [];
this.errored = [];
this.failed = [];
this.started = new Date();
return this;
},
in: function (msg) {
this.msg.push(msg);
},
out: function () {
this.msg.pop();
},
log: function (type, data) {
var o = { type: type, time: new Date(), data: data, msg: aFrom(this.msg) };
this.push(o);
this[type + 'ed'].push(o);
this.emit('data', o);
},
end: function () {
this.emit('end');
}
});
o.log.partial = partial;
o.error = o.log.partial('error');
o.pass = o.log.partial('pass');
o.fail = o.log.partial('fail');
module.exports = function () {
return mixin([], o).init();
};
| Update up to changes in es5-ext | Update up to changes in es5-ext
| JavaScript | isc | medikoo/tad | ---
+++
@@ -2,7 +2,7 @@
var aFrom = require('es5-ext/array/from')
, partial = require('es5-ext/function/#/partial')
- , extend = require('es5-ext/object/extend-properties')
+ , mixin = require('es5-ext/object/mixin')
, ee = require('event-emitter')
, o;
@@ -39,5 +39,5 @@
o.fail = o.log.partial('fail');
module.exports = function () {
- return extend([], o).init();
+ return mixin([], o).init();
}; |
3318df78d163ba860674899a5bcec9e8b0ef9b65 | lib/logger.js | lib/logger.js | 'use strict';
const Winston = require('winston');
function Logger(level) {
const logLevel = level || 'info';
const logger = new Winston.Logger({
level: logLevel,
transports: [
new Winston.transports.Console({
colorize: true,
timestamp: true,
json: true,
stringify: true
})
]
});
return logger;
}
exports.attach = Logger;
| 'use strict';
const Winston = require('winston');
function Logger(level) {
const logLevel = level || 'info';
const logger = new Winston.Logger({
level: logLevel,
transports: [
new Winston.transports.Console({
colorize: false,
timestamp: true,
json: true,
stringify: true
})
]
});
return logger;
}
exports.attach = Logger;
| Set colorize to false for downstream consumers | Set colorize to false for downstream consumers
| JavaScript | mit | rapid7/acs,rapid7/acs,rapid7/acs | ---
+++
@@ -9,7 +9,7 @@
level: logLevel,
transports: [
new Winston.transports.Console({
- colorize: true,
+ colorize: false,
timestamp: true,
json: true,
stringify: true |
4a0c00a9553977ca6c8fde6ee75eb3d3b71aae37 | app/assets/javascripts/rawnet_admin/modules/menu.js | app/assets/javascripts/rawnet_admin/modules/menu.js | var RawnetAdmin = window.RawnetAdmin || {};
RawnetAdmin.menu = function(){
function toggleNav(link) {
var active = $('#mainNav a.active'),
target = $(link.attr('href')),
activeMenu = $('#subNav nav.active');
active.removeClass('active');
activeMenu.removeClass('active');
link.addClass('active');
target.addClass('active');
}
function openSearch() {
var search = $('#searchControl');
search.fadeIn("fast").addClass('open');
search.find('input').focus();
$(document).keyup(function(e) {
if (e.keyCode === 27) {
search.fadeOut("fast").removeClass('open');
$(document).unbind("keyup");
}else if (e.keyCode === 13) {
search.find('form').trigger('submit');
}
});
}
function init() {
var activeLink = $('#subNav a.active'),
activeMenu = activeLink.closest('nav'),
activeSelector = $('#mainNav a[href="#' + activeMenu.attr('id') + '"]');
activeMenu.addClass('active');
activeSelector.addClass('active');
$(document).on('click', '#mainNav a, #dashboardNav a', function(e) {
e.preventDefault();
toggleNav($(this));
});
$(document).on('click', '#subNav a.search', function(e) {
e.preventDefault();
openSearch();
});
}
return {
init: init
};
}();
| var RawnetAdmin = window.RawnetAdmin || {};
RawnetAdmin.menu = function(){
function toggleNav(link) {
var active = $('#mainNav a.active'),
target = $(link.attr('href')),
activeMenu = $('#subNav nav.active');
active.removeClass('active');
activeMenu.removeClass('active');
link.addClass('active');
target.addClass('active');
}
function openSearch() {
var search = $('#searchControl');
search.fadeIn("fast").addClass('open');
search.find('input').focus();
$(document).keyup(function(e) {
if (e.keyCode === 27) {
search.fadeOut("fast").removeClass('open');
$(document).unbind("keyup");
}else if (e.keyCode === 13) {
search.find('form').trigger('submit');
}
});
}
function init() {
var activeLink = $('#subNav a.active'),
activeMenu = activeLink.closest('nav'),
activeSelector = $('#mainNav a[href="#' + activeMenu.attr('id') + '"]');
activeMenu.addClass('active');
activeSelector.addClass('active');
$(document).on('click', '#mainNav a[href^="#"], #dashboardNav a[href^="#"]', function(e) {
e.preventDefault();
toggleNav($(this));
});
$(document).on('click', '#subNav a.search', function(e) {
e.preventDefault();
openSearch();
});
}
return {
init: init
};
}();
| Allow non-anchor links to click through normally | Allow non-anchor links to click through normally
| JavaScript | mit | rawnet/rawnet-admin,rawnet/rawnet-admin,rawnet/rawnet-admin | ---
+++
@@ -36,7 +36,7 @@
activeMenu.addClass('active');
activeSelector.addClass('active');
- $(document).on('click', '#mainNav a, #dashboardNav a', function(e) {
+ $(document).on('click', '#mainNav a[href^="#"], #dashboardNav a[href^="#"]', function(e) {
e.preventDefault();
toggleNav($(this));
}); |
773c7265e8725c87a8220c2de111c7e252becc8b | scripts/gen-nav.js | scripts/gen-nav.js | #!/usr/bin/env node
const path = require('path');
const proc = require('child_process');
const startCase = require('lodash.startcase');
const baseDir = process.argv[2];
const files = proc.execFileSync(
'find', [baseDir, '-type', 'f'], { encoding: 'utf8' },
).split('\n').filter(s => s !== '');
console.log('.API');
const links = files.map((file) => {
const doc = file.replace(baseDir, '');
const title = path.parse(file).name;
return {
xref: `* xref:${doc}[${startCase(title)}]`,
title,
};
});
// Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20')
const sortedLinks = links.sort(function (a, b) {
return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true });
});
for (const link of sortedLinks) {
console.log(link.xref);
}
| #!/usr/bin/env node
const path = require('path');
const proc = require('child_process');
const startCase = require('lodash.startcase');
const baseDir = process.argv[2];
const files = proc.execFileSync(
'find', [baseDir, '-type', 'f'], { encoding: 'utf8' },
).split('\n').filter(s => s !== '');
console.log('.API');
function getPageTitle (directory) {
if (directory === 'metatx') {
return 'Meta Transactions';
} else {
return startCase(directory);
}
}
const links = files.map((file) => {
const doc = file.replace(baseDir, '');
const title = path.parse(file).name;
return {
xref: `* xref:${doc}[${getPageTitle(title)}]`,
title,
};
});
// Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20')
const sortedLinks = links.sort(function (a, b) {
return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true });
});
for (const link of sortedLinks) {
console.log(link.xref);
}
| Change title of meta transactions page in docs sidebar | Change title of meta transactions page in docs sidebar
| JavaScript | mit | OpenZeppelin/zeppelin-solidity,OpenZeppelin/openzeppelin-contracts,OpenZeppelin/zeppelin-solidity,OpenZeppelin/openzeppelin-contracts,OpenZeppelin/zep-solidity,OpenZeppelin/openzeppelin-contracts,OpenZeppelin/zep-solidity | ---
+++
@@ -12,12 +12,20 @@
console.log('.API');
+function getPageTitle (directory) {
+ if (directory === 'metatx') {
+ return 'Meta Transactions';
+ } else {
+ return startCase(directory);
+ }
+}
+
const links = files.map((file) => {
const doc = file.replace(baseDir, '');
const title = path.parse(file).name;
return {
- xref: `* xref:${doc}[${startCase(title)}]`,
+ xref: `* xref:${doc}[${getPageTitle(title)}]`,
title,
};
}); |
bfd61aed0e339c4043d2045146be76cd11e2f7fd | .eslint-config/config.js | .eslint-config/config.js | const commonRules = require("./rules");
module.exports = {
parser: "babel-eslint",
plugins: ["react", "babel", "flowtype", "prettier", "import"],
env: {
browser: true,
es6: true,
jest: true,
node: true,
},
parserOptions: {
sourceType: "module",
ecmaFeatures: {
modules: true,
jsx: true,
},
},
settings: {
flowtype: {
onlyFilesWithFlowAnnotation: true,
},
react: {
version: "detect",
},
},
rules: Object.assign(
{},
{
"prettier/prettier": [
"error",
{
printWidth: 120,
tabWidth: 4,
useTabs: false,
semi: true,
singleQuote: false,
trailingComma: "es5",
bracketSpacing: true,
jsxBracketSameLine: true,
},
],
},
commonRules,
{ "flowtype/require-return-type": ["warn", "always", { excludeArrowFunctions: true }] }
),
};
| const commonRules = require("./rules");
module.exports = {
parser: "babel-eslint",
plugins: ["react", "babel", "flowtype", "prettier", "import"],
env: {
browser: true,
es6: true,
jest: true,
node: true,
},
parserOptions: {
sourceType: "module",
ecmaFeatures: {
modules: true,
jsx: true,
},
},
settings: {
flowtype: {
onlyFilesWithFlowAnnotation: true,
},
react: {
version: "detect",
},
},
rules: Object.assign(
{},
{
"prettier/prettier": [
"error",
{
printWidth: 120,
tabWidth: 4,
useTabs: false,
semi: true,
singleQuote: false,
trailingComma: "es5",
bracketSpacing: true,
jsxBracketSameLine: true,
},
],
},
commonRules,
{ "flowtype/require-return-type": ["warn", "always", { excludeArrowFunctions: true }] },
{ "react/prop-types": "off" }
),
};
| Disable prop-types rule because Flow | Disable prop-types rule because Flow
| JavaScript | mit | moira-alert/web2.0,moira-alert/web2.0,moira-alert/web2.0,moira-alert/web2.0 | ---
+++
@@ -42,6 +42,7 @@
],
},
commonRules,
- { "flowtype/require-return-type": ["warn", "always", { excludeArrowFunctions: true }] }
+ { "flowtype/require-return-type": ["warn", "always", { excludeArrowFunctions: true }] },
+ { "react/prop-types": "off" }
),
}; |
ab8400331070068aec4878be59fc7861daf35d2a | modules/mds/src/main/resources/webapp/js/app.js | modules/mds/src/main/resources/webapp/js/app.js | (function () {
'use strict';
var mds = angular.module('mds', [
'motech-dashboard', 'entityService','instanceService', 'mdsSettingsService', 'ngCookies', 'ui.directives',
'ngRoute', 'ui.directives'
]);
$.get('../mds/available/mdsTabs').done(function(data) {
mds.constant('AVAILABLE_TABS', data);
});
mds.run(function ($rootScope, AVAILABLE_TABS) {
$rootScope.AVAILABLE_TABS = AVAILABLE_TABS;
});
mds.config(function ($routeProvider, AVAILABLE_TABS) {
angular.forEach(AVAILABLE_TABS, function (tab) {
$routeProvider.when(
'/{0}'.format(tab),
{
templateUrl: '../mds/resources/partials/{0}.html'.format(tab),
controller: '{0}Ctrl'.format(tab.capitalize())
}
);
});
$routeProvider.otherwise({
redirectTo: '/{0}'.format(AVAILABLE_TABS[0])
});
});
}());
| (function () {
'use strict';
var mds = angular.module('mds', [
'motech-dashboard', 'entityService','instanceService', 'mdsSettingsService', 'ngCookies', 'ui.directives',
'ngRoute', 'ui.directives'
]);
$.ajax({
url: '../mds/available/mdsTabs',
success: function(data) {
mds.constant('AVAILABLE_TABS', data);
},
async: false
});
mds.run(function ($rootScope, AVAILABLE_TABS) {
$rootScope.AVAILABLE_TABS = AVAILABLE_TABS;
});
mds.config(function ($routeProvider, AVAILABLE_TABS) {
angular.forEach(AVAILABLE_TABS, function (tab) {
$routeProvider.when(
'/{0}'.format(tab),
{
templateUrl: '../mds/resources/partials/{0}.html'.format(tab),
controller: '{0}Ctrl'.format(tab.capitalize())
}
);
});
$routeProvider.otherwise({
redirectTo: '/{0}'.format(AVAILABLE_TABS[0])
});
});
}());
| Fix ajax error while checking available tabs | MDS: Fix ajax error while checking available tabs
Change-Id: I4f8a4d538e59dcdb03659c7f5405c40abcdafed8
| JavaScript | bsd-3-clause | smalecki/modules,wstrzelczyk/modules,sebbrudzinski/modules,1stmateusz/modules,sebbrudzinski/modules,ScottKimball/modules,pmuchowski/modules,mkwiatkowskisoldevelo/modules,martokarski/modules,frankhuster/modules,pgesek/modules,atish160384/modules,shubhambeehyv/modules,pmuchowski/modules,sebbrudzinski/modules,ScottKimball/modules,ngraczewski/modules,1stmateusz/modules,mkwiatkowskisoldevelo/modules,wstrzelczyk/modules,koshalt/modules,tstalka/modules,frankhuster/modules,martokarski/modules,wstrzelczyk/modules,ngraczewski/modules,koshalt/modules,koshalt/modules,frankhuster/modules,atish160384/modules,martokarski/modules,smalecki/modules,1stmateusz/modules,ngraczewski/modules,shubhambeehyv/modules,tstalka/modules,sebbrudzinski/modules,tstalka/modules,pgesek/modules,justin-hayes/modules,pmuchowski/modules,LukSkarDev/modules,ScottKimball/modules,martokarski/modules,smalecki/modules,pgesek/modules,ngraczewski/modules,atish160384/modules,tstalka/modules,justin-hayes/modules,ScottKimball/modules,shubhambeehyv/modules,LukSkarDev/modules,atish160384/modules,LukSkarDev/modules,justin-hayes/modules,frankhuster/modules,LukSkarDev/modules,shubhambeehyv/modules,justin-hayes/modules,wstrzelczyk/modules,mkwiatkowskisoldevelo/modules,1stmateusz/modules,mkwiatkowskisoldevelo/modules,pgesek/modules,koshalt/modules,pmuchowski/modules,smalecki/modules | ---
+++
@@ -6,8 +6,12 @@
'ngRoute', 'ui.directives'
]);
- $.get('../mds/available/mdsTabs').done(function(data) {
- mds.constant('AVAILABLE_TABS', data);
+ $.ajax({
+ url: '../mds/available/mdsTabs',
+ success: function(data) {
+ mds.constant('AVAILABLE_TABS', data);
+ },
+ async: false
});
mds.run(function ($rootScope, AVAILABLE_TABS) { |
10b427e9ed67937b0c09f164a518f5f408dfd050 | reactUtils.js | reactUtils.js | /**
* React-related utilities
*/
import React from 'react';
/**
* Like React.Children.forEach(), but traverses through all descendant children.
*
* @param children Children of a React element, i.e. `elem.props.children`
* @param callback {function} A function to be run for each child; parameters passed: (child, indexOfChildInImmediateParent)
*/
export function reactChildrenForEachDeep(children, callback) {
React.Children.forEach(children, (child, i) => {
callback(child, i);
if (child.props.children) {
reactChildrenForEachDeep(child.props.children, callback);
}
});
}
| /**
* React-related utilities
*/
import React from 'react';
/**
* Like React.Children.forEach(), but traverses through all descendant children.
*
* @param children Children of a React element, i.e. `elem.props.children`
* @param callback {forEachCallback} A function to be run for each child
*/
export function reactChildrenForEachDeep(children, callback) {
React.Children.forEach(children, (child, i) => {
callback(child, i);
if (child.props.children) {
reactChildrenForEachDeep(child.props.children, callback);
}
});
}
/**
* This callback is displayed as part of the Requester class.
*
* @callback forEachCallback
* @param {*} child The React child
* @param {number} index The index of the child in its immediate parent
* @param {number} depth The number of parents traversed to react this child (top-level children have depth === 1)
*/
| Add inline documentation for reactChildrenForEachDeep | Add inline documentation for reactChildrenForEachDeep
| JavaScript | mit | elliottsj/react-children-utils | ---
+++
@@ -8,7 +8,7 @@
* Like React.Children.forEach(), but traverses through all descendant children.
*
* @param children Children of a React element, i.e. `elem.props.children`
- * @param callback {function} A function to be run for each child; parameters passed: (child, indexOfChildInImmediateParent)
+ * @param callback {forEachCallback} A function to be run for each child
*/
export function reactChildrenForEachDeep(children, callback) {
React.Children.forEach(children, (child, i) => {
@@ -18,3 +18,12 @@
}
});
}
+
+/**
+ * This callback is displayed as part of the Requester class.
+ *
+ * @callback forEachCallback
+ * @param {*} child The React child
+ * @param {number} index The index of the child in its immediate parent
+ * @param {number} depth The number of parents traversed to react this child (top-level children have depth === 1)
+ */ |
24557a3b1b096e96baf8cb7e99c02f2a52181ee5 | lib/translations/es_ES.js | lib/translations/es_ES.js | // Spanish
$.extend( $.fn.pickadate.defaults, {
monthsFull: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
monthsShort: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ],
weekdaysFull: [ 'domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado' ],
weekdaysShort: [ 'dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sab' ],
today: 'hoy',
clear: 'borrar',
firstDay: 1,
format: 'dddd d de mmmm de yyyy',
formatSubmit: 'yyyy/mm/dd'
}); | // Spanish
$.extend( $.fn.pickadate.defaults, {
monthsFull: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
monthsShort: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ],
weekdaysFull: [ 'domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado' ],
weekdaysShort: [ 'dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sab' ],
today: 'hoy',
clear: 'borrar',
firstDay: 1,
format: 'dddd d De mmmm De yyyy',
formatSubmit: 'yyyy/mm/dd'
});
| Fix 'd' problem on translation | Fix 'd' problem on translation
Since in spanish you use 'de' to say 'of' it gets mistaken for a d in the date format. An easy way to fix this is to use 'De' with capital D so it doesn't get mistaken. It's better to have a misplaced capital letter to a useless date name (the dates get rendered as "Domingo 22 22e Junio 22e 2013" instead of "Domingo 22 de Junio de 2013" | JavaScript | mit | wghust/pickadate.js,nayosx/pickadate.js,okusawa/pickadate.js,b-cuts/pickadate.js,spinlister/pickadate.js,perdona/pickadate.js,mdehoog/pickadate.js,dribehance/pickadate.js,nsmith7989/pickadate.js,bluespore/pickadate.js,Drooids/pickadate.js,baminteractive/pickadatebam,mdehoog/pickadate.js,mohamnag/pickadate.js,baminteractive/pickadatebam,ivandoric/pickadate.js,mskrajnowski/pickadate.js,arkmancetz/pickadate.js,mskrajnowski/pickadate.js,atis--/pickadate.js,ryaneof/pickadate.js,grgcnnr/pickadate.js-SASS,elton0895/pickadate.js,bespoormsed/pickadate.js,bianjp/pickadate.js,spinlister/pickadate.js,okusawa/pickadate.js,rollbrettler/pickadate.js,amsul/pickadate.js,blacklane/pickadate.js,bianjp/pickadate.js,Betterez/pickadate.js,nsmith7989/pickadate.js,Betterez/pickadate.js,nikoz84/pickadate.js,cmaddalozzo/pickadate.js,blacklane/pickadate.js,amsul/pickadate.js,FOOLHOLI/pickadate.js,bluespore/pickadate.js,nayosx/pickadate.js,FronterAS/pickadate.js,ben-nsng/pickadate.js,burakkp/pickadate.js,arkmancetz/pickadate.js,loki315zx/pickadate.js,loki315zx/pickadate.js,burakkp/pickadate.js,FOOLHOLI/pickadate.js,fecori/pickadate.js,Drooids/pickadate.js,wghust/pickadate.js,fecori/pickadate.js,b-cuts/pickadate.js,ben-nsng/pickadate.js,iwanttotellyou/pickadate.js,dribehance/pickadate.js,nikoz84/pickadate.js,prashen/pickadate.js,AleksandrChukhray/pickadate.js,prashen/pickadate.js,bespoormsed/pickadate.js,AleksandrChukhray/pickadate.js,mohamnag/pickadate.js,iwanttotellyou/pickadate.js,ivandoric/pickadate.js,elton0895/pickadate.js,ryaneof/pickadate.js,perdona/pickadate.js,cmaddalozzo/pickadate.js,atis--/pickadate.js,rollbrettler/pickadate.js | ---
+++
@@ -8,6 +8,6 @@
today: 'hoy',
clear: 'borrar',
firstDay: 1,
- format: 'dddd d de mmmm de yyyy',
+ format: 'dddd d De mmmm De yyyy',
formatSubmit: 'yyyy/mm/dd'
}); |
d0fda64c6e4db63f14c894e89a9f1faace9c7eb5 | src/components/Servers/serverReducer.js | src/components/Servers/serverReducer.js | import moment from 'moment';
import getServerList from './../../utils/getServerList';
function getInitialState() {
return {
time: undefined,
servers: getServerList().map(server => Object.assign(server, {state: 'loading', delay: 0}))
};
}
export default function serverReducer(state = getInitialState(), action) {
switch (action.type) {
case "server.current.time":
return setCurrentTime(state);
case "server.online":
return modifyServerState(state, action, 'online');
case "server.offline":
return modifyServerState(state, action, 'offline');
default:
return state;
}
}
function setCurrentTime(state) {
return {
...state,
time: moment().unix()
};
}
function modifyServerState(state, {server, responseTime}, newStateValue) {
return {
...state,
servers: state.servers.map(server => {
if (server.name === server.name) {
server.state = newStateValue;
server.delay = moment().unix() - state.time;
}
return server;
})
};
}
| import moment from 'moment';
import getServerList from './../../utils/getServerList';
function getInitialState() {
return {
time: undefined,
servers: getServerList().map(server => Object.assign(server, {state: 'loading', delay: 0}))
};
}
export default function serverReducer(state = getInitialState(), action) {
switch (action.type) {
case "server.current.time":
return setCurrentTime(state);
case "server.online":
return modifyServerState(state, action, 'online');
case "server.offline":
return modifyServerState(state, action, 'offline');
default:
return state;
}
}
function setCurrentTime(state) {
return {
...state,
time: moment().unix()
};
}
function modifyServerState(state, {server, responseTime}, newStateValue) {
return {
...state,
servers: state.servers.map(stateServer => {
if (server.name === stateServer.name) {
return {
...stateServer,
state: newStateValue,
delay: moment().unix() - state.time
};
}
return stateServer;
})
};
}
| Fix a bug in the reducer | Fix a bug in the reducer
| JavaScript | mit | jseminck/jseminck-be-main,jseminck/jseminck-be-main | ---
+++
@@ -31,12 +31,15 @@
function modifyServerState(state, {server, responseTime}, newStateValue) {
return {
...state,
- servers: state.servers.map(server => {
- if (server.name === server.name) {
- server.state = newStateValue;
- server.delay = moment().unix() - state.time;
+ servers: state.servers.map(stateServer => {
+ if (server.name === stateServer.name) {
+ return {
+ ...stateServer,
+ state: newStateValue,
+ delay: moment().unix() - state.time
+ };
}
- return server;
+ return stateServer;
})
};
} |
db46938bd0b4fe175928b9d13626f6ced9cb1206 | src/util/getOwnObjectValues.js | src/util/getOwnObjectValues.js | /**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @flow strict
* @typechecks
* @format
*/
/**
* Retrieve an object's own values as an array. If you want the values in the
* protoype chain, too, use getObjectValuesIncludingPrototype.
*
* If you are looking for a function that creates an Array instance based
* on an "Array-like" object, use createArrayFrom instead.
*
* @param {object} obj An object.
* @return {array} The object's values.
*/
function getOwnObjectValues<TValue>(obj: {
+[key: string]: TValue,
...,
}): Array<TValue> {
return Object.keys(obj).map(key => obj[key]);
}
module.exports = getOwnObjectValues;
| /**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @flow strict
* @typechecks
* @format
*/
/**
* Retrieve an object's own values as an array. If you want the values in the
* protoype chain, too, use getObjectValuesIncludingPrototype.
*
* If you are looking for a function that creates an Array instance based
* on an "Array-like" object, use createArrayFrom instead.
*
* @param {object} obj An object.
* @return {array} The object's values.
*/
function getOwnObjectValues<TValue>(obj: {
+[key: string]: TValue,
...
}): Array<TValue> {
return Object.keys(obj).map(key => obj[key]);
}
module.exports = getOwnObjectValues;
| Format JavaScript files with Prettier: scripts/draft-js/__github__/src/util | Format JavaScript files with Prettier: scripts/draft-js/__github__/src/util
Reviewed By: creedarky
Differential Revision: D26975892
fbshipit-source-id: cee70c968071c7017fe078a1d31636b7174fcf4f
| JavaScript | mit | facebook/draft-js | ---
+++
@@ -18,7 +18,7 @@
*/
function getOwnObjectValues<TValue>(obj: {
+[key: string]: TValue,
- ...,
+ ...
}): Array<TValue> {
return Object.keys(obj).map(key => obj[key]);
} |
c699baa93814c1b50209b42e31c2108c14b4e380 | src/client/app/states/orders/details/details.state.js | src/client/app/states/orders/details/details.state.js | (function(){
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'orders.details': {
url: '/details/:orderId',
templateUrl: 'app/states/orders/details/details.html',
controller: StateController,
controllerAs: 'vm',
title: 'Order Details',
resolve: {
order: resolveOrder
}
}
};
}
/** @ngInject */
function resolveOrder($stateParams, Order){
return Order.get({
id: $stateParams.orderId,
'includes[]': ['product', 'project', 'service', 'staff']
}).$promise;
}
/** @ngInject */
function StateController(order) {
var vm = this;
vm.order = order;
vm.staff = order.staff;
vm.product = order.product;
vm.service = order.service;
vm.project = order.project;
vm.activate = activate;
activate();
function activate() {
}
}
})();
| (function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'orders.details': {
url: '/details/:orderId',
templateUrl: 'app/states/orders/details/details.html',
controller: StateController,
controllerAs: 'vm',
title: 'Order Details',
resolve: {
order: resolveOrder
}
}
};
}
/** @ngInject */
function resolveOrder($stateParams, Order) {
return Order.get({
id: $stateParams.orderId,
'includes[]': ['product', 'project', 'service', 'staff']
}).$promise;
}
/** @ngInject */
function StateController(order) {
var vm = this;
vm.order = order;
vm.staff = order.staff;
vm.product = order.product;
vm.service = order.service;
vm.project = order.project;
vm.activate = activate;
activate();
function activate() {
}
}
})();
| Fix JSCS violation that snuck in while the reporter was broken | Fix JSCS violation that snuck in while the reporter was broken
| JavaScript | apache-2.0 | boozallen/projectjellyfish,AllenBW/api,boozallen/projectjellyfish,mafernando/api,projectjellyfish/api,stackus/api,mafernando/api,boozallen/projectjellyfish,projectjellyfish/api,stackus/api,sonejah21/api,sreekantch/JellyFish,AllenBW/api,sreekantch/JellyFish,sreekantch/JellyFish,AllenBW/api,sonejah21/api,boozallen/projectjellyfish,stackus/api,mafernando/api,sonejah21/api,projectjellyfish/api | ---
+++
@@ -1,4 +1,4 @@
-(function(){
+(function() {
'use strict';
angular.module('app.states')
@@ -25,7 +25,7 @@
}
/** @ngInject */
- function resolveOrder($stateParams, Order){
+ function resolveOrder($stateParams, Order) {
return Order.get({
id: $stateParams.orderId,
'includes[]': ['product', 'project', 'service', 'staff'] |
c0f0589e955cb00860f5018b12678a3c60428e9d | client/app/NewPledge/containers/ActivePledgeForm.js | client/app/NewPledge/containers/ActivePledgeForm.js | import { connect } from 'react-redux'
import merge from 'lodash/merge'
import { setEntity } from '../../lib/actions/entityActions'
import { toggleSessionPopup } from '../../UserSession/actions/SessionActions'
import PledgeForm from '../components/PledgeForm'
import updateAction from '../../lib/Form/actions/updateAction'
const mapStateToProps = function(state, ownProps) {
return {
availableTags: assembleTags(ownProps.tags),
currentUser: state.currentUser,
}
}
function assembleTags(tags) {
return tags.map(function(tag) {
return {
value: tag.id,
label: tag.name,
}
})
}
const mapDispatchToProps = dispatch => ({
onLinkClick: function(event) {
event.preventDefault()
dispatch(toggleSessionPopup())
window.scrollTo(0, 0)
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(PledgeForm)
| import { connect } from 'react-redux'
import merge from 'lodash/merge'
import I18n from 'i18n-js'
import { setEntity } from '../../lib/actions/entityActions'
import { toggleSessionPopup } from '../../UserSession/actions/SessionActions'
import PledgeForm from '../components/PledgeForm'
import updateAction from '../../lib/Form/actions/updateAction'
const mapStateToProps = function(state, ownProps) {
return {
availableTags: assembleTags(ownProps.tags),
currentUser: state.currentUser,
}
}
function assembleTags(tags) {
return tags.map(function(tag) {
return {
value: tag.id,
label: I18n.t(`tags.names.${tag.name}`),
}
})
}
const mapDispatchToProps = dispatch => ({
onLinkClick: function(event) {
event.preventDefault()
dispatch(toggleSessionPopup())
window.scrollTo(0, 0)
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(PledgeForm)
| Use tag name translations in new pledge form | Use tag name translations in new pledge form
| JavaScript | agpl-3.0 | initiatived21/d21,initiatived21/d21,initiatived21/d21 | ---
+++
@@ -1,5 +1,6 @@
import { connect } from 'react-redux'
import merge from 'lodash/merge'
+import I18n from 'i18n-js'
import { setEntity } from '../../lib/actions/entityActions'
import { toggleSessionPopup } from '../../UserSession/actions/SessionActions'
import PledgeForm from '../components/PledgeForm'
@@ -16,7 +17,7 @@
return tags.map(function(tag) {
return {
value: tag.id,
- label: tag.name,
+ label: I18n.t(`tags.names.${tag.name}`),
}
})
} |
b3bb2ea4896414553a2b18573310eb9b7cdc4f09 | lib/partials/in-memory.js | lib/partials/in-memory.js | 'use strict';
const parser = require('../parser');
function InMemory(partials) {
this.partials = partials;
this.compiledPartials = {};
}
InMemory.prototype.get = function (id) {
if (this.compiledPartials.hasOwnProperty(id)) return this.compiledPartials[id];
if (this.partials.hasOwnProperty(id)) {
return this.compiledPartials[id] = parser(this.partials[id]);
}
return null;
};
module.exports = InMemory;
| 'use strict';
const parser = require('../parser');
function InMemory(partials) {
this.partials = partials;
this.compiledPartials = {};
}
InMemory.prototype.get = function (id) {
const compileTemplate = require('../../').compileTemplate;
if (this.compiledPartials.hasOwnProperty(id)) return this.compiledPartials[id];
if (this.partials.hasOwnProperty(id)) {
return this.compiledPartials[id] = compileTemplate(parser(this.partials[id]));
}
return null;
};
module.exports = InMemory;
| Update InMemory partials resolved to resolve compiled templates. This makes unit tests work again | Update InMemory partials resolved to resolve compiled templates. This makes unit tests work again
| JavaScript | mit | maghoff/mustachio,maghoff/mustachio,maghoff/mustachio | ---
+++
@@ -8,9 +8,11 @@
}
InMemory.prototype.get = function (id) {
+ const compileTemplate = require('../../').compileTemplate;
+
if (this.compiledPartials.hasOwnProperty(id)) return this.compiledPartials[id];
if (this.partials.hasOwnProperty(id)) {
- return this.compiledPartials[id] = parser(this.partials[id]);
+ return this.compiledPartials[id] = compileTemplate(parser(this.partials[id]));
}
return null;
}; |
985f707ada6f4299b0c886f25550bd1a932419f4 | lib/runner/run_phantom.js | lib/runner/run_phantom.js | var page = require('webpage').create();
var _ = require('underscore');
var fs = require('fs');
function stdout(str) {
fs.write('/dev/stdout', str, 'w')
}
function stderr(str) {
fs.write('/dev/stderr', str, 'w')
}
page.onAlert = stdout;
page.onConsoleMessage = stdout;
page.onError = stderr;
page.onLoadFinished = function() {
phantom.exit();
};
page.open(phantom.args[0]);
| var page = require('webpage').create();
var _ = require('underscore');
var system = require('system');
page.onAlert = system.stdout.write;
page.onConsoleMessage = system.stdout.write;
page.onError = system.stderr.write;
page.onLoadFinished = function() {
phantom.exit(0);
};
page.open(phantom.args[0]);
| Use `system` module for phantom runner script stdout/stderr | Use `system` module for phantom runner script stdout/stderr
| JavaScript | mit | sclevine/jasmine-runner-node | ---
+++
@@ -1,21 +1,13 @@
var page = require('webpage').create();
var _ = require('underscore');
-var fs = require('fs');
+var system = require('system');
-function stdout(str) {
- fs.write('/dev/stdout', str, 'w')
-}
-
-function stderr(str) {
- fs.write('/dev/stderr', str, 'w')
-}
-
-page.onAlert = stdout;
-page.onConsoleMessage = stdout;
-page.onError = stderr;
+page.onAlert = system.stdout.write;
+page.onConsoleMessage = system.stdout.write;
+page.onError = system.stderr.write;
page.onLoadFinished = function() {
- phantom.exit();
+ phantom.exit(0);
};
page.open(phantom.args[0]); |
2d329f918e5a5eaa5ccd19b32f745caf7beca020 | public/javascripts/app.js | public/javascripts/app.js | $(document).ready(function () {
$('#columns .tweets').empty(); // Remove dummy content.
$('.not-signed-in #the-sign-in-menu').popover({
placement: 'below',
trigger: 'manual'
}).popover('show');
});
// __END__ {{{1
// vim: expandtab shiftwidth=2 softtabstop=2
// vim: foldmethod=marker
| $(document).ready(function () {
$('#columns .tweets').empty(); // Remove dummy content.
$('.not-signed-in #the-sign-in-menu').popover({
placement: 'below',
trigger: 'manual'
}).popover('show');
var update_character_count = function () {
$('#character-count').text(140 - $(this).val().length); // FIXME
};
$('#status')
.keydown(update_character_count)
.keyup(update_character_count);
});
// __END__ {{{1
// vim: expandtab shiftwidth=2 softtabstop=2
// vim: foldmethod=marker
| Update character count for new tweet | Update character count for new tweet
| JavaScript | mit | kana/ddh0313,kana/ddh0313 | ---
+++
@@ -5,6 +5,13 @@
placement: 'below',
trigger: 'manual'
}).popover('show');
+
+ var update_character_count = function () {
+ $('#character-count').text(140 - $(this).val().length); // FIXME
+ };
+ $('#status')
+ .keydown(update_character_count)
+ .keyup(update_character_count);
});
// __END__ {{{1 |
ae73a9c27835b80d3f4102b9239e16506e534c75 | packages/storybook/examples/Popover/DemoList.js | packages/storybook/examples/Popover/DemoList.js | import React from 'react';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
import TextLabel from '@ichef/gypcrete/src/TextLabel';
function DemoList() {
return (
<List>
<ListRow>
<TextLabel basic="Row 1" />
</ListRow>
<ListRow>
<TextLabel basic="Row 2" />
</ListRow>
<ListRow>
<TextLabel basic="Row 3" />
</ListRow>
</List>
);
}
export default DemoList;
| import React from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
function DemoButton(props) {
return (
<Button
bold
minified={false}
color="black"
{...props} />
);
}
function DemoList() {
return (
<List>
<ListRow>
<DemoButton basic="Row 1" onClick={action('click.1')} />
</ListRow>
<ListRow>
<DemoButton basic="Row 2" onClick={action('click.2')} />
</ListRow>
<ListRow>
<DemoButton basic="Row 3" onClick={action('click.3')} />
</ListRow>
</List>
);
}
export default DemoList;
| Update example for <Popover> to verify behavior | [core] Update example for <Popover> to verify behavior
| JavaScript | apache-2.0 | iCHEF/gypcrete,iCHEF/gypcrete | ---
+++
@@ -1,20 +1,31 @@
import React from 'react';
+import { action } from '@storybook/addon-actions';
+import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
-import TextLabel from '@ichef/gypcrete/src/TextLabel';
+
+function DemoButton(props) {
+ return (
+ <Button
+ bold
+ minified={false}
+ color="black"
+ {...props} />
+ );
+}
function DemoList() {
return (
<List>
<ListRow>
- <TextLabel basic="Row 1" />
+ <DemoButton basic="Row 1" onClick={action('click.1')} />
</ListRow>
<ListRow>
- <TextLabel basic="Row 2" />
+ <DemoButton basic="Row 2" onClick={action('click.2')} />
</ListRow>
<ListRow>
- <TextLabel basic="Row 3" />
+ <DemoButton basic="Row 3" onClick={action('click.3')} />
</ListRow>
</List>
); |
716761802895ad4a681a07e70f56532abe573075 | test/helpers/fixtures/index.js | test/helpers/fixtures/index.js | var fixtures = require('node-require-directory')(__dirname);
exports.load = function(specificFixtures) {
return exports.unload().then(function() {
if (typeof specificFixtures === 'string') {
specificFixtures = [specificFixtures];
}
var promises = [];
Object.keys(fixtures).filter(function(key) {
if (key === 'index') {
return false;
}
if (specificFixtures && specificFixtures.indexOf(key) === -1) {
return false;
}
return true;
}).forEach(function(key) {
var promise = fixtures[key].load().then(function(instances) {
exports[key] = instances;
});
promises.push(promise);
});
return Promise.all(promises);
}).catch(function(err) {
console.error(err.stack);
});
};
exports.unload = function() {
return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() {
return sequelize.sync({ force: true });
}).then(function() {
return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
});
};
| var fixtures = require('node-require-directory')(__dirname);
exports.load = function(specificFixtures) {
return exports.unload().then(function() {
if (typeof specificFixtures === 'string') {
specificFixtures = [specificFixtures];
}
var promises = [];
Object.keys(fixtures).filter(function(key) {
if (key === 'index') {
return false;
}
if (specificFixtures && specificFixtures.indexOf(key) === -1) {
return false;
}
return true;
}).forEach(function(key) {
var promise = fixtures[key].load().then(function(instances) {
exports[key] = instances;
});
promises.push(promise);
});
return Promise.all(promises);
}).catch(function(err) {
console.error(err.stack);
});
};
exports.unload = function() {
if (sequelize.options.dialect === 'mysql') {
return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() {
return sequelize.sync({ force: true });
}).then(function() {
return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
});
} else {
return sequelize.sync({ force: true });
}
};
| Fix running SET command in sqlite | Fix running SET command in sqlite
| JavaScript | mit | luin/doclab,luin/doclab | ---
+++
@@ -27,9 +27,13 @@
};
exports.unload = function() {
- return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() {
+ if (sequelize.options.dialect === 'mysql') {
+ return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() {
+ return sequelize.sync({ force: true });
+ }).then(function() {
+ return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
+ });
+ } else {
return sequelize.sync({ force: true });
- }).then(function() {
- return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
- });
+ }
}; |
4388e9713abf80d4d001a86c67a447bd5a9f3beb | app/auth/bearer/verify.js | app/auth/bearer/verify.js | exports = module.exports = function(authenticate) {
return function verify(req, token, cb) {
authenticate(token, function(err, tkn, ctx) {
if (err) { return cb(err); }
// TODO: Check confirmation methods, etc
var info = {};
if (tkn.client) {
info.client = tkn.client;
}
if (tkn.scope) {
info.scope = tkn.scope;
}
if (!tkn.subject) {
return cb(null, false);
}
return cb(null, tkn.subject, info);
});
};
};
exports['@require'] = [
'http://i.bixbyjs.org/security/authentication/token/authenticate'
];
| exports = module.exports = function(authenticate) {
return function verify(req, token, cb) {
authenticate(token, function(err, tkn, ctx) {
if (err) { return cb(err); }
// TODO: Check confirmation methods, etc
var info = {};
if (tkn.client) {
info.client = tkn.client;
}
if (tkn.scope) {
info.scope = tkn.scope;
}
if (!tkn.user) {
return cb(null, false);
}
return cb(null, tkn.user, info);
});
};
};
exports['@require'] = [
'http://i.bixbyjs.org/security/authentication/token/authenticate'
];
| Switch from subject to user. | Switch from subject to user.
| JavaScript | mit | bixbyjs/bixby-http | ---
+++
@@ -14,10 +14,10 @@
info.scope = tkn.scope;
}
- if (!tkn.subject) {
+ if (!tkn.user) {
return cb(null, false);
}
- return cb(null, tkn.subject, info);
+ return cb(null, tkn.user, info);
});
};
}; |
71ed439f9f6e5e958c4aeac5522cd37dd90ec997 | app/components/Results.js | app/components/Results.js | import React, {PropTypes} from 'react';
const puke = (obj) => <pre>{JSON.stringify(obj, 2, ' ')}</pre>
const Results = React.createClass({
render() {
return (
<div>
Results: {puke(this.props)}
</div>
);
}
});
Results.propTypes = {
isLoading: PropTypes.bool.isRequired,
playersInfo: PropTypes.array.isRequired,
scores: PropTypes.array.isRequired
}
export default Results; | import React, {PropTypes} from 'react';
import {Link} from 'react-router';
import UserDetails from './UserDetails';
import UserDetailsWrapper from './UserDetailsWrapper';
const StartOver = () => {
return (
<div className="col-sm-12" style={{"margin-top": 20}}>
<Link to="/playerOne">
<button type="button" className="btn btn-lg btn-danger">
Start Over
</button>
</Link>
</div>
)
}
const Results = React.createClass({
render() {
const winnerIndex = this.props.scores[0] > this.props.scores[1] ? 0 : 1;
const loserIndex = 1 - winnerIndex; // 1 - [0] = 1 ; 1 - [1] = 0
if (this.props.isLoading) {
return (
<p>LOADING...</p>
)
}
if (this.props.scores[0] === this.props.scores[1]) {
return (
<div className="jumbotron col-sm-12 text-center">
<h1>It's a tie</h1>
<StartOver />
</div>
)
}
return (
<div className="jumbotron col-sm-12 text-center">
<h1>Results</h1>
<div className="col-sm-8 col-sm-offset-2">
<UserDetailsWrapper header="Winner">
<UserDetails score={this.props.scores[winnerIndex]} info={this.props.playersInfo[winnerIndex]} />
</UserDetailsWrapper>
<UserDetailsWrapper header="Loser">
<UserDetails score={this.props.scores[loserIndex]} info={this.props.playersInfo[loserIndex]} />
</UserDetailsWrapper>
</div>
<StartOver />
</div>
);
}
});
Results.propTypes = {
isLoading: PropTypes.bool.isRequired,
playersInfo: PropTypes.array.isRequired,
scores: PropTypes.array.isRequired
}
export default Results; | Add the score result to the UI to show the battle's winner | Add the score result to the UI to show the battle's winner
| JavaScript | mit | DiegoCardoso/github-battle,DiegoCardoso/github-battle | ---
+++
@@ -1,12 +1,54 @@
import React, {PropTypes} from 'react';
+import {Link} from 'react-router';
-const puke = (obj) => <pre>{JSON.stringify(obj, 2, ' ')}</pre>
+import UserDetails from './UserDetails';
+import UserDetailsWrapper from './UserDetailsWrapper';
+
+const StartOver = () => {
+ return (
+ <div className="col-sm-12" style={{"margin-top": 20}}>
+ <Link to="/playerOne">
+ <button type="button" className="btn btn-lg btn-danger">
+ Start Over
+ </button>
+ </Link>
+ </div>
+ )
+}
const Results = React.createClass({
render() {
+ const winnerIndex = this.props.scores[0] > this.props.scores[1] ? 0 : 1;
+ const loserIndex = 1 - winnerIndex; // 1 - [0] = 1 ; 1 - [1] = 0
+
+ if (this.props.isLoading) {
+ return (
+ <p>LOADING...</p>
+ )
+ }
+
+ if (this.props.scores[0] === this.props.scores[1]) {
+ return (
+ <div className="jumbotron col-sm-12 text-center">
+ <h1>It's a tie</h1>
+ <StartOver />
+ </div>
+ )
+ }
+
return (
- <div>
- Results: {puke(this.props)}
+ <div className="jumbotron col-sm-12 text-center">
+ <h1>Results</h1>
+ <div className="col-sm-8 col-sm-offset-2">
+ <UserDetailsWrapper header="Winner">
+ <UserDetails score={this.props.scores[winnerIndex]} info={this.props.playersInfo[winnerIndex]} />
+ </UserDetailsWrapper>
+
+ <UserDetailsWrapper header="Loser">
+ <UserDetails score={this.props.scores[loserIndex]} info={this.props.playersInfo[loserIndex]} />
+ </UserDetailsWrapper>
+ </div>
+ <StartOver />
</div>
);
} |
0f4aa813546a29fb55e08bf67c2a659b0f85b0fa | routes/index.js | routes/index.js | var express = require('express');
var kue = require('kue');
var Bot = require('../models/bot');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.post('/destroy_jobs', function(req, res, next) {
kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) {
jobs.forEach(function(job) {
job.remove(function() {});
});
res.send();
});
});
router.post('/destroy_all_the_things', function(req, res, next) {
kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) {
jobs.forEach(function(job) {
job.remove()
.then(function(res) {
})
.catch(function(err) {
res.status(500).send(err);
});
});
});
Bot.remove({})
.then(function(result) {
})
.catch(function(err) {
res.status(500).send(err);
});
res.send();
});
module.exports = router;
| var express = require('express');
var kue = require('kue');
var Bot = require('../models/bot');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.post('/destroy_jobs', function(req, res, next) {
kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) {
jobs.forEach(function(job) {
job.remove(function() {});
});
res.send();
});
});
router.post('/destroy_all_the_things', function(req, res, next) {
kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) {
jobs.forEach(function(job) {
job.remove(function(err) {
if (err) console.log(err);
});
});
});
Bot.remove({})
.then(function(result) {
})
.catch(function(err) {
res.status(500).send(err);
});
res.send();
});
module.exports = router;
| Fix error handler on remove job | Fix error handler on remove job
| JavaScript | mit | Ecotaco/bumblebee-bot,Ecotaco/bumblebee-bot | ---
+++
@@ -21,11 +21,8 @@
router.post('/destroy_all_the_things', function(req, res, next) {
kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) {
jobs.forEach(function(job) {
- job.remove()
- .then(function(res) {
- })
- .catch(function(err) {
- res.status(500).send(err);
+ job.remove(function(err) {
+ if (err) console.log(err);
});
});
}); |
48995b0af392863844f77825cba4a1f228f8c407 | src/request/repository/request-repository-local.js | src/request/repository/request-repository-local.js | var glimpse = require('glimpse');
var store = require('store.js');
var _storeSummaryKey = 'glimpse.data.summary',
_storeDetailKey = 'glimpse.data.request';
// store Found Summary
(function() {
function storeFoundSummary(data) {
store.set(_storeSummaryKey, data);
}
glimpse.on('data.request.summary.found.remote', storeFoundSummary);
glimpse.on('data.request.summary.found.stream', storeFoundSummary);
})();
// store Found Detail
(function() {
function storeFoundDetail(data) {
var key = _storeDetailKey + '.' + data.id;
store.set(key, data);
}
glimpse.on('data.request.detail.found.remote', storeFoundDetail);
})();
module.exports = {
triggerGetLastestSummaries: function() {
var data = store.get(_storeSummaryKey);
if(data && data.length > 0)
glimpse.emit('data.request.summary.found.local', data);
},
triggerGetDetailsFor: function(requestId) {
var data = store.get(_storeDetailKey + '.' + requestId);
if(data && data.length > 0)
glimpse.emit('data.request.detail.found.local', data);
}
};
| var glimpse = require('glimpse');
var store = require('store.js');
var _storeSummaryKey = 'glimpse.data.summary',
_storeDetailKey = 'glimpse.data.request';
// store Found Summary
(function() {
//TODO: Need to complete
//Push into local storage
//address error handling, flushing out old data
function storeFoundSummary(data) {
store.set(_storeSummaryKey, data);
}
glimpse.on('data.request.summary.found.remote', storeFoundSummary);
glimpse.on('data.request.summary.found.stream', storeFoundSummary);
})();
// store Found Detail
(function() {
//TODO: Need to complete
//Push into local storage
//address error handling, flushing out old data
function storeFoundDetail(data) {
var key = _storeDetailKey + '.' + data.id;
store.set(key, data);
}
glimpse.on('data.request.detail.found.remote', storeFoundDetail);
})();
module.exports = {
triggerGetLastestSummaries: function() {
//TODO: Need to complete
//Pull from local storage
//address error handling
var data = store.get(_storeSummaryKey);
if(data && data.length > 0)
glimpse.emit('data.request.summary.found.local', data);
},
triggerGetDetailsFor: function(requestId) {
//TODO: Need to complete
//Pull from local storage
//address error handling
var data = store.get(_storeDetailKey + '.' + requestId);
if(data && data.length > 0)
glimpse.emit('data.request.detail.found.local', data);
}
};
| Add todo comments for local storage request repository | Add todo comments for local storage request repository
| JavaScript | unknown | Glimpse/Glimpse.Client.Prototype,avanderhoorn/Glimpse.Client.Prototype,avanderhoorn/Glimpse.Client.Prototype,Glimpse/Glimpse.Client.Prototype,Glimpse/Glimpse.Client.Prototype | ---
+++
@@ -5,6 +5,9 @@
_storeDetailKey = 'glimpse.data.request';
// store Found Summary
(function() {
+ //TODO: Need to complete
+ //Push into local storage
+ //address error handling, flushing out old data
function storeFoundSummary(data) {
store.set(_storeSummaryKey, data);
}
@@ -15,6 +18,9 @@
// store Found Detail
(function() {
+ //TODO: Need to complete
+ //Push into local storage
+ //address error handling, flushing out old data
function storeFoundDetail(data) {
var key = _storeDetailKey + '.' + data.id;
store.set(key, data);
@@ -25,11 +31,17 @@
module.exports = {
triggerGetLastestSummaries: function() {
+ //TODO: Need to complete
+ //Pull from local storage
+ //address error handling
var data = store.get(_storeSummaryKey);
if(data && data.length > 0)
glimpse.emit('data.request.summary.found.local', data);
},
triggerGetDetailsFor: function(requestId) {
+ //TODO: Need to complete
+ //Pull from local storage
+ //address error handling
var data = store.get(_storeDetailKey + '.' + requestId);
if(data && data.length > 0)
glimpse.emit('data.request.detail.found.local', data); |
a2772d17f97ad597e731d3fa71b363e9a190c1dc | web-app/src/utils/api.js | web-app/src/utils/api.js | /* global localStorage */
import axios from 'axios';
export const BASE_URL = process.env.REACT_APP_API_URL;
const request = (endpoint, { headers = {}, body, ...otherOptions }, method) => {
return axios(`${BASE_URL}${endpoint}`, {
...otherOptions,
headers: {
...headers,
Authorization: `Bearer ${localStorage.getItem('jwt.token')}}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
data: body ? JSON.stringify(body) : undefined,
method,
});
};
export const api = {
get(endpoint, options = {}) {
return request(endpoint, options, 'get');
},
post(endpoint, options = {}) {
return request(endpoint, options, 'post');
},
};
export default api;
| /* global window */
import axios from 'axios';
export const BASE_URL = process.env.REACT_APP_API_URL;
const getToken = () => {
return window.localStorage.getItem('jwt.token');
};
const setToken = ({ newToken }) => {
window.localStorage.setItem('jwt.token', newToken);
};
const abstractRequest = (endpoint, { headers = {}, body, ...otherOptions }, method) => {
return axios(`${BASE_URL}${endpoint}`, {
...otherOptions,
headers: {
...headers,
Authorization: `Bearer ${getToken()}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
data: body ? JSON.stringify(body) : undefined,
method,
});
};
const checkForRefreshToken = (endpoint, content, method) => (error) => {
if (error.response && error.response.status === 401) {
return abstractRequest('/auth/refresh', {}, 'post').then(({ data }) => {
setToken(data);
return abstractRequest(endpoint, content, method);
});
}
return Promise.reject(error);
};
const checkForRelogin = error => {
if (!error.response || !error.response.data || window.location.pathname === '/login') {
return Promise.reject(error);
}
const message = error.response.data.error;
if (['token_expired', 'token_invalid', 'token_not_provided'].includes(message)) {
window.location = '/login';
}
return Promise.reject(error);
};
const request = (endpoint, content, method) => {
return abstractRequest(endpoint, content, method)
.catch(checkForRefreshToken(endpoint, content, method))
.catch(checkForRelogin);
};
export const api = {
get(endpoint, options = {}) {
return request(endpoint, options, 'get');
},
post(endpoint, options = {}) {
return request(endpoint, options, 'post');
},
};
export default api;
| Refresh JWT token if expires | Refresh JWT token if expires
| JavaScript | mit | oSoc17/code9000,oSoc17/code9000,oSoc17/code9000,oSoc17/code9000,oSoc17/code9000,oSoc17/code9000 | ---
+++
@@ -1,20 +1,59 @@
-/* global localStorage */
+/* global window */
import axios from 'axios';
export const BASE_URL = process.env.REACT_APP_API_URL;
-const request = (endpoint, { headers = {}, body, ...otherOptions }, method) => {
+const getToken = () => {
+ return window.localStorage.getItem('jwt.token');
+};
+
+const setToken = ({ newToken }) => {
+ window.localStorage.setItem('jwt.token', newToken);
+};
+
+const abstractRequest = (endpoint, { headers = {}, body, ...otherOptions }, method) => {
return axios(`${BASE_URL}${endpoint}`, {
...otherOptions,
headers: {
...headers,
- Authorization: `Bearer ${localStorage.getItem('jwt.token')}}`,
+ Authorization: `Bearer ${getToken()}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
data: body ? JSON.stringify(body) : undefined,
method,
});
+};
+
+const checkForRefreshToken = (endpoint, content, method) => (error) => {
+ if (error.response && error.response.status === 401) {
+ return abstractRequest('/auth/refresh', {}, 'post').then(({ data }) => {
+ setToken(data);
+
+ return abstractRequest(endpoint, content, method);
+ });
+ }
+ return Promise.reject(error);
+};
+
+const checkForRelogin = error => {
+ if (!error.response || !error.response.data || window.location.pathname === '/login') {
+ return Promise.reject(error);
+ }
+
+ const message = error.response.data.error;
+
+ if (['token_expired', 'token_invalid', 'token_not_provided'].includes(message)) {
+ window.location = '/login';
+ }
+
+ return Promise.reject(error);
+};
+
+const request = (endpoint, content, method) => {
+ return abstractRequest(endpoint, content, method)
+ .catch(checkForRefreshToken(endpoint, content, method))
+ .catch(checkForRelogin);
};
export const api = { |
801c830a6f128a09ae1575069e2e20e8457e9ce9 | api/script-rules-rule-action.vm.js | api/script-rules-rule-action.vm.js | (function() {
var rule = data.rules[parseInt(request.param.num, 10)] || null;
if (rule === null) return response.error(404);
switch (request.method) {
case 'PUT':
var cmd = '';
switch (request.param.action) {
case 'enable':
cmd = 'node app-cli.js -mode rule --enable -n ' + request.param.num;
break;
case 'disable':
cmd = 'node app-cli.js -mode rule --disable -n ' + request.param.num;
break;
}
child_process.exec(cmd, function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200);
response.end('{}');
});
return;
}
})(); | (function() {
var num = parseInt(request.param.num, 10).toString(10);
var rule = data.rules[num] || null;
if (rule === null) return response.error(404);
switch (request.method) {
case 'PUT':
var cmd = '';
switch (request.param.action) {
case 'enable':
cmd = 'node app-cli.js -mode rule --enable -n ' + num;
break;
case 'disable':
cmd = 'node app-cli.js -mode rule --disable -n ' + num;
break;
}
child_process.exec(cmd, function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200);
response.end('{}');
});
return;
}
})();
| Fix same rule parameter validation | Fix same rule parameter validation
| JavaScript | mit | miyukki/Chinachu,xtne6f/Chinachu,xtne6f/Chinachu,kounoike/Chinachu,kounoike/Chinachu,xtne6f/Chinachu,valda/Chinachu,valda/Chinachu,kanreisa/Chinachu,polamjag/Chinachu,wangjun/Chinachu,miyukki/Chinachu,polamjag/Chinachu,kanreisa/Chinachu,valda/Chinachu,miyukki/Chinachu,kounoike/Chinachu,wangjun/Chinachu,wangjun/Chinachu,kanreisa/Chinachu,upsilon/Chinachu,polamjag/Chinachu,upsilon/Chinachu,tdenc/Chinachu,upsilon/Chinachu,tdenc/Chinachu,tdenc/Chinachu | ---
+++
@@ -1,6 +1,7 @@
(function() {
- var rule = data.rules[parseInt(request.param.num, 10)] || null;
+ var num = parseInt(request.param.num, 10).toString(10);
+ var rule = data.rules[num] || null;
if (rule === null) return response.error(404);
@@ -10,10 +11,10 @@
switch (request.param.action) {
case 'enable':
- cmd = 'node app-cli.js -mode rule --enable -n ' + request.param.num;
+ cmd = 'node app-cli.js -mode rule --enable -n ' + num;
break;
case 'disable':
- cmd = 'node app-cli.js -mode rule --disable -n ' + request.param.num;
+ cmd = 'node app-cli.js -mode rule --disable -n ' + num;
break;
}
|
80c24f86d0ed9655f74c710f11a59bc050df5432 | app/assets/javascripts/spree/apps/checkout/checkout_controller.js | app/assets/javascripts/spree/apps/checkout/checkout_controller.js | SpreeStore.module('Checkout',function(Checkout, SpreeStore, Backbone,Marionette,$,_){
Checkout.Controller = {
show: function(state) {
SpreeStore.noSidebar()
order = new SpreeStore.Models.Order({ number: SpreeStore.current_order_id })
order.fetch({
data: $.param({ order_token: SpreeStore.current_order_token}),
success: function(order) {
if (order.attributes.state == "complete") {
SpreeStore.navigate("/orders/" + order.attributes.number, true)
} else {
Checkout.Controller.renderFor(order, state)
}
}
})
},
renderFor: function(order, state) {
state = state || order.attributes.state
SpreeStore.navigate("/checkout/" + state)
orderView = Checkout[state + 'View']
if (orderView != undefined) {
SpreeStore.mainRegion.show(new orderView({model: order}))
} else {
SpreeStore.navigate("/checkout/" + order.attributes.state)
this.renderFor(order, order.attributes.state)
}
}
}
}) | SpreeStore.module('Checkout',function(Checkout, SpreeStore, Backbone,Marionette,$,_){
Checkout.Controller = {
show: function(state) {
SpreeStore.noSidebar()
order = new SpreeStore.Models.Order({ number: SpreeStore.current_order_id })
order.fetch({
data: $.param({ order_token: SpreeStore.current_order_token}),
success: function(order) {
if (order.attributes.state == "complete") {
window.localStorage.removeItem('current_order_id');
window.localStorage.removeItem('current_order_token');
SpreeStore.navigate("/orders/" + order.attributes.number, true)
} else {
Checkout.Controller.renderFor(order, state)
}
}
})
},
renderFor: function(order, state) {
state = state || order.attributes.state
SpreeStore.navigate("/checkout/" + state)
orderView = Checkout[state + 'View']
if (orderView != undefined) {
SpreeStore.mainRegion.show(new orderView({model: order}))
} else {
SpreeStore.navigate("/checkout/" + order.attributes.state)
this.renderFor(order, order.attributes.state)
}
}
}
}) | Clear localStorage order variables when order is complete | Clear localStorage order variables when order is complete
| JavaScript | bsd-3-clause | njaw/spree,njaw/spree,njaw/spree | ---
+++
@@ -7,6 +7,8 @@
data: $.param({ order_token: SpreeStore.current_order_token}),
success: function(order) {
if (order.attributes.state == "complete") {
+ window.localStorage.removeItem('current_order_id');
+ window.localStorage.removeItem('current_order_token');
SpreeStore.navigate("/orders/" + order.attributes.number, true)
} else {
Checkout.Controller.renderFor(order, state) |
8ee09efd28cfce24b0d712d5a1713caef4dd6819 | app/assets/javascripts/comments.js | app/assets/javascripts/comments.js | /* All related comment actions will be managed here */
/* appending comment see views/comments/create.js.erb */
$(function(){
// declare variables for link, button, form ids
var viewCommentForm = '#view_comment_form';
var commentForm = '#comment_form';
var newComment = '#new_comment';
toggleLink(commentForm); // initially hide comment form
// show/hide form when user clicks on comment
$('h3').on('click', viewCommentForm, function(e) {
e.preventDefault();
toggleLink(commentForm);
});
// edit form text when user clicks on comment
$('h3').on('click', viewCommentForm, function(e) {
e.preventDefault();
$(viewCommentForm).text(toggleLinkText($(viewCommentForm))); // set text depending on current text
});
// remove comments form when user submits
$(commentForm).on('submit', newComment, function(e) {
e.preventDefault();
toggleLink(commentForm);
$(viewCommentForm).text(toggleLinkText($(viewCommentForm)));
});
});
/*** Helper Methods Below ***/
// toggle between show and hidden
function toggleLink(selector) {
$(selector).toggle("medium");
}
// toggle text on link/button depending on what is currently set
function toggleLinkText(linkText) {
text = linkText.text();
var text = text === "Add a comment" ? "Cancel comment" : "Add a comment";
return text;
}
| /* All related comment actions will be managed here */
/* appending comment see views/comments/create.js.erb */
$(function(){
// declare variables for link, button, form ids
var viewCommentForm = '#view_comment_form';
var commentForm = '#comment_form';
var newComment = '#new_comment';
toggleLink(commentForm); // initially hide comment form
// show/hide form when user clicks on comment
$('h3').on('click', viewCommentForm, function(e) {
e.preventDefault();
toggleLink(commentForm);
});
// edit form text when user clicks on comment
$('h3').on('click', viewCommentForm, function(e) {
e.preventDefault();
changeFormText(viewCommentForm); // set text depending on current text
});
// remove comments form when user submits
$(commentForm).on('submit', newComment, function(e) {
e.preventDefault();
clearFormText(); // clear form contents
toggleLink(commentForm); // remove form from view
changeFormText(viewCommentForm); // toggle link/button text
});
});
/*** Helper Methods Below ***/
// toggle between show and hidden
function toggleLink(selector) {
$(selector).toggle("medium");
}
// toggle text on link/button depending on what is currently set
function toggleLinkText(linkText) {
text = linkText.text();
var text = text === "Add a comment" ? "Cancel comment" : "Add a comment";
return text;
}
// change text on comment form link/button
function changeFormText(form) {
$(form).text(toggleLinkText($(form)));
}
// clear tiny mce form text after user submits
function clearFormText() {
tinyMCE.activeEditor.setContent('');
} | Clean up file and remove editor text on submit | Clean up file and remove editor text on submit
| JavaScript | mit | pratikmshah/myblog,pratikmshah/myblog,pratikmshah/myblog | ---
+++
@@ -19,14 +19,15 @@
// edit form text when user clicks on comment
$('h3').on('click', viewCommentForm, function(e) {
e.preventDefault();
- $(viewCommentForm).text(toggleLinkText($(viewCommentForm))); // set text depending on current text
+ changeFormText(viewCommentForm); // set text depending on current text
});
// remove comments form when user submits
$(commentForm).on('submit', newComment, function(e) {
e.preventDefault();
- toggleLink(commentForm);
- $(viewCommentForm).text(toggleLinkText($(viewCommentForm)));
+ clearFormText(); // clear form contents
+ toggleLink(commentForm); // remove form from view
+ changeFormText(viewCommentForm); // toggle link/button text
});
});
@@ -44,3 +45,13 @@
var text = text === "Add a comment" ? "Cancel comment" : "Add a comment";
return text;
}
+
+// change text on comment form link/button
+function changeFormText(form) {
+ $(form).text(toggleLinkText($(form)));
+}
+
+// clear tiny mce form text after user submits
+function clearFormText() {
+ tinyMCE.activeEditor.setContent('');
+} |
6e0974dc5db259931419a64cd4d13a61425283b5 | app/components/DeleteIcon/index.js | app/components/DeleteIcon/index.js | import React, { Component, PropTypes } from 'react';
import { openModal } from 'actions/uiActions';
import Icon from 'utils/icons';
import ConfirmModal from '../Modals/ConfirmModal';
export default class DeleteIcon extends Component {
static propTypes = {
onClick: PropTypes.func.isRequired,
message: PropTypes.string.isRequired,
dispatch: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
const { onClick, message, dispatch } = this.props;
dispatch(openModal(
<ConfirmModal
confirm={onClick}
message={message}
/>),
);
}
render() {
return (
<button className="table__delete" onClick={this.onClick}><Icon icon="circleWithLine" /></button>
);
}
}
| import React, { Component, PropTypes } from 'react';
import { openModal } from 'actions/uiActions';
import Icon from 'utils/icons';
import ConfirmModal from '../Modals/ConfirmModal';
export default class DeleteIcon extends Component {
static propTypes = {
onClick: PropTypes.func.isRequired,
message: PropTypes.string,
dispatch: PropTypes.func.isRequired,
}
static defaultProps = {
message: undefined,
}
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
const { onClick, message, dispatch } = this.props;
dispatch(openModal(
<ConfirmModal
confirm={onClick}
message={message}
/>),
);
}
render() {
return (
<button type="button" className="table__delete" onClick={this.onClick}><Icon icon="circleWithLine" /></button>
);
}
}
| Fix defaults for DeleteIcon message | :wrench: Fix defaults for DeleteIcon message
| JavaScript | mit | JasonEtco/flintcms,JasonEtco/flintcms | ---
+++
@@ -6,9 +6,13 @@
export default class DeleteIcon extends Component {
static propTypes = {
onClick: PropTypes.func.isRequired,
- message: PropTypes.string.isRequired,
+ message: PropTypes.string,
dispatch: PropTypes.func.isRequired,
- };
+ }
+
+ static defaultProps = {
+ message: undefined,
+ }
constructor(props) {
super(props);
@@ -27,7 +31,7 @@
render() {
return (
- <button className="table__delete" onClick={this.onClick}><Icon icon="circleWithLine" /></button>
+ <button type="button" className="table__delete" onClick={this.onClick}><Icon icon="circleWithLine" /></button>
);
}
} |
aadce336447569e40160034e87fa3e674540239d | routes/api.js | routes/api.js | var express = require('express');
_ = require('underscore')._
var request = require('request');
var router = express.Router({mergeParams: true});
var exec = require('child_process').exec;
var path = require('path');
var parentDir = path.resolve(process.cwd());
var jsonStream = require('express-jsonstream');
router.get('/', function(req, res, next) {
res.json({'info' : 'This is the ControCurator API v0.1'});
});
router.post('/',function(req,res) {
req.jsonStream()
.on('object',console.log);
return;
var input = req.body;
var amountofitems = input.length;
var gooditems = 0;
var baditems = 0;
for (var i=0; i < amountofitems; i++)
{
var currentitem = input[i];
if (!currentitem.hasOwnProperty('id') || !currentitem.hasOwnProperty('text')) //Test for an id and an actual body
{
baditems++;
continue;
}
gooditems++;
}
var controscore = Math.random();
res.json({'controversy':controscore,'totalItems':amountofitems,'goodItems':gooditems,'badItems':baditems});
});
module.exports = router;
| var express = require('express');
_ = require('underscore')._
var request = require('request');
var router = express.Router({mergeParams: true});
var exec = require('child_process').exec;
var path = require('path');
var parentDir = path.resolve(process.cwd());
router.get('/', function(req, res, next) {
res.json({'info' : 'This is the ControCurator API v0.1'});
});
router.post('/',function(req,res) {
var input = req.body;
var amountofitems = input.length;
var gooditems = 0;
var baditems = 0;
for (var i=0; i < amountofitems; i++)
{
var currentitem = input[i];
if (!currentitem.hasOwnProperty('id') || !currentitem.hasOwnProperty('text')) //Test for an id and an actual body
{
baditems++;
continue;
}
gooditems++;
}
var controscore = Math.random();
res.json({'controversy':controscore,'totalItems':amountofitems,'goodItems':gooditems,'badItems':baditems});
});
module.exports = router;
| Revert back to limited situation | Revert back to limited situation
| JavaScript | mit | ControCurator/controcurator,ControCurator/controcurator,ControCurator/controcurator | ---
+++
@@ -6,19 +6,12 @@
var path = require('path');
var parentDir = path.resolve(process.cwd());
-var jsonStream = require('express-jsonstream');
-
router.get('/', function(req, res, next) {
res.json({'info' : 'This is the ControCurator API v0.1'});
});
router.post('/',function(req,res) {
- req.jsonStream()
- .on('object',console.log);
- return;
-
-
var input = req.body;
var amountofitems = input.length;
|
2268bfb7be50412878eaa38627ab0a06c981aef8 | assets/js/EditorApp.js | assets/js/EditorApp.js | var innerInitialize = function() {
console.log("It's the editor, man");
} | $(document).ready(function() {
innerInitialize();
});
var innerInitialize = function() {
// Create the canvas and context
initCanvas($(window).width(), $(window).height());
// initialize the camera
camera = new Camera();
} | Create the canvas on editor start | Create the canvas on editor start
| JavaScript | mit | Tactique/jswars | ---
+++
@@ -1,3 +1,10 @@
+$(document).ready(function() {
+ innerInitialize();
+});
+
var innerInitialize = function() {
- console.log("It's the editor, man");
+ // Create the canvas and context
+ initCanvas($(window).width(), $(window).height());
+ // initialize the camera
+ camera = new Camera();
} |
77f69e6f30817e31a34203cce6dbdbdc6eed86dd | server/app.js | server/app.js | // node dependencies
var express = require('express');
var db = require('./db');
var passport = require('passport');
var morgan = require('morgan');
var parser = require('body-parser');
// custom dependencies
var db = require('../db/Listings.js');
var db = require('../db/Users.js');
var db = require('../db/Categories.js');
// use middleware
server.use(session({
secret: 'hackyhackifiers',
resave: false,
saveUninitialized: true
}));
server.use(passport.initialize());
server.use(passport.session());
// Router
var app = express();
// configure passport
// passport.use(new LocalStrategy(User.authenticate()));
// passport.serializeUser(User.serializeUser());
// passport.deserializeUser(User.deserializeUser());
// Set what we are listening on.
app.set('port', 3000);
// Logging and parsing
app.use(morgan('dev'));
app.use(parser.json());
// Set up and use our routes
// app.use('/', router);
// var router = require('./routes.js');
// Serve the client files
app.use(express.static(__dirname + '/../client'));
// If we are being run directly, run the server.
if (!module.parent) {
app.listen(app.get('port'));
console.log('Listening on', app.get('port'));
}
module.exports.app = app;
| // node dependencies
var express = require('express');
var session = require('express-session');
var passport = require('passport');
var morgan = require('morgan');
var parser = require('body-parser');
// custom dependencies
var db = require('../db/db.js');
// var db = require('../db/Listings.js');
// var db = require('../db/Users.js');
// var db = require('../db/Categories.js');
var app = express();
// use middleware
app.use(session({
secret: 'hackyhackifiers',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// Router
// configure passport
// passport.use(new LocalStrategy(User.authenticate()));
// passport.serializeUser(User.serializeUser());
// passport.deserializeUser(User.deserializeUser());
// Set what we are listening on.
app.set('port', 3000);
// Logging and parsing
app.use(morgan('dev'));
app.use(parser.json());
// Set up and use our routes
// app.use('/', router);
// var router = require('./routes.js');
// Serve the client files
app.use(express.static(__dirname + '/../client'));
// If we are being run directly, run the server.
if (!module.parent) {
app.listen(app.get('port'));
console.log('Listening on', app.get('port'));
}
module.exports.app = app;
| Fix db-connect commit (to working server state!) | Fix db-connect commit (to working server state!)
- Note: eventually, the node directive that requires 'db.js' will be
replaced by the commented out directives that require the
Listings/Users/Categories models.
| JavaScript | mit | aphavichitr/hackifieds,glistening-gibus/hackifieds,Hackifieds/hackifieds,glistening-gibus/hackifieds,Hackifieds/hackifieds,glistening-gibus/hackifieds,aphavichitr/hackifieds | ---
+++
@@ -1,29 +1,29 @@
// node dependencies
var express = require('express');
-
-var db = require('./db');
+var session = require('express-session');
var passport = require('passport');
var morgan = require('morgan');
var parser = require('body-parser');
// custom dependencies
-var db = require('../db/Listings.js');
-var db = require('../db/Users.js');
-var db = require('../db/Categories.js');
+var db = require('../db/db.js');
+// var db = require('../db/Listings.js');
+// var db = require('../db/Users.js');
+// var db = require('../db/Categories.js');
+
+var app = express();
// use middleware
-server.use(session({
+app.use(session({
secret: 'hackyhackifiers',
resave: false,
saveUninitialized: true
}));
-server.use(passport.initialize());
-server.use(passport.session());
+app.use(passport.initialize());
+app.use(passport.session());
// Router
-
-var app = express();
// configure passport
// passport.use(new LocalStrategy(User.authenticate())); |
a394119b4badf2fda57fa48989bff0e9810b7c79 | server-dev.js | server-dev.js | import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.babel';
import open from 'open';
const webpackServer = new WebpackDevServer(webpack(config), config.devServer);
webpackServer.listen(config.port, 'localhost', (err) => {
if (err) {
console.log(err);
}
console.log(`Listening at localhost: ${config.devServer.port}`);
console.log('Opening your system browser...');
open(`http://localhost:${config.devServer.port}/webpack-dev-server/`);
});
| /* eslint no-console: 0 */
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.babel';
import open from 'open';
const webpackServer = new WebpackDevServer(webpack(config), config.devServer);
webpackServer.listen(config.port, 'localhost', (err) => {
if (err) {
console.log(err);
}
console.log(`Listening at localhost: ${config.devServer.port}`);
console.log('Opening your system browser...');
open(`http://localhost:${config.devServer.port}/webpack-dev-server/`);
});
| Allow console.log statement in server | Allow console.log statement in server
| JavaScript | mit | frostney/react-app-starterkit,frostney/react-app-starterkit | ---
+++
@@ -1,3 +1,5 @@
+/* eslint no-console: 0 */
+
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.babel'; |
061c79c86dec927d07c9566f982c9909abfbccad | app/rollDataRefresher.js | app/rollDataRefresher.js | const i = require('itemDataRefresher.js');
fateBus.subscribe(module, 'fate.configurationLoaded', function(topic, configuration) {
new i.ItemDataRefresher('roll', configuration.shaderDataTSV)
});
| const i = require('itemDataRefresher.js');
fateBus.subscribe(module, 'fate.configurationLoaded', function(topic, configuration) {
new i.ItemDataRefresher('roll', configuration.rollDataTSV)
});
| Use the right TSV data source | Use the right TSV data source
| JavaScript | mit | rslifka/fate_of_all_fools,rslifka/fate_of_all_fools | ---
+++
@@ -1,5 +1,5 @@
const i = require('itemDataRefresher.js');
fateBus.subscribe(module, 'fate.configurationLoaded', function(topic, configuration) {
- new i.ItemDataRefresher('roll', configuration.shaderDataTSV)
+ new i.ItemDataRefresher('roll', configuration.rollDataTSV)
}); |
c313bafe3cf063cf0f32318363050f4cce43afae | www/cdvah/js/app.js | www/cdvah/js/app.js |
var myApp = angular.module('CordovaAppHarness', ['ngRoute']);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'views/list.html',
controller: 'ListCtrl'
});
$routeProvider.when('/add', {
templateUrl: 'views/add.html',
controller: 'AddCtrl'
});
$routeProvider.when('/edit/:appId', {
templateUrl: 'views/add.html',
controller: 'AddCtrl'
});
$routeProvider.when('/details/:index', {
templateUrl: 'views/details.html',
controller: 'DetailsCtrl'
});
}]);
// foo
document.addEventListener('deviceready', function() {
cordova.plugins.fileextras.getDataDirectory(false, function(dirEntry) {
var path = dirEntry.fullPath;
myApp.value('INSTALL_DIRECTORY', path + '/apps');
myApp.value('APPS_JSON', path + '/apps.json');
myApp.factory('UrlCleanup', function() {
return function(url) {
url = url.replace(/\/$/, '').replace(new RegExp(cordova.platformId + '$'), '').replace(/\/$/, '');
if (!/^[a-z]+:/.test(url)) {
url = 'http://' + url;
}
return url;
};
});
angular.bootstrap(document, ['CordovaAppHarness']);
});
}, false);
|
var myApp = angular.module('CordovaAppHarness', ['ngRoute']);
myApp.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'views/list.html',
controller: 'ListCtrl'
});
$routeProvider.when('/add', {
templateUrl: 'views/add.html',
controller: 'AddCtrl'
});
$routeProvider.when('/edit/:appId', {
templateUrl: 'views/add.html',
controller: 'AddCtrl'
});
$routeProvider.when('/details/:index', {
templateUrl: 'views/details.html',
controller: 'DetailsCtrl'
});
}]);
// foo
document.addEventListener('deviceready', function() {
cordova.filesystem.getDataDirectory(false, function(dirEntry) {
var path = dirEntry.fullPath;
myApp.value('INSTALL_DIRECTORY', path + '/apps');
myApp.value('APPS_JSON', path + '/apps.json');
myApp.factory('UrlCleanup', function() {
return function(url) {
url = url.replace(/\/$/, '').replace(new RegExp(cordova.platformId + '$'), '').replace(/\/$/, '');
if (!/^[a-z]+:/.test(url)) {
url = 'http://' + url;
}
return url;
};
});
angular.bootstrap(document, ['CordovaAppHarness']);
});
}, false);
| Use updated symbol path for file-system-roots plugin | Use updated symbol path for file-system-roots plugin
| JavaScript | apache-2.0 | guozanhua/chrome-app-developer-tool,apache/cordova-app-harness,guozanhua/chrome-app-developer-tool,feedhenry/cordova-app-harness,feedhenry/cordova-app-harness,apache/cordova-app-harness,apache/cordova-app-harness,feedhenry/cordova-app-harness,guozanhua/chrome-app-developer-tool,apache/cordova-app-harness,guozanhua/chrome-app-developer-tool,feedhenry/cordova-app-harness | ---
+++
@@ -23,7 +23,7 @@
// foo
document.addEventListener('deviceready', function() {
- cordova.plugins.fileextras.getDataDirectory(false, function(dirEntry) {
+ cordova.filesystem.getDataDirectory(false, function(dirEntry) {
var path = dirEntry.fullPath;
myApp.value('INSTALL_DIRECTORY', path + '/apps');
myApp.value('APPS_JSON', path + '/apps.json'); |
00a621ec5e411bf070d789c8f7a6344b30986844 | main.start.js | main.start.js | //electron entry-point
const REACT_DEVELOPER_TOOLS = require('electron-devtools-installer').REACT_DEVELOPER_TOOLS;
var installExtension = require('electron-devtools-installer').default;
var app = require('electron').app;
var BrowserWindow = require('electron').BrowserWindow;
var path = require( "path" );
if (process.env.NODE_ENV === 'development') {
require('electron-debug')(); // eslint-disable-line global-require
}
app.on('ready',function() {
installExtension(REACT_DEVELOPER_TOOLS)
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log('An error occurred: ', err));
var mainWindow = new BrowserWindow({
width: 1200,
height: 600
});
mainWindow.loadURL('file://' + __dirname + '/src/index-electron.html');
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.show();
mainWindow.focus();
});
mainWindow.on('closed', () => {
mainWindow = null;
});
if (process.env.NODE_ENV === 'development') {
mainWindow.openDevTools();
}
});
| //electron entry-point
var app = require('electron').app;
var BrowserWindow = require('electron').BrowserWindow;
var path = require( "path" );
if (process.env.NODE_ENV === 'development') {
require('electron-debug')(); // eslint-disable-line global-require
}
app.on('ready',function() {
if(process.env.NODE_ENV === 'development') {
const REACT_DEVELOPER_TOOLS = require('electron-devtools-installer').REACT_DEVELOPER_TOOLS;
var installExtension = require('electron-devtools-installer').default;
installExtension(REACT_DEVELOPER_TOOLS)
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log('An error occurred: ', err));
}
var mainWindow = new BrowserWindow({
width: 1200,
height: 600
});
mainWindow.loadURL('file://' + __dirname + '/src/index-electron.html');
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.show();
mainWindow.focus();
});
mainWindow.on('closed', () => {
mainWindow = null;
});
if (process.env.NODE_ENV === 'development') {
mainWindow.openDevTools();
}
});
| Load react-devtools in dev env only | Load react-devtools in dev env only
| JavaScript | mit | cynicaldevil/gitrobotic,cynicaldevil/gitrobotic | ---
+++
@@ -1,7 +1,4 @@
//electron entry-point
-
-const REACT_DEVELOPER_TOOLS = require('electron-devtools-installer').REACT_DEVELOPER_TOOLS;
-var installExtension = require('electron-devtools-installer').default;
var app = require('electron').app;
var BrowserWindow = require('electron').BrowserWindow;
var path = require( "path" );
@@ -12,9 +9,13 @@
app.on('ready',function() {
-installExtension(REACT_DEVELOPER_TOOLS)
+if(process.env.NODE_ENV === 'development') {
+ const REACT_DEVELOPER_TOOLS = require('electron-devtools-installer').REACT_DEVELOPER_TOOLS;
+ var installExtension = require('electron-devtools-installer').default;
+ installExtension(REACT_DEVELOPER_TOOLS)
.then((name) => console.log(`Added Extension: ${name}`))
.catch((err) => console.log('An error occurred: ', err));
+}
var mainWindow = new BrowserWindow({
width: 1200, |
67b10db38f23873d832009c29519b57fb1e769e2 | blueocean-web/gulpfile.js | blueocean-web/gulpfile.js | //
// See https://github.com/jenkinsci/js-builder
//
var builder = require('@jenkins-cd/js-builder');
// Disable js-builder based linting for now.
// Will get fixed with https://github.com/cloudbees/blueocean/pull/55
builder.lint('none');
//
// Create the main "App" bundle.
// generateNoImportsBundle makes it easier to test with zombie.
//
builder.bundle('src/main/js/blueocean.js')
.withExternalModuleMapping('jquery-detached', 'jquery-detached:jquery2')
.inDir('target/classes/io/jenkins/blueocean')
.less('src/main/less/blueocean.less')
.generateNoImportsBundle();
| //
// See https://github.com/jenkinsci/js-builder
//
var builder = require('@jenkins-cd/js-builder');
// Disable js-builder based linting for now.
// Will get fixed with https://github.com/cloudbees/blueocean/pull/55
builder.lint('none');
// Explicitly setting the src paths in order to allow the rebundle task to
// watch for changes in the JDL (js, css, icons etc).
// See https://github.com/jenkinsci/js-builder#setting-src-and-test-spec-paths
builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language']);
//
// Create the main "App" bundle.
// generateNoImportsBundle makes it easier to test with zombie.
//
builder.bundle('src/main/js/blueocean.js')
.withExternalModuleMapping('jquery-detached', 'jquery-detached:jquery2')
.inDir('target/classes/io/jenkins/blueocean')
.less('src/main/less/blueocean.less')
.generateNoImportsBundle();
| Watch for changes in the JDL package (rebundle) | Watch for changes in the JDL package (rebundle)
| JavaScript | mit | ModuloM/blueocean-plugin,kzantow/blueocean-plugin,jenkinsci/blueocean-plugin,tfennelly/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,kzantow/blueocean-plugin,jenkinsci/blueocean-plugin,tfennelly/blueocean-plugin,ModuloM/blueocean-plugin,alvarolobato/blueocean-plugin,kzantow/blueocean-plugin,jenkinsci/blueocean-plugin,tfennelly/blueocean-plugin,alvarolobato/blueocean-plugin,alvarolobato/blueocean-plugin,ModuloM/blueocean-plugin,ModuloM/blueocean-plugin,kzantow/blueocean-plugin,alvarolobato/blueocean-plugin,tfennelly/blueocean-plugin | ---
+++
@@ -6,6 +6,11 @@
// Disable js-builder based linting for now.
// Will get fixed with https://github.com/cloudbees/blueocean/pull/55
builder.lint('none');
+
+// Explicitly setting the src paths in order to allow the rebundle task to
+// watch for changes in the JDL (js, css, icons etc).
+// See https://github.com/jenkinsci/js-builder#setting-src-and-test-spec-paths
+builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language']);
//
// Create the main "App" bundle. |
80a8734522b5aaaf12ff2fb4e1f93500bd33b423 | src/Backdrop.js | src/Backdrop.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, StyleSheet, TouchableWithoutFeedback, Animated } from 'react-native';
import { OPEN_ANIM_DURATION, CLOSE_ANIM_DURATION } from './constants';
class Backdrop extends Component {
constructor(...args) {
super(...args);
this.fadeAnim = new Animated.Value(0.001);
}
open() {
return new Promise(resolve => {
Animated.timing(this.fadeAnim, {
duration: OPEN_ANIM_DURATION,
toValue: 1,
useNativeDriver: true,
}).start(resolve);
});
}
close() {
return new Promise(resolve => {
Animated.timing(this.fadeAnim, {
duration: CLOSE_ANIM_DURATION,
toValue: 0,
useNativeDriver: true,
}).start(resolve);
});
}
render() {
const { onPress, style } = this.props;
return (
<TouchableWithoutFeedback onPress={onPress}>
<Animated.View style={[styles.fullscreen, { opacity: this.fadeAnim }]}>
<View style={[styles.fullscreen, style]} />
</Animated.View>
</TouchableWithoutFeedback>
);
}
}
Backdrop.propTypes = {
onPress: PropTypes.func.isRequired,
};
const styles = StyleSheet.create({
fullscreen: {
opacity: 0,
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
},
});
export default Backdrop;
| import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, StyleSheet, TouchableWithoutFeedback, Animated, Platform } from 'react-native';
import { OPEN_ANIM_DURATION, CLOSE_ANIM_DURATION } from './constants';
class Backdrop extends Component {
constructor(...args) {
super(...args);
this.fadeAnim = new Animated.Value(0.001);
}
open() {
return new Promise(resolve => {
Animated.timing(this.fadeAnim, {
duration: OPEN_ANIM_DURATION,
toValue: 1,
useNativeDriver: (Platform.OS !== "web"),
}).start(resolve);
});
}
close() {
return new Promise(resolve => {
Animated.timing(this.fadeAnim, {
duration: CLOSE_ANIM_DURATION,
toValue: 0,
useNativeDriver: (Platform.OS !== "web"),
}).start(resolve);
});
}
render() {
const { onPress, style } = this.props;
return (
<TouchableWithoutFeedback onPress={onPress}>
<Animated.View style={[styles.fullscreen, { opacity: this.fadeAnim }]}>
<View style={[styles.fullscreen, style]} />
</Animated.View>
</TouchableWithoutFeedback>
);
}
}
Backdrop.propTypes = {
onPress: PropTypes.func.isRequired,
};
const styles = StyleSheet.create({
fullscreen: {
opacity: 0,
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
},
});
export default Backdrop;
| Fix web warning about useNativeDriver | Fix web warning about useNativeDriver
| JavaScript | isc | instea/react-native-popup-menu | ---
+++
@@ -1,6 +1,6 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
-import { View, StyleSheet, TouchableWithoutFeedback, Animated } from 'react-native';
+import { View, StyleSheet, TouchableWithoutFeedback, Animated, Platform } from 'react-native';
import { OPEN_ANIM_DURATION, CLOSE_ANIM_DURATION } from './constants';
class Backdrop extends Component {
@@ -15,7 +15,7 @@
Animated.timing(this.fadeAnim, {
duration: OPEN_ANIM_DURATION,
toValue: 1,
- useNativeDriver: true,
+ useNativeDriver: (Platform.OS !== "web"),
}).start(resolve);
});
}
@@ -25,7 +25,7 @@
Animated.timing(this.fadeAnim, {
duration: CLOSE_ANIM_DURATION,
toValue: 0,
- useNativeDriver: true,
+ useNativeDriver: (Platform.OS !== "web"),
}).start(resolve);
});
} |
48b03917df05a8c9892a3340d93ba4b92b16b81c | client/config/environment.js | client/config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'client',
environment: environment,
baseURL: '/',
locationType: 'auto',
'ember-simple-auth-token': {
serverTokenEndpoint: 'http://localhost:8080/api-token-auth/',
serverTokenRefreshEndpoint: 'http://localhost:8080/api-token-refresh/',
refreshLeeway: 20
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'client',
environment: environment,
baseURL: '/',
locationType: 'auto',
'ember-simple-auth-token': {
serverTokenEndpoint: 'http://localhost:8080/api-token-auth/',
serverTokenRefreshEndpoint: 'http://localhost:8080/api-token-refresh/',
refreshLeeway: 20,
timeFactor: 1000, // backend is in seconds and the frontend is in ms.
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| Adjust the time factor to align frontent and backend auth. | Adjust the time factor to align frontent and backend auth.
Fixes #27
| JavaScript | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp | ---
+++
@@ -10,7 +10,8 @@
'ember-simple-auth-token': {
serverTokenEndpoint: 'http://localhost:8080/api-token-auth/',
serverTokenRefreshEndpoint: 'http://localhost:8080/api-token-refresh/',
- refreshLeeway: 20
+ refreshLeeway: 20,
+ timeFactor: 1000, // backend is in seconds and the frontend is in ms.
},
EmberENV: { |
9d19611474e61db68fcf2f7b9ee8505fea59092e | src/Camera.js | src/Camera.js | /**
* @depends MatrixStack.js
*/
var Camera = new Class({
initialize: function() {
this.projection = new MatrixStack();
this.modelview = new MatrixStack();
},
perspective: function(fovy, aspect, near, far) {
mat4.perspective(fovy, aspect, near, far, this.projection);
},
ortho: function(left, right, top, bottom, near, far) {
mat4.ortho(left, right, top, bottom, near, far, this.projection);
},
lookAt: function(eye, center, up) {
mat4.lookAt(eye, center, up, this.modelview);
}
});
| /**
* @depends MatrixStack.js
*/
var Camera = new Class({
initialize: function() {
this.projection = new MatrixStack();
this.modelview = new MatrixStack();
},
perspective: function(fovy, aspect, near, far) {
mat4.perspective(fovy, aspect, near, far, this.projection.matrix);
},
ortho: function(left, right, top, bottom, near, far) {
mat4.ortho(left, right, top, bottom, near, far, this.projection.matrix);
},
lookAt: function(eye, center, up) {
mat4.lookAt(eye, center, up, this.modelview.matrix);
}
});
| Make camera function actually affect the matrices | Make camera function actually affect the matrices
| JavaScript | mit | oampo/webglet | ---
+++
@@ -8,14 +8,14 @@
},
perspective: function(fovy, aspect, near, far) {
- mat4.perspective(fovy, aspect, near, far, this.projection);
+ mat4.perspective(fovy, aspect, near, far, this.projection.matrix);
},
ortho: function(left, right, top, bottom, near, far) {
- mat4.ortho(left, right, top, bottom, near, far, this.projection);
+ mat4.ortho(left, right, top, bottom, near, far, this.projection.matrix);
},
lookAt: function(eye, center, up) {
- mat4.lookAt(eye, center, up, this.modelview);
+ mat4.lookAt(eye, center, up, this.modelview.matrix);
}
}); |
1a3aeafe8f22d5e80276a7e0caaae99a274f2641 | Analyser/src/External.js | Analyser/src/External.js | /* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */
"use strict";
/**
* This is a function that detects whether we are using Electron and
* if so does a remote call through IPC rather than a direct require.
*/
const ELECTRON_PATH_MAGIC = '/electron/';
export default function (library) {
let lrequire = require;
if (process && process.execPath && process.execPath.indexOf(ELECTRON_PATH_MAGIC) != -1) {
lrequire = require('electron').remote.require;
}
const result = lrequire(library);
return result.default ? result.default : result;
} | /* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */
"use strict";
export default function (library) {
return require(library);
}
| Remove external electron link as we're rethinking that for now | Remove external electron link as we're rethinking that for now
| JavaScript | mit | ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE | ---
+++
@@ -2,21 +2,6 @@
"use strict";
-/**
- * This is a function that detects whether we are using Electron and
- * if so does a remote call through IPC rather than a direct require.
- */
-
- const ELECTRON_PATH_MAGIC = '/electron/';
-
export default function (library) {
- let lrequire = require;
-
- if (process && process.execPath && process.execPath.indexOf(ELECTRON_PATH_MAGIC) != -1) {
- lrequire = require('electron').remote.require;
- }
-
- const result = lrequire(library);
-
- return result.default ? result.default : result;
+ return require(library);
} |
fa09a1300bb527ad8c804e06bc33edc1b9213ea4 | test/integration-test.js | test/integration-test.js | var injection = require('../services/injection.js');
var Q = require('q');
var mongoose = require('mongoose');
module.exports = function (test, fixtureName, testFn) {
var dbUrl = 'mongodb://localhost:27017/' + fixtureName;
var cleanUp = function () {
return Q.nbind(mongoose.connect, mongoose)(dbUrl).then(function () {
var db = mongoose.connection.db;
return Q.nbind(db.dropDatabase, db)().then(function () {
db.close();
});
});
};
cleanUp().then(function () {
var allcountServer = require('../allcount-server.js');
injection.resetInjection();
injection.bindFactory('port', 9080);
injection.bindFactory('dbUrl', dbUrl);
injection.bindFactory('gitRepoUrl', 'test-fixtures/' + fixtureName);
allcountServer.reconfigureAllcount();
return allcountServer.inject('allcountServerStartup');
}).then(function (server) {
return Q.nbind(server.startup, server)().then(function (errors) {
if (errors) {
throw new Error(errors.join('\n'));
}
return Q(testFn()).then(function () {
return server.stop().then(function () {
injection.resetInjection();
});
});
});
}).finally(cleanUp).done(function () {
test.done();
});
}; | var injection = require('../services/injection.js');
var Q = require('q');
var mongoose = require('mongoose');
module.exports = function (test, fixtureName, testFn) {
var dbUrl = 'mongodb://localhost:27017/' + fixtureName;
var cleanUp = function () {
return Q.nbind(mongoose.connect, mongoose)(dbUrl).then(function () {
var db = mongoose.connection.db;
return Q.nbind(db.dropDatabase, db)().then(function () {
db.close();
});
});
};
cleanUp().then(function () {
var allcountServer = require('../allcount-server.js');
injection.resetInjection();
injection.bindFactory('port', 9080);
injection.bindFactory('dbUrl', dbUrl);
injection.bindFactory('gitRepoUrl', 'test-fixtures/' + fixtureName);
allcountServer.reconfigureAllcount();
return allcountServer.inject('allcountServerStartup');
}).then(function (server) {
return Q.nbind(server.startup, server)().then(function (errors) {
if (errors) {
throw new Error(errors.join('\n'));
}
return Q(testFn()).then(function () {
return server.stop().then(function () {
injection.resetInjection();
});
});
});
}).finally(cleanUp).finally(function () {
test.done();
}).done();
}; | Fix endless execution of integration tests | Fix endless execution of integration tests
| JavaScript | mit | allcount/allcountjs,chikh/allcountjs,chikh/allcountjs,allcount/allcountjs | ---
+++
@@ -35,7 +35,7 @@
});
});
});
- }).finally(cleanUp).done(function () {
+ }).finally(cleanUp).finally(function () {
test.done();
- });
+ }).done();
}; |
11c5510b06900c328ff61101bbf11cabf00419c4 | tests/e2e/jest.config.js | tests/e2e/jest.config.js | const path = require( 'path' );
module.exports = {
preset: 'jest-puppeteer',
setupFilesAfterEnv: [
'<rootDir>/config/bootstrap.js',
'@wordpress/jest-console',
'expect-puppeteer',
],
testMatch: [
'<rootDir>/**/*.test.js',
'<rootDir>/specs/**/__tests__/**/*.js',
'<rootDir>/specs/**/?(*.)(spec|test).js',
'<rootDir>/specs/**/test/*.js',
],
transform: {
'^.+\\.[jt]sx?$': path.join( __dirname, 'babel-transform' ),
},
transformIgnorePatterns: [ 'node_modules' ],
testPathIgnorePatterns: [ '.git', 'node_modules' ],
};
| const path = require( 'path' );
module.exports = {
preset: 'jest-puppeteer',
setupFilesAfterEnv: [
'<rootDir>/config/bootstrap.js',
'@wordpress/jest-console',
'expect-puppeteer',
],
testMatch: [
'<rootDir>/**/*.test.js',
'<rootDir>/specs/**/__tests__/**/*.js',
'<rootDir>/specs/**/?(*.)(spec|test).js',
'<rootDir>/specs/**/test/*.js',
],
transform: {
'^.+\\.[jt]sx?$': path.join( __dirname, 'babel-transform' ),
},
transformIgnorePatterns: [ 'node_modules' ],
testPathIgnorePatterns: [ '.git', 'node_modules' ],
verbose: true,
};
| Add verbose option to E2E tests. | Add verbose option to E2E tests.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -18,4 +18,5 @@
},
transformIgnorePatterns: [ 'node_modules' ],
testPathIgnorePatterns: [ '.git', 'node_modules' ],
+ verbose: true,
}; |
0ab42696086c681302a2718f89b557bbe40442e8 | src/foam/u2/HTMLElement.js | src/foam/u2/HTMLElement.js | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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
*/
foam.CLASS({
package: 'foam.u2',
name: 'HTMLValidator',
extends: 'foam.u2.DefaultValidator',
axioms: [ foam.pattern.Singleton.create() ],
methods: [
function sanitizeText(text) {
// TODO: validate text
return text;
}
]
});
// An Element which does not escape HTML content
foam.CLASS({
package: 'foam.u2',
name: 'HTMLElement',
extends: 'foam.u2.Element',
exports: [ 'validator as elementValidator' ],
properties: [
{
class: 'Proxy',
of: 'foam.u2.DefaultValidator',
name: 'validator',
value: foam.u2.HTMLValidator.create()
}
]
});
| /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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
*/
foam.CLASS({
package: 'foam.u2',
name: 'HTMLValidator',
extends: 'foam.u2.DefaultValidator',
axioms: [ foam.pattern.Singleton.create() ],
methods: [
function sanitizeText(text) {
// TODO: validate text
return text;
}
]
});
// An Element which does not escape HTML content
foam.CLASS({
package: 'foam.u2',
name: 'HTMLElement',
extends: 'foam.u2.Element',
requires: [ 'foam.u2.HTMLValidator' ],
exports: [ 'validator as elementValidator' ],
properties: [
{
class: 'Proxy',
of: 'foam.u2.DefaultValidator',
name: 'validator',
factory: function() { return this.HTMLValidator.create() }
}
]
});
| Use a factory instead of creating an HTMLValidator inline. | Use a factory instead of creating an HTMLValidator inline.
| JavaScript | apache-2.0 | foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm | ---
+++
@@ -31,6 +31,8 @@
name: 'HTMLElement',
extends: 'foam.u2.Element',
+ requires: [ 'foam.u2.HTMLValidator' ],
+
exports: [ 'validator as elementValidator' ],
properties: [
@@ -38,7 +40,7 @@
class: 'Proxy',
of: 'foam.u2.DefaultValidator',
name: 'validator',
- value: foam.u2.HTMLValidator.create()
+ factory: function() { return this.HTMLValidator.create() }
}
]
}); |
fee641c22a50f685055139a8abb34a6a6159378e | src/js/index.js | src/js/index.js | require("../scss/index.scss");
var React = require('react');
var Locale = require('grommet/utils/Locale');
var Cabler = require('./components/Cabler');
var locale = Locale.getCurrentLocale();
var localeData;
try {
localeData = Locale.getLocaleData(require('../messages/' + locale));
} catch (e) {
localeData = Locale.getLocaleData(require('../messages/en-US'));
}
var element = document.getElementById('content');
React.render(React.createElement(Cabler, {locales: localeData.locale, messages: localeData.messages}), element);
document.body.classList.remove('loading');
| require("../scss/index.scss");
var React = require('react');
var ReactDOM = require('react-dom');
var Locale = require('grommet/utils/Locale');
var Cabler = require('./components/Cabler');
var locale = Locale.getCurrentLocale();
var localeData;
try {
localeData = Locale.getLocaleData(require('../messages/' + locale));
} catch (e) {
localeData = Locale.getLocaleData(require('../messages/en-US'));
}
var element = document.getElementById('content');
ReactDOM.render(React.createElement(Cabler, {locales: localeData.locale, messages: localeData.messages}), element);
document.body.classList.remove('loading');
| Use react-dom package for rendering application | Use react-dom package for rendering application
| JavaScript | apache-2.0 | grommet/grommet-cabler,grommet/grommet-cabler | ---
+++
@@ -1,6 +1,7 @@
require("../scss/index.scss");
var React = require('react');
+var ReactDOM = require('react-dom');
var Locale = require('grommet/utils/Locale');
var Cabler = require('./components/Cabler');
@@ -13,6 +14,6 @@
}
var element = document.getElementById('content');
-React.render(React.createElement(Cabler, {locales: localeData.locale, messages: localeData.messages}), element);
+ReactDOM.render(React.createElement(Cabler, {locales: localeData.locale, messages: localeData.messages}), element);
document.body.classList.remove('loading'); |
dadee563a1ea459c588b1507a4a98078e20d0dc6 | javascript/cucumber-blanket.js | javascript/cucumber-blanket.js | (function (){
/* ADAPTER
*
* This blanket.js adapter is designed to autostart coverage
* immediately. The other side of this is handled from Cucumber
*
* Required blanket commands:
* blanket.setupCoverage(); // Do it ASAP
* blanket.onTestStart(); // Do it ASAP
* blanket.onTestDone(); // After Scenario Hook
* blanket.onTestsDone(); // After Scenario Hook
*/
blanket.beforeStartTestRunner({
callback: function() {
blanket.setupCoverage();
blanket.onTestStart();
}
});
/* REPORTER
*
* Blanket.js docs speak of blanket.customReporter but
* that doesn't actually work so we'll override defaultReporter
*/
blanket.defaultReporter = function(coverage_results){
window.COVERAGE_RESULTS = coverage_results; // We'll grab this on selenium side
};
})();
| (function (){
/* ADAPTER
*
* This blanket.js adapter is designed to autostart coverage
* immediately. The other side of this is handled from Cucumber
*
* Required blanket commands:
* blanket.setupCoverage(); // Do it ASAP
* blanket.onTestStart(); // Do it ASAP
* blanket.onTestDone(); // After Scenario Hook (Not necessary)
* blanket.onTestsDone(); // After Scenario Hook
*/
blanket.beforeStartTestRunner({
callback: function() {
blanket.setupCoverage();
blanket.onTestStart();
window.CUCUMBER_BLANKET = {
files: {},
sources: {},
done: false,
is_setup: true
};
}
});
/* REPORTER
*
* Blanket.js docs speak of blanket.customReporter but
* that doesn't actually work so we'll override defaultReporter
*/
blanket.defaultReporter = function(coverage_results){
window.CUCUMBER_BLANKET.files = coverage_results.files;
// Strangely enough it looks like we need to iterate in order to grab the `source`
// data which is necessary to know which lines of code are being reported on.
var files = Object.keys(coverage_results.files);
for (var i = 0, l = files.length; i < l; i ++) {
var file = files[i];
window.CUCUMBER_BLANKET.sources[file] = window.CUCUMBER_BLANKET.files[file].source;
}
window.CUCUMBER_BLANKET.done = true;
// Now we can grab all this on the selenium side through window.CUCUMBER_BLANKET
};
})();
| Update javascript blanket adapter to include sources data. | Update javascript blanket adapter to include sources data. | JavaScript | mit | vemperor/capybara-blanket,kfatehi/cucumber-blanket,kfatehi/cucumber-blanket,keyvanfatehi/cucumber-blanket,keyvanfatehi/cucumber-blanket | ---
+++
@@ -7,7 +7,7 @@
* Required blanket commands:
* blanket.setupCoverage(); // Do it ASAP
* blanket.onTestStart(); // Do it ASAP
- * blanket.onTestDone(); // After Scenario Hook
+ * blanket.onTestDone(); // After Scenario Hook (Not necessary)
* blanket.onTestsDone(); // After Scenario Hook
*/
@@ -15,6 +15,12 @@
callback: function() {
blanket.setupCoverage();
blanket.onTestStart();
+ window.CUCUMBER_BLANKET = {
+ files: {},
+ sources: {},
+ done: false,
+ is_setup: true
+ };
}
});
@@ -25,6 +31,16 @@
* that doesn't actually work so we'll override defaultReporter
*/
blanket.defaultReporter = function(coverage_results){
- window.COVERAGE_RESULTS = coverage_results; // We'll grab this on selenium side
+ window.CUCUMBER_BLANKET.files = coverage_results.files;
+ // Strangely enough it looks like we need to iterate in order to grab the `source`
+ // data which is necessary to know which lines of code are being reported on.
+ var files = Object.keys(coverage_results.files);
+ for (var i = 0, l = files.length; i < l; i ++) {
+ var file = files[i];
+ window.CUCUMBER_BLANKET.sources[file] = window.CUCUMBER_BLANKET.files[file].source;
+ }
+ window.CUCUMBER_BLANKET.done = true;
+ // Now we can grab all this on the selenium side through window.CUCUMBER_BLANKET
};
})();
+ |
a37ea675122ca7da96a84090aa86f7e7eaa038d4 | src/lib/get-costume-url.js | src/lib/get-costume-url.js | import storage from './storage';
import {SVGRenderer} from 'scratch-svg-renderer';
// Contains 'font-family', but doesn't only contain 'font-family="none"'
const HAS_FONT_REGEXP = 'font-family(?!="none")';
const getCostumeUrl = (function () {
let cachedAssetId;
let cachedUrl;
return function (asset) {
if (cachedAssetId === asset.assetId) {
return cachedUrl;
}
cachedAssetId = asset.assetId;
// If the SVG refers to fonts, they must be inlined in order to display correctly in the img tag.
// Avoid parsing the SVG when possible, since it's expensive.
if (asset.assetType === storage.AssetType.ImageVector) {
const svgString = asset.decodeText();
if (svgString.match(HAS_FONT_REGEXP)) {
const svgRenderer = new SVGRenderer();
svgRenderer.loadString(svgString);
const svgText = svgRenderer.toString(true /* shouldInjectFonts */);
cachedUrl = `data:image/svg+xml;utf8,${encodeURIComponent(svgText)}`;
} else {
cachedUrl = asset.encodeDataURI();
}
} else {
cachedUrl = asset.encodeDataURI();
}
return cachedUrl;
};
}());
export {
getCostumeUrl as default,
HAS_FONT_REGEXP
};
| import storage from './storage';
import {inlineSvgFonts} from 'scratch-svg-renderer';
// Contains 'font-family', but doesn't only contain 'font-family="none"'
const HAS_FONT_REGEXP = 'font-family(?!="none")';
const getCostumeUrl = (function () {
let cachedAssetId;
let cachedUrl;
return function (asset) {
if (cachedAssetId === asset.assetId) {
return cachedUrl;
}
cachedAssetId = asset.assetId;
// If the SVG refers to fonts, they must be inlined in order to display correctly in the img tag.
// Avoid parsing the SVG when possible, since it's expensive.
if (asset.assetType === storage.AssetType.ImageVector) {
const svgString = asset.decodeText();
if (svgString.match(HAS_FONT_REGEXP)) {
const svgText = inlineSvgFonts(svgString);
cachedUrl = `data:image/svg+xml;utf8,${encodeURIComponent(svgText)}`;
} else {
cachedUrl = asset.encodeDataURI();
}
} else {
cachedUrl = asset.encodeDataURI();
}
return cachedUrl;
};
}());
export {
getCostumeUrl as default,
HAS_FONT_REGEXP
};
| Use fontInliner instead of entire SVGRenderer for showing costume tiles. | Use fontInliner instead of entire SVGRenderer for showing costume tiles.
The fontInliner from the scratch-svg-renderer was changed recently to work entirely on strings, so we can use that instead of parsing/loading/possibly drawing/stringifying the entire SVG.
This does not address the size-1 cache issue where the cache is invalidated any time there is more than 1 sprite. But that can be handled later.
Using the 4x CPU slowdown in chrome dev tools, on a simple costume that just has a single text element the getCostumeUrl time goes from 10ms to 1ms, very important for updating in a timely way.
| JavaScript | bsd-3-clause | LLK/scratch-gui,LLK/scratch-gui | ---
+++
@@ -1,5 +1,5 @@
import storage from './storage';
-import {SVGRenderer} from 'scratch-svg-renderer';
+import {inlineSvgFonts} from 'scratch-svg-renderer';
// Contains 'font-family', but doesn't only contain 'font-family="none"'
const HAS_FONT_REGEXP = 'font-family(?!="none")';
@@ -21,9 +21,7 @@
if (asset.assetType === storage.AssetType.ImageVector) {
const svgString = asset.decodeText();
if (svgString.match(HAS_FONT_REGEXP)) {
- const svgRenderer = new SVGRenderer();
- svgRenderer.loadString(svgString);
- const svgText = svgRenderer.toString(true /* shouldInjectFonts */);
+ const svgText = inlineSvgFonts(svgString);
cachedUrl = `data:image/svg+xml;utf8,${encodeURIComponent(svgText)}`;
} else {
cachedUrl = asset.encodeDataURI(); |
69772952eaa4bbde2a35fc767ac5f496e1c57e99 | src/filter.js | src/filter.js | function hide_covers() {
// Remove covers
$(".mix_element div.cover").remove()
// Add class so cards can be restyled
$(".mix_card.half_card").addClass("ext-coverless_card")
// Remove covers on track page
$("#cover_art").remove()
// Remove covers in the sidebar of a track page
$(".card.sidebar_mix .cover").remove()
$(".card.sidebar_mix").addClass("ext-coverless_card")
}
function filter() {
chrome.storage.local.get("state", function(result) {
if(result["state"] == "on") {
hide_covers()
}
});
}
// Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run
$('#body_container').bind('DOMSubtreeModified',filter);
filter();
| function hide_covers() {
// Remove covers
$(".mix_element div.cover").remove()
// Add class so cards can be restyled
$(".mix_card.half_card").addClass("ext-coverless_card")
// Remove covers on track page
$("#cover_art").remove()
// Remove covers in the sidebar of a track page
$(".card.sidebar_mix .cover").remove()
$(".card.sidebar_mix").addClass("ext-coverless_card")
}
function filter() {
chrome.storage.local.get("state", function(result) {
if(result["state"] == "on") {
hide_covers()
}
});
}
// Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run
var observer = new MutationObserver(filter)
observer.observe(document.getElementById("main"), {childList: true, subtree: true})
filter();
| Use MutationObserver API to catch dom updates | Use MutationObserver API to catch dom updates
| JavaScript | mit | pbhavsar/8tracks-Filter | ---
+++
@@ -19,5 +19,6 @@
});
}
// Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run
-$('#body_container').bind('DOMSubtreeModified',filter);
+var observer = new MutationObserver(filter)
+observer.observe(document.getElementById("main"), {childList: true, subtree: true})
filter(); |
63625631eafd8b8d68bcc213243f8105d76269dd | src/js/app.js | src/js/app.js | // JS Goes here - ES6 supported
if (window.netlifyIdentity) {
window.netlifyIdentity.on('login', () => {
document.location.href = '/admin/';
});
}
| // JS Goes here - ES6 supported
if (window.netlifyIdentity && !window.netlifyIdentity.currentUser()) {
window.netlifyIdentity.on('login', () => {
document.location.href = '/admin/';
});
}
| Fix issue with always redirecting to /admin when logged in | Fix issue with always redirecting to /admin when logged in
| JavaScript | mit | netlify-templates/one-click-hugo-cms,chromicant/blog,doudigit/doudigit.github.io,netlify-templates/one-click-hugo-cms,chromicant/blog,doudigit/doudigit.github.io | ---
+++
@@ -1,5 +1,5 @@
// JS Goes here - ES6 supported
-if (window.netlifyIdentity) {
+if (window.netlifyIdentity && !window.netlifyIdentity.currentUser()) {
window.netlifyIdentity.on('login', () => {
document.location.href = '/admin/';
}); |
b2648c0b5fa32934d24b271fdb050d11d0484c21 | src/index.js | src/index.js | /**
* Detects if only the primary button has been clicked in mouse events.
* @param {MouseEvent} e Event instance (or Event-like, i.e. `SyntheticEvent`)
* @return {Boolean}
*/
export const isPrimaryClick = e =>
!(e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) &&
(("button" in e && e.button === 0) || ("buttons" in e && e.buttons === 1));
/**
* Decorates a function so it calls if only the primary button has been
* pressed in mouse events.
* @param {Function} fn
* @return {Function}
*/
export const onPrimaryClick = fn => e => (isPrimaryClick(e) ? fn(e) : true);
| /**
* Detects if only the primary button has been clicked in mouse events.
* @param {MouseEvent} e Event instance (or Event-like, i.e. `SyntheticEvent`)
* @return {Boolean}
*/
export const isPrimaryClick = e =>
!(e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) &&
(("button" in e && e.button === 0) || ("buttons" in e && e.buttons === 1));
/**
* Decorates a function so it calls if only the primary button has been
* pressed in mouse events.
* @param {Function} fn
* @return {Function}
*/
export const onPrimaryClick = fn => (e, ...args) =>
isPrimaryClick(e, ...args) ? fn(e) : true;
| Update onPrimaryClick to pass down multiple args | Update onPrimaryClick to pass down multiple args
| JavaScript | mit | jacobbuck/primary-click | ---
+++
@@ -13,4 +13,5 @@
* @param {Function} fn
* @return {Function}
*/
-export const onPrimaryClick = fn => e => (isPrimaryClick(e) ? fn(e) : true);
+export const onPrimaryClick = fn => (e, ...args) =>
+ isPrimaryClick(e, ...args) ? fn(e) : true; |
d54e3be13f374f3aa9b2f1e24bc476e7aadbfbcb | src/index.js | src/index.js | require('Common');
var win = new Window();
application.exitAfterWindowsClose = true;
win.visible = true;
win.title = "Hi Tint World!";
var webview = new WebView(); // Create a new webview for HTML.
win.appendChild(webview); // attach the webview to the window.
// position the webview 0 pixels from all the window's edges.
webview.left=webview.right=webview.top=webview.bottom=0;
// What we should do when the web-page loads.
webview.addEventListener('load', function() {
webview.postMessage(JSON.stringify(process.versions));
});
webview.location = "app://src/index.html"; // Tell the webview to render the index.html | require('Common');
var win = new Window();
var toolbar = new Toolbar();
application.exitAfterWindowsClose = true;
win.visible = true;
win.title = "Hi Tint World!";
btn = new Button();
btn.image = 'back';
toolbar.appendChild( btn );
win.toolbar = toolbar;
var webview = new WebView(); // Create a new webview for HTML.
win.appendChild(webview); // attach the webview to the window.
// position the webview 0 pixels from all the window's edges.
webview.left=webview.right=webview.top=webview.bottom=0;
// What we should do when the web-page loads.
webview.addEventListener('load', function() {
webview.postMessage(JSON.stringify(process.versions));
});
webview.location = "app://src/index.html"; // Tell the webview to render the index.html | Add toolbar with back button | Add toolbar with back button
| JavaScript | mit | niaxi/hello-tint,niaxi/hello-tint | ---
+++
@@ -1,8 +1,16 @@
require('Common');
var win = new Window();
+var toolbar = new Toolbar();
+
+
application.exitAfterWindowsClose = true;
win.visible = true;
win.title = "Hi Tint World!";
+
+btn = new Button();
+btn.image = 'back';
+toolbar.appendChild( btn );
+win.toolbar = toolbar;
var webview = new WebView(); // Create a new webview for HTML. |
0c28f538d9382d85c69ecb06a208ae1b0874b29c | src/index.js | src/index.js | /**
* Created by thram on 21/01/17.
*/
import forEach from "lodash/forEach";
import assign from "lodash/assign";
import isArray from "lodash/isArray";
import {observe, state, removeObserver} from "thrux";
export const connect = (stateKey, ReactComponent) => {
class ThruxComponent extends ReactComponent {
observers = {};
constructor(props) {
super(props);
this.state = assign(this.state || {}, state([].concat(stateKey)));
}
addObserver = (key) => {
this.observers[key] = (state) => {
let newState = {};
newState[key] = state;
this.setState(newState);
};
observe(key, this.observers[key]);
};
componentDidMount(...args) {
isArray(stateKey) ? forEach(stateKey, this.addObserver) : this.addObserver(stateKey);
super.componentDidMount.apply(this, args);
}
componentWillUnmount(...args) {
super.componentWillUnmount.apply(this, args);
forEach(this.observers, (observer, key) => removeObserver(key, observer));
}
}
return ThruxComponent;
}; | /**
* Created by thram on 21/01/17.
*/
import forEach from "lodash/forEach";
import assign from "lodash/assign";
import isArray from "lodash/isArray";
import {observe, state, removeObserver} from "thrux";
export const connect = (stateKey, ReactComponent) => {
class ThruxComponent extends ReactComponent {
observers = {};
constructor(props) {
super(props);
this.state = assign(this.state || {}, state([].concat(stateKey)));
}
addObserver = (key) => {
this.observers[key] = (state) => {
let newState = {};
newState[key] = state;
this.setState(newState);
};
observe(key, this.observers[key]);
};
componentDidMount(...args) {
isArray(stateKey) ? forEach(stateKey, this.addObserver) : this.addObserver(stateKey);
super.componentDidMount && super.componentDidMount.apply(this, args);
}
componentWillUnmount(...args) {
super.componentWillUnmount && super.componentWillUnmount.apply(this, args);
forEach(this.observers, (observer, key) => removeObserver(key, observer));
}
}
return ThruxComponent;
}; | Check first if the componentDidMount and componentWillUnmount are defined | fix(mount): Check first if the componentDidMount and componentWillUnmount are defined
| JavaScript | mit | Thram/react-thrux | ---
+++
@@ -27,11 +27,11 @@
componentDidMount(...args) {
isArray(stateKey) ? forEach(stateKey, this.addObserver) : this.addObserver(stateKey);
- super.componentDidMount.apply(this, args);
+ super.componentDidMount && super.componentDidMount.apply(this, args);
}
componentWillUnmount(...args) {
- super.componentWillUnmount.apply(this, args);
+ super.componentWillUnmount && super.componentWillUnmount.apply(this, args);
forEach(this.observers, (observer, key) => removeObserver(key, observer));
}
} |
f563f24c06d6de9401aa7d43fea0d5319bf5df0e | src/index.js | src/index.js | #! /usr/bin/env node
import chalk from 'chalk';
import console from 'console';
import gitAuthorStats from './git-author-stats';
gitAuthorStats().forEach((gitAuthorStat) => {
const author = chalk.bold(gitAuthorStat.author);
const commits = `${gitAuthorStat.commits} commits`;
const added = chalk.green(`${gitAuthorStat.added} ++`);
const removed = chalk.red(`${gitAuthorStat.removed} --`);
const authorStats = [commits, added, removed].join(' / ');
console.log(`${author}: ${authorStats}`);
});
| #! /usr/bin/env node
import { bold, green, red } from 'chalk';
import console from 'console';
import gitAuthorStats from './git-author-stats';
gitAuthorStats().forEach((gitAuthorStat) => {
const {
author,
commits,
added,
removed,
} = gitAuthorStat;
const gitAuthorText = [
`${commits} commits`,
green(`${added} ++`),
red(`${removed} --`),
].join(' / ');
console.log(`${bold(author)}: ${gitAuthorText}`);
});
| Refactor Git author text writing | Refactor Git author text writing
| JavaScript | mit | caedes/git-author-stats | ---
+++
@@ -1,17 +1,23 @@
#! /usr/bin/env node
-import chalk from 'chalk';
+import { bold, green, red } from 'chalk';
import console from 'console';
import gitAuthorStats from './git-author-stats';
gitAuthorStats().forEach((gitAuthorStat) => {
- const author = chalk.bold(gitAuthorStat.author);
- const commits = `${gitAuthorStat.commits} commits`;
- const added = chalk.green(`${gitAuthorStat.added} ++`);
- const removed = chalk.red(`${gitAuthorStat.removed} --`);
+ const {
+ author,
+ commits,
+ added,
+ removed,
+ } = gitAuthorStat;
- const authorStats = [commits, added, removed].join(' / ');
+ const gitAuthorText = [
+ `${commits} commits`,
+ green(`${added} ++`),
+ red(`${removed} --`),
+ ].join(' / ');
- console.log(`${author}: ${authorStats}`);
+ console.log(`${bold(author)}: ${gitAuthorText}`);
}); |
15093e0594b007941d29d17751bc8de40e65a346 | src/index.js | src/index.js | const path = require('path')
const parse = require('./parsers/index')
// TODO Fix ampersand in selectors
// TODO ENFORCE THESE RULES
// value-no-vendor-prefix – don't allow vendor prefixes
// property-no-vendor-prefix – don't allow vendor prefixes
const ignoredRules = [
// Don't throw if there's no styled-components in a file
'no-empty-source',
// We don't care about end-of-source newlines, users cannot control them
'no-missing-end-of-source-newline'
]
const sourceMapsCorrections = {}
module.exports = (/* options */) => ({
// Get string for stylelint to lint
code(input, filepath) {
const absolutePath = path.resolve(process.cwd(), filepath)
sourceMapsCorrections[absolutePath] = {}
const { extractedCSS, sourceMap } = parse(input, absolutePath)
// Save source location, merging existing corrections with current corrections
sourceMapsCorrections[absolutePath] = Object.assign(
sourceMapsCorrections[absolutePath],
sourceMap
)
return extractedCSS
},
// Fix sourcemaps
result(stylelintResult, filepath) {
const lineCorrection = sourceMapsCorrections[filepath]
const newWarnings = stylelintResult.warnings.reduce((prevWarnings, warning) => {
if (ignoredRules.includes(warning.rule)) return prevWarnings
const correctedWarning = Object.assign(warning, {
// Replace "brace" with "backtick" in warnings, e.g.
// "Unexpected empty line before closing backtick" (instead of "brace")
text: warning.text.replace(/brace/, 'backtick'),
line: lineCorrection[warning.line]
})
prevWarnings.push(correctedWarning)
return prevWarnings
}, [])
if (newWarnings.length === 0) {
// eslint-disable-next-line no-param-reassign
stylelintResult.errored = false
}
return Object.assign(stylelintResult, { warnings: newWarnings })
}
})
| const path = require('path')
const parse = require('./parsers/index')
// TODO Fix ampersand in selectors
const sourceMapsCorrections = {}
module.exports = (/* options */) => ({
// Get string for stylelint to lint
code(input, filepath) {
const absolutePath = path.resolve(process.cwd(), filepath)
sourceMapsCorrections[absolutePath] = {}
const { extractedCSS, sourceMap } = parse(input, absolutePath)
// Save source location, merging existing corrections with current corrections
sourceMapsCorrections[absolutePath] = Object.assign(
sourceMapsCorrections[absolutePath],
sourceMap
)
return extractedCSS
},
// Fix sourcemaps
result(stylelintResult, filepath) {
const lineCorrection = sourceMapsCorrections[filepath]
const warnings = stylelintResult.warnings.map(warning =>
Object.assign(warning, {
// Replace "brace" with "backtick" in warnings, e.g.
// "Unexpected empty line before closing backtick" (instead of "brace")
text: warning.text.replace(/brace/, 'backtick'),
line: lineCorrection[warning.line]
})
)
return Object.assign(stylelintResult, { warnings })
}
})
| Remove ignoring of stylelint rules | Remove ignoring of stylelint rules
| JavaScript | mit | styled-components/stylelint-processor-styled-components | ---
+++
@@ -1,16 +1,6 @@
const path = require('path')
const parse = require('./parsers/index')
// TODO Fix ampersand in selectors
-// TODO ENFORCE THESE RULES
-// value-no-vendor-prefix – don't allow vendor prefixes
-// property-no-vendor-prefix – don't allow vendor prefixes
-
-const ignoredRules = [
- // Don't throw if there's no styled-components in a file
- 'no-empty-source',
- // We don't care about end-of-source newlines, users cannot control them
- 'no-missing-end-of-source-newline'
-]
const sourceMapsCorrections = {}
@@ -30,23 +20,15 @@
// Fix sourcemaps
result(stylelintResult, filepath) {
const lineCorrection = sourceMapsCorrections[filepath]
- const newWarnings = stylelintResult.warnings.reduce((prevWarnings, warning) => {
- if (ignoredRules.includes(warning.rule)) return prevWarnings
- const correctedWarning = Object.assign(warning, {
+ const warnings = stylelintResult.warnings.map(warning =>
+ Object.assign(warning, {
// Replace "brace" with "backtick" in warnings, e.g.
// "Unexpected empty line before closing backtick" (instead of "brace")
text: warning.text.replace(/brace/, 'backtick'),
line: lineCorrection[warning.line]
})
- prevWarnings.push(correctedWarning)
- return prevWarnings
- }, [])
+ )
- if (newWarnings.length === 0) {
- // eslint-disable-next-line no-param-reassign
- stylelintResult.errored = false
- }
-
- return Object.assign(stylelintResult, { warnings: newWarnings })
+ return Object.assign(stylelintResult, { warnings })
}
}) |
af6776fc87f7a18c18355f40e58364e5ca3237b7 | components/base/Footer.js | components/base/Footer.js | import React from 'react'
class Footer extends React.PureComponent {
render () {
return <footer className='container row'>
<p className='col-xs-12'>
Copyright 2017 Junyoung Choi. <a href='https://github.com/CarbonStack/carbonstack' target='_blank'>Source code of Carbonstack</a> is published under MIT.
</p>
<style jsx>{`
p {
text-align: center;
margin: 0 auto;
line-height: 60px;
}
`}</style>
</footer>
}
}
export default Footer
| import React from 'react'
class Footer extends React.PureComponent {
render () {
return <footer>
<p>
Copyright 2017 Junyoung Choi. <a href='https://github.com/CarbonStack/carbonstack' target='_blank'>Source code of Carbonstack</a> is published under MIT.
</p>
<style jsx>{`
p {
text-align: center;
padding: 15px 0;
}
`}</style>
</footer>
}
}
export default Footer
| Fix stye bug of footer again | Fix stye bug of footer again
| JavaScript | mit | CarbonStack/carbonstack | ---
+++
@@ -2,15 +2,14 @@
class Footer extends React.PureComponent {
render () {
- return <footer className='container row'>
- <p className='col-xs-12'>
+ return <footer>
+ <p>
Copyright 2017 Junyoung Choi. <a href='https://github.com/CarbonStack/carbonstack' target='_blank'>Source code of Carbonstack</a> is published under MIT.
</p>
<style jsx>{`
p {
text-align: center;
- margin: 0 auto;
- line-height: 60px;
+ padding: 15px 0;
}
`}</style>
</footer> |
f01915febfe98c8dd27a97af00473a64030d5e4f | src/index.js | src/index.js | import isPromise from './isPromise';
const defaultTypes = ['PENDING', 'FULFILLED', 'REJECTED'];
export default function promiseMiddleware(config={}) {
const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypes;
return (_ref) => {
const dispatch = _ref.dispatch;
return next => action => {
if (!isPromise(action.payload)) {
return next(action);
}
const { type, payload, meta } = action;
const { promise, data } = payload;
const [ PENDING, FULFILLED, REJECTED ] = (meta || {}).promiseTypeSuffixes || promiseTypeSuffixes;
/**
* Dispatch the first async handler. This tells the
* reducer that an async action has been dispatched.
*/
next({
type: `${type}_${PENDING}`,
...data && { payload: data },
...meta && { meta }
});
/**
* Return either the fulfilled action object or the rejected
* action object.
*/
return promise.then(
(resolved={}) => dispatch({
type: `${type}_${FULFILLED}`,
...resolved.meta || resolved.payload ? resolved : {
...resolved && { payload: resolved },
...meta && { meta }
}
}),
error => dispatch({
type: `${type}_${REJECTED}`,
payload: error,
error: true,
...meta && { meta }
})
);
};
};
}
| import isPromise from './isPromise';
const defaultTypes = ['PENDING', 'FULFILLED', 'REJECTED'];
export default function promiseMiddleware(config={}) {
const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypes;
return (_ref) => {
const dispatch = _ref.dispatch;
return next => action => {
if (!isPromise(action.payload)) {
return next(action);
}
const { type, payload, meta } = action;
const { promise, data } = payload;
const [ PENDING, FULFILLED, REJECTED ] = (meta || {}).promiseTypeSuffixes || promiseTypeSuffixes;
/**
* Dispatch the first async handler. This tells the
* reducer that an async action has been dispatched.
*/
next({
type: `${type}_${PENDING}`,
...data && { payload: data },
...meta && { meta }
});
/**
* Return either the fulfilled action object or the rejected
* action object.
*/
return promise.then(
(resolved={}) => dispatch({
type: `${type}_${FULFILLED}`,
...resolved.meta || resolved.payload ? resolved : {
...resolved && { payload: resolved },
...meta && { meta }
}
}),
error => dispatch({
type: `${type}_${REJECTED}`,
payload: error,
error: true,
...meta && { meta }
})
);
};
};
}
| Use default parameters for default suffixes | Use default parameters for default suffixes
| JavaScript | mit | pburtchaell/redux-promise-middleware | ---
+++
@@ -4,8 +4,10 @@
export default function promiseMiddleware(config={}) {
const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypes;
+
return (_ref) => {
const dispatch = _ref.dispatch;
+
return next => action => {
if (!isPromise(action.payload)) {
return next(action); |
08cad5105b71b10b063af27ed256bc4ab7571896 | src/index.js | src/index.js | import _ from './utils';
export default {
has: (value = {}, conditions = {}) => {
if (!_.isObject(conditions)) return false;
if (_.isArray(value)) return !!_.find(value, conditions);
if (_.isObject(value)) return !!_.find(value.transitions, conditions);
return false;
},
find: (value = {}, conditions = {}) => {
if (!_.isObject(conditions) && typeof (conditions) !== 'function') return undefined;
if (_.isArray(value)) return _.find(value, conditions);
if (_.isObject(value)) return _.find(value.transitions, conditions);
return undefined;
},
filter: (value = {}, conditions = {}) => {
if (!_.isObject(conditions) && typeof (conditions) !== 'function') return [];
if (_.isArray(value)) return _.filter(value, conditions);
if (_.isObject(value)) return _.filter(value.transitions, conditions);
return [];
},
metaAttributes: (obj = {}) => {
if (!_.isObject(obj)) return {};
if (!_.isObject(obj.meta)) return {};
return obj.meta.attributes || {};
},
metaLinks: (obj = {}) => {
if (!_.isObject(obj)) return [];
if (!_.isObject(obj.meta)) return [];
return obj.meta.links || [];
},
attributes: (obj = {}) => {
if (!_.isObject(obj)) return {};
return obj.attributes || {};
},
transitions: (obj = {}) => {
if (!_.isObject(obj)) return [];
return obj.transitions || [];
},
get: _.get,
};
| import _ from './utils';
function getTransitions(value) {
if (_.isArray(value)) return value;
if (_.isObject(value)) return value.transitions;
}
export default {
has: (value = {}, conditions = {}) => {
return !!_.find(getTransitions(value), conditions);
},
find: (value = {}, conditions = {}) => {
return _.find(getTransitions(value), conditions);
},
filter: (value = {}, conditions = {}) => {
return _.filter(getTransitions(value), conditions);
},
metaAttributes: (obj = {}) => {
if (!_.isObject(obj)) return {};
if (!_.isObject(obj.meta)) return {};
return obj.meta.attributes || {};
},
metaLinks: (obj = {}) => {
if (!_.isObject(obj)) return [];
if (!_.isObject(obj.meta)) return [];
return obj.meta.links || [];
},
attributes: (obj = {}) => {
if (!_.isObject(obj)) return {};
return obj.attributes || {};
},
transitions: (obj = {}) => {
if (!_.isObject(obj)) return [];
return obj.transitions || [];
},
get: _.get,
};
| Trim code a little more | Trim code a little more
| JavaScript | mit | smizell/hf | ---
+++
@@ -1,25 +1,21 @@
import _ from './utils';
+
+function getTransitions(value) {
+ if (_.isArray(value)) return value;
+ if (_.isObject(value)) return value.transitions;
+}
export default {
has: (value = {}, conditions = {}) => {
- if (!_.isObject(conditions)) return false;
- if (_.isArray(value)) return !!_.find(value, conditions);
- if (_.isObject(value)) return !!_.find(value.transitions, conditions);
- return false;
+ return !!_.find(getTransitions(value), conditions);
},
find: (value = {}, conditions = {}) => {
- if (!_.isObject(conditions) && typeof (conditions) !== 'function') return undefined;
- if (_.isArray(value)) return _.find(value, conditions);
- if (_.isObject(value)) return _.find(value.transitions, conditions);
- return undefined;
+ return _.find(getTransitions(value), conditions);
},
filter: (value = {}, conditions = {}) => {
- if (!_.isObject(conditions) && typeof (conditions) !== 'function') return [];
- if (_.isArray(value)) return _.filter(value, conditions);
- if (_.isObject(value)) return _.filter(value.transitions, conditions);
- return [];
+ return _.filter(getTransitions(value), conditions);
},
metaAttributes: (obj = {}) => { |
236683fb55facf7062e6d3e95ddff7ce37c2ef1b | client/app/TrustLineService/TrustLineService.service.spec.js | client/app/TrustLineService/TrustLineService.service.spec.js | 'use strict';
describe('Service: trustLineService', function () {
// load the service's module
beforeEach(module('riwebApp'));
// instantiate service
var trustLineService;
beforeEach(inject(function (_trustLineService_) {
trustLineService = _trustLineService_;
}));
it('should do something', function () {
expect(!!trustLineService).toBe(true);
});
});
| 'use strict';
describe('Service: TrustLineService', function () {
// load the service's module
beforeEach(module('riwebApp'));
// instantiate service
var TrustLineService;
beforeEach(inject(function (_trustLineService_) {
TrustLineService = _trustLineService_;
}));
it('should do something', function () {
expect(!!TrustLineService).toBe(true);
});
});
| Rename service var to TrustLineService just in case. | Rename service var to TrustLineService just in case.
| JavaScript | agpl-3.0 | cegeka/riweb,cegeka/riweb,andreicristianpetcu/riweb,andreicristianpetcu/riweb,cegeka/riweb,crazyquark/riweb,andreicristianpetcu/riweb,crazyquark/riweb,crazyquark/riweb | ---
+++
@@ -1,18 +1,18 @@
'use strict';
-describe('Service: trustLineService', function () {
+describe('Service: TrustLineService', function () {
// load the service's module
beforeEach(module('riwebApp'));
// instantiate service
- var trustLineService;
+ var TrustLineService;
beforeEach(inject(function (_trustLineService_) {
- trustLineService = _trustLineService_;
+ TrustLineService = _trustLineService_;
}));
it('should do something', function () {
- expect(!!trustLineService).toBe(true);
+ expect(!!TrustLineService).toBe(true);
});
}); |
f47b43cee6bbd40a6879f5ce09eb2612c83496f9 | src/index.js | src/index.js | import AtomControl from './components/AtomControl';
import CardControl from './components/CardControl';
import { classToDOMCard } from './utils/classToCard';
import Container, { EMPTY_MOBILEDOC } from './components/Container';
import DropWrapper from './components/DropWrapper';
import Editor from './components/Editor';
import LinkControl from './components/LinkControl';
import LinkForm from './components/LinkForm';
import MarkupControl from './components/MarkupControl';
import SectionControl from './components/SectionControl';
import Toolbar from './components/Toolbar';
export {
AtomControl,
CardControl,
classToDOMCard,
Container,
DropWrapper,
Editor,
EMPTY_MOBILEDOC,
LinkControl,
LinkForm,
MarkupControl,
SectionControl,
Toolbar
};
| import AtomControl from './components/AtomControl';
import CardControl from './components/CardControl';
import { classToDOMCard } from './utils/classToCard';
import Container, { EMPTY_MOBILEDOC } from './components/Container';
import Editor from './components/Editor';
import LinkControl from './components/LinkControl';
import LinkForm from './components/LinkForm';
import MarkupControl from './components/MarkupControl';
import SectionControl from './components/SectionControl';
import Toolbar from './components/Toolbar';
export {
AtomControl,
CardControl,
classToDOMCard,
Container,
Editor,
EMPTY_MOBILEDOC,
LinkControl,
LinkForm,
MarkupControl,
SectionControl,
Toolbar
};
| Remove drop wrapper from exports | Remove drop wrapper from exports
| JavaScript | bsd-3-clause | upworthy/react-mobiledoc-editor | ---
+++
@@ -2,7 +2,6 @@
import CardControl from './components/CardControl';
import { classToDOMCard } from './utils/classToCard';
import Container, { EMPTY_MOBILEDOC } from './components/Container';
-import DropWrapper from './components/DropWrapper';
import Editor from './components/Editor';
import LinkControl from './components/LinkControl';
import LinkForm from './components/LinkForm';
@@ -15,7 +14,6 @@
CardControl,
classToDOMCard,
Container,
- DropWrapper,
Editor,
EMPTY_MOBILEDOC,
LinkControl, |
7390f356615c375960ebf49bca2001a1fee43788 | lib/dasher.js | lib/dasher.js | var url = require('url')
var dashButton = require('node-dash-button');
var request = require('request')
function DasherButton(button) {
var options = {headers: button.headers, body: button.body, json: button.json}
this.dashButton = dashButton(button.address, button.interface)
this.dashButton.on("detected", function() {
console.log(button.name + " pressed.")
doRequest(button.url, button.method, options)
})
console.log(button.name + " added.")
}
function doRequest(requestUrl, method, options, callback) {
options = options || {}
options.query = options.query || {}
options.json = options.json || false
options.headers = options.headers || {}
var reqOpts = {
url: url.parse(requestUrl),
method: method || 'GET',
qs: options.query,
body: options.body,
json: options.json,
headers: options.headers
}
request(reqOpts, function onResponse(error, response, body) {
if (error) {
console.log("there was an error");
console.log(error);
}
if (response.statusCode === 401) {
console.log("Not authenticated");
console.log(error);
}
if (response.statusCode !== 200) {
console.log("Not a 200");
console.log(error);
}
if (callback) {
callback(error, response, body)
}
})
}
module.exports = DasherButton
| var url = require('url')
var dashButton = require('node-dash-button');
var request = require('request')
function DasherButton(button) {
var options = {headers: button.headers, body: button.body, json: button.json}
this.dashButton = dashButton(button.address, button.interface)
this.dashButton.on("detected", function() {
console.log(button.name + " pressed.")
doRequest(button.url, button.method, options)
})
console.log(button.name + " added.")
}
function doRequest(requestUrl, method, options, callback) {
options = options || {}
options.query = options.query || {}
options.json = options.json || false
options.headers = options.headers || {}
var reqOpts = {
url: url.parse(requestUrl),
method: method || 'GET',
qs: options.query,
body: options.body,
json: options.json,
headers: options.headers
}
request(reqOpts, function onResponse(error, response, body) {
if (error) {
console.log("there was an error");
console.log(error);
}
if (response && response.statusCode === 401) {
console.log("Not authenticated");
console.log(error);
}
if (response && response.statusCode !== 200) {
console.log("Not a 200");
console.log(error);
}
if (callback) {
callback(error, response, body)
}
})
}
module.exports = DasherButton
| Add check for nil response | Add check for nil response
The app was erroring on missing statusCode when no response
was received. This allows the app not to crash if the url
doesn't respond.
| JavaScript | mit | maddox/dasher,maddox/dasher | ---
+++
@@ -35,11 +35,11 @@
console.log("there was an error");
console.log(error);
}
- if (response.statusCode === 401) {
+ if (response && response.statusCode === 401) {
console.log("Not authenticated");
console.log(error);
}
- if (response.statusCode !== 200) {
+ if (response && response.statusCode !== 200) {
console.log("Not a 200");
console.log(error);
} |
f234cf043c80a66e742862cff36218fa04589398 | src/index.js | src/index.js | 'use strict';
import AssetLoader from './assetloader';
import Input from './input';
import Loop from './loop';
import Log from './log';
import Timer from './timer';
import Math from './math';
export default {
AssetLoader,
Input,
Loop,
Log,
Timer,
Math
};
| 'use strict';
import AssetLoader from './assetloader';
import Input from './input';
import Loop from './loop';
import Log from './log';
import Timer from './timer';
import Math from './math';
import Types from './types';
export default {
AssetLoader,
Input,
Loop,
Log,
Timer,
Math
};
| Add types to be exported | Add types to be exported
| JavaScript | unknown | freezedev/gamebox,gamebricks/gamebricks,freezedev/gamebox,gamebricks/gamebricks,maxwerr/gamebox | ---
+++
@@ -6,7 +6,8 @@
import Log from './log';
import Timer from './timer';
import Math from './math';
-
+import Types from './types';
+
export default {
AssetLoader,
Input, |
4aa75606353bd190240cbfd559eb291a891a7432 | src/ui/app.js | src/ui/app.js | angular.module('proxtop', ['ngMaterial', 'ui.router', 'angular-progress-arc', 'pascalprecht.translate'])
.config(['$stateProvider', '$urlRouterProvider', '$translateProvider', function($stateProvider, $urlRouterProvider, $translateProvider) {
$urlRouterProvider.otherwise('/');
$translateProvider.useStaticFilesLoader({
prefix: 'ui/locale/locale-',
suffix: '.json'
});
$translateProvider.preferredLanguage('de');
$translateProvider.useSanitizeValueStrategy('sanitizeParameters');
}]);
| angular.module('proxtop', ['ngMaterial', 'ui.router', 'angular-progress-arc', 'pascalprecht.translate'])
.config(['$stateProvider', '$urlRouterProvider', '$translateProvider', function($stateProvider, $urlRouterProvider, $translateProvider) {
$urlRouterProvider.otherwise('/');
$translateProvider.useStaticFilesLoader({
prefix: 'ui/locale/locale-',
suffix: '.json'
});
$translateProvider.preferredLanguage('de');
$translateProvider.useSanitizeValueStrategy('escape');
}]);
| Fix missing dependency when using ng-translate | Fix missing dependency when using ng-translate
| JavaScript | mit | kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop | ---
+++
@@ -7,5 +7,5 @@
});
$translateProvider.preferredLanguage('de');
- $translateProvider.useSanitizeValueStrategy('sanitizeParameters');
+ $translateProvider.useSanitizeValueStrategy('escape');
}]); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.