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 |
|---|---|---|---|---|---|---|---|---|---|---|
ff56d760687283d69a9f82045627f30246dba8ec | content.js | content.js | document.addEventListener('mouseup', function (e) {
var ws = null;
var el = e.srcElement;
while (ws == null && el && el.getAttribute) {
ws = el.getAttribute("wicketsource");
el = el.parentNode;
}
chrome.extension.sendRequest({
wicketsource: ws
});
});
| document.addEventListener('mouseup', function (e) {
var ws = null;
var el = e.target;
while (ws == null && el && el.getAttribute) {
ws = el.getAttribute("wicketsource");
el = el.parentNode;
}
chrome.extension.sendRequest({
wicketsource: ws
});
});
| Use target attribute instead of srcElement | Use target attribute instead of srcElement
| JavaScript | apache-2.0 | cleiter/wicketsource-contextmenu | ---
+++
@@ -1,6 +1,6 @@
document.addEventListener('mouseup', function (e) {
var ws = null;
- var el = e.srcElement;
+ var el = e.target;
while (ws == null && el && el.getAttribute) {
ws = el.getAttribute("wicketsource"); |
d806a1c4cd904dc9db5dd09932760b797beceac5 | lib/field_ref.js | lib/field_ref.js | lunr.FieldRef = function (docRef, fieldName) {
this.docRef = docRef
this.fieldName = fieldName
this._stringValue = fieldName + lunr.FieldRef.joiner + docRef
}
lunr.FieldRef.joiner = "/"
lunr.FieldRef.fromString = function (s) {
var n = s.indexOf(lunr.FieldRef.joiner)
if (n === -1) {
throw "malformed field ref string"
}
var fieldRef = s.slice(0, n),
docRef = s.slice(n + 1)
return new lunr.FieldRef (docRef, fieldRef)
}
lunr.FieldRef.prototype.toString = function () {
return this._stringValue
}
| lunr.FieldRef = function (docRef, fieldName, stringValue) {
this.docRef = docRef
this.fieldName = fieldName
this._stringValue = stringValue
}
lunr.FieldRef.joiner = "/"
lunr.FieldRef.fromString = function (s) {
var n = s.indexOf(lunr.FieldRef.joiner)
if (n === -1) {
throw "malformed field ref string"
}
var fieldRef = s.slice(0, n),
docRef = s.slice(n + 1)
return new lunr.FieldRef (docRef, fieldRef, s)
}
lunr.FieldRef.prototype.toString = function () {
if (this._stringValue == undefined) {
this._stringValue = this.fieldName + lunr.FieldRef.joiner + this.docRef
}
return this._stringValue
}
| Stop needlessly recreating field ref string | Stop needlessly recreating field ref string
| JavaScript | mit | olivernn/lunr.js,olivernn/lunr.js,olivernn/lunr.js | ---
+++
@@ -1,7 +1,7 @@
-lunr.FieldRef = function (docRef, fieldName) {
+lunr.FieldRef = function (docRef, fieldName, stringValue) {
this.docRef = docRef
this.fieldName = fieldName
- this._stringValue = fieldName + lunr.FieldRef.joiner + docRef
+ this._stringValue = stringValue
}
lunr.FieldRef.joiner = "/"
@@ -16,9 +16,13 @@
var fieldRef = s.slice(0, n),
docRef = s.slice(n + 1)
- return new lunr.FieldRef (docRef, fieldRef)
+ return new lunr.FieldRef (docRef, fieldRef, s)
}
lunr.FieldRef.prototype.toString = function () {
+ if (this._stringValue == undefined) {
+ this._stringValue = this.fieldName + lunr.FieldRef.joiner + this.docRef
+ }
+
return this._stringValue
} |
3de90480307a12d0dc1679b93a767b086f8420a2 | jquery.sticky.js | jquery.sticky.js | (function ($) {
// http://davidwalsh.name/ways-css-javascript-interact
function addCSSRule (sheet, selector, rules, index) {
if (sheet.insertRule) {
sheet.insertRule(selector + '{ ' + rules + ' }', index)
} else {
sheet.addRule(selector, rules, index)
}
}
function heightOffset (elem) {
var height = 0
elem.prevAll(':visible').each(function (_, sibling) {
height += $(sibling).outerHeight()
})
return height || elem.outerHeight()
}
$.fn.sticky = function () {
var elem = $(this),
nextVisible = elem.siblings().first(':visible'),
stuck = false,
styleSheet = document.styleSheets[0]
addCSSRule(styleSheet, '.stuck', 'position: fixed !important; top: 0 !important; z-index: 10')
$(window).on('scroll', function () {
if ($(this).scrollTop() > heightOffset(elem)) {
if (stuck) return;
elem.addClass('stuck')
nextVisible.css('margin-top', elem.outerHeight())
stuck = true
} else {
elem.removeClass('stuck')
nextVisible.css('margin-top', "")
stuck = false
}
})
}
})(jQuery)
| (function ($) {
// http://davidwalsh.name/ways-css-javascript-interact
function addCSSRule (sheet, selector, rules, index) {
if (sheet.insertRule) {
sheet.insertRule(selector + '{ ' + rules + ' }', index)
} else {
sheet.addRule(selector, rules, index)
}
}
function heightOffset (elem) {
return elem.offset.top() || elem.outerHeight()
}
$.fn.sticky = function () {
var elem = $(this),
nextVisible = elem.siblings().first(':visible'),
stuck = false,
styleSheet = document.styleSheets[0]
addCSSRule(styleSheet, '.stuck', 'position: fixed !important; top: 0 !important; z-index: 10')
$(window).on('scroll', function () {
if ($(this).scrollTop() > heightOffset(elem)) {
if (stuck) return;
elem.addClass('stuck')
nextVisible.css('margin-top', elem.outerHeight())
stuck = true
} else {
elem.removeClass('stuck')
nextVisible.css('margin-top', "")
stuck = false
}
})
}
})(jQuery)
| Use offset rather than calculating position by hand | Use offset rather than calculating position by hand | JavaScript | mit | leemachin/sticky.js,leemachin/sticky.js | ---
+++
@@ -10,13 +10,7 @@
}
function heightOffset (elem) {
- var height = 0
-
- elem.prevAll(':visible').each(function (_, sibling) {
- height += $(sibling).outerHeight()
- })
-
- return height || elem.outerHeight()
+ return elem.offset.top() || elem.outerHeight()
}
$.fn.sticky = function () { |
5357686b071fd82a3326576afd7aa61c46862f32 | examples/witExample.js | examples/witExample.js | const speeech = require("../src/index");
const get = require("lodash.get");
const say = require("say");
const serviceConfig = require("../witkeyfile.json");
const process = result => {
const intent = get(result, "entities.intent[0].value");
if (intent === "weather") {
const location = get(result, "entities.location[0].value");
say.speak("You want weather of " + location);
}
console.log(result.entities);
};
speeech.emit("start", speeech.witService(serviceConfig));
speeech.on("result", result => process(result));
| const speeech = require("../src/index");
const get = require("lodash.get");
const serviceConfig = require("../witkeyfile.json");
const process = result => {
const intent = get(result, "entities.intent[0].value");
console.log(`The intent is ${intent}`);
};
speeech.emit("start", speeech.witService(serviceConfig));
speeech.on("result", result => process(result));
| Update first Wit example to do it more simple | Update first Wit example to do it more simple
| JavaScript | mit | joyarzun/speeech | ---
+++
@@ -1,16 +1,11 @@
const speeech = require("../src/index");
const get = require("lodash.get");
-const say = require("say");
const serviceConfig = require("../witkeyfile.json");
const process = result => {
const intent = get(result, "entities.intent[0].value");
- if (intent === "weather") {
- const location = get(result, "entities.location[0].value");
- say.speak("You want weather of " + location);
- }
- console.log(result.entities);
+ console.log(`The intent is ${intent}`);
};
speeech.emit("start", speeech.witService(serviceConfig)); |
291ada1316f07518a5168578e8d9b0cb97298cc7 | lib/models/user/pushNotifications.js | lib/models/user/pushNotifications.js | "use strict";
const config = require("../../../config.js");
const Client = require("node-rest-client").Client;
const client = new Client();
module.exports = function (UserSchema) {
UserSchema.methods.sendPushNotification = function (payload) {
if (!config.pushNotificationsEnabled) return;
var user = this;
const username = user.email;
const pushData = [
Object.assign({username}, payload)
];
const authArgs = {
headers: {"Content-Type": "application/json"},
data: {
username: config.pushNotificationsServiceUserUsername,
password: config.pushNotificationsServiceUserPassword
}
};
client.post(`${config.authServiceAPI}/v1/auth/login`, authArgs, function (data, response) {
const { token } = data;
const pushNotificationArgs = {
headers: {"Content-Type": "application/json", "Authorization":"Bearer " + token},
data: {pushData}
};
client.post(`${config.notificationServiceAPI}/notifications/sendPushNotifications`, pushNotificationArgs, function (data, response) {
});
});
};
};
| "use strict";
const config = require("../../../config.js");
const Client = require("node-rest-client").Client;
const client = new Client();
module.exports = function (UserSchema) {
UserSchema.methods.sendPushNotification = function (payload) {
if (!config.pushNotificationsEnabled) return;
var user = this;
const username = user.email;
const pushData = [
Object.assign({username}, payload)
];
const authArgs = {
headers: {"Content-Type": "application/json"},
data: {
username: config.pushNotificationsServiceUserUsername,
password: config.pushNotificationsServiceUserPassword
}
};
client.post(`${config.authServiceAPI}/auth/login`, authArgs, function (data, response) {
const { token } = data;
const pushNotificationArgs = {
headers: {"Content-Type": "application/json", "Authorization":"Bearer " + token},
data: {pushData}
};
client.post(`${config.notificationServiceAPI}/notifications/sendPushNotifications`, pushNotificationArgs, function (data, response) {
});
});
};
};
| Fix extra v1 for microservice user login | Fix extra v1 for microservice user login
| JavaScript | apache-2.0 | amida-tech/orange-api,amida-tech/orange-api,amida-tech/orange-api,amida-tech/orange-api | ---
+++
@@ -23,7 +23,7 @@
}
};
- client.post(`${config.authServiceAPI}/v1/auth/login`, authArgs, function (data, response) {
+ client.post(`${config.authServiceAPI}/auth/login`, authArgs, function (data, response) {
const { token } = data;
const pushNotificationArgs = {
headers: {"Content-Type": "application/json", "Authorization":"Bearer " + token}, |
285abec25cba485a463e6dfaa30c1844736e899b | mltsp/tests/frontend/index.js | mltsp/tests/frontend/index.js | casper.test.begin('index loads', 1, function suite(test) {
casper.start('http://localhost:5000', function() {
test.assertTextExists('MLTSP', 'successfully loaded index page');
});
casper.run(function() {
test.done();
});
});
| casper.test.begin('index loads', 1, function suite(test) {
casper.start('http://localhost:5000', function() {
test.assertTextExists('Sign in with your Google Account',
'Authentication displayed on index page');
});
casper.run(function() {
test.done();
});
});
| Add valid test for front page | Add valid test for front page
| JavaScript | bsd-3-clause | bnaul/mltsp,mltsp/mltsp,bnaul/mltsp,mltsp/mltsp,bnaul/mltsp,mltsp/mltsp,acrellin/mltsp,mltsp/mltsp,acrellin/mltsp,acrellin/mltsp,acrellin/mltsp,bnaul/mltsp,acrellin/mltsp,mltsp/mltsp,bnaul/mltsp,acrellin/mltsp,bnaul/mltsp,mltsp/mltsp | ---
+++
@@ -1,6 +1,7 @@
casper.test.begin('index loads', 1, function suite(test) {
casper.start('http://localhost:5000', function() {
- test.assertTextExists('MLTSP', 'successfully loaded index page');
+ test.assertTextExists('Sign in with your Google Account',
+ 'Authentication displayed on index page');
});
casper.run(function() { |
89ace9a841c782fa9172b2255eded1e42ba9a9c2 | src/rethinkdbConfig.js | src/rethinkdbConfig.js | let rethinkdbConfig = {
host: process.env.RETHINKDB_HOST || 'localhost',
port: process.env.RETHINKDB_PORT || 28015,
db: 'quill_lessons'
}
if (process.env.RETHINKDB_USER) {
rethinkdbConfig['user'] = process.env.RETHINKDB_USER
}
if (process.env.RETHINKDB_PASSWORD) {
rethinkdbConfig['password'] = process.env.RETHINKDB_PASSWORD
}
export default rethinkdbConfig
| const rethinkdbConfig = (() => {
let config = {
host: process.env.RETHINKDB_HOST || 'localhost',
port: process.env.RETHINKDB_PORT || 28015,
db: 'quill_lessons'
}
if (process.env.RETHINKDB_USER) {
config['user'] = process.env.RETHINKDB_USER
}
if (process.env.RETHINKDB_PASSWORD) {
config['password'] = process.env.RETHINKDB_PASSWORD
}
return config
})()
export default rethinkdbConfig
| Use module pattern because its javascript | Use module pattern because its javascript
| JavaScript | agpl-3.0 | empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core | ---
+++
@@ -1,15 +1,19 @@
-let rethinkdbConfig = {
- host: process.env.RETHINKDB_HOST || 'localhost',
- port: process.env.RETHINKDB_PORT || 28015,
- db: 'quill_lessons'
-}
+const rethinkdbConfig = (() => {
+ let config = {
+ host: process.env.RETHINKDB_HOST || 'localhost',
+ port: process.env.RETHINKDB_PORT || 28015,
+ db: 'quill_lessons'
+ }
-if (process.env.RETHINKDB_USER) {
- rethinkdbConfig['user'] = process.env.RETHINKDB_USER
-}
+ if (process.env.RETHINKDB_USER) {
+ config['user'] = process.env.RETHINKDB_USER
+ }
-if (process.env.RETHINKDB_PASSWORD) {
- rethinkdbConfig['password'] = process.env.RETHINKDB_PASSWORD
-}
+ if (process.env.RETHINKDB_PASSWORD) {
+ config['password'] = process.env.RETHINKDB_PASSWORD
+ }
+
+ return config
+})()
export default rethinkdbConfig |
20b0c0845feb6c87d622683b580f6b32552cdba8 | localization/jquery-ui-timepicker-sk.js | localization/jquery-ui-timepicker-sk.js | /* Slovak translation for the jQuery Timepicker Addon */
/* Written by David Vallner */
(function($) {
$.timepicker.regional['sk'] = {
timeOnlyTitle: 'Zvoľte čas',
timeText: 'Čas',
hourText: 'Hodiny',
minuteText: 'Minuty',
secondText: 'Sekundy',
millisecText: 'Milisekundy',
timezoneText: 'Časové pásmo',
currentText: 'Teraz',
closeText: 'Zavřít',
timeFormat: 'h:m',
amNames: ['dop.', 'AM', 'A'],
pmNames: ['odp.', 'PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['sk']);
})(jQuery);
| /* Slovak translation for the jQuery Timepicker Addon */
/* Written by David Vallner */
(function($) {
$.timepicker.regional['sk'] = {
timeOnlyTitle: 'Zvoľte čas',
timeText: 'Čas',
hourText: 'Hodiny',
minuteText: 'Minúty',
secondText: 'Sekundy',
millisecText: 'Milisekundy',
timezoneText: 'Časové pásmo',
currentText: 'Teraz',
closeText: 'Zavrieť',
timeFormat: 'h:m',
amNames: ['dop.', 'AM', 'A'],
pmNames: ['pop.', 'PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['sk']);
})(jQuery);
| Fix Slovak localisation and add AM/PM markers | Fix Slovak localisation and add AM/PM markers | JavaScript | mit | ssyang0102/jQuery-Timepicker-Addon,trentrichardson/jQuery-Timepicker-Addon,trentrichardson/jQuery-Timepicker-Addon,pyonnuka/jQuery-Timepicker-Addon,pyonnuka/jQuery-Timepicker-Addon,ssyang0102/jQuery-Timepicker-Addon,gaissa/jQuery-Timepicker-Addon,gaissa/jQuery-Timepicker-Addon,ristovskiv/jQuery-Timepicker-Addon,ristovskiv/jQuery-Timepicker-Addon,Youraiseme/jQuery-Timepicker-Addon,brenosilver/jQuery-Timepicker-Addon,nicofrand/jQuery-Timepicker-Addon,nicofrand/jQuery-Timepicker-Addon,Youraiseme/jQuery-Timepicker-Addon,Jaspersoft/jQuery-Timepicker-Addon,Jaspersoft/jQuery-Timepicker-Addon,brenosilver/jQuery-Timepicker-Addon | ---
+++
@@ -5,15 +5,15 @@
timeOnlyTitle: 'Zvoľte čas',
timeText: 'Čas',
hourText: 'Hodiny',
- minuteText: 'Minuty',
+ minuteText: 'Minúty',
secondText: 'Sekundy',
millisecText: 'Milisekundy',
timezoneText: 'Časové pásmo',
currentText: 'Teraz',
- closeText: 'Zavřít',
+ closeText: 'Zavrieť',
timeFormat: 'h:m',
amNames: ['dop.', 'AM', 'A'],
- pmNames: ['odp.', 'PM', 'P'],
+ pmNames: ['pop.', 'PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['sk']); |
eb5e847adf69f0d183f6a13f72eb72ce7a1d2dc9 | test/unit/game_of_life.support.spec.js | test/unit/game_of_life.support.spec.js | describe('Support module', function () {
var S = GameOfLife.Support;
describe('For validating canvas', function () {
it('throws InvalidArgument if given other than a canvas element', function () {
expect(function () {
S.validateCanvas($('<p>foo</p>')[0]);
}).toThrow(new S.InvalidArgument('Not a canvas element'));
});
it('returns the given element if the element is a canvas', function () {
expect(S.validateCanvas($('<canvas></canvas>')[0]).getContext).toBeFunction();
});
});
});
| describe('Support module', function () {
var S = GameOfLife.Support;
describe('For validating canvas', function () {
it('throws InvalidArgument if given other than a canvas element', function () {
expect(function () {
S.validateCanvas($('<p>foo</p>')[0]);
}).toThrow(new S.InvalidArgument('Not a canvas element'));
});
it('returns the given element if the element is a canvas', function () {
expect(S.validateCanvas($('<canvas></canvas>')[0]).getContext).toBeFunction();
});
});
it('inverts an object', function () {
var obj = { foo: 1, bar: 2};
expect(S.invertObject(obj)).toEqual({1: 'foo', 2: 'bar'});
});
});
| Add unit test for object inversion | Add unit test for object inversion
| JavaScript | mit | tkareine/game_of_life,tkareine/game_of_life,tkareine/game_of_life | ---
+++
@@ -12,4 +12,9 @@
expect(S.validateCanvas($('<canvas></canvas>')[0]).getContext).toBeFunction();
});
});
+
+ it('inverts an object', function () {
+ var obj = { foo: 1, bar: 2};
+ expect(S.invertObject(obj)).toEqual({1: 'foo', 2: 'bar'});
+ });
}); |
4a69ba9da100f91abd49e90a1c810655e3785419 | lib/templates.js | lib/templates.js | const utilities = require('./utilities');
const limited = (limited) => limited ? ' | limited' : '';
const unique = (unique) => unique ? ' | unique' : '';
const points = (points) => (typeof points !== 'undefined' ? `${points}pt${points > 1 || points === 0 ? 's': ''}` : '');
const multiCard = (card) => `\n• *${card.name}* (${card.slot}) use \`/card ${card.name} (${card.slot})\` or \`/card #id ${utilities.cardId(card)}\``;
const effect = (effect) => effect ? `\n> ${effect}` : '';
function cardReduce(currentString, card) {
if(typeof currentString === 'object') {
currentString = cardReduce('', currentString);
}
return currentString + multiCard(card);
}
const templates = {
// Template for a single card
card: (card) => `${card.name} (${card.slot}${limited(card.limited)}${unique(card.unique)}): ${points(card.points)}\n${card.text}${effect(card.effect)}`,
// Template for multiple cards
multiple: (cards, query) => {
let cardString = cards.reduce(cardReduce);
return `I found more than one card matching *'${query.text}'*:${cardString}`;
},
// Template for no results
notFound: (query) => `Sorry i couldn't find a card for *'${query.text}'*`
};
module.exports = templates;
| const utilities = require('./utilities');
const limited = (limited) => limited ? ' | limited' : '';
const unique = (unique) => unique ? ' | unique' : '';
const cardIntro = (card) => `${card.name} (${card.slot}${limited(card.limited)}${unique(card.unique)}): ${points(card.points)}`;
const points = (points) => (typeof points !== 'undefined' ? `${points}pt${points > 1 || points === 0 ? 's': ''}` : '');
const multiCard = (card) => `\n• *${card.name}* (${card.slot}) use \`/card ${card.name} (${card.slot})\` or \`/card #id ${utilities.cardId(card)}\``;
const effect = (effect) => effect ? `\n> ${effect}` : '';
function cardReduce(currentString, card) {
if(typeof currentString === 'object') {
currentString = cardReduce('', currentString);
}
return currentString + multiCard(card);
}
const templates = {
// Template for a single card
card: (card) => `${cardIntro(card)}\n${card.text}${effect(card.effect)}`,
// Template for multiple cards
multiple: (cards, query) => {
let cardString = cards.reduce(cardReduce);
return `I found more than one card matching *'${query.text}'*:${cardString}`;
},
// Template for no results
notFound: (query) => `Sorry i couldn't find a card for *'${query.text}'*`
};
module.exports = templates;
| Split out the card template funciton | chore: Split out the card template funciton
| JavaScript | mit | bmds/SlackXWingCardCmd | ---
+++
@@ -2,6 +2,7 @@
const limited = (limited) => limited ? ' | limited' : '';
const unique = (unique) => unique ? ' | unique' : '';
+const cardIntro = (card) => `${card.name} (${card.slot}${limited(card.limited)}${unique(card.unique)}): ${points(card.points)}`;
const points = (points) => (typeof points !== 'undefined' ? `${points}pt${points > 1 || points === 0 ? 's': ''}` : '');
const multiCard = (card) => `\n• *${card.name}* (${card.slot}) use \`/card ${card.name} (${card.slot})\` or \`/card #id ${utilities.cardId(card)}\``;
const effect = (effect) => effect ? `\n> ${effect}` : '';
@@ -16,7 +17,7 @@
const templates = {
// Template for a single card
- card: (card) => `${card.name} (${card.slot}${limited(card.limited)}${unique(card.unique)}): ${points(card.points)}\n${card.text}${effect(card.effect)}`,
+ card: (card) => `${cardIntro(card)}\n${card.text}${effect(card.effect)}`,
// Template for multiple cards
multiple: (cards, query) => { |
d5a2f021fc31a29bc2be216f43b8baf6850a1ee7 | lib/transform.js | lib/transform.js | const sharp = require('sharp')
const cropDimensions = (width, height, maxSize) => {
if (width <= maxSize && height <= maxSize) return [width, height]
const aspectRatio = width / height
if (width > height) return [maxSize, Math.round(maxSize / aspectRatio)]
return [maxSize * aspectRatio, maxSize]
}
module.exports = (image, {
width,
height,
crop = false,
cropMaxSize,
gravity = sharp.gravity.center,
format = sharp.format.jpeg.id,
progressive = true,
quality = 80,
} = {}) => {
const transformer = sharp(image)
if (crop) {
transformer.resize(...cropDimensions(width, height, cropMaxSize)).crop(gravity)
} else {
transformer.resize(width, height).min().withoutEnlargement()
}
return transformer[format]({quality, progressive}).toBuffer()
}
| const sharp = require('sharp')
const cropDimensions = (width, height, maxSize) => {
if (width <= maxSize && height <= maxSize) return [width, height]
const aspectRatio = width / height
if (width > height) return [maxSize, Math.round(maxSize / aspectRatio)]
return [maxSize * aspectRatio, maxSize]
}
module.exports = (image, {
width,
height,
crop = false,
cropMaxSize,
gravity = sharp.gravity.center,
format = sharp.format.jpeg.id,
progressive = true,
quality = 80,
} = {}) => {
const transformer = sharp(image)
if (crop) {
transformer.resize(...cropDimensions(width, height, cropMaxSize)).crop(gravity)
} else {
transformer.resize(width, height, { fit: 'inside', withoutEnlargement: true })
}
return transformer[format]({quality, progressive}).toBuffer()
}
| Fix compatibility with sharp >=0.22.x | Fix compatibility with sharp >=0.22.x
.min() was removed | JavaScript | mit | pmb0/express-sharp,pmb0/express-sharp,pmb0/express-sharp | ---
+++
@@ -22,7 +22,7 @@
if (crop) {
transformer.resize(...cropDimensions(width, height, cropMaxSize)).crop(gravity)
} else {
- transformer.resize(width, height).min().withoutEnlargement()
+ transformer.resize(width, height, { fit: 'inside', withoutEnlargement: true })
}
return transformer[format]({quality, progressive}).toBuffer() |
a84f95e02670bb8f512ef1b0293610584de938f3 | web/js/main.js | web/js/main.js | jQuery(function ($) {
setup_search_box();
$('.tablesorter').tablesorter({
sortList: [[1,0]],
headers: {
0: { sorter: false },
1: { sorter: 'text'},
3: { sorter: false }
}
});
});
function setup_search_box() {
var el = $('#my_search_box .search');
if ( ! el.length ) { return; }
// Here we have logic for handling cases where user views a repo
// and then presses "Back" to go back to the list. We want to
// (a) NOT scroll to search input if scroll position is offset.
// This is a "Back" after scrolling and viewing a repo
// (b) Refresh 'search' if search input has some text.
// This is a "Back" after clicking on search results
if ( $(window).scrollTop() == 0 ) {
el.focus();
}
if ( el.val().length ) {
userList.search(el.val());
}
}
| jQuery(function ($) {
setup_search_box();
$('.tablesorter').tablesorter({
sortList: [[1,0]],
headers: {
1: { sorter: 'text'},
2: { sorter: false }
}
});
});
function setup_search_box() {
var el = $('#my_search_box .search');
if ( ! el.length ) { return; }
// Here we have logic for handling cases where user views a repo
// and then presses "Back" to go back to the list. We want to
// (a) NOT scroll to search input if scroll position is offset.
// This is a "Back" after scrolling and viewing a repo
// (b) Refresh 'search' if search input has some text.
// This is a "Back" after clicking on search results
if ( $(window).scrollTop() == 0 ) {
el.focus();
}
if ( el.val().length ) {
userList.search(el.val());
}
}
| Fix sort order since we now display the module logo right aligned to the module name cell | Fix sort order since we now display the module logo right aligned to the module name cell
| JavaScript | artistic-2.0 | perl6/modules.perl6.org,perl6/modules.perl6.org,perl6/modules.perl6.org,perl6/modules.perl6.org | ---
+++
@@ -3,9 +3,8 @@
$('.tablesorter').tablesorter({
sortList: [[1,0]],
headers: {
- 0: { sorter: false },
1: { sorter: 'text'},
- 3: { sorter: false }
+ 2: { sorter: false }
}
});
}); |
5b1c489335c68a97698a3b9bd3799cdcb4b8c4f6 | js/game.js | js/game.js | var Game = function(boardString){
this.board = '';
if (arguments.length === 1) {
this.board = boardString;
} else {
function random() {
return Math.floor(Math.random() * 10 + 6);
};
var firstTwo = random();
var secondTwo = random();
for ( var i = 0; i < 16; i++ ) {
if (i === firstTwo || i === secondTwo) {
this.board += '2';
} else {
this.board += '0';
};
};
}
};
Game.prototype.toString = function() {
this.board.
};
| Create board in Game constructor | Create board in Game constructor
| JavaScript | mit | suprfrye/galaxy-256,suprfrye/galaxy-256 | ---
+++
@@ -0,0 +1,23 @@
+var Game = function(boardString){
+ this.board = '';
+ if (arguments.length === 1) {
+ this.board = boardString;
+ } else {
+ function random() {
+ return Math.floor(Math.random() * 10 + 6);
+ };
+ var firstTwo = random();
+ var secondTwo = random();
+ for ( var i = 0; i < 16; i++ ) {
+ if (i === firstTwo || i === secondTwo) {
+ this.board += '2';
+ } else {
+ this.board += '0';
+ };
+ };
+ }
+};
+
+Game.prototype.toString = function() {
+ this.board.
+}; | |
ef980661130b68cfed37d32f29e3ad6069361fb9 | lib/feedpaper.js | lib/feedpaper.js | var Cache = require('./cache');
var fs = require('fs');
var handlers = require('./handlers');
var Ute = require('ute');
var util = require('./util');
function FeedPaper() {
this.ute = new Ute();
this.init();
}
FeedPaper.prototype.init = function () {
var categoryList = [];
var urlLookup = {};
var conf = JSON.parse(fs.readFileSync('conf/data.json'));
conf.forEach(function (category) {
var feeds = [];
category.feeds.forEach(function (feed) {
var feedId = util.slug(feed.title);
feeds.push({
id : feedId,
title: feed.title,
url : feed.url
});
urlLookup[feedId] = feed.url;
});
categoryList.push({
id : util.slug(category.title),
title: category.title,
feeds: feeds
});
});
this.cache = new Cache(categoryList, urlLookup);
};
FeedPaper.prototype.start = function () {
var self = this;
handlers.cache = this.cache;
this.ute.start(handlers);
this.cache.build(function (err) {
if (err) {
console.error(err);
}
self.cache.refresh();
});
};
module.exports = FeedPaper; | var Cache = require('./cache');
var fs = require('fs');
var handlers = require('./handlers');
var Ute = require('ute');
var util = require('./util');
function FeedPaper() {
this.ute = new Ute();
this.init();
}
FeedPaper.prototype.init = function () {
var categoryList = [];
var urlLookup = {};
console.log('[i] Loading data');
var conf = JSON.parse(fs.readFileSync('conf/data.json'));
conf.forEach(function (category) {
var feeds = [];
category.feeds.forEach(function (feed) {
var feedId = util.slug(feed.title);
feeds.push({
id : feedId,
title: feed.title,
url : feed.url
});
urlLookup[feedId] = feed.url;
});
categoryList.push({
id : util.slug(category.title),
title: category.title,
feeds: feeds
});
});
this.cache = new Cache(categoryList, urlLookup);
};
FeedPaper.prototype.start = function () {
var self = this;
handlers.cache = this.cache;
this.ute.start(handlers);
this.cache.build(function (err) {
if (err) {
console.error(err);
}
self.cache.refresh();
});
};
module.exports = FeedPaper; | Add loading data log message. | Add loading data log message.
| JavaScript | mit | cliffano/feedpaper,cliffano/feedpaper,cliffano/feedpaper | ---
+++
@@ -12,6 +12,8 @@
FeedPaper.prototype.init = function () {
var categoryList = [];
var urlLookup = {};
+
+ console.log('[i] Loading data');
var conf = JSON.parse(fs.readFileSync('conf/data.json'));
conf.forEach(function (category) { |
e5816421524dfb1d809b921923c7afb371471779 | lib/emitters/custom-event-emitter.js | lib/emitters/custom-event-emitter.js | var util = require("util")
, EventEmitter = require("events").EventEmitter
module.exports = (function() {
var CustomEventEmitter = function(fct) {
this.fct = fct
}
util.inherits(CustomEventEmitter, EventEmitter)
CustomEventEmitter.prototype.run = function() {
var self = this
// delay the function call and return the emitter
setTimeout(function(){
self.fct.call(self, self)
}, 1)
return this
}
CustomEventEmitter.prototype.success =
CustomEventEmitter.prototype.ok =
function(fct) {
this.on('success', fct)
return this
}
CustomEventEmitter.prototype.failure =
CustomEventEmitter.prototype.fail =
CustomEventEmitter.prototype.error =
function(fct) {
this.on('error', fct)
return this
}
CustomEventEmitter.prototype.done =
CustomEventEmitter.prototype.complete =
function(fct) {
this.on('error', function(err) { fct(err, null) })
.on('success', function(result) { fct(null, result) })
return this
}
return CustomEventEmitter
})()
| var util = require("util")
, EventEmitter = require("events").EventEmitter
module.exports = (function() {
var CustomEventEmitter = function(fct) {
this.fct = fct;
var self = this;
process.nextTick(function() {
if (self.fct) {
self.fct.call(self, self)
}
}.bind(this));
}
util.inherits(CustomEventEmitter, EventEmitter)
CustomEventEmitter.prototype.run = function() {
var self = this
return this
}
CustomEventEmitter.prototype.success =
CustomEventEmitter.prototype.ok =
function(fct) {
this.on('success', fct)
return this
}
CustomEventEmitter.prototype.failure =
CustomEventEmitter.prototype.fail =
CustomEventEmitter.prototype.error =
function(fct) {
this.on('error', fct)
return this
}
CustomEventEmitter.prototype.done =
CustomEventEmitter.prototype.complete =
function(fct) {
this.on('error', function(err) { fct(err, null) })
.on('success', function(result) { fct(null, result) })
return this
}
return CustomEventEmitter
})()
| Remove setTimeout in favor of process.nextTick() | Remove setTimeout in favor of process.nextTick()
According to [process.nextTick() documentation](http://nodejs.org/api/process.html#process_process_nexttick_callback), using setTimeout is not recommended:
On the next loop around the event loop call this callback. This is not a simple alias to setTimeout(fn, 0), it's much more efficient.
I'm not sure why you didn't use `nextTick()` yet, so if it was intended, please close :)
I'm currently testing this change and it seems to work better than with setTimeout.
What I'm unsure is the run function - it's not needed anymore imho.
| JavaScript | mit | IrfanBaqui/sequelize | ---
+++
@@ -3,18 +3,18 @@
module.exports = (function() {
var CustomEventEmitter = function(fct) {
- this.fct = fct
+ this.fct = fct;
+ var self = this;
+ process.nextTick(function() {
+ if (self.fct) {
+ self.fct.call(self, self)
+ }
+ }.bind(this));
}
util.inherits(CustomEventEmitter, EventEmitter)
CustomEventEmitter.prototype.run = function() {
var self = this
-
- // delay the function call and return the emitter
- setTimeout(function(){
- self.fct.call(self, self)
- }, 1)
-
return this
}
|
99bbcbebfc35cfca348860c2ea93e0a54ba2c25c | lib/output/modifiers/inlineAssets.js | lib/output/modifiers/inlineAssets.js | var svgToImg = require('./svgToImg');
var svgToPng = require('./svgToPng');
var resolveImages = require('./resolveImages');
var fetchRemoteImages = require('./fetchRemoteImages');
var Promise = require('../../utils/promise');
/**
Inline all assets in a page
@param {String} rootFolder
*/
function inlineAssets(rootFolder, currentFile) {
return function($) {
return Promise()
// Resolving images and fetching external images should be
// done before svg conversion
.then(resolveImages.bind(null, currentFile))
.then(fetchRemoteImages.bind(null, rootFolder, currentFile))
.then(svgToImg.bind(null, rootFolder, currentFile))
.then(svgToPng.bind(null, rootFolder, currentFile));
};
}
module.exports = inlineAssets;
| var svgToImg = require('./svgToImg');
var svgToPng = require('./svgToPng');
var resolveImages = require('./resolveImages');
var fetchRemoteImages = require('./fetchRemoteImages');
var Promise = require('../../utils/promise');
/**
Inline all assets in a page
@param {String} rootFolder
*/
function inlineAssets(rootFolder, currentFile) {
return function($) {
return Promise()
// Resolving images and fetching external images should be
// done before svg conversion
.then(resolveImages.bind(null, currentFile, $))
.then(fetchRemoteImages.bind(null, rootFolder, currentFile, $))
.then(svgToImg.bind(null, rootFolder, currentFile, $))
.then(svgToPng.bind(null, rootFolder, currentFile, $));
};
}
module.exports = inlineAssets;
| Fix modifiers for ebook format | Fix modifiers for ebook format
| JavaScript | apache-2.0 | gencer/gitbook,strawluffy/gitbook,tshoper/gitbook,gencer/gitbook,tshoper/gitbook,GitbookIO/gitbook,ryanswanson/gitbook | ---
+++
@@ -16,11 +16,11 @@
// Resolving images and fetching external images should be
// done before svg conversion
- .then(resolveImages.bind(null, currentFile))
- .then(fetchRemoteImages.bind(null, rootFolder, currentFile))
+ .then(resolveImages.bind(null, currentFile, $))
+ .then(fetchRemoteImages.bind(null, rootFolder, currentFile, $))
- .then(svgToImg.bind(null, rootFolder, currentFile))
- .then(svgToPng.bind(null, rootFolder, currentFile));
+ .then(svgToImg.bind(null, rootFolder, currentFile, $))
+ .then(svgToPng.bind(null, rootFolder, currentFile, $));
};
}
|
1fbef25c78e8677116d2bee0aea2a239b4653de6 | src/util/encodeToVT100.js | src/util/encodeToVT100.js | /**
* Bytes to encode to VT100 control sequence.
*
* @param {String} code Control code that you want to encode
* @returns {Buffer} Returns encoded bytes
*/
export const encodeToVT100 = code => `\u001b${code}`;
| /**
* Bytes to encode to VT100 control sequence.
*
* @param {String} code Control code that you want to encode
* @returns {String} Returns encoded string
*/
export const encodeToVT100 = code => '\u001b' + code;
| Change template string to concatenation | perf(util): Change template string to concatenation
| JavaScript | mit | kittikjs/cursor,ghaiklor/terminal-canvas,ghaiklor/terminal-canvas | ---
+++
@@ -2,6 +2,6 @@
* Bytes to encode to VT100 control sequence.
*
* @param {String} code Control code that you want to encode
- * @returns {Buffer} Returns encoded bytes
+ * @returns {String} Returns encoded string
*/
-export const encodeToVT100 = code => `\u001b${code}`;
+export const encodeToVT100 = code => '\u001b' + code; |
6a04967c6133b67b3525f2383dc9fbc6ba627ab8 | test/data-structures/testFenwickTree.js | test/data-structures/testFenwickTree.js | /* eslint-env mocha */
const FenwickTree = require('../../src').DataStructures.FenwickTree;
const assert = require('assert');
describe('Fenwick Tree', () => {
it('should be empty when initialized', () => {
const inst = new FenwickTree([]);
assert(inst.isEmpty());
assert.equal(inst.size, 0);
});
it('should build tree with array', () => {
const inst = new FenwickTree(4);
inst.buildTree([1, 2, 3, 4]);
assert(!inst.isEmpty());
assert.equal(inst.size, 4);
});
});
| /* eslint-env mocha */
const FenwickTree = require('../../src').DataStructures.FenwickTree;
const assert = require('assert');
describe('Fenwick Tree', () => {
it('should be empty when initialized', () => {
const inst = new FenwickTree([]);
assert(inst.isEmpty());
assert.equal(inst.size, 0);
});
it('should build tree with array', () => {
const inst = new FenwickTree(4);
inst.buildTree([1, 2, 3, 4]);
assert(!inst.isEmpty());
assert.equal(inst.size, 4);
});
it('should sum the array till index', () => {
const inst = new FenwickTree(4);
inst.buildTree([1, 2, 3, 4]);
assert.equal(inst.getSum(2), 6);
assert.equal(inst.getSum(0), 1);
assert.equal(inst.getSum(3), 10);
assert.throws(() => inst.getSum(4), Error);
});
});
| Test Fenwick Tree: Sums till index | Test Fenwick Tree: Sums till index
| JavaScript | mit | ManrajGrover/algorithms-js | ---
+++
@@ -17,4 +17,14 @@
assert.equal(inst.size, 4);
});
+ it('should sum the array till index', () => {
+ const inst = new FenwickTree(4);
+
+ inst.buildTree([1, 2, 3, 4]);
+
+ assert.equal(inst.getSum(2), 6);
+ assert.equal(inst.getSum(0), 1);
+ assert.equal(inst.getSum(3), 10);
+ assert.throws(() => inst.getSum(4), Error);
+ });
}); |
a4f7a4cf1b2aaaf0a5bec5d7de43057ef7b80e8f | server/config/config.js | server/config/config.js | const config = {
development: {
username: 'postgres',
password: '212213',
database: 'more-recipes-development',
host: '127.0.0.1',
dialect: 'postgres'
},
test: {
username: 'postgres',
password: '212213',
database: 'more-recipes-tests',
host: '127.0.0.1',
dialect: 'postgres',
logging: false
},
production: {
username: 'postgres',
password: '212213',
database: 'more-recipes-development',
host: '127.0.0.1',
dialect: 'postgres'
}
};
module.exports = config;
| const config = {
development: {
username: 'postgres',
password: '212213',
database: 'more-recipes-development',
host: '127.0.0.1',
dialect: 'postgres'
},
test: {
username: 'postgres',
password: '212213',
database: 'more-recipes-tests',
host: '127.0.0.1',
dialect: 'postgres',
logging: false
},
production: {
use_env_variable: 'DATABASE_URL'
}
};
module.exports = config;
| Add database url for production | Add database url for production
| JavaScript | mit | WillyWunderdog/More-Recipes-Gbenga,WillyWunderdog/More-Recipes-Gbenga | ---
+++
@@ -15,11 +15,7 @@
logging: false
},
production: {
- username: 'postgres',
- password: '212213',
- database: 'more-recipes-development',
- host: '127.0.0.1',
- dialect: 'postgres'
+ use_env_variable: 'DATABASE_URL'
}
};
module.exports = config; |
244cd6cc04e1f092f68654764ed054f5c1a1c77a | src/googleHandler.js | src/googleHandler.js | (function(){
angular.module('angularytics').factory('AngularyticsGoogleHandler', function($log) {
var service = {};
service.trackPageView = function(url) {
_gaq.push(['_set', 'page', url]);
_gaq.push(['_trackPageview', url]);
}
service.trackEvent = function(category, action, opt_label, opt_value, opt_noninteraction) {
_gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction]);
}
return service;
}).factory('AngularyticsGoogleUniversalHandler', function () {
var service = {};
service.trackPageView = function (url) {
ga('send', 'pageView', url);
};
service.trackEvent = function (category, action, opt_label, opt_value, opt_noninteraction) {
ga('send', 'event', category, action, opt_label, opt_value, {'nonInteraction': opt_noninteraction});
};
return service;
});
})();
| (function(){
angular.module('angularytics').factory('AngularyticsGoogleHandler', function($log) {
var service = {};
service.trackPageView = function(url) {
_gaq.push(['_set', 'page', url]);
_gaq.push(['_trackPageview', url]);
}
service.trackEvent = function(category, action, opt_label, opt_value, opt_noninteraction) {
_gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction]);
}
return service;
}).factory('AngularyticsGoogleUniversalHandler', function () {
var service = {};
service.trackPageView = function (url) {
ga('set', 'page', url);
ga('send', 'pageView');
};
service.trackEvent = function (category, action, opt_label, opt_value, opt_noninteraction) {
ga('send', 'event', category, action, opt_label, opt_value, {'nonInteraction': opt_noninteraction});
};
return service;
});
})();
| Change GoogleUniversal to set page as well | Change GoogleUniversal to set page as well
This has additional benefit that future trackEvent() calls will use the new page value as well.
Also, it silences a minor warning from the Analytics Debugger. | JavaScript | mit | mgonto/angularytics,l3r/angul3rytics,mirez/angularytics,suhyunjeon/angularytics | ---
+++
@@ -16,7 +16,8 @@
var service = {};
service.trackPageView = function (url) {
- ga('send', 'pageView', url);
+ ga('set', 'page', url);
+ ga('send', 'pageView');
};
service.trackEvent = function (category, action, opt_label, opt_value, opt_noninteraction) { |
31ec3d4799621b5464076e0535183c1b5403fec2 | tests/dummy/app/components/trigger-event-widget.js | tests/dummy/app/components/trigger-event-widget.js | import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { keyResponder, onKey } from 'ember-keyboard';
@keyResponder({ activated: true })
export default class extends Component {
@tracked keyboardActivated = true;
@tracked keyDown = false;
@tracked keyDownWithMods = false;
@tracked keyPress = false;
@tracked keyUp = false;
@onKey('KeyA', { event: 'keydown' })
toggleKeyDown = () => (this.keyDown = !this.keyDown);
@onKey('KeyA+cmd+shift', { event: 'keydown' })
toggleKeyDownWithMods = () => (this.keyDownWithMods = !this.keyDownWithMods);
@onKey('KeyA', { event: 'keypress' })
toggleKeyPress = () => (this.keyPress = !this.keyPress);
@onKey('KeyA', { event: 'keyup' })
toggleKeyUp = () => (this.keyUp = !this.keyUp);
}
| import Component from '@glimmer/component';
import { set } from '@ember/object';
import { keyResponder, onKey } from 'ember-keyboard';
// Use set(this) instead of tracked properties for Ember 3.8 compatibility.
@keyResponder({ activated: true })
export default class extends Component {
keyboardActivated = true;
keyDown = false;
keyDownWithMods = false;
keyPress = false;
keyUp = false;
@onKey('KeyA', { event: 'keydown' })
toggleKeyDown = () => set(this, 'keyDown', !this.keyDown);
@onKey('KeyA+cmd+shift', { event: 'keydown' })
toggleKeyDownWithMods = () =>
set(this, 'keyDownWithMods', !this.keyDownWithMods);
@onKey('KeyA', { event: 'keypress' })
toggleKeyPress = () => set(this, 'keyPress', !this.keyPress);
@onKey('KeyA', { event: 'keyup' })
toggleKeyUp = () => set(this, 'keyUp', !this.keyUp);
}
| Make TriggerEventWidgetComponent compatible with Ember 3.8 | Make TriggerEventWidgetComponent compatible with Ember 3.8
| JavaScript | mit | null-null-null/ember-keyboard,null-null-null/ember-keyboard | ---
+++
@@ -1,24 +1,26 @@
import Component from '@glimmer/component';
-import { tracked } from '@glimmer/tracking';
+import { set } from '@ember/object';
import { keyResponder, onKey } from 'ember-keyboard';
+// Use set(this) instead of tracked properties for Ember 3.8 compatibility.
@keyResponder({ activated: true })
export default class extends Component {
- @tracked keyboardActivated = true;
- @tracked keyDown = false;
- @tracked keyDownWithMods = false;
- @tracked keyPress = false;
- @tracked keyUp = false;
+ keyboardActivated = true;
+ keyDown = false;
+ keyDownWithMods = false;
+ keyPress = false;
+ keyUp = false;
@onKey('KeyA', { event: 'keydown' })
- toggleKeyDown = () => (this.keyDown = !this.keyDown);
+ toggleKeyDown = () => set(this, 'keyDown', !this.keyDown);
@onKey('KeyA+cmd+shift', { event: 'keydown' })
- toggleKeyDownWithMods = () => (this.keyDownWithMods = !this.keyDownWithMods);
+ toggleKeyDownWithMods = () =>
+ set(this, 'keyDownWithMods', !this.keyDownWithMods);
@onKey('KeyA', { event: 'keypress' })
- toggleKeyPress = () => (this.keyPress = !this.keyPress);
+ toggleKeyPress = () => set(this, 'keyPress', !this.keyPress);
@onKey('KeyA', { event: 'keyup' })
- toggleKeyUp = () => (this.keyUp = !this.keyUp);
+ toggleKeyUp = () => set(this, 'keyUp', !this.keyUp);
} |
615a6b80cf560ab39e912349ff70d783d796c45b | src/routes/teams.js | src/routes/teams.js | const _ = require('koa-route');
const { teams } = require('src/api');
const { read } = require('src/middlewares/methods');
module.exports = [
_.get('/teams/', read(teams.list, {
schema: {
type: 'object',
properties: {
page: {default: '1'},
per_page: {default: '100'}
}
},
access: {permission: true}
})),
_.get('/teams/:id', read(teams.get, {
access: {permission: true}
}))
];
| const _ = require('koa-route');
const { teams } = require('src/api');
const { read } = require('src/middlewares/methods');
module.exports = [
_.get('/organizations/:orgId/teams/', read(teams.list, {
schema: {
type: 'object',
properties: {
page: {default: '1'},
per_page: {default: '100'}
}
},
access: {permission: true}
})),
_.get('/teams/:id', read(teams.get, {
access: {permission: true}
}))
];
| Fix team list endpoint to start with /organizations/:orgId | Fix team list endpoint to start with /organizations/:orgId
| JavaScript | bsd-3-clause | praekelt/numi-api | ---
+++
@@ -4,7 +4,7 @@
module.exports = [
- _.get('/teams/', read(teams.list, {
+ _.get('/organizations/:orgId/teams/', read(teams.list, {
schema: {
type: 'object',
properties: { |
67c97274f6e1440124625ada17e00e801c9bb9a0 | api/services/NorthstarService.js | api/services/NorthstarService.js | 'use strict';
const NorthstarClient = require('@dosomething/northstar-js');
/**
* Nortstar client service.
*/
module.exports = {
getClient() {
if (!this.client) {
this.client = new NorthstarClient({
baseURI: sails.config.northstar.apiBaseURI,
apiKey: sails.config.northstar.apiKey,
});
}
return this.client;
},
getUserFor(model) {
const options = this.resolveRequestId(model);
return this.getClient().getUser(options.type, options.id);
},
resolveRequestId(model) {
let id;
let type;
if (model.user_id) {
type = 'id';
id = model.user_id;
} else if (model.email) {
type = 'email';
id = model.email;
} else if (model.mobile) {
type = 'mobile';
id = model.mobile;
}
return { type, id };
},
};
| 'use strict';
const NorthstarClient = require('@dosomething/northstar-js');
/**
* Nortstar client service.
*/
module.exports = {
getClient() {
if (!this.client) {
this.client = new NorthstarClient({
baseURI: sails.config.northstar.apiBaseURI,
apiKey: sails.config.northstar.apiKey,
});
}
return this.client;
},
getUserFor(model) {
const options = this.resolveRequestId(model);
return this.getClient().getUser(options.type, options.id);
},
resolveRequestId(model) {
let id;
let type;
if (model.user_id) {
type = 'id';
id = model.user_id;
} else if (model.email) {
type = 'email';
id = model.email;
} else if (model.mobile) {
type = 'mobile';
id = model.mobile;
}
return { type, id };
},
isOneOfFieldSet(submission) {
return ['user_id', 'email', 'mobile'].every(userField => !submission[userField]);
}
};
| Add isOneOfFieldSet method to Northstar service | Add isOneOfFieldSet method to Northstar service
| JavaScript | mit | DoSomething/quicksilver-api,DoSomething/quicksilver-api | ---
+++
@@ -40,4 +40,8 @@
return { type, id };
},
+ isOneOfFieldSet(submission) {
+ return ['user_id', 'email', 'mobile'].every(userField => !submission[userField]);
+ }
+
}; |
0cddf22bb68647e638bfaa25e5e3d686ca34617f | tests/test031.js | tests/test031.js | // test for string split
var b = "1,4,7";
var a = b.split(",");
result = a.length==3 && a[0]==1 && a[1]==4 && a[2]==7;
| // test for string split
var b = "1,4,7";
var a = b.split(",");
assert (a.length == 3, "a.length = " + a.length);
assert (a[0]==1, "a[0]=" + a[0]);
assert (a[1]==4, "a[1]=" + a[1]);
assert (a[2]==7, "a[2]=" + a[2]);
result = 1;
| Test rewritten to get more precise error location. | Test rewritten to get more precise error location. | JavaScript | mit | GuillermoHernan/AsyncScript,GuillermoHernan/AsyncScript,GuillermoHernan/AsyncScript | ---
+++
@@ -2,4 +2,9 @@
var b = "1,4,7";
var a = b.split(",");
-result = a.length==3 && a[0]==1 && a[1]==4 && a[2]==7;
+assert (a.length == 3, "a.length = " + a.length);
+assert (a[0]==1, "a[0]=" + a[0]);
+assert (a[1]==4, "a[1]=" + a[1]);
+assert (a[2]==7, "a[2]=" + a[2]);
+
+result = 1; |
4f46a23512c590500edde08e3ef7fe15310ead46 | website/static/js/pages/project-registrations-page.js | website/static/js/pages/project-registrations-page.js | 'use strict';
require('css/registrations.css');
var ko = require('knockout');
var $ = require('jquery');
var $osf = require('js/osfHelpers');
var RegistrationManager = require('js/registrationUtils').RegistrationManager;
var ctx = window.contextVars;
var node = window.contextVars.node;
$(document).ready(function() {
$('#registrationsTabs').tab();
$('#registrationsTabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
var draftManager = new RegistrationManager(node, '#draftRegistrationScope', {
list: node.urls.api + 'draft/',
submit: node.urls.api + 'draft/{draft_pk}/submit/',
get: node.urls.api + 'draft/{draft_pk}/',
delete: node.urls.api + 'draft/{draft_pk}/',
schemas: '/api/v1/project/schema/',
edit: node.urls.web + 'draft/{draft_pk}/'
});
draftManager.init();
$('#registerNode').click(function(event) {
event.preventDefault();
draftManager.beforeCreateDraft();
});
});
| 'use strict';
require('css/registrations.css');
var ko = require('knockout');
var $ = require('jquery');
var $osf = require('js/osfHelpers');
var RegistrationManager = require('js/registrationUtils').RegistrationManager;
var ctx = window.contextVars;
var node = window.contextVars.node;
$(document).ready(function() {
$('#registrationsTabs').tab();
$('#registrationsTabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
var draftManager = new RegistrationManager(node, '#draftRegistrationScope', {
list: node.urls.api + 'draft/',
// TODO: uncomment when we support draft submission for review
//submit: node.urls.api + 'draft/{draft_pk}/submit/',
delete: node.urls.api + 'draft/{draft_pk}/',
schemas: '/api/v1/project/schema/',
edit: node.urls.web + 'draft/{draft_pk}/'
});
draftManager.init();
$('#registerNode').click(function(event) {
event.preventDefault();
draftManager.beforeCreateDraft();
});
});
| Remove unnescessary routes from registration parameters | Remove unnescessary routes from registration parameters
| JavaScript | apache-2.0 | zachjanicki/osf.io,caseyrollins/osf.io,abought/osf.io,saradbowman/osf.io,chrisseto/osf.io,wearpants/osf.io,caneruguz/osf.io,mluke93/osf.io,doublebits/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,GageGaskins/osf.io,danielneis/osf.io,SSJohns/osf.io,adlius/osf.io,samchrisinger/osf.io,hmoco/osf.io,mfraezz/osf.io,samanehsan/osf.io,icereval/osf.io,leb2dg/osf.io,RomanZWang/osf.io,Ghalko/osf.io,TomHeatwole/osf.io,Nesiehr/osf.io,kwierman/osf.io,RomanZWang/osf.io,HalcyonChimera/osf.io,TomHeatwole/osf.io,aaxelb/osf.io,KAsante95/osf.io,acshi/osf.io,DanielSBrown/osf.io,caseyrygt/osf.io,mluke93/osf.io,adlius/osf.io,abought/osf.io,emetsger/osf.io,doublebits/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,erinspace/osf.io,alexschiller/osf.io,mfraezz/osf.io,jnayak1/osf.io,hmoco/osf.io,GageGaskins/osf.io,mfraezz/osf.io,KAsante95/osf.io,ticklemepierce/osf.io,sloria/osf.io,Nesiehr/osf.io,doublebits/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,icereval/osf.io,RomanZWang/osf.io,rdhyee/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,baylee-d/osf.io,Ghalko/osf.io,acshi/osf.io,billyhunt/osf.io,brandonPurvis/osf.io,sloria/osf.io,samchrisinger/osf.io,pattisdr/osf.io,jnayak1/osf.io,SSJohns/osf.io,felliott/osf.io,TomBaxter/osf.io,kch8qx/osf.io,doublebits/osf.io,amyshi188/osf.io,brianjgeiger/osf.io,ZobairAlijan/osf.io,danielneis/osf.io,crcresearch/osf.io,danielneis/osf.io,binoculars/osf.io,aaxelb/osf.io,pattisdr/osf.io,brandonPurvis/osf.io,zamattiac/osf.io,KAsante95/osf.io,emetsger/osf.io,mattclark/osf.io,laurenrevere/osf.io,rdhyee/osf.io,leb2dg/osf.io,felliott/osf.io,ZobairAlijan/osf.io,TomBaxter/osf.io,asanfilippo7/osf.io,HalcyonChimera/osf.io,RomanZWang/osf.io,alexschiller/osf.io,saradbowman/osf.io,hmoco/osf.io,zamattiac/osf.io,Ghalko/osf.io,HalcyonChimera/osf.io,caseyrygt/osf.io,asanfilippo7/osf.io,felliott/osf.io,abought/osf.io,rdhyee/osf.io,Johnetordoff/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,asanfilippo7/osf.io,aaxelb/osf.io,kch8qx/osf.io,caseyrollins/osf.io,caneruguz/osf.io,mluo613/osf.io,doublebits/osf.io,samchrisinger/osf.io,TomHeatwole/osf.io,billyhunt/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,binoculars/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,billyhunt/osf.io,crcresearch/osf.io,KAsante95/osf.io,emetsger/osf.io,SSJohns/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,alexschiller/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,Nesiehr/osf.io,sloria/osf.io,jnayak1/osf.io,erinspace/osf.io,samanehsan/osf.io,samanehsan/osf.io,cslzchen/osf.io,hmoco/osf.io,mfraezz/osf.io,acshi/osf.io,amyshi188/osf.io,adlius/osf.io,mattclark/osf.io,abought/osf.io,caseyrygt/osf.io,RomanZWang/osf.io,leb2dg/osf.io,crcresearch/osf.io,DanielSBrown/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,cwisecarver/osf.io,felliott/osf.io,danielneis/osf.io,amyshi188/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,wearpants/osf.io,caseyrygt/osf.io,samchrisinger/osf.io,alexschiller/osf.io,kwierman/osf.io,kch8qx/osf.io,binoculars/osf.io,Ghalko/osf.io,cwisecarver/osf.io,amyshi188/osf.io,mluke93/osf.io,laurenrevere/osf.io,mluo613/osf.io,ZobairAlijan/osf.io,mattclark/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,kwierman/osf.io,chrisseto/osf.io,brandonPurvis/osf.io,erinspace/osf.io,kch8qx/osf.io,samanehsan/osf.io,zamattiac/osf.io,cwisecarver/osf.io,adlius/osf.io,kwierman/osf.io,laurenrevere/osf.io,acshi/osf.io,wearpants/osf.io,billyhunt/osf.io,DanielSBrown/osf.io,emetsger/osf.io,Nesiehr/osf.io,mluke93/osf.io,caneruguz/osf.io,chennan47/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,brandonPurvis/osf.io,jnayak1/osf.io,caseyrollins/osf.io,leb2dg/osf.io,zachjanicki/osf.io,ticklemepierce/osf.io,mluo613/osf.io,baylee-d/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,chennan47/osf.io,Johnetordoff/osf.io,GageGaskins/osf.io,wearpants/osf.io,aaxelb/osf.io,mluo613/osf.io,TomHeatwole/osf.io,asanfilippo7/osf.io,alexschiller/osf.io,rdhyee/osf.io,icereval/osf.io,TomBaxter/osf.io,SSJohns/osf.io,pattisdr/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,GageGaskins/osf.io,KAsante95/osf.io,zachjanicki/osf.io,cslzchen/osf.io | ---
+++
@@ -20,8 +20,8 @@
var draftManager = new RegistrationManager(node, '#draftRegistrationScope', {
list: node.urls.api + 'draft/',
- submit: node.urls.api + 'draft/{draft_pk}/submit/',
- get: node.urls.api + 'draft/{draft_pk}/',
+ // TODO: uncomment when we support draft submission for review
+ //submit: node.urls.api + 'draft/{draft_pk}/submit/',
delete: node.urls.api + 'draft/{draft_pk}/',
schemas: '/api/v1/project/schema/',
edit: node.urls.web + 'draft/{draft_pk}/' |
01f264010f691f9c86fd6c83c3a231064d2b4913 | client/components/lists/ListSignupFormCreator.js | client/components/lists/ListSignupFormCreator.js | import React from 'react';
import { Modal } from 'react-bootstrap';
export default class ListSignupFormCreator extends React.Component {
constructor(props) {
super(props);
this.state = {
subscribeKey: this.props.subscribeKey,
showModal: false
};
}
showModal() {
this.setState({
showModal: true
});
}
componentWillReceiveProps(props) {
this.setState({
showModal: props.showModal,
subscribeKey: props.subscribeKey
})
}
closeModal() {
this.setState({
showModal: false
});
}
render() {
const actionUrl = `${window.location.origin}/api/list/subscribe`;
return (
<Modal show={this.state.showModal} onHide={this.closeModal.bind(this)}>
<div className="modal-content">
<div className="modal-header">
<h4 class="modal-title">Modal title</h4>
</div>
<div className="modal-body">
{`
<form action="${actionUrl}" target="_blank">
<label for="signup-email">Email</label>
<input type="email" value="" name="email" label="signup-email">
<input type="hidden" name="subscribeKey" value="${this.state.subscribeKey}" />
<input type="submit" value="Subscribe" name="Subscribe">
</form>
`}
</div>
<div className="modal-footer">Footer</div>
</div>
</Modal>
);
}
}
| import React from 'react';
import { Modal } from 'react-bootstrap';
export default class ListSignupFormCreator extends React.Component {
constructor(props) {
super(props);
this.state = {
subscribeKey: this.props.subscribeKey,
showModal: false
};
}
showModal() {
this.setState({
showModal: true
});
}
componentWillReceiveProps(props) {
this.setState({
showModal: props.showModal,
subscribeKey: props.subscribeKey
})
}
closeModal() {
this.setState({
showModal: false
});
}
render() {
const actionUrl = `${window.location.origin}/api/list/subscribe`;
return (
<Modal show={this.state.showModal} onHide={this.closeModal.bind(this)}>
<div className="modal-content">
<div className="modal-header">
<h3 class="modal-title">Embeddable subscription form</h3>
</div>
<div className="modal-body">
<h4>Allow users to sign up to your mailing list by embedding this HTML code into your website</h4>
<br/>
<textarea className="form-control" rows="5">
{`
<form action="${actionUrl}" target="_blank">
<label for="signup-email">Email</label>
<input type="email" value="" name="email" label="signup-email">
<input type="hidden" name="subscribeKey" value="${this.state.subscribeKey}" />
<input type="submit" value="Subscribe" name="Subscribe">
</form>
`}
</textarea>
</div>
<div className="modal-footer"></div>
</div>
</Modal>
);
}
}
| Add instructions and improve formatting | Add instructions and improve formatting
| JavaScript | bsd-3-clause | zhakkarn/Mail-for-Good,zhakkarn/Mail-for-Good,karuppiah7890/Mail-for-Good,zhakkarn/Mail-for-Good,karuppiah7890/Mail-for-Good,karuppiah7890/Mail-for-Good | ---
+++
@@ -38,10 +38,13 @@
<Modal show={this.state.showModal} onHide={this.closeModal.bind(this)}>
<div className="modal-content">
<div className="modal-header">
- <h4 class="modal-title">Modal title</h4>
+ <h3 class="modal-title">Embeddable subscription form</h3>
</div>
<div className="modal-body">
- {`
+ <h4>Allow users to sign up to your mailing list by embedding this HTML code into your website</h4>
+ <br/>
+ <textarea className="form-control" rows="5">
+ {`
<form action="${actionUrl}" target="_blank">
<label for="signup-email">Email</label>
<input type="email" value="" name="email" label="signup-email">
@@ -49,8 +52,9 @@
<input type="submit" value="Subscribe" name="Subscribe">
</form>
`}
+ </textarea>
</div>
- <div className="modal-footer">Footer</div>
+ <div className="modal-footer"></div>
</div>
</Modal>
); |
cadc5ff5d1060a77cb00d90f1eb4d0cff81c0d14 | extract.js | extract.js | (function () {
function descend(path, o) {
var step = path.shift();
if (typeof(o[step]) === "undefined") {
throw new Error("Broken descend path");
}
while (path.length > 0) {
if (typeof(o[step]) !== "object") {
throw new Error("Invalid descend path");
}
return descend(path, o[step]);
}
return o[step];
}
define({
load: function (name, req, load, config) {
var mod, x;
if (name.indexOf("?") === -1) {
load.error("No params specified");
} else {
x = name.slice(0, name.indexOf("?")).split(",");
mod = name.slice(name.indexOf("?") + 1);
req([mod], function (inc) {
var ret = {};
var path;
try {
if (x.length > 1) {
x.forEach(function (pname) {
path = pname.split(".");
ret[path[path.length - 1]] = descend(path, inc);
});
} else {
path = x[0].split(".");
ret = descend(path, inc);
}
load(ret);
} catch (e) {
load.error(e.message);
}
});
}
}
});
}());
| (function () {
function descend(path, o) {
var step = path.shift();
if (typeof(o[step]) === "undefined") {
throw new Error("Broken descend path");
}
while (path.length > 0) {
if (typeof(o[step]) !== "object") {
throw new Error("Invalid descend path");
}
return descend(path, o[step]);
}
return o[step];
}
define({
load: function (name, req, load, config) {
var mod, x;
if (name.indexOf("?") === -1) {
load.error("No params specified");
} else {
x = name.slice(0, name.indexOf("?")).split(",");
mod = name.slice(name.indexOf("?") + 1);
req([mod], function (inc) {
var ret = {};
var path;
try {
if (x.length > 1) {
while (x.length > 0) {
path = x.shift().split(".");
ret[path[path.length - 1]] = descend(path, inc);
}
} else {
path = x[0].split(".");
ret = descend(path, inc);
}
load(ret);
} catch (e) {
load.error(e.message);
}
});
}
}
});
}());
| Replace forEach with while for wider reach | Replace forEach with while for wider reach
| JavaScript | mit | nikcorg/extract | ---
+++
@@ -33,10 +33,10 @@
try {
if (x.length > 1) {
- x.forEach(function (pname) {
- path = pname.split(".");
+ while (x.length > 0) {
+ path = x.shift().split(".");
ret[path[path.length - 1]] = descend(path, inc);
- });
+ }
} else {
path = x[0].split(".");
ret = descend(path, inc); |
5d07a09b4d5c72eca8564dd30bcd5f2f2a4bb6f0 | tasks/watch.js | tasks/watch.js | 'use strict';
var gulp = require('gulp');
exports.css = function() {
gulp.watch('./app/**/*.css', ['autoprefix']);
};
exports.copy = function() {
gulp.watch('./app/**/*.html', ['copy']);
};
exports.js = function() {
gulp.watch('./app/**/*.js', ['browserify']);
};
| 'use strict';
var gulp = require('gulp');
exports.css = function() {
gulp.watch('./app/**/*.css', ['autoprefix']);
};
exports.copy = function() {
gulp.watch('./app/**/*.{html,jpg,jpeg,png,svg}', ['copy']);
};
exports.js = function() {
gulp.watch('./app/**/*.js', ['browserify']);
};
| Add images to the copy task | Add images to the copy task
| JavaScript | mit | dasilvacontin/animus,formap/animus | ---
+++
@@ -6,7 +6,7 @@
};
exports.copy = function() {
- gulp.watch('./app/**/*.html', ['copy']);
+ gulp.watch('./app/**/*.{html,jpg,jpeg,png,svg}', ['copy']);
};
exports.js = function() { |
1bcffdea0361b75307330351722a1fa48c6e758e | app.js | app.js | const express = require('express');
const aws = require('aws-sdk');
const app = express();
const port = process.env.PORT || 3000;
const bucket = process.env.S3_BUCKET;
app.use(express.static('./public'));
app.listen(port);
console.log('listening on port', port);
app.get('/sign-s3', (req, res) => {
const s3 = new aws.S3();
const fileName = req.query['file-name'];
const fileType = req.query['file-type'];
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
console.log('error getting signed url: ', err);
return res.end();
}
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
res.send(returnData);
});
}) | const express = require('express');
const aws = require('aws-sdk');
const app = express();
const port = process.env.PORT || 3000;
const S3_BUCKET = process.env.S3_BUCKET;
app.use(express.static('./public'));
app.listen(port);
console.log('listening on port', port);
app.get('/sign-s3', (req, res) => {
const s3 = new aws.S3();
const fileName = req.query['file-name'];
const fileType = req.query['file-type'];
const s3Params = {
Bucket: S3_BUCKET,
Key: fileName,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
console.log(s3Params)
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
console.log('error getting signed url: ', err);
return res.end();
}
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
res.send(returnData);
});
}) | Fix s3 bucket variable name bug | Fix s3 bucket variable name bug
| JavaScript | mit | bkilrain/FamilyPhotoShare,bkilrain/FamilyPhotoShare | ---
+++
@@ -3,7 +3,7 @@
const app = express();
const port = process.env.PORT || 3000;
-const bucket = process.env.S3_BUCKET;
+const S3_BUCKET = process.env.S3_BUCKET;
app.use(express.static('./public'));
@@ -23,7 +23,7 @@
ContentType: fileType,
ACL: 'public-read'
};
-
+ console.log(s3Params)
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
console.log('error getting signed url: ', err); |
fe48a78bfc5402cca34be93914efd2700c3864d8 | app.js | app.js | const express = require('express');
const db = require('./lib/db');
const app = express();
const port = process.env.PORT || 3000;
process.env.PATH = `${process.env.PATH}:./node_modules/.bin`;
app.use('/current', require('./routes/current'));
app.use('/sparkline', require('./routes/sparkline'));
app.use('/update', require('./routes/update'));
async function main() {
db.startup()
.catch( err => console.error(err.stack) )
.finally( () => app.listen(port) );
}
main();
| const express = require('express');
const db = require('./lib/db');
const app = express();
const port = process.env.PORT || 3000;
process.env.PATH = `${process.env.PATH}:./node_modules/.bin`;
app.use('/app/current', require('./routes/current'));
app.use('/app/sparkline', require('./routes/sparkline'));
app.use('/app/update', require('./routes/update'));
async function main() {
db.startup()
.catch( err => console.error(err.stack) )
.finally( () => app.listen(port) );
}
main();
| Make routes match nginx config | Make routes match nginx config
| JavaScript | mit | andyjack/neo-tracker,andyjack/neo-tracker,andyjack/neo-tracker | ---
+++
@@ -6,9 +6,9 @@
process.env.PATH = `${process.env.PATH}:./node_modules/.bin`;
-app.use('/current', require('./routes/current'));
-app.use('/sparkline', require('./routes/sparkline'));
-app.use('/update', require('./routes/update'));
+app.use('/app/current', require('./routes/current'));
+app.use('/app/sparkline', require('./routes/sparkline'));
+app.use('/app/update', require('./routes/update'));
async function main() {
db.startup() |
ad6472393c023af674fbd547f51c0473ee2cd8e2 | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var meow = require('meow');
var chalk = require('chalk');
var updateNotifier = require('update-notifier');
var quote = require('./index.js');
var pkg = require('./package.json');
var cli = meow({
help: [
'Usage',
' $ quote-cli',
'',
'Options',
' qotd Display quote of the day',
'',
'Examples',
' $ quote-cli',
' To be or not be, that is the question. - William Shakespeare',
' $ quote-cli qotd',
' Wars teach us not to love our enemies, but to hate our allies. - W. L. George'
]
});
updateNotifier({pkg: pkg}).notify();
quote(cli.input[0], function (err, result) {
if (err) {
console.log(chalk.bold.red(err));
process.exit(1);
}
console.log(chalk.cyan(chalk.yellow(result.quote.body) + ' - ' + result.quote.author));
process.exit();
});
| #!/usr/bin/env node
'use strict';
const meow = require('meow');
const chalk = require('chalk');
const updateNotifier = require('update-notifier');
const pkg = require('./package.json');
const quote = require('./index.js');
const cli = meow({
help: [
'Usage',
' $ quote-cli',
'',
'Options',
' qotd Display quote of the day',
'',
'Examples',
' $ quote-cli',
' To be or not be, that is the question. - William Shakespeare',
' $ quote-cli qotd',
' Wars teach us not to love our enemies, but to hate our allies. - W. L. George'
]
});
updateNotifier({pkg: pkg}).notify();
quote(cli.input[0], function (err, result) {
if (err) {
console.log(chalk.bold.red(err));
process.exit(1);
}
console.log(chalk.cyan(chalk.yellow(result.quote.body) + ' - ' + result.quote.author));
process.exit();
});
| Change import order for package.json | Change import order for package.json | JavaScript | mit | riyadhalnur/quote-cli | ---
+++
@@ -1,13 +1,13 @@
#!/usr/bin/env node
'use strict';
-var meow = require('meow');
-var chalk = require('chalk');
-var updateNotifier = require('update-notifier');
-var quote = require('./index.js');
-var pkg = require('./package.json');
+const meow = require('meow');
+const chalk = require('chalk');
+const updateNotifier = require('update-notifier');
+const pkg = require('./package.json');
+const quote = require('./index.js');
-var cli = meow({
+const cli = meow({
help: [
'Usage',
' $ quote-cli', |
f641be737b0aa7033aab09cc61a9ebcf168bb20f | package.js | package.js | Package.describe({
name: 'templates:tabs',
summary: 'Reactive tabbed interfaces compatible with routing.',
version: '2.2.1',
git: 'https://github.com/meteortemplates/tabs.git'
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@1.0');
api.use([
'templating',
'tracker',
'check',
'coffeescript'
], 'client');
api.addFiles('templates:tabs.html', 'client');
api.addFiles('templates:tabs.coffee', 'client');
api.addFiles('templates:tabs.css', 'client');
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('templates:tabs');
api.addFiles('templates:tabs-tests.js');
});
| Package.describe({
name: 'templates_tabs',
summary: 'Reactive tabbed interfaces compatible with routing.',
version: '2.2.1',
git: 'https://github.com/meteortemplates/tabs.git'
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@1.0');
api.use([
'templating',
'tracker',
'check',
'coffeescript'
], 'client');
api.addFiles('templates_tabs.html', 'client');
api.addFiles('templates_tabs.coffee', 'client');
api.addFiles('templates_tabs.css', 'client');
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('templates_tabs');
api.addFiles('templates_tabs-tests.js');
});
| Update filenames for Windows support | Update filenames for Windows support | JavaScript | mit | meteortemplates/tabs,meteortemplates/tabs | ---
+++
@@ -1,5 +1,5 @@
Package.describe({
- name: 'templates:tabs',
+ name: 'templates_tabs',
summary: 'Reactive tabbed interfaces compatible with routing.',
version: '2.2.1',
git: 'https://github.com/meteortemplates/tabs.git'
@@ -13,13 +13,13 @@
'check',
'coffeescript'
], 'client');
- api.addFiles('templates:tabs.html', 'client');
- api.addFiles('templates:tabs.coffee', 'client');
- api.addFiles('templates:tabs.css', 'client');
+ api.addFiles('templates_tabs.html', 'client');
+ api.addFiles('templates_tabs.coffee', 'client');
+ api.addFiles('templates_tabs.css', 'client');
});
Package.onTest(function(api) {
api.use('tinytest');
- api.use('templates:tabs');
- api.addFiles('templates:tabs-tests.js');
+ api.use('templates_tabs');
+ api.addFiles('templates_tabs-tests.js');
}); |
dc160773cb01bb87a14000335e72d5d40250be03 | example.js | example.js | var Pokeio = require('./poke.io')
Pokeio.playerInfo.latitude = 62.0395926
Pokeio.playerInfo.longitude = 14.0266575
Pokeio.GetLocation(function(loc) {
console.log('[i] Current location: ' + loc)
});
Pokeio.GetAccessToken("Arm4x","OHSHITWADDUP", function(token) {
Pokeio.GetApiEndpoint(function(api_endpoint) {
Pokeio.GetProfile(function(profile) {
console.log("[i] Username: " + profile.username)
console.log("[i] Poke Storage: " + profile.poke_storage)
console.log("[i] Item Storage: " + profile.item_storage)
if(profile.currency[0].amount == null) {
var poke = 0
}
else {
var poke = profile.currency[0].amount
}
console.log("[i] Pokecoin: " + poke)
console.log("[i] Stardust: " + profile.currency[1].amount)
})
});
})
| var Pokeio = require('./poke.io')
Pokeio.playerInfo.latitude = 62.0395926
Pokeio.playerInfo.longitude = 14.0266575
Pokeio.GetLocation(function(err, loc) {
if (err) throw err;
console.log('[i] Current location: ' + loc)
});
Pokeio.GetAccessToken("Arm4x","OHSHITWADDUP", function(err, token) {
if (err) throw err;
Pokeio.GetApiEndpoint(function(err, api_endpoint) {
if (err) throw err;
Pokeio.GetProfile(function(err, profile) {
if (err) throw err;
console.log("[i] Username: " + profile.username)
console.log("[i] Poke Storage: " + profile.poke_storage)
console.log("[i] Item Storage: " + profile.item_storage)
if(profile.currency[0].amount == null) {
var poke = 0
}
else {
var poke = profile.currency[0].amount
}
console.log("[i] Pokecoin: " + poke)
console.log("[i] Stardust: " + profile.currency[1].amount)
})
});
})
| Add error check. Throw errors for now | Add error check. Throw errors for now
| JavaScript | mit | Tolia/Pokemon-GO-node-api,dddicillo/IBM-Dublin-PokeTracker,Armax/Pokemon-GO-node-api | ---
+++
@@ -3,13 +3,21 @@
Pokeio.playerInfo.latitude = 62.0395926
Pokeio.playerInfo.longitude = 14.0266575
-Pokeio.GetLocation(function(loc) {
+Pokeio.GetLocation(function(err, loc) {
+ if (err) throw err;
+
console.log('[i] Current location: ' + loc)
});
-Pokeio.GetAccessToken("Arm4x","OHSHITWADDUP", function(token) {
- Pokeio.GetApiEndpoint(function(api_endpoint) {
- Pokeio.GetProfile(function(profile) {
+Pokeio.GetAccessToken("Arm4x","OHSHITWADDUP", function(err, token) {
+ if (err) throw err;
+
+ Pokeio.GetApiEndpoint(function(err, api_endpoint) {
+ if (err) throw err;
+
+ Pokeio.GetProfile(function(err, profile) {
+ if (err) throw err;
+
console.log("[i] Username: " + profile.username)
console.log("[i] Poke Storage: " + profile.poke_storage)
console.log("[i] Item Storage: " + profile.item_storage) |
ef34b55bcca9a136f1c00a4112e2011f5279ccf1 | test/client_test.js | test/client_test.js | var client = require('../dist/client.js');
describe('A suite', function () {
it('contains spec with an expectation', function () {
expect(true).toBe(true);
});
});
| var client = require('../dist/client.js');
describe('Client', function () {
var sut;
beforeEach(function () {
sut = client({ on: function () {} });
});
it('should have a function called update', function () {
expect(sut.update).toBeDefined();
});
});
| Test if function update is defined | Test if function update is defined
| JavaScript | mit | klambycom/diffsync,klambycom/diffsync,klambycom/diffsync | ---
+++
@@ -1,7 +1,13 @@
var client = require('../dist/client.js');
-describe('A suite', function () {
- it('contains spec with an expectation', function () {
- expect(true).toBe(true);
+describe('Client', function () {
+ var sut;
+
+ beforeEach(function () {
+ sut = client({ on: function () {} });
+ });
+
+ it('should have a function called update', function () {
+ expect(sut.update).toBeDefined();
});
}); |
378538acadeca08f3efd885699e0d2f8ef0b34db | eliza.js | eliza.js | var Eliza = require('./lib/eliza');
var eliza = new Eliza();
eliza.memSize = 500;
var initial = eliza.getInitial();
module.exports = {
conversation: 'You can @mention me in a channel (or DM me) and I\'ll start a conversation with you. After you get my attention, no need to tag me again -- but I\'ll stop if you don\'t say anything for a few minutes. I have things to do!',
'{DM}': function(text, cb) {
var reply = eliza.transform(text);
cb(null, reply);
}
}
| var Eliza = require('./lib/eliza');
var eliza = new Eliza();
eliza.memSize = 500;
var initial = eliza.getInitial();
module.exports = {
conversation: 'You can @mention me in a channel (or DM me) and I\'ll start a conversation with you. After you get my attention, no need to tag me again -- but I\'ll stop if you don\'t say anything for a few minutes. I have things to do!',
'{DM}': function(text, cb) {
var reply = eliza.transform(text.parsed);
cb(null, reply);
}
}
| Upgrade to new snarl API. | Upgrade to new snarl API.
| JavaScript | mit | martindale/snarl-eliza | ---
+++
@@ -8,7 +8,7 @@
module.exports = {
conversation: 'You can @mention me in a channel (or DM me) and I\'ll start a conversation with you. After you get my attention, no need to tag me again -- but I\'ll stop if you don\'t say anything for a few minutes. I have things to do!',
'{DM}': function(text, cb) {
- var reply = eliza.transform(text);
+ var reply = eliza.transform(text.parsed);
cb(null, reply);
}
} |
97d944bbcd6da304f51ed921707233e94f0e9e3c | test/create-test.js | test/create-test.js | var tape = require("tape"),
jsdom = require("jsdom"),
d3 = Object.assign(require("../"), require("d3-selection"));
/*************************************
************ Components *************
*************************************/
// Leveraging create hook with selection as first argument.
var checkboxHTML = `
<label class="form-check-label">
<input type="checkbox" class="form-check-input">
<span class="checkbox-label-span"></span>
</label>
`,
checkbox = d3.component("div", "form-check")
.create(function (selection){
selection.html(checkboxHTML);
})
.render(function (selection, props){
});
/*************************************
************** Tests ****************
*************************************/
tape("Create hook should pass selection on enter.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox);
test.equal(div.html(), `<div class="form-check">${checkboxHTML}</div>`);
test.end();
});
| var tape = require("tape"),
jsdom = require("jsdom"),
d3 = Object.assign(require("../"), require("d3-selection"));
/*************************************
************ Components *************
*************************************/
// Leveraging create hook with selection as first argument.
var checkboxHTML = `
<label class="form-check-label">
<input type="checkbox" class="form-check-input">
<span class="checkbox-label-span"></span>
</label>
`,
checkbox = d3.component("div", "form-check")
.create(function (selection){
selection.html(checkboxHTML);
})
.render(function (selection, props){
if(props && props.label){
selection.select(".checkbox-label-span")
.text(props.label);
}
});
/*************************************
************** Tests ****************
*************************************/
tape("Create hook should pass selection on enter.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox);
test.equal(div.html(), `<div class="form-check">${checkboxHTML}</div>`);
test.end();
});
tape("Render should have access to selection content from create hook.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox, { label: "My Checkbox"});
test.equal(div.select(".checkbox-label-span").text(), "My Checkbox");
test.end();
});
| Add more to test for selection in create hook. | Add more to test for selection in create hook.
| JavaScript | bsd-3-clause | curran/d3-component | ---
+++
@@ -18,6 +18,10 @@
selection.html(checkboxHTML);
})
.render(function (selection, props){
+ if(props && props.label){
+ selection.select(".checkbox-label-span")
+ .text(props.label);
+ }
});
@@ -30,3 +34,10 @@
test.equal(div.html(), `<div class="form-check">${checkboxHTML}</div>`);
test.end();
});
+
+tape("Render should have access to selection content from create hook.", function(test) {
+ var div = d3.select(jsdom.jsdom().body).append("div");
+ div.call(checkbox, { label: "My Checkbox"});
+ test.equal(div.select(".checkbox-label-span").text(), "My Checkbox");
+ test.end();
+}); |
232e8435d70c41c0a56d82b853e9f7e0710a8ee8 | test/declaration.js | test/declaration.js | 'use strict';
const path = require('path');
const mocksPath = path.join(__dirname, 'mocks');
module.exports = {
computationPath: path.resolve(__dirname, '../src/index.js'),
local: [
{
files: [
{
filename: path.join(mocksPath, 'M1.txt'),
},
{
filename: path.join(mocksPath, 'M2.txt'),
},
],
metaCovariateMapping: {
'2': 0,
'3': 1,
},
metaFile: [
['filename', 'is control', 'age'],
['M1.txt', '1', '36'],
['M2.txt', '0', '55'],
],
name: 'project-1',
},
{
files: [
{
filename: path.join(mocksPath, 'M3.txt'),
},
{
filename: path.join(mocksPath, 'M4.txt'),
},
],
metaCovariateMapping: {
'2': 1,
'3': 0,
},
metaFile: [
['File', 'Age', 'IsControl'],
['M3.txt', '27', true],
['M4.txt', '48', false],
],
name: 'project-2',
},
],
verbose: true,
};
| 'use strict';
const path = require('path');
const mocksPath = path.join(__dirname, 'mocks');
module.exports = {
computationPath: path.resolve(__dirname, '../src/index.js'),
local: [
{
files: [
{
filename: path.join(mocksPath, 'M1.txt'),
},
{
filename: path.join(mocksPath, 'M2.txt'),
},
],
metaCovariateMapping: {
2: 0,
3: 1,
},
metaFile: [
['filename', 'is control', 'age'],
['M1.txt', '1', '36'],
['M2.txt', '0', '55'],
],
name: 'project-1',
},
{
files: [
{
filename: path.join(mocksPath, 'M3.txt'),
},
{
filename: path.join(mocksPath, 'M4.txt'),
},
],
metaCovariateMapping: {
2: 1,
3: 0,
},
metaFile: [
['File', 'Age', 'IsControl'],
['M3.txt', '27', true],
['M4.txt', '48', false],
],
name: 'project-2',
},
],
verbose: true,
};
| Remove unnecessary strings from object keys. | Remove unnecessary strings from object keys.
| JavaScript | mit | MRN-Code/decentralized-single-shot-ridge-regression | ---
+++
@@ -17,8 +17,8 @@
},
],
metaCovariateMapping: {
- '2': 0,
- '3': 1,
+ 2: 0,
+ 3: 1,
},
metaFile: [
['filename', 'is control', 'age'],
@@ -37,8 +37,8 @@
},
],
metaCovariateMapping: {
- '2': 1,
- '3': 0,
+ 2: 1,
+ 3: 0,
},
metaFile: [
['File', 'Age', 'IsControl'], |
253564d368e32bec0507d8959be82f1b15a27e42 | test/thumbs_test.js | test/thumbs_test.js | window.addEventListener('load', function(){
module('touchstart');
test('should use touchstart when touchstart is supported', function() {
assert({ listener:'touchstart', receives:'touchstart' });
});
test('should use mousedown when touchstart is unsupported', function() {
assert({ listener:'touchstart', receives:'mousedown' });
});
module('touchend');
test('should use touchend when touchend is supported', function() {
assert({ listener:'touchend', receives:'touchend' });
});
test('should use mouseup when touchend is unsupported', function() {
assert({ listener:'touchend', receives:'mouseup' });
});
module('touchmove');
test('should use touchmove when touchmove is supported', function() {
assert({ listener:'touchmove', receives:'touchmove' });
});
test('should use mousemove when touchmove is unsupported', function() {
assert({ listener:'touchmove', receives:'mousemove' });
});
module('tap');
test('should use tap when touch events are supported', function() {
ok(false, 'not implemented');
// assert({ listener:'tap', receives:'tap' });
});
test('should use click when tap is unsupported', function() {
assert({ listener:'tap', receives:'click' });
});
});
| window.addEventListener('load', function(){
module('mousedown');
test('should use mousedown', function() {
assert({ listener:'mousedown', receives:'mousedown' });
});
module('mouseup');
test('should use mouseup', function() {
assert({ listener:'mouseup', receives:'mouseup' });
});
module('mousemove');
test('should use mousemove', function() {
assert({ listener:'mousemove', receives:'mousemove' });
});
module('click');
test('should use click', function() {
assert({ listener:'click', receives:'click' });
});
module('touchstart');
test('should use touchstart when touchstart is supported', function() {
assert({ listener:'touchstart', receives:'touchstart' });
});
test('should use mousedown when touchstart is unsupported', function() {
assert({ listener:'touchstart', receives:'mousedown' });
});
module('touchend');
test('should use touchend when touchend is supported', function() {
assert({ listener:'touchend', receives:'touchend' });
});
test('should use mouseup when touchend is unsupported', function() {
assert({ listener:'touchend', receives:'mouseup' });
});
module('touchmove');
test('should use touchmove when touchmove is supported', function() {
assert({ listener:'touchmove', receives:'touchmove' });
});
test('should use mousemove when touchmove is unsupported', function() {
assert({ listener:'touchmove', receives:'mousemove' });
});
module('tap');
test('should use tap when touch events are supported', function() {
ok(false, 'not implemented');
// assert({ listener:'tap', receives:'tap' });
});
test('should use click when tap is unsupported', function() {
assert({ listener:'tap', receives:'click' });
});
});
| Add tests against destroying mouse events. | Add tests against destroying mouse events.
| JavaScript | mit | mwbrooks/thumbs.js,pyrinelaw/thumbs.js,pyrinelaw/thumbs.js | ---
+++
@@ -1,4 +1,28 @@
window.addEventListener('load', function(){
+
+ module('mousedown');
+
+ test('should use mousedown', function() {
+ assert({ listener:'mousedown', receives:'mousedown' });
+ });
+
+ module('mouseup');
+
+ test('should use mouseup', function() {
+ assert({ listener:'mouseup', receives:'mouseup' });
+ });
+
+ module('mousemove');
+
+ test('should use mousemove', function() {
+ assert({ listener:'mousemove', receives:'mousemove' });
+ });
+
+ module('click');
+
+ test('should use click', function() {
+ assert({ listener:'click', receives:'click' });
+ });
module('touchstart');
|
fb614d14fff4d9d0fdd4abdd56881553ebe49ecf | modules/gtp/index.js | modules/gtp/index.js | const {exec} = require('child_process')
const Command = exports.Command = require('./command')
const Response = exports.Response = require('./response')
const Controller = exports.Controller = require('./controller')
// System paths are not inherited in macOS
// This is a quick & dirty fix
if (process.platform === 'darwin') {
exec('/bin/bash -ilc "env; exit"', (err, result) => {
if (err) return
process.env.PATH = result.trim().split('\n')
.map(x => x.split('='))
.find(x => x[0] === 'PATH')[1]
})
}
exports.parseCommand = function(input) {
input = input.replace(/\t/g, ' ').trim()
let inputs = input.split(' ').filter(x => x !== '')
let id = parseFloat(inputs[0])
if (!isNaN(id)) inputs.shift()
else id = null
let name = inputs[0]
inputs.shift()
return new Command(id, name, inputs)
}
exports.parseResponse = function(input) {
input = input.replace(/\t/g, ' ').trim()
let error = input[0] !== '='
let hasId = input.length >= 2 && input[1] !== ' '
input = input.substr(1)
let id = hasId ? +input.split(' ')[0] : null
if (hasId) input = input.substr((id + '').length)
return new Response(id, input.substr(1), error)
}
| const {exec} = require('child_process')
const Command = exports.Command = require('./command')
const Response = exports.Response = require('./response')
const Controller = exports.Controller = require('./controller')
// System paths are not inherited in macOS
// This is a quick & dirty fix
if (process.platform === 'darwin') {
exec('/bin/bash -ilc "env; exit"', (err, result) => {
if (err) return
process.env.PATH = result.trim().split('\n')
.map(x => x.split('='))
.find(x => x[0] === 'PATH')[1]
})
}
exports.parseCommand = function(input) {
input = input.replace(/\t/g, ' ').trim()
let inputs = input.split(' ').filter(x => x !== '')
let id = parseFloat(inputs[0])
if (!isNaN(id)) inputs.shift()
else id = null
let name = inputs[0]
inputs.shift()
return new Command(id, name, ...inputs)
}
exports.parseResponse = function(input) {
input = input.replace(/\t/g, ' ').trim()
let error = input[0] !== '='
let hasId = input.length >= 2 && input[1] !== ' '
input = input.substr(1)
let id = hasId ? +input.split(' ')[0] : null
if (hasId) input = input.substr((id + '').length)
return new Response(id, input.substr(1), error)
}
| Fix how parseCommand sends arguments to Command class | Fix how parseCommand sends arguments to Command class | JavaScript | mit | yishn/Goban,yishn/Sabaki,yishn/Sabaki,yishn/Goban | ---
+++
@@ -28,7 +28,7 @@
let name = inputs[0]
inputs.shift()
- return new Command(id, name, inputs)
+ return new Command(id, name, ...inputs)
}
exports.parseResponse = function(input) { |
969a640cac2e979a50f1837624023be7d90030d2 | packages/konomi/test/propertyTest.js | packages/konomi/test/propertyTest.js | import assert from "power-assert";
import Component from "../src/Component";
import * as property from "../src/property";
describe("property", () => {
describe(".bind", () => {
const c1 = new Component();
property.define(c1, "p1");
const c2 = new Component();
property.bind(c2, "p2", [[c1, "p1"]], () => c1.p1 * 2);
it("binds a property", () => {
c1.p1 = 123;
assert(c2.p2 === 246);
});
it("discard binding on source component disposal", () => {
c1.dispose();
assert(c1.changes.listeners("p1").length === 0);
});
it("discard binding on dest component disposal", () => {
c2.dispose();
assert(c1.changes.listeners("p1").length === 0);
});
});
});
| import assert from "power-assert";
import Component from "../src/Component";
import * as property from "../src/property";
describe("property", () => {
describe(".bind", () => {
let c1, c2;
beforeEach(() => {
c1 = new Component();
property.define(c1, "p1");
c2 = new Component();
property.bind(c2, "p2", [[c1, "p1"]], () => c1.p1 * 2);
});
it("binds a property", () => {
c1.p1 = 123;
assert(c2.p2 === 246);
});
it("discard binding on source component disposal", () => {
c1.dispose();
assert(c1.changes.listeners("p1").length === 0);
});
it("discard binding on dest component disposal", () => {
c2.dispose();
assert(c1.changes.listeners("p1").length === 0);
});
});
});
| Use beforeEach in property test | Use beforeEach in property test
| JavaScript | mit | seanchas116/konomi | ---
+++
@@ -4,10 +4,14 @@
describe("property", () => {
describe(".bind", () => {
- const c1 = new Component();
- property.define(c1, "p1");
- const c2 = new Component();
- property.bind(c2, "p2", [[c1, "p1"]], () => c1.p1 * 2);
+ let c1, c2;
+
+ beforeEach(() => {
+ c1 = new Component();
+ property.define(c1, "p1");
+ c2 = new Component();
+ property.bind(c2, "p2", [[c1, "p1"]], () => c1.p1 * 2);
+ });
it("binds a property", () => {
c1.p1 = 123; |
b2f43f2406835f8a1b1858966abbf36d1f0afe2d | env.js | env.js | define(function () {
'use strict';
var env = {};
env.getEnvironment = function (callback) {
// FIXME: we assume this code runs on the same thread as the
// javascript executed from sugar-toolkit-gtk3 (python)
if (env.isStandalone()) {
setTimeout(function () {
callback(null, {});
}, 0);
} else {
var environmentCallback = function () {
callback(null, window.top.sugar.environment);
};
if (window.top.sugar) {
setTimeout(function () {
environmentCallback();
}, 0);
} else {
window.top.sugar = {};
window.top.sugar.onEnvironmentSet = function () {
environmentCallback();
};
}
}
};
env.getObjectId = function (callback) {
env.getEnvironment(function (error, environment) {
callback(environment.objectId);
});
};
env.getURLScheme = function () {
return window.location.protocol;
};
env.isStandalone = function () {
var webActivityURLScheme = "activity:";
var currentURLScheme = env.getURLScheme();
return currentURLScheme !== webActivityURLScheme;
};
return env;
});
| define(function () {
'use strict';
var env = {};
env.getEnvironment = function (callback) {
// FIXME: we assume this code runs on the same thread as the
// javascript executed from sugar-toolkit-gtk3 (python)
if (env.isStandalone()) {
setTimeout(function () {
callback(null, {});
}, 0);
} else {
var environmentCallback = function () {
callback(null, window.top.sugar.environment);
};
if (window.top.sugar) {
setTimeout(function () {
environmentCallback();
}, 0);
} else {
window.top.sugar = {};
window.top.sugar.onEnvironmentSet = function () {
environmentCallback();
};
}
}
};
env.getObjectId = function (callback) {
env.getEnvironment(function (error, environment) {
callback(environment.objectId);
});
};
env.getURLScheme = function () {
return window.location.protocol;
};
env.isStandalone = function () {
var webActivityURLScheme = "activity:";
var currentURLScheme = env.getURLScheme();
// the control of hostname !== '0.0.0.0' is used
// for compatibility with F18 and webkit1
return currentURLScheme !== webActivityURLScheme &&
window.location.hostname !== '0.0.0.0';
};
return env;
});
| Make isStandalone() compatible with webkit1 | Make isStandalone() compatible with webkit1
In webkit1 implementation, we don't use 'activity' as a protocol.
| JavaScript | apache-2.0 | sugarlabs/sugar-web,godiard/sugar-web | ---
+++
@@ -44,7 +44,10 @@
var webActivityURLScheme = "activity:";
var currentURLScheme = env.getURLScheme();
- return currentURLScheme !== webActivityURLScheme;
+ // the control of hostname !== '0.0.0.0' is used
+ // for compatibility with F18 and webkit1
+ return currentURLScheme !== webActivityURLScheme &&
+ window.location.hostname !== '0.0.0.0';
};
return env; |
54498cb23b8b3e50e9dad44cbd8509916e917ae3 | test/select.js | test/select.js | var test = require("tape")
var h = require("hyperscript")
var FormData = require("../index")
test("FormData works with <select> elements", function (assert) {
var elements = {
foo: h("select", [
h("option", { value: "one" })
, h("option", { value: "two", selected: true })
, h("option", { value: "three" })
])
}
var data = FormData(elements)
assert.deepEqual(data, {
foo: "two"
})
assert.end()
})
| var test = require("tape")
var h = require("hyperscript")
var FormData = require("../index")
var getFormData = require("../element")
test("FormData works with <select> elements", function (assert) {
var elements = {
foo: h("select", [
h("option", { value: "one" })
, h("option", { value: "two", selected: true })
, h("option", { value: "three" })
])
}
var data = FormData(elements)
assert.deepEqual(data, {
foo: "two"
})
assert.end()
})
test("getFormData works when root element has a name", function(assert) {
var element = h("select", {
name: "foo"
}, [
h("option", { value: "one" })
, h("option", { value: "two", selected: true })
])
var data = getFormData(element)
assert.deepEqual(data, {
foo: "two"
})
assert.end()
}) | Add test for rootElm with name prop fix. | Add test for rootElm with name prop fix.
| JavaScript | mit | Raynos/form-data-set | ---
+++
@@ -2,6 +2,7 @@
var h = require("hyperscript")
var FormData = require("../index")
+var getFormData = require("../element")
test("FormData works with <select> elements", function (assert) {
var elements = {
@@ -20,3 +21,20 @@
assert.end()
})
+
+test("getFormData works when root element has a name", function(assert) {
+ var element = h("select", {
+ name: "foo"
+ }, [
+ h("option", { value: "one" })
+ , h("option", { value: "two", selected: true })
+ ])
+
+ var data = getFormData(element)
+
+ assert.deepEqual(data, {
+ foo: "two"
+ })
+
+ assert.end()
+}) |
2dc0f2b8842af35ab001f765f95b0d237e361efe | resources/js/picker.js | resources/js/picker.js | $(document).on('ajaxComplete ready', function () {
// Initialize inputs
$('input[data-provides="anomaly.field_type.datetime"]:not([data-initialized])').each(function () {
var $this = $(this);
var inputMode = $this.data('input-mode');
var options = {
altInput: true,
allowInput: true,
minuteIncrement: $this.data('step') || 1,
dateFormat: $this.data('datetime-format'),
enableTime: inputMode !== 'date',
noCalendar: inputMode === 'time'
};
$this.attr('data-initialized', '').flatpickr(options);
});
});
| $(document).on('ajaxComplete ready', function () {
// Initialize inputs
$('input[data-provides="anomaly.field_type.datetime"]:not([data-initialized])').each(function () {
var $this = $(this);
var inputMode = $this.data('input-mode');
var options = {
altInput: true,
allowInput: true,
minuteIncrement: $this.data('step') || 1,
dateFormat: $this.data('datetime-format'),
time_24hr: Boolean($this.data('datetime-format').match(/[GH]/)),
enableTime: inputMode !== 'date',
noCalendar: inputMode === 'time'
};
$this.attr('data-initialized', '').flatpickr(options);
});
});
| Fix issue where 24h format needed additional configuration for the plugin | Fix issue where 24h format needed additional configuration for the plugin
| JavaScript | mit | anomalylabs/datetime-field_type,anomalylabs/datetime-field_type | ---
+++
@@ -11,6 +11,7 @@
allowInput: true,
minuteIncrement: $this.data('step') || 1,
dateFormat: $this.data('datetime-format'),
+ time_24hr: Boolean($this.data('datetime-format').match(/[GH]/)),
enableTime: inputMode !== 'date',
noCalendar: inputMode === 'time'
}; |
6c4bad448fdc3753e24ab74824f7ed00e714c489 | problems/commit_to_it/verify.js | problems/commit_to_it/verify.js | #!/usr/bin/env node
var exec = require('child_process').exec
// check that they've commited changes
exec('git status', function(err, stdout, stdrr) {
var show = stdout.trim()
if (show.match("nothing to commit")) {
console.log("Changes have been committed!")
}
else if (show.match("Changes not staged for commit")){
console.log("Seems there are changes\nto commit still.")
} else console.log("Hmm, can't find\ncommitted changes.")
})
| #!/usr/bin/env node
var exec = require('child_process').exec
// check that they've commited changes
exec('git status', function(err, stdout, stdrr) {
var show = stdout.trim()
if (show.match("Initial commit")) {
console.log("Hmm, can't find\ncommitted changes.")
}
else if (show.match("nothing to commit")) {
console.log("Changes have been committed!")
}
else {
console.log("Seems there are changes\nto commit still.")
}
})
| Make commit_to_it fail when the repo is blank | Make commit_to_it fail when the repo is blank
Before that I could PASS the tests with an empty repo :
* no commits
* no files
| JavaScript | bsd-2-clause | aijiekj/git-it,pushnoy100500/git-it,strider99/git-it,ubergrafik/git-it,anilmainali/git-it,thenaughtychild/git-it,itha92/git-it-1,jlord/git-it,seenaomi/git-it,strider99/git-it,thenaughtychild/git-it,pushnoy100500/git-it,gjbianco/git-it,jlord/git-it,AkimSolovyov/git-it,gjbianco/git-it,hicksca/git-it,aijiekj/git-it,anilmainali/git-it,jasonevrtt/git-it,vlandham/git-it,AkimSolovyov/git-it,eyecatchup/git-it,vlandham/git-it,LindsayElia/git-it,ubergrafik/git-it,itha92/git-it-1,LindsayElia/git-it,CLAV1ER/git-it,hicksca/git-it,eyecatchup/git-it,CLAV1ER/git-it,jasonevrtt/git-it,seenaomi/git-it | ---
+++
@@ -6,11 +6,14 @@
exec('git status', function(err, stdout, stdrr) {
var show = stdout.trim()
-
- if (show.match("nothing to commit")) {
+
+ if (show.match("Initial commit")) {
+ console.log("Hmm, can't find\ncommitted changes.")
+ }
+ else if (show.match("nothing to commit")) {
console.log("Changes have been committed!")
}
- else if (show.match("Changes not staged for commit")){
+ else {
console.log("Seems there are changes\nto commit still.")
- } else console.log("Hmm, can't find\ncommitted changes.")
+ }
}) |
d4156a3af771cd57da3f7719e9afb4c92b327e21 | app/routes/preprints.js | app/routes/preprints.js | import Ember from 'ember';
var dateCreated = new Date();
var meta = {
title: 'The Linux Command Line',
authors: 'Zach Janicki',
dateCreated: dateCreated,
abstract: "This is a sample usage of the MFR on the preprint server. This document will teach you everything you would ever want to know about the linux command line. Enjoy!" +
" From here on out this is just filler text to give a better sense of what the page layout may look like with a more real to life abstract length. Hopefully the scientists" +
" who write these abstracts have more to day about their own topics than I do about the linux command line...",
publisher: "Linus Torvalds",
project: "http://localhost:5000/re58y/",
supplementalMaterials: "NONE",
figures: "NONE",
License: "Mit License",
link: 'http://localhost:7778/render?url=http://localhost:5000/sqdwh/?action=download%26mode=render',
};
export default Ember.Route.extend({
model() {
console.log(this.store.findAll('preprint'));
//return this.store.findRecord('preprint', 1);
return meta;
}
});
| import Ember from 'ember';
var dateCreated = new Date();
var meta = {
title: 'The Linux Command Line',
authors: 'Zach Janicki',
dateCreated: dateCreated,
abstract: "This is a sample usage of the MFR on the preprint server. This document will teach you everything you would ever want to know about the linux command line. Enjoy!" +
" From here on out this is just filler text to give a better sense of what the page layout may look like with a more real to life abstract length. Hopefully the scientists" +
" who write these abstracts have more to day about their own topics than I do about the linux command line...",
publisher: "Linus Torvalds",
project: "http://localhost:5000/re58y/",
supplementalMaterials: "NONE",
figures: "NONE",
License: "Mit License",
link: "https://test-mfr.osf.io/render?url=https://test.osf.io/yr6ch/?action=download%26mode=render",
};
export default Ember.Route.extend({
model() {
console.log(this.store.findAll('preprint'));
//return this.store.findRecord('preprint', 1);
return meta;
}
});
//
// 'https://test-mfr.osf.io/export?url=https://test.osf.io/2r4cz/?action=download%26direct%26mode=render&initialWidth=755&childId=mfrIframe&format=pdf'
//
// 'https://test-mfr.osf.io/export?url=https://test.osf.io/2r4cz/?action=download%26direct%26mode=render&initialWidth=755&childId=mfrIframe&format=pdf'
| Make all right with the world | Make all right with the world
| JavaScript | apache-2.0 | pattisdr/ember-preprints,hmoco/ember-preprints,pattisdr/ember-preprints,laurenrevere/ember-preprints,CenterForOpenScience/ember-preprints,laurenrevere/ember-preprints,hmoco/ember-preprints,caneruguz/ember-preprints,baylee-d/ember-preprints,caneruguz/ember-preprints,CenterForOpenScience/ember-preprints,baylee-d/ember-preprints | ---
+++
@@ -14,7 +14,7 @@
supplementalMaterials: "NONE",
figures: "NONE",
License: "Mit License",
- link: 'http://localhost:7778/render?url=http://localhost:5000/sqdwh/?action=download%26mode=render',
+ link: "https://test-mfr.osf.io/render?url=https://test.osf.io/yr6ch/?action=download%26mode=render",
};
export default Ember.Route.extend({
@@ -24,3 +24,8 @@
return meta;
}
});
+//
+// 'https://test-mfr.osf.io/export?url=https://test.osf.io/2r4cz/?action=download%26direct%26mode=render&initialWidth=755&childId=mfrIframe&format=pdf'
+//
+// 'https://test-mfr.osf.io/export?url=https://test.osf.io/2r4cz/?action=download%26direct%26mode=render&initialWidth=755&childId=mfrIframe&format=pdf'
+ |
8e39fd7762d1ccebd5647d96aaf7eeb30b6f1bbc | packages/non-core/bundle-visualizer/package.js | packages/non-core/bundle-visualizer/package.js | Package.describe({
version: '1.1.0',
summary: 'Meteor bundle analysis and visualization.',
documentation: 'README.md',
});
Npm.depends({
"d3-selection": "1.0.5",
"d3-shape": "1.0.6",
"d3-hierarchy": "1.1.4",
"d3-transition": "1.0.4",
"d3-collection": "1.0.4",
"pretty-bytes": "4.0.2",
});
Package.onUse(function(api) {
api.use('isobuild:dynamic-import@1.5.0');
api.use([
'ecmascript',
'http',
]);
api.mainModule('server.js', 'server');
api.mainModule('client.js', 'client');
});
| Package.describe({
version: '1.1.0',
summary: 'Meteor bundle analysis and visualization.',
documentation: 'README.md',
});
Npm.depends({
"d3-selection": "1.0.5",
"d3-shape": "1.0.6",
"d3-hierarchy": "1.1.4",
"d3-transition": "1.0.4",
"d3-collection": "1.0.4",
"pretty-bytes": "4.0.2",
});
Package.onUse(function(api) {
api.use('isobuild:dynamic-import@1.5.0');
api.use([
'ecmascript',
'dynamic-import',
'http',
]);
api.mainModule('server.js', 'server');
api.mainModule('client.js', 'client');
});
| Make bundle-visualizer depend on dynamic-import directly again. | Make bundle-visualizer depend on dynamic-import directly again.
Since bundle-visualizer is a non-core package, it could be used with a
version of ecmascript that does not imply dynamic-import, though it
definitely requires support for `import()` to function properly.
| JavaScript | mit | Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor | ---
+++
@@ -17,6 +17,7 @@
api.use('isobuild:dynamic-import@1.5.0');
api.use([
'ecmascript',
+ 'dynamic-import',
'http',
]);
api.mainModule('server.js', 'server'); |
554e12b30919a04779a4b96b2da50f15d770728d | e2e-tests/scenarios.js | e2e-tests/scenarios.js | 'use strict';
/* https://github.com/angular/protractor/blob/master/docs/toc.md */
describe('my app', function() {
browser.get('index.html');
it('should automatically redirect to /play when location hash/fragment is empty', function() {
expect(browser.getLocationAbsUrl()).toMatch("/play");
});
describe('play', function() {
beforeEach(function() {
browser.get('index.html#/play');
});
it('should render view1 when user navigates to /view1', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/playing/i);
});
});
describe('preferences', function() {
beforeEach(function() {
browser.get('index.html#/preferences');
});
it('should have the difficulty sections', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/difficulty/i);
});
it('should have the characters sections', function() {
expect(element.all(by.css('[ng-view] h3')).last().getText()).
toMatch(/characters/i);
});
});
});
| 'use strict';
describe('my app', function() {
browser.get('index.html');
it('should automatically redirect to /play when location hash/fragment is empty', function() {
expect(browser.getLocationAbsUrl()).toMatch("/play");
});
describe('play', function() {
beforeEach(function() {
browser.get('index.html#/play');
});
it('should render view1 when user navigates to /view1', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/playing/i);
});
});
describe('preferences', function() {
beforeEach(function() {
browser.get('index.html#/preferences');
});
it('should have the difficulty sections', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/difficulty/i);
});
it('should have the characters sections', function() {
expect(element.all(by.css('[ng-view] h3')).last().getText()).
toMatch(/characters/i);
});
});
});
| Remove spaces from basic e2e tests. | Remove spaces from basic e2e tests.
| JavaScript | mit | blainesch/angular-morse,blainesch/angular-morse,blainesch/angular-morse | ---
+++
@@ -1,9 +1,6 @@
'use strict';
-/* https://github.com/angular/protractor/blob/master/docs/toc.md */
-
describe('my app', function() {
-
browser.get('index.html');
it('should automatically redirect to /play when location hash/fragment is empty', function() {
@@ -12,7 +9,6 @@
describe('play', function() {
-
beforeEach(function() {
browser.get('index.html#/play');
});
@@ -22,16 +18,13 @@
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/playing/i);
});
-
});
describe('preferences', function() {
-
beforeEach(function() {
browser.get('index.html#/preferences');
});
-
it('should have the difficulty sections', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
@@ -42,6 +35,5 @@
expect(element.all(by.css('[ng-view] h3')).last().getText()).
toMatch(/characters/i);
});
-
});
}); |
f32ed63a71a9d3b57061830d4f6de470bbe76fd9 | nodejs/lib/models/account_stats.js | nodejs/lib/models/account_stats.js | var wompt = require("../includes"),
mongoose = wompt.mongoose,
ObjectId = mongoose.Schema.ObjectId;
var AccountStats = new mongoose.Schema({
account_id : {type: ObjectId, index: true}
,frequency : String
,t : Date
,peak_connections : Integer
,connections : Integer
});
// Model name, Schema, collection name
mongoose.model('AccountStats', AccountStats, 'account_stats');
module.exports = mongoose.model('AccountStats');
| var wompt = require("../includes"),
mongoose = wompt.mongoose,
ObjectId = mongoose.Schema.ObjectId;
var AccountStats = new mongoose.Schema({
account_id : {type: ObjectId, index: true}
,frequency : String
,t : Date
,peak_connections : Number
,connections : Number
});
// Model name, Schema, collection name
mongoose.model('AccountStats', AccountStats);
module.exports = mongoose.model('AccountStats');
| Change AcountStats field type from Integer -> Number Integer isn't a type. | Change AcountStats field type from Integer -> Number
Integer isn't a type.
| JavaScript | mit | iFixit/wompt.com,iFixit/wompt.com,Wompt/wompt.com,iFixit/wompt.com,iFixit/wompt.com,Wompt/wompt.com,Wompt/wompt.com | ---
+++
@@ -6,10 +6,10 @@
account_id : {type: ObjectId, index: true}
,frequency : String
,t : Date
- ,peak_connections : Integer
- ,connections : Integer
+ ,peak_connections : Number
+ ,connections : Number
});
// Model name, Schema, collection name
-mongoose.model('AccountStats', AccountStats, 'account_stats');
+mongoose.model('AccountStats', AccountStats);
module.exports = mongoose.model('AccountStats'); |
de1edd3537adc17c1da10a67c16f5bdd5199a230 | server/jobs/update-activity-cache.js | server/jobs/update-activity-cache.js | const Logger = require('franston')('jobs/update-cache')
const GithubActivity = require('../models/github-activity')
const GithubCache = require('../models/github-cache')
const Series = require('run-series')
let dateMap = {}
function saveActivityCounts (date, next) {
let count = dateMap[date]
let options = {
upsert: true,
setDefaultsOnInsert: true
}
GithubCache.update({ date }, { date, total: count }, options, (err) => {
if (err) return (Logger.error(err), next(err))
return next()
})
}
function updateCache (done) {
GithubActivity.find({}, (err, found) => {
if (err) return done(err)
found.forEach((event) => {
let date = new Date(event.created).toDateString()
if (dateMap.hasOwnProperty(date)) dateMap[date] += parseInt(event.count, 10)
else dateMap[date] = parseInt(event.count, 10)
})
return Series(Object.keys(dateMap).map((date) => saveActivityCounts.bind(null, date)))
})
}
module.exports = function updateActivityCache () {
Logger.info('Running job...')
updateCache((err) => {
if (err) return Logger.error(`error: ${err.message}`)
return Logger.info('...completed')
})
}
| const Logger = require('franston')('jobs/update-cache')
const GithubActivity = require('../models/github-activity')
const GithubCache = require('../models/github-cache')
const Series = require('run-series')
let dateMap = {}
function saveActivityCounts (date, next) {
let count = dateMap[date]
let options = {
upsert: true,
setDefaultsOnInsert: true
}
GithubCache.update({ date }, { date, total: count }, options, (err) => {
if (err) return (Logger.error(err), next(err))
return next()
})
}
function updateCache (done) {
dateMap = {}
GithubActivity.find({}, (err, found) => {
if (err) return done(err)
found.forEach((event) => {
let date = new Date(event.created).toDateString()
if (dateMap.hasOwnProperty(date)) dateMap[date] += parseInt(event.count, 10)
else dateMap[date] = parseInt(event.count, 10)
})
return Series(Object.keys(dateMap).map((date) => saveActivityCounts.bind(null, date)))
})
}
module.exports = function updateActivityCache () {
Logger.info('Running job...')
updateCache((err) => {
if (err) return Logger.error(`error: ${err.message}`)
return Logger.info('...completed')
})
}
| Fix bug by resetting dateMap during update | Fix bug by resetting dateMap during update
| JavaScript | mit | franvarney/franvarney-api | ---
+++
@@ -20,6 +20,8 @@
}
function updateCache (done) {
+ dateMap = {}
+
GithubActivity.find({}, (err, found) => {
if (err) return done(err)
|
5520c40d6dc84d89b7133a5c1041b94a997eed14 | app/spark_bootstrap.js | app/spark_bootstrap.js | // Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
(function() {
if (navigator.webkitStartDart) {
// NOTE: This is already done in polymer/boot.js, and this attempt to
// execute it the second time breaks polymer-element instantiations.
// This is in a transient state: boot.js is going away soon, and so it
// the requirement to run webkitStartDart(). By Dart 1.0 both should be
// gone. However, depending on which goes first, this might need to be
// uncommented for a brief period.
// TODO: Remove this completely after Dart 1.0.
// navigator.webkitStartDart();
} else {
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
if (scripts[i].type == "application/dart") {
if (scripts[i].src && scripts[i].src != '') {
var script = document.createElement('script');
script.src = scripts[i].src.replace(/\.dart(?=\?|$)/, '.dart.precompiled.js');
document.currentScript = script;
scripts[i].parentNode.replaceChild(script, scripts[i]);
}
} else if (scripts[i].src.indexOf('.dart.js') == scripts[i].src.length - 8) {
var script = document.createElement('script');
script.src = scripts[i].src.replace(/\.dart\.js$/, '.dart.precompiled.js');
document.currentScript = script;
scripts[i].parentNode.replaceChild(script, scripts[i]);
}
}
}
})();
| // Copyright (c) 2013, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
(function() {
if (navigator.webkitStartDart) {
navigator.webkitStartDart();
} else {
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
if (scripts[i].type == "application/dart") {
if (scripts[i].src && scripts[i].src != '') {
var script = document.createElement('script');
script.src = scripts[i].src.replace(/\.dart(?=\?|$)/, '.dart.precompiled.js');
document.currentScript = script;
scripts[i].parentNode.replaceChild(script, scripts[i]);
}
} else if (scripts[i].src.indexOf('.dart.js') == scripts[i].src.length - 8) {
var script = document.createElement('script');
script.src = scripts[i].src.replace(/\.dart\.js$/, '.dart.precompiled.js');
document.currentScript = script;
scripts[i].parentNode.replaceChild(script, scripts[i]);
}
}
}
})();
| Revert "Fixed: double-execution of webkitStartDart() broke polymer-element instantiations." | Revert "Fixed: double-execution of webkitStartDart() broke polymer-element instantiations."
This reverts commit 77cfec11555d42515b809f7aa5624dfdbbce4379.
| JavaScript | bsd-3-clause | 2947721120/chromedeveditor,b0dh1sattva/chromedeveditor,modulexcite/chromedeveditor,valmzetvn/chromedeveditor,googlearchive/chromedeveditor,vivalaralstin/chromedeveditor,valmzetvn/chromedeveditor,2947721120/chromedeveditor,beaufortfrancois/chromedeveditor,beaufortfrancois/chromedeveditor,2947721120/choredev,hxddh/chromedeveditor,beaufortfrancois/chromedeveditor,2947721120/choredev,2947721120/chromedeveditor,b0dh1sattva/chromedeveditor,modulexcite/chromedeveditor,2947721120/chromedeveditor,googlearchive/chromedeveditor,modulexcite/chromedeveditor,devoncarew/spark,ussuri/chromedeveditor,hxddh/chromedeveditor,hxddh/chromedeveditor,b0dh1sattva/chromedeveditor,modulexcite/chromedeveditor,2947721120/choredev,2947721120/chromedeveditor,devoncarew/spark,b0dh1sattva/chromedeveditor,ussuri/chromedeveditor,valmzetvn/chromedeveditor,beaufortfrancois/chromedeveditor,vivalaralstin/chromedeveditor,b0dh1sattva/chromedeveditor,valmzetvn/chromedeveditor,yikaraman/chromedeveditor,modulexcite/chromedeveditor,devoncarew/spark,vivalaralstin/chromedeveditor,ussuri/chromedeveditor,valmzetvn/chromedeveditor,vivalaralstin/chromedeveditor,beaufortfrancois/chromedeveditor,2947721120/choredev,googlearchive/chromedeveditor,hxddh/chromedeveditor,googlearchive/chromedeveditor,ussuri/chromedeveditor,modulexcite/chromedeveditor,modulexcite/chromedeveditor,2947721120/choredev,vivalaralstin/chromedeveditor,googlearchive/chromedeveditor,hxddh/chromedeveditor,yikaraman/chromedeveditor,2947721120/choredev,devoncarew/spark,yikaraman/chromedeveditor,2947721120/choredev,ussuri/chromedeveditor,beaufortfrancois/chromedeveditor,hxddh/chromedeveditor,googlearchive/chromedeveditor,yikaraman/chromedeveditor,beaufortfrancois/chromedeveditor,hxddh/chromedeveditor,yikaraman/chromedeveditor,yikaraman/chromedeveditor,devoncarew/spark,ussuri/chromedeveditor,valmzetvn/chromedeveditor,googlearchive/chromedeveditor,vivalaralstin/chromedeveditor,b0dh1sattva/chromedeveditor,valmzetvn/chromedeveditor,vivalaralstin/chromedeveditor,2947721120/chromedeveditor,2947721120/chromedeveditor,b0dh1sattva/chromedeveditor,ussuri/chromedeveditor,yikaraman/chromedeveditor,devoncarew/spark | ---
+++
@@ -4,14 +4,7 @@
(function() {
if (navigator.webkitStartDart) {
- // NOTE: This is already done in polymer/boot.js, and this attempt to
- // execute it the second time breaks polymer-element instantiations.
- // This is in a transient state: boot.js is going away soon, and so it
- // the requirement to run webkitStartDart(). By Dart 1.0 both should be
- // gone. However, depending on which goes first, this might need to be
- // uncommented for a brief period.
- // TODO: Remove this completely after Dart 1.0.
- // navigator.webkitStartDart();
+ navigator.webkitStartDart();
} else {
var scripts = document.getElementsByTagName("script");
|
89e6ce73a259f2bb050700e77b3059c6a327fe61 | src/components/forms/UsernameControl.js | src/components/forms/UsernameControl.js | import React, { Component, PropTypes } from 'react'
import FormControl from './FormControl'
class UsernameControl extends Component {
static propTypes = {
suggestions: PropTypes.array,
}
static defaultProps = {
className: 'UsernameControl',
id: 'username',
label: 'Username',
name: 'user[username]',
placeholder: 'Enter your username',
suggestions: null,
}
onClickUsernameSuggestion = (e) => {
const val = e.target.title
this.formControl.onChangeControl({ target: { value: val } })
}
renderSuggestions = () => {
const { suggestions } = this.props
if (suggestions && suggestions.length) {
return (
<ul className="FormControlSuggestionList hasSuggestions">
<p>Here are some available usernames —</p>
{suggestions.map((suggestion, i) =>
<li key={`suggestion_${i}`}>
<button
className="FormControlSuggestionButton"
title={suggestion}
onClick={this.onClickUsernameSuggestion}
>
{suggestion}
</button>
</li>
)}
</ul>
)
}
return (
<p className="FormControlSuggestionList">
<span />
</p>
)
}
render() {
return (
<FormControl
{...this.props}
autoCapitalize="off"
autoCorrect="off"
ref={(comp) => { this.formControl = comp }}
maxLength="50"
renderFeedback={this.renderSuggestions}
trimWhitespace
type="text"
/>
)
}
}
export default UsernameControl
| import React, { Component, PropTypes } from 'react'
import FormControl from './FormControl'
class UsernameControl extends Component {
static propTypes = {
suggestions: PropTypes.array,
}
static defaultProps = {
className: 'UsernameControl',
id: 'username',
label: 'Username',
name: 'user[username]',
placeholder: 'Enter your username',
suggestions: null,
}
onClickUsernameSuggestion = (e) => {
const val = e.target.title
const element = document.getElementById('username')
if (element) {
element.value = val
}
}
renderSuggestions = () => {
const { suggestions } = this.props
if (suggestions && suggestions.length) {
return (
<ul className="FormControlSuggestionList hasSuggestions">
<p>Here are some available usernames —</p>
{suggestions.map((suggestion, i) =>
<li key={`suggestion_${i}`}>
<button
className="FormControlSuggestionButton"
title={suggestion}
onClick={this.onClickUsernameSuggestion}
>
{suggestion}
</button>
</li>
)}
</ul>
)
}
return (
<p className="FormControlSuggestionList">
<span />
</p>
)
}
render() {
return (
<FormControl
{...this.props}
autoCapitalize="off"
autoCorrect="off"
maxLength="50"
renderFeedback={this.renderSuggestions}
trimWhitespace
type="text"
/>
)
}
}
export default UsernameControl
| Fix clicking on suggestion to set the username | Fix clicking on suggestion to set the username
[Fixes: #128912639](https://www.pivotaltracker.com/story/show/128912639)
| JavaScript | mit | ello/webapp,ello/webapp,ello/webapp | ---
+++
@@ -18,7 +18,10 @@
onClickUsernameSuggestion = (e) => {
const val = e.target.title
- this.formControl.onChangeControl({ target: { value: val } })
+ const element = document.getElementById('username')
+ if (element) {
+ element.value = val
+ }
}
renderSuggestions = () => {
@@ -54,7 +57,6 @@
{...this.props}
autoCapitalize="off"
autoCorrect="off"
- ref={(comp) => { this.formControl = comp }}
maxLength="50"
renderFeedback={this.renderSuggestions}
trimWhitespace |
400bf74845b5c97670e3e4d65b33c01d2489e4ca | lib/confirm-retract.js | lib/confirm-retract.js | var React = require("react");
var {Button} = require("react-bootstrap");
var confirmMark = "\u2713"; // check mark
var retractMark = "\u00D7"; // multiplication sign
function confirmOrRetractButton(userSelected, confirm, retract, size = "medium") {
return userSelected
? <Button className="dim" bsSize={size} onClick={retract}>{retractMark}</Button>
: <Button className="dim" bsSize={size} onClick={confirm}>{confirmMark}</Button>;
}
module.exports = {confirmOrRetractButton}
| var React = require("react");
var {Button, Glyphicon} = require("react-bootstrap");
function confirmOrRetractButton(userSelected, confirm, retract, size = "medium") {
return userSelected
? <Button className="dim" bsSize={size} onClick={retract}><Glyphicon glyph="remove"/></Button>
: <Button className="dim" bsSize={size} onClick={confirm}><Glyphicon glyph="ok" /></Button>;
}
module.exports = {confirmOrRetractButton}
| Use Glyphicons for confirm/retract buttons. | Use Glyphicons for confirm/retract buttons.
| JavaScript | mit | webXcerpt/openCPQ | ---
+++
@@ -1,14 +1,11 @@
var React = require("react");
-var {Button} = require("react-bootstrap");
+var {Button, Glyphicon} = require("react-bootstrap");
-
-var confirmMark = "\u2713"; // check mark
-var retractMark = "\u00D7"; // multiplication sign
function confirmOrRetractButton(userSelected, confirm, retract, size = "medium") {
return userSelected
- ? <Button className="dim" bsSize={size} onClick={retract}>{retractMark}</Button>
- : <Button className="dim" bsSize={size} onClick={confirm}>{confirmMark}</Button>;
+ ? <Button className="dim" bsSize={size} onClick={retract}><Glyphicon glyph="remove"/></Button>
+ : <Button className="dim" bsSize={size} onClick={confirm}><Glyphicon glyph="ok" /></Button>;
}
module.exports = {confirmOrRetractButton} |
a05f58f5b0131787ca26fcef2cec3d30dea70d9f | test/webpack.conf.js | test/webpack.conf.js | var path = require('path');
module.exports = {
entry: './test/build/index.js',
output: {
path: __dirname + "/build",
filename: "bundle.js",
publicPath: "./build/"
},
bail: true,
module: {
loaders: [
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.md$/, loader: 'raw-loader'},
{ test: /\.html$/, loader: "file?name=[name].[ext]" },
{ test: /\.ipynb$/, loader: 'json-loader' },
],
}
}
| var path = require('path');
module.exports = {
entry: './test/build/index.js',
output: {
path: __dirname + "/build",
filename: "bundle.js",
publicPath: "./build/"
},
bail: true,
module: {
loaders: [
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.md$/, loader: 'raw-loader'},
{ test: /\.html$/, loader: "file?name=[name].[ext]" },
{ test: /\.ipynb$/, loader: 'json-loader' },
{ test: /\.json$/, loader: 'json-loader' }
]
}
}
| Fix broken test build: htmlparser2 loads a .json file so webpack needs to use json-loader. | Fix broken test build: htmlparser2 loads a .json file so webpack needs to use json-loader.
| JavaScript | bsd-3-clause | jupyter/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab,TypeFox/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab | ---
+++
@@ -14,6 +14,7 @@
{ test: /\.md$/, loader: 'raw-loader'},
{ test: /\.html$/, loader: "file?name=[name].[ext]" },
{ test: /\.ipynb$/, loader: 'json-loader' },
- ],
+ { test: /\.json$/, loader: 'json-loader' }
+ ]
}
} |
68f0bfbcc401e756c4da8d73d2320a89aa2296ee | lib/poor-mans-proxy.js | lib/poor-mans-proxy.js | 'use strict';
if (global.Proxy)
{
return;
}
var decorateProperty = require('poor-mans-proxy-decorate-property');
global.Proxy = function(target, handler) {
var proxy = Object.create(Object.getPrototypeOf(target));
switch (typeof target)
{
case 'object':
for (var prop in target)
{
decorateProperty(proxy, target, handler, prop);
}
break;
case 'function':
// Apply Handler
if (handler && handler.apply && typeof handler.apply === 'function')
{
proxy = function() {
return handler.apply.call(handler, target, this, arguments);
};
}
else
{
proxy = target;
}
proxy.prototype = Object.getPrototypeOf(target);
for (prop in target)
{
decorateProperty(proxy, target, handler, prop);
}
break;
default:
throw new TypeError('target must be an Object or a Function');
}
return proxy;
};
| 'use strict';
var decorateProperty = require('poor-mans-proxy-decorate-property');
module.exports = function(target, handler) {
var proxy = Object.create(Object.getPrototypeOf(target));
switch (typeof target)
{
case 'object':
for (var prop in target)
{
decorateProperty(proxy, target, handler, prop);
}
break;
case 'function':
// Apply Handler
if (handler && handler.apply && typeof handler.apply === 'function')
{
proxy = function() {
return handler.apply.call(handler, target, this, arguments);
};
}
else
{
proxy = target;
}
proxy.prototype = Object.getPrototypeOf(target);
for (prop in target)
{
decorateProperty(proxy, target, handler, prop);
}
break;
default:
throw new TypeError('target must be an Object or a Function');
}
return proxy;
};
module.exports.isPolyfill = true;
if (!global.Proxy)
{
global.Proxy = module.exports;
}
| Allow poly fill usage, even if native Proxy exists | Allow poly fill usage, even if native Proxy exists
| JavaScript | mit | bealearts/poor-mans-proxy | ---
+++
@@ -1,14 +1,9 @@
'use strict';
-
-if (global.Proxy)
-{
- return;
-}
var decorateProperty = require('poor-mans-proxy-decorate-property');
-global.Proxy = function(target, handler) {
+module.exports = function(target, handler) {
var proxy = Object.create(Object.getPrototypeOf(target));
@@ -49,3 +44,12 @@
return proxy;
};
+
+
+module.exports.isPolyfill = true;
+
+
+if (!global.Proxy)
+{
+ global.Proxy = module.exports;
+} |
0ed92d8d54147a621354ad5de39818df2f48438b | lib/rules/zero-unit.js | lib/rules/zero-unit.js | 'use strict';
var helpers = require('../helpers');
var units = ['em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax',
'px', 'mm', 'cm', 'in', 'pt', 'pc'];
module.exports = {
'name': 'zero-unit',
'defaults': {
'include': false
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('number', function (item, i, parent) {
if (item.content === '0') {
if (parent.type === 'dimension') {
var next = parent.content[i + 1] || false;
if (units.indexOf(next.content) !== -1) {
if (!parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'severity': parser.severity,
'line': item.end.line,
'column': item.end.column,
'message': 'No unit allowed for values of 0'
});
}
}
}
else {
if (parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'severity': parser.severity,
'line': item.end.line,
'column': item.end.column,
'message': 'Unit required for values of 0'
});
}
}
}
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
var units = ['em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax',
'px', 'mm', 'cm', 'in', 'pt', 'pc'];
module.exports = {
'name': 'zero-unit',
'defaults': {
'include': false
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('number', function (item, i, parent) {
if (item.content === '0') {
if (parent.type === 'dimension') {
var next = parent.content[i + 1] || false;
if (units.indexOf(next.content) !== -1) {
if (!parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'severity': parser.severity,
'line': item.end.line,
'column': item.end.column,
'message': 'No unit allowed for values of 0'
});
}
}
}
else {
if (parent.type === 'value') {
if (parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'severity': parser.severity,
'line': item.end.line,
'column': item.end.column,
'message': 'Unit required for values of 0'
});
}
}
}
}
});
return result;
}
};
| Fix by targeting zeros within values only | :bug: Fix by targeting zeros within values only
| JavaScript | mit | zaplab/sass-lint,zallek/sass-lint,sktt/sass-lint,DanPurdy/sass-lint,flacerdk/sass-lint,sasstools/sass-lint,srowhani/sass-lint,ngryman/sass-lint,benthemonkey/sass-lint,joshuacc/sass-lint,MethodGrab/sass-lint,bgriffith/sass-lint,donabrams/sass-lint,sasstools/sass-lint,alansouzati/sass-lint,skovhus/sass-lint,Snugug/sass-lint,Dru89/sass-lint,srowhani/sass-lint | ---
+++
@@ -32,14 +32,16 @@
}
}
else {
- if (parser.options.include) {
- result = helpers.addUnique(result, {
- 'ruleId': parser.rule.name,
- 'severity': parser.severity,
- 'line': item.end.line,
- 'column': item.end.column,
- 'message': 'Unit required for values of 0'
- });
+ if (parent.type === 'value') {
+ if (parser.options.include) {
+ result = helpers.addUnique(result, {
+ 'ruleId': parser.rule.name,
+ 'severity': parser.severity,
+ 'line': item.end.line,
+ 'column': item.end.column,
+ 'message': 'Unit required for values of 0'
+ });
+ }
}
}
} |
5fcb21e8ffbc97c31f0a5a2ae657f820b67e913e | lib/task-data/tasks/flash-quanta-bmc.js | lib/task-data/tasks/flash-quanta-bmc.js | // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Flash Quanta BMC',
injectableName: 'Task.Linux.Flash.Quanta.Bmc',
implementsTask: 'Task.Base.Linux.Commands',
options: {
file: null,
downloadDir: '/opt/downloads',
commands: [
// Backup files
'sudo /opt/socflash/socflash_x64 -b /opt/uploads/bmc-backup.bin',
'sudo curl -T /opt/uploads/bmc-backup.bin ' +
'{{ api.files }}/{{ task.nodeId }}-bmc-backup.bin',
// Flash files
'sudo /opt/socflash/socflash_x64 -s option=x ' +
'flashtype=2 if={{ options.downloadDir }}/{{ options.file }}',
]
},
properties: {
flash: {
type: 'bmc',
vendor: {
quanta: { }
}
}
}
};
| // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Flash Quanta BMC',
injectableName: 'Task.Linux.Flash.Quanta.Bmc',
implementsTask: 'Task.Base.Linux.Commands',
options: {
file: null,
downloadDir: '/opt/downloads',
commands: [
// Backup files
'sudo /opt/socflash/socflash_x64 -b /opt/uploads/bmc-backup.bin',
'sudo curl -T /opt/uploads/bmc-backup.bin ' +
'{{ api.files }}/{{ task.nodeId }}-bmc-backup.bin',
// Flash files
'sudo /opt/socflash/socflash_x64 -s option=x ' +
'flashtype=2 if={{ options.downloadDir }}/{{ options.file }}',
// Wait for the new BMC to take effect, suggested in script provided by Quanta
// Otherwise following bmc related tasks (if any) might possibly fail
'sleep 90'
]
},
properties: {
flash: {
type: 'bmc',
vendor: {
quanta: { }
}
}
}
};
| Add waiting time for the new bmc to take effect after flashing quanta, which is suggested by quanta in demo script | Add waiting time for the new bmc to take effect after flashing quanta,
which is suggested by quanta in demo script
| JavaScript | apache-2.0 | nortonluo/on-tasks,bbcyyb/on-tasks,AlaricChan/on-tasks,nortonluo/on-tasks,AlaricChan/on-tasks,bbcyyb/on-tasks | ---
+++
@@ -17,6 +17,9 @@
// Flash files
'sudo /opt/socflash/socflash_x64 -s option=x ' +
'flashtype=2 if={{ options.downloadDir }}/{{ options.file }}',
+ // Wait for the new BMC to take effect, suggested in script provided by Quanta
+ // Otherwise following bmc related tasks (if any) might possibly fail
+ 'sleep 90'
]
},
properties: { |
7189905bf94124240176dfff30df4dc4fc7e0021 | lib/throttle-stream.js | lib/throttle-stream.js | var Transform = require('readable-stream/transform');
var util = require('util');
function ThrottleStream (options) {
if (!(this instanceof ThrottleStream)) {
return new ThrottleStream(options);
}
options = options || {};
options.writeableObjectMode = true;
options.readableObjectMode = true;
this.lastTime = 0;
this.interval = (1000 / 5);
this.timeoutId = null;
this.buffer = [];
Transform.call(this, options);
}
util.inherits(ThrottleStream, Transform);
ThrottleStream.prototype.flush = function (callback) {
if (this.buffer.length > 0) {
var chunk = this.buffer.shift();
this.push(chunk);
if (this.buffer.length > 0) {
this.timeoutId = setTimeout(this.flush.bind(this, callback), this.interval);
} else {
if (callback) {
return callback();
}
}
}
};
ThrottleStream.prototype._transform = function (chunk, encoding, callback) {
this.buffer.push(chunk);
this.timeoutId = setTimeout(this.flush.bind(this, callback), this.interval);
};
ThrottleStream.prototype._flush = function (callback) {
this.flush(callback);
};
module.exports = ThrottleStream;
| var Transform = require('readable-stream/transform');
var util = require('util');
function ThrottleStream (options) {
if (!(this instanceof ThrottleStream)) {
return new ThrottleStream(options);
}
options = options || {};
options.objectMode = true;
options.writeableObjectMode = true;
options.readableObjectMode = true;
this.lastTime = 0;
this.interval = (1000 / 5);
this.timeoutId = null;
this.buffer = [];
Transform.call(this, options);
}
util.inherits(ThrottleStream, Transform);
ThrottleStream.prototype.flush = function (callback) {
if (this.buffer.length > 0) {
var chunk = this.buffer.shift();
this.push(chunk);
if (this.buffer.length > 0) {
this.timeoutId = setTimeout(this.flush.bind(this, callback), this.interval);
} else {
if (callback) {
return callback();
}
}
}
};
ThrottleStream.prototype._transform = function (chunk, encoding, callback) {
this.buffer.push(chunk);
this.timeoutId = setTimeout(this.flush.bind(this, callback), this.interval);
};
ThrottleStream.prototype._flush = function (callback) {
this.flush(callback);
};
module.exports = ThrottleStream;
| Use objectMode for throttle stream | Use objectMode for throttle stream
| JavaScript | mit | dbhowell/pino-cloudwatch | ---
+++
@@ -7,6 +7,7 @@
}
options = options || {};
+ options.objectMode = true;
options.writeableObjectMode = true;
options.readableObjectMode = true;
|
b83aed401a78906d69ff24b86613c7f8323f0290 | libs/runway-browser.js | libs/runway-browser.js |
var runway = require('./runway.js')
module.exports = runway
document.onclick = function(event) {
event = event || window.event // IE specials
var target = event.target || event.srcElement // IE specials
if (target.tagName === 'A') {
event.preventDefault()
processLink.call(target)
}
}
function processLink(){
var href = this.href.replace(location.origin,'')
// console.log('processLink', this.href, href)
if (this.dataset.ajax !== 'none') {
goto(href)
return false
}
return true
}
function goto(href){
var ctrl = runway.finder(href)
if (ctrl) {
ctrl()
updateUrl(href)
}
}
function updateUrl(url){
if (history.pushState) history.pushState(null, '', url)
else location.assign(url)
}
window.onpopstate = function(event){
window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))
}
function init(){ goto(location.pathname) }
// setTimeout(init,100)
window.addEventListener ? addEventListener('load', init, false) : window.attachEvent ? attachEvent('onload', init) : (onload = init)
|
var runway = require('./runway.js')
module.exports = runway
document.onclick = function(event) {
event = event || window.event // IE specials
var target = event.target || event.srcElement // IE specials
if (target.tagName === 'A') {
event.preventDefault()
processLink.call(target)
}
}
function processLink(){
var href = this.href.replace(location.origin,'')
// console.log('processLink', this.href, href)
if (this.dataset.ajax !== 'none') {
goForward(href)
doRoute(href)
return false
}
return true
}
function doRoute(href){
var ctrl = runway.finder(href)
if (ctrl) ctrl()
}
function goForward(url){
var title = Math.random().toString().split('.')[1]
if (history.pushState) history.pushState({url:url, title:title}, null, url)
else location.assign(url)
}
window.addEventListener('popstate',function(event){
doRoute(event.state.url)
})
window.onpopstate = function(event){
// doRoute(event.state.url)
// console.log( event )
// window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))
}
function init(){
history.replaceState( {url:location.pathname}, null, location.pathname )
var ctrl = runway.finder(location.pathname)
if (ctrl) ctrl()
}
// setTimeout(init,100)
window.addEventListener ? addEventListener('load', init, false) : window.attachEvent ? attachEvent('onload', init) : (onload = init)
| Fix bug in popstate navigating. | Fix bug in popstate navigating.
| JavaScript | mit | rm-rf-etc/concise-demo,rm-rf-etc/concise-demo,rm-rf-etc/concise | ---
+++
@@ -18,29 +18,38 @@
var href = this.href.replace(location.origin,'')
// console.log('processLink', this.href, href)
if (this.dataset.ajax !== 'none') {
- goto(href)
+ goForward(href)
+ doRoute(href)
return false
}
return true
}
-function goto(href){
+function doRoute(href){
var ctrl = runway.finder(href)
- if (ctrl) {
- ctrl()
- updateUrl(href)
- }
+ if (ctrl) ctrl()
}
-function updateUrl(url){
- if (history.pushState) history.pushState(null, '', url)
+function goForward(url){
+ var title = Math.random().toString().split('.')[1]
+ if (history.pushState) history.pushState({url:url, title:title}, null, url)
else location.assign(url)
}
+window.addEventListener('popstate',function(event){
+ doRoute(event.state.url)
+})
+
window.onpopstate = function(event){
- window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))
+ // doRoute(event.state.url)
+ // console.log( event )
+ // window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))
}
-function init(){ goto(location.pathname) }
+function init(){
+ history.replaceState( {url:location.pathname}, null, location.pathname )
+ var ctrl = runway.finder(location.pathname)
+ if (ctrl) ctrl()
+}
// setTimeout(init,100)
window.addEventListener ? addEventListener('load', init, false) : window.attachEvent ? attachEvent('onload', init) : (onload = init) |
1d7c5b856de2b01f84a26dba6c9b2c60b4a94ebe | src/react-chayns-tag_input/utils/getInputSize.js | src/react-chayns-tag_input/utils/getInputSize.js | let input = null;
export default function getInputSize(value) {
if (!input) {
input = document.createElement('div');
input.className = 'input';
input.style.display = 'inline-block';
input.style.visibility = 'hidden';
input.style.position = 'relative';
input.style.top = '0';
input.style.left = '100%';
document.body.appendChild(input);
}
input.innerText = value;
return input.getBoundingClientRect();
}
| let input = null;
export default function getInputSize(value) {
if (!input) {
input = document.createElement('div');
input.className = 'input';
input.style.visibility = 'hidden';
input.style.position = 'absolute';
input.style.top = '-999px';
input.style.left = '-999px';
document.body.appendChild(input);
}
input.innerText = value;
return input.getBoundingClientRect();
}
| Improve input size helper function | Improve input size helper function
The input could affect layout of tapps | JavaScript | mit | TobitSoftware/chayns-components,TobitSoftware/chayns-components,TobitSoftware/chayns-components | ---
+++
@@ -4,11 +4,10 @@
if (!input) {
input = document.createElement('div');
input.className = 'input';
- input.style.display = 'inline-block';
input.style.visibility = 'hidden';
- input.style.position = 'relative';
- input.style.top = '0';
- input.style.left = '100%';
+ input.style.position = 'absolute';
+ input.style.top = '-999px';
+ input.style.left = '-999px';
document.body.appendChild(input);
} |
23d038de57c680bbde5dea03ab0b07d552c84fea | webpack/plugins/svg-compiler-plugin.js | webpack/plugins/svg-compiler-plugin.js | import fs from 'fs';
import glob from 'glob';
import path from 'path';
import SVGSprite from 'svg-sprite';
import vinyl from 'vinyl';
function SVGCompilerPlugin(options) {
this.options = {baseDir: path.resolve(options.baseDir)};
}
SVGCompilerPlugin.prototype.apply = function(compiler) {
var baseDir = this.options.baseDir;
compiler.plugin('emit', function(compilation, callback) {
let content = null;
let files = glob.sync('**/*.svg', {cwd: baseDir});
let svgSpriter = new SVGSprite({
mode: {
symbol: true
},
shape: {
id: {
separator: '--'
}
}
});
files.forEach(function (file) {
svgSpriter.add(new vinyl({
path: path.join(baseDir, file),
base: baseDir,
contents: fs.readFileSync(path.join(baseDir, file))
}));
});
svgSpriter.compile(function (error, result, data) {
content = result.symbol.sprite.contents.toString();
});
// Insert this list into the Webpack build as a new file asset:
compilation.assets['sprite.svg'] = {
source: function() {
return content;
},
size: function() {
return content.length;
}
};
callback();
});
};
module.exports = SVGCompilerPlugin;
| import fs from 'fs';
import glob from 'glob';
import path from 'path';
import SVGSprite from 'svg-sprite';
import vinyl from 'vinyl';
function SVGCompilerPlugin(options) {
this.options = {baseDir: path.resolve(options.baseDir)};
}
SVGCompilerPlugin.prototype.apply = function(compiler) {
var baseDir = this.options.baseDir;
compiler.plugin('emit', function(compilation, callback) {
let content = null;
let files = glob.sync('**/*.svg', {cwd: baseDir});
let svgSpriter = new SVGSprite({
mode: {
defs: true
},
shape: {
id: {
separator: '--'
}
}
});
files.forEach(function (file) {
svgSpriter.add(new vinyl({
path: path.join(baseDir, file),
base: baseDir,
contents: fs.readFileSync(path.join(baseDir, file))
}));
});
svgSpriter.compile(function (error, result, data) {
content = result.defs.sprite.contents.toString();
});
// Insert this list into the Webpack build as a new file asset:
compilation.assets['sprite.svg'] = {
source: function() {
return content;
},
size: function() {
return content.length;
}
};
callback();
});
};
module.exports = SVGCompilerPlugin;
| Use defs instead of symbol in SVG sprite | Use defs instead of symbol in SVG sprite
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -16,7 +16,7 @@
let files = glob.sync('**/*.svg', {cwd: baseDir});
let svgSpriter = new SVGSprite({
mode: {
- symbol: true
+ defs: true
},
shape: {
id: {
@@ -34,7 +34,7 @@
});
svgSpriter.compile(function (error, result, data) {
- content = result.symbol.sprite.contents.toString();
+ content = result.defs.sprite.contents.toString();
});
// Insert this list into the Webpack build as a new file asset: |
130a9affffb3ef959ca1cbaf8abaa23849b8c964 | server/models/index.js | server/models/index.js | 'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/..\config\config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
| 'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
| Edit path to config.json in require statement | Edit path to config.json in require statement
| JavaScript | mit | 3m3kalionel/PostIt,3m3kalionel/PostIt | ---
+++
@@ -5,7 +5,7 @@
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
-var config = require(__dirname + '/..\config\config.json')[env];
+var config = require(__dirname + '/../config/config.json')[env];
var db = {};
if (config.use_env_variable) { |
a30db6341374e4d90862f55d4b83bbd81fa26f93 | index.js | index.js | const path = require('path');
const ghost = require('ghost');
const express = require('express');
const path = require('path');
const wrapperApp = express();
ghost({
config: path.join(__dirname, 'config.js')
}).then(function (ghostServer) {
wrapperApp.get('/.well-known/keybase.txt', function(req, res, next) {
res.sendFile(path.join(__dirname, 'well-known', 'keybase.txt'));
});
wrapperApp.use(ghostServer.config.paths.subdir, ghostServer.rootApp);
ghostServer.start(wrapperApp);
});
| const path = require('path');
const ghost = require('ghost');
const express = require('express');
const wrapperApp = express();
ghost({
config: path.join(__dirname, 'config.js')
}).then(function (ghostServer) {
wrapperApp.get('/.well-known/keybase.txt', function(req, res, next) {
res.sendFile(path.join(__dirname, 'well-known', 'keybase.txt'));
});
wrapperApp.use(ghostServer.config.paths.subdir, ghostServer.rootApp);
ghostServer.start(wrapperApp);
});
| Fix the duplicate import again | Fix the duplicate import again
| JavaScript | mit | jtanguy/clevercloud-ghost | ---
+++
@@ -1,7 +1,6 @@
const path = require('path');
const ghost = require('ghost');
const express = require('express');
-const path = require('path');
const wrapperApp = express();
|
b72991c0ee1ea973dcd9527bbb686a6c6ec29138 | index.js | index.js | var ActivityStream = require('./activity-stream.js');
var SimplerEventLogger = require('./simple-event-logger.js');
(new ActivityStream())
.pipe(new SimplerEventLogger())
.pipe(process.stdout);
| var ActivityStream = require('./activity-stream.js');
var SimplerEventLogger = require('./simple-event-logger.js');
var activityStream = new ActivityStream();
activityStream
.pipe(new SimplerEventLogger())
.pipe(process.stdout);
process.stdout.on('error', function(err) {
if (err.code == 'EPIPE') {
process.exit(1);
}
});
| Exit cleanly on a broken pipe | Exit cleanly on a broken pipe
| JavaScript | mit | danielbeardsley/gwhid | ---
+++
@@ -1,6 +1,14 @@
var ActivityStream = require('./activity-stream.js');
var SimplerEventLogger = require('./simple-event-logger.js');
-(new ActivityStream())
+var activityStream = new ActivityStream();
+
+activityStream
.pipe(new SimplerEventLogger())
.pipe(process.stdout);
+
+process.stdout.on('error', function(err) {
+ if (err.code == 'EPIPE') {
+ process.exit(1);
+ }
+}); |
062ffc8422fe1f8a37f1e3108ff3e829b9a1f027 | index.js | index.js | const express = require('express')
const socketio = require('socket.io')
const http = require('http')
const config = require('./config')
const app = express()
const server = http.Server(app)
const io = socketio(server)
const host = config.host || '0.0.0.0'
const port = config.port || 8080
app.get('/', (req, res) => {
res.status(200).json({ message: 'Hello World!' })
})
io.on('connection', function(socket) {
socket.on('sendWifiSignalStrength', data => {
io.emit('updateWifiSignalStrength', data)
})
})
app.use((err, req, res, next) => {
return res.status(500).json({ message: 'An unknown error occured.', err })
})
server.listen(port, host, () => {
process.stdout.write(`[Server] Listening on ${host}:${port}\n`)
})
| const express = require('express')
const socketio = require('socket.io')
const http = require('http')
const config = require('./config')
const app = express()
const server = http.Server(app)
const io = socketio(server, { path: '/ws' })
const host = config.host || '0.0.0.0'
const port = config.port || 8080
let connections = 0
let timer = 0
io.on('connection', function(connection) {
const socket = connection
++connections
process.stdout.write('[Server] A websocket client connected.\n')
if (connections && !timer) {
timer = setInterval(() => {
socket.emit('testTimer', { timestamp: Date.now() })
}, 1000)
}
socket.on('disconnect', () => {
--connections
process.stdout.write('[Server] A websocket client disconnected.\n')
if (!connections && timer) {
clearInterval(timer)
timer = null
}
})
})
app.get('/api/v1/hello-world', (req, res) => {
return res.status(200).json({ message: 'Hello World!' })
})
app.use((req, res, next) => {
return res
.status(404)
.jsonp({ message: 'This API endpoint is not supported.' })
})
app.use((err, req, res, next) => {
return res.status(500).json({ message: 'An unknown error occured.' })
})
server.listen(port, host, () => {
process.stdout.write(`[Server] Listening on ${host}:${port}\n`)
})
| Add test event and adjust URL to proxy config | Add test event and adjust URL to proxy config
| JavaScript | mit | nicklasfrahm/indesy-server | ---
+++
@@ -5,22 +5,46 @@
const app = express()
const server = http.Server(app)
-const io = socketio(server)
+const io = socketio(server, { path: '/ws' })
const host = config.host || '0.0.0.0'
const port = config.port || 8080
-app.get('/', (req, res) => {
- res.status(200).json({ message: 'Hello World!' })
-})
+let connections = 0
+let timer = 0
-io.on('connection', function(socket) {
- socket.on('sendWifiSignalStrength', data => {
- io.emit('updateWifiSignalStrength', data)
+io.on('connection', function(connection) {
+ const socket = connection
+
+ ++connections
+ process.stdout.write('[Server] A websocket client connected.\n')
+ if (connections && !timer) {
+ timer = setInterval(() => {
+ socket.emit('testTimer', { timestamp: Date.now() })
+ }, 1000)
+ }
+
+ socket.on('disconnect', () => {
+ --connections
+ process.stdout.write('[Server] A websocket client disconnected.\n')
+ if (!connections && timer) {
+ clearInterval(timer)
+ timer = null
+ }
})
})
+app.get('/api/v1/hello-world', (req, res) => {
+ return res.status(200).json({ message: 'Hello World!' })
+})
+
+app.use((req, res, next) => {
+ return res
+ .status(404)
+ .jsonp({ message: 'This API endpoint is not supported.' })
+})
+
app.use((err, req, res, next) => {
- return res.status(500).json({ message: 'An unknown error occured.', err })
+ return res.status(500).json({ message: 'An unknown error occured.' })
})
server.listen(port, host, () => { |
e9659281048a1c171bc894ba14c49e62d5b8b5d0 | lib/modules/methods/utils/wrapMethod.js | lib/modules/methods/utils/wrapMethod.js | import {
isFunction,
last
}
from 'lodash';
import callMeteorMethod from '../../storage/utils/call_meteor_method';
import rawAll from '../../fields/utils/rawAll';
function wrapMethod(methodName) {
return function(...methodArgs) {
const doc = this;
const Class = doc.constructor;
// Get the last argument.
let callback = last(methodArgs);
// If the last argument is a callback function, then remove the last
// argument.
if (isFunction(callback)) {
methodArgs.pop();
}
// If the last argument is not a callback function, then clear the
// "callback" variable.
else {
callback = undefined;
}
// Prepare arguments to be sent to the "/Astronomy/execute" method.
const meteorMethodArgs = {
className: Class.getName(),
methodName,
methodArgs
};
if (doc._isNew) {
meteorMethodArgs.rawDoc = rawAll(doc, {
transient: false
});
}
else {
meteorMethodArgs.id = doc._id;
}
return callMeteorMethod(
Class, '/Astronomy/execute', [meteorMethodArgs], callback
);
};
}
export default wrapMethod; | import {
isFunction,
last
}
from 'lodash';
import callMeteorMethod from '../../storage/utils/call_meteor_method';
import rawAll from '../../fields/utils/rawAll';
function wrapMethod(methodName) {
return function(...methodArgs) {
const doc = this;
const Class = doc.constructor;
// Get the last argument.
let callback = last(methodArgs);
// If the last argument is a callback function, then remove the last
// argument.
if (isFunction(callback)) {
methodArgs.pop();
}
// If the last argument is not a callback function, then clear the
// "callback" variable.
else {
callback = undefined;
}
// Prepare arguments to be sent to the "/Astronomy/execute" method.
const meteorMethodArgs = {
className: Class.getName(),
methodName,
methodArgs
};
if (doc._isNew) {
meteorMethodArgs.rawDoc = rawAll(doc, {
transient: false
});
}
else {
meteorMethodArgs.id = doc._id;
}
try {
// Run Meteor method.
return callMeteorMethod(
Class, '/Astronomy/execute', [meteorMethodArgs], callback
);
}
// Catch stub exceptions.
catch (err) {
if (callback) {
callback(err);
return null;
}
throw err;
}
};
}
export default wrapMethod; | Fix a bug with not catching meteor method errors thrown on the client | Fix a bug with not catching meteor method errors thrown on the client
| JavaScript | mit | jagi/meteor-astronomy | ---
+++
@@ -37,9 +37,21 @@
else {
meteorMethodArgs.id = doc._id;
}
- return callMeteorMethod(
- Class, '/Astronomy/execute', [meteorMethodArgs], callback
- );
+
+ try {
+ // Run Meteor method.
+ return callMeteorMethod(
+ Class, '/Astronomy/execute', [meteorMethodArgs], callback
+ );
+ }
+ // Catch stub exceptions.
+ catch (err) {
+ if (callback) {
+ callback(err);
+ return null;
+ }
+ throw err;
+ }
};
}
|
3cf9ce5642d2168c6751eb82924052747ab53799 | sigh/static/js/sigh.js | sigh/static/js/sigh.js | $().ready(function () {
$("form.comment").on("submit", function (event) {
event.preventDefault();
var $form = $(this);
var $comments = $(".comment-group");
$.ajax({
type: $form.attr("method"),
url: $form.attr("action"),
data: $form.serialize(),
success: function (e, status) {
$comments.prepend("<p>"+e.content+"</p>");
},
error: function (e, status) {
var errors = e.responseJSON;
$form.find(".content").addClass("has-error").find("span.tip").text(errors.content[0])
}
});
return false;
});
}); | $().ready(function () {
$("form.comment").on("submit", function (event) {
event.preventDefault();
var $form = $(this);
var $comments = $(".comment-group");
var $input = $("textarea.comment");
$.ajax({
type: $form.attr("method"),
url: $form.attr("action"),
data: $form.serialize(),
success: function (e, status) {
$comments.prepend("<p>"+e.content+"</p>");
$input.val("");
},
error: function (e, status) {
var errors = e.responseJSON;
$form.find(".content").addClass("has-error").find("span.tip").text(errors.content[0])
}
});
return false;
});
});
| Clear textarea after posting successfully | Clear textarea after posting successfully
| JavaScript | mit | kxxoling/Programmer-Sign,kxxoling/Programmer-Sign,kxxoling/Programmer-Sign | ---
+++
@@ -4,12 +4,14 @@
event.preventDefault();
var $form = $(this);
var $comments = $(".comment-group");
+ var $input = $("textarea.comment");
$.ajax({
type: $form.attr("method"),
url: $form.attr("action"),
data: $form.serialize(),
success: function (e, status) {
$comments.prepend("<p>"+e.content+"</p>");
+ $input.val("");
},
error: function (e, status) {
var errors = e.responseJSON; |
b0b23cae304d007a7d17049bcd0e43c9c48d2bfb | scripts/things/light_ambient.js | scripts/things/light_ambient.js | elation.require(['engine.things.light'], function() {
elation.component.add('engine.things.light_ambient', function() {
this.postinit = function() {
this.defineProperties({
'color': { type: 'color', default: 0xffffff },
});
}
this.createObject3D = function() {
this.lightobj = new THREE.AmbientLight(this.properties.color);
return this.lightobj;
}
}, elation.engine.things.light);
});
| elation.require(['engine.things.light'], function() {
elation.component.add('engine.things.light_ambient', function() {
this.postinit = function() {
this.defineProperties({
'color': { type: 'color', default: 0xffffff, set: this.updateLight },
});
}
this.createObject3D = function() {
this.lightobj = new THREE.AmbientLight(this.properties.color);
return this.lightobj;
}
this.updateLight = function() {
if (this.lightobj) {
this.lightobj.color.copy(this.color);
}
}
}, elation.engine.things.light);
});
| Update ambient light when color changes | Update ambient light when color changes
| JavaScript | mit | jbaicoianu/elation-engine | ---
+++
@@ -2,12 +2,17 @@
elation.component.add('engine.things.light_ambient', function() {
this.postinit = function() {
this.defineProperties({
- 'color': { type: 'color', default: 0xffffff },
+ 'color': { type: 'color', default: 0xffffff, set: this.updateLight },
});
}
this.createObject3D = function() {
this.lightobj = new THREE.AmbientLight(this.properties.color);
return this.lightobj;
}
+ this.updateLight = function() {
+ if (this.lightobj) {
+ this.lightobj.color.copy(this.color);
+ }
+ }
}, elation.engine.things.light);
}); |
97090bcf550e01d371673a472d6a8b2f8c94f0ff | IfPermission.js | IfPermission.js | import _ from 'lodash';
const IfPermission = props =>
(props.stripes.hasPerm(props.perm) ? props.children : null);
export default IfPermission;
| import _ from 'lodash';
import PropTypes from 'prop-types';
const IfPermission = (props, context) => {
return (context.stripes.hasPerm(props.perm) ? props.children : null);
}
IfPermission.contextTypes = {
stripes: PropTypes.shape({
hasPerm: PropTypes.func.isRequired,
}).isRequired,
};
export default IfPermission;
| Use Stripes object from context, not from prop | Use Stripes object from context, not from prop
Part of STRIPES-395.
| JavaScript | apache-2.0 | folio-org/stripes-core,folio-org/stripes-core,folio-org/stripes-core | ---
+++
@@ -1,6 +1,14 @@
import _ from 'lodash';
+import PropTypes from 'prop-types';
-const IfPermission = props =>
- (props.stripes.hasPerm(props.perm) ? props.children : null);
+const IfPermission = (props, context) => {
+ return (context.stripes.hasPerm(props.perm) ? props.children : null);
+}
+
+IfPermission.contextTypes = {
+ stripes: PropTypes.shape({
+ hasPerm: PropTypes.func.isRequired,
+ }).isRequired,
+};
export default IfPermission; |
74a94988c7e815688d9e740f6f3f7f7e8dbf08ca | lib/graph.js | lib/graph.js | import _ from 'lodash';
import { Graph, alg } from 'graphlib';
_.memoize.Cache = WeakMap;
let dijkstra = _.memoize(alg.dijkstra);
export function setupGraph(pairs) {
let graph = new Graph({ directed: true });
_.each(pairs, ({ from, to, method }) => graph.setEdge(from, to, method));
return graph;
}
export function getPath(graph, source, destination, path = []) {
let map = dijkstra(graph, source);
if (map[destination].distance) {
let predecessor = map[destination].predecessor;
path.push(graph.edge(predecessor, destination));
return getPath(graph, source, predecessor, path);
} else {
return path.reverse();
}
}
export function validateRelationship({ from, to, method }) {
let validations = [
_.isString(from),
_.isString(to),
_.isFunction(method)
];
return _.every(validations, Boolean);
}
| import _ from 'lodash';
import { Graph, alg } from 'graphlib';
export function setupGraph(pairs) {
let graph = new Graph({ directed: true });
_.each(pairs, ({ from, to, method }) => graph.setEdge(from, to, method));
return graph;
}
export function getPath(graph, source, destination, path = []) {
let map = alg.dijkstra(graph, source);
if (map[destination].distance) {
let predecessor = map[destination].predecessor;
path.push(graph.edge(predecessor, destination));
return getPath(graph, source, predecessor, path);
} else {
return path.reverse();
}
}
export function validateRelationship({ from, to, method }) {
let validations = [
_.isString(from),
_.isString(to),
_.isFunction(method)
];
return _.every(validations, Boolean);
}
| Remove usage of _.memoize and WeakMap | Remove usage of _.memoize and WeakMap
| JavaScript | mit | siddharthkchatterjee/graph-resolver | ---
+++
@@ -1,8 +1,5 @@
import _ from 'lodash';
import { Graph, alg } from 'graphlib';
-
-_.memoize.Cache = WeakMap;
-let dijkstra = _.memoize(alg.dijkstra);
export function setupGraph(pairs) {
let graph = new Graph({ directed: true });
@@ -11,7 +8,7 @@
}
export function getPath(graph, source, destination, path = []) {
- let map = dijkstra(graph, source);
+ let map = alg.dijkstra(graph, source);
if (map[destination].distance) {
let predecessor = map[destination].predecessor;
path.push(graph.edge(predecessor, destination)); |
30c34a2e367a628f8568f6a1377a743554fd0de8 | lib/index.js | lib/index.js | const Joi = require('joi');
const ValidationError = require('./validation-error');
const { mergeJoiOptions, joiSchema } = require('./joi');
const { mergeEvOptions, evSchema } = require('./ev');
const { parameters } = require('./parameters');
const { handleMutation } = require('./mutation');
const { clean, keyByField } = require('./reducers');
exports.validate = (schema = {}, options = {}, joi = {}) => {
Joi.assert(options, evSchema);
Joi.assert(schema, joiSchema);
return (request, response, next) => {
const evOptions = mergeEvOptions(options);
const joiOptions = mergeJoiOptions(joi, options.context, request);
const validate = (parameter) => schema[parameter].validateAsync(request[parameter], joiOptions)
.then(result => handleMutation(request, parameter, result.value, evOptions.context))
.catch(error => ({ [parameter]: error.details }));
const hasErrors = (errors) => (errors ? new ValidationError(errors, evOptions) : null);
const promises = parameters
.filter(parameter => request[parameter] && schema[parameter])
.map(parameter => validate(parameter));
return Promise.all(promises)
.then(e => clean(e))
.then(e => keyByField(e, options.keyByField))
.then(r => next(hasErrors(r)));
};
};
exports.ValidationError = ValidationError;
exports.Joi = Joi;
| const Joi = require('joi');
const ValidationError = require('./validation-error');
const { mergeJoiOptions, joiSchema } = require('./joi');
const { mergeEvOptions, evSchema } = require('./ev');
const { parameters } = require('./parameters');
const { handleMutation } = require('./mutation');
const { clean, keyByField } = require('./reducers');
exports.validate = (schema = {}, options = {}, joi = {}) => {
Joi.assert(options, evSchema);
Joi.assert(schema, joiSchema);
return (request, response, next) => {
const evOptions = mergeEvOptions(options);
const joiOptions = mergeJoiOptions(joi, options.context, request);
async function validate(parameter) {
let result;
try {
result = await schema[parameter].validateAsync(request[parameter], joiOptions);
} catch (error) {
return { [parameter]: error.details };
}
handleMutation(request, parameter, result.value, evOptions.context);
return undefined;
}
const hasErrors = (errors) => (errors ? new ValidationError(errors, evOptions) : null);
const promises = parameters
.filter(parameter => request[parameter] && schema[parameter])
.map(parameter => validate(parameter));
return Promise.all(promises)
.then(e => clean(e))
.then(e => keyByField(e, options.keyByField))
.then(r => next(hasErrors(r)));
};
};
exports.ValidationError = ValidationError;
exports.Joi = Joi;
| Make the validate function async | Make the validate function async
| JavaScript | mit | AndrewKeig/express-validation,AndrewKeig/express-validation | ---
+++
@@ -15,9 +15,16 @@
const evOptions = mergeEvOptions(options);
const joiOptions = mergeJoiOptions(joi, options.context, request);
- const validate = (parameter) => schema[parameter].validateAsync(request[parameter], joiOptions)
- .then(result => handleMutation(request, parameter, result.value, evOptions.context))
- .catch(error => ({ [parameter]: error.details }));
+ async function validate(parameter) {
+ let result;
+ try {
+ result = await schema[parameter].validateAsync(request[parameter], joiOptions);
+ } catch (error) {
+ return { [parameter]: error.details };
+ }
+ handleMutation(request, parameter, result.value, evOptions.context);
+ return undefined;
+ }
const hasErrors = (errors) => (errors ? new ValidationError(errors, evOptions) : null);
|
58ac22f06ec371a15b29a6aed7b5032d2453ad1c | lib/index.js | lib/index.js | var net = require('net');
var server = net.createServer(function (socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1'); | var net = require('net');
var server = net.createServer(function(c) {
console.log('client connected');
c.on('end', function() {
console.log('client disconnected');
});
c.on('data', function(data) {
console.log(data.toString());
});
});
server.listen(1337, function() {
console.log('server bound');
}); | Print incomming message on console | Print incomming message on console
| JavaScript | mit | FuriKuri/info-bundling | ---
+++
@@ -1,8 +1,13 @@
var net = require('net');
-
-var server = net.createServer(function (socket) {
- socket.write('Echo server\r\n');
- socket.pipe(socket);
+var server = net.createServer(function(c) {
+ console.log('client connected');
+ c.on('end', function() {
+ console.log('client disconnected');
+ });
+ c.on('data', function(data) {
+ console.log(data.toString());
+ });
});
-
-server.listen(1337, '127.0.0.1');
+server.listen(1337, function() {
+ console.log('server bound');
+}); |
f694d8ac5b83c5e0ccc25ab2aef44dd8427132ba | client/templates/registerWizard/steps/review/review.js | client/templates/registerWizard/steps/review/review.js | Template.wizardReview.onCreated(function () {
// Get reference to template instance
const instance = this;
// Get form data as instance variable
instance.registration = instance.data.wizard.mergedData();
});
Template.wizardReview.helpers({
'registration': function () {
// Get reference to template instance
const instance = Template.instance();
// Get registration from template instance
return instance.registration;
},
'accommodationsFee': function () {
// Get reference to template instance
const instance = Template.instance();
// Get registration data
const registration = instance.registration;
// Adjust attributes of registration data to match accommodations fee function
registration.type = registration.registrationType;
registration.ageGroup = calculateAgeGroup(registration.age);
// Calculate accommodations fee
const accommodationsFee = calculateAccommodationsFee(registration);
return accommodationsFee;
}
});
| Template.wizardReview.onCreated(function () {
// Get reference to template instance
const instance = this;
// Get form data as instance variable
instance.registration = instance.data.wizard.mergedData();
});
Template.wizardReview.helpers({
'registration': function () {
// Get reference to template instance
const instance = Template.instance();
// Get registration from template instance
return instance.registration;
},
'accommodationsFee': function () {
// Get reference to template instance
const instance = Template.instance();
// Get registration data
const registration = instance.registration;
// Adjust attributes of registration data to match accommodations fee function
registration.type = registration.registrationType;
registration.ageGroup = calculateAgeGroup(registration.age);
// Calculate accommodations fee
const accommodationsFee = calculateAccommodationsFee(registration);
return accommodationsFee;
},
'firstTimeAttenderDiscount': function () {
// Get reference to template instance
const instance = Template.instance();
// Get registration
const registration = instance.registration;
// Calculate first time attender discount
if (registration.firstTimeAttender) {
return firstTimeAttenderDiscount;
}
}
});
| Add first time attender helper | Add first time attender helper
| JavaScript | agpl-3.0 | quaker-io/pym-2015,quaker-io/pym-online-registration,quaker-io/pym-online-registration,quaker-io/pym-2015 | ---
+++
@@ -29,5 +29,17 @@
const accommodationsFee = calculateAccommodationsFee(registration);
return accommodationsFee;
+ },
+ 'firstTimeAttenderDiscount': function () {
+ // Get reference to template instance
+ const instance = Template.instance();
+
+ // Get registration
+ const registration = instance.registration;
+
+ // Calculate first time attender discount
+ if (registration.firstTimeAttender) {
+ return firstTimeAttenderDiscount;
+ }
}
}); |
5302e3e876f6c9fbba2b7c1c2121a4056c2ea690 | localization/jquery-ui-timepicker-vi.js | localization/jquery-ui-timepicker-vi.js | /* Vietnamese translation for the jQuery Timepicker Addon */
/* Written by Nguyen Dinh Trung */
(function($) {
$.timepicker.regional['vi'] = {
timeOnlyTitle: 'Chọn giờ',
timeText: 'Thời gian',
hourText: 'Giờ',
minuteText: 'Phút',
secondText: 'Giây',
millisecText: 'Phần nghìn giây',
timezoneText: 'Múi giờ',
currentText: 'Hiện thời',
closeText: 'Đóng'
timeFormat: 'h:m',
amNames: ['SA', 'AM', 'A'],
pmNames: ['CH', 'PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['vi']);
})(jQuery);
| /* Vietnamese translation for the jQuery Timepicker Addon */
/* Written by Nguyen Dinh Trung */
(function($) {
$.timepicker.regional['vi'] = {
timeOnlyTitle: 'Chọn giờ',
timeText: 'Thời gian',
hourText: 'Giờ',
minuteText: 'Phút',
secondText: 'Giây',
millisecText: 'Phần nghìn giây',
timezoneText: 'Múi giờ',
currentText: 'Hiện thời',
closeText: 'Đóng',
timeFormat: 'h:m',
amNames: ['SA', 'AM', 'A'],
pmNames: ['CH', 'PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['vi']);
})(jQuery);
| Fix missing comma by Ximik | Fix missing comma by Ximik
| JavaScript | mit | pyonnuka/jQuery-Timepicker-Addon,Youraiseme/jQuery-Timepicker-Addon,Jaspersoft/jQuery-Timepicker-Addon,trentrichardson/jQuery-Timepicker-Addon,ristovskiv/jQuery-Timepicker-Addon,nicofrand/jQuery-Timepicker-Addon,ssyang0102/jQuery-Timepicker-Addon,ristovskiv/jQuery-Timepicker-Addon,Jaspersoft/jQuery-Timepicker-Addon,brenosilver/jQuery-Timepicker-Addon,pyonnuka/jQuery-Timepicker-Addon,trentrichardson/jQuery-Timepicker-Addon,gaissa/jQuery-Timepicker-Addon,brenosilver/jQuery-Timepicker-Addon,ssyang0102/jQuery-Timepicker-Addon,Youraiseme/jQuery-Timepicker-Addon,nicofrand/jQuery-Timepicker-Addon,gaissa/jQuery-Timepicker-Addon | ---
+++
@@ -10,7 +10,7 @@
millisecText: 'Phần nghìn giây',
timezoneText: 'Múi giờ',
currentText: 'Hiện thời',
- closeText: 'Đóng'
+ closeText: 'Đóng',
timeFormat: 'h:m',
amNames: ['SA', 'AM', 'A'],
pmNames: ['CH', 'PM', 'P'], |
30db793631ea4c2062b3e3d941ef580c9ca8035b | webpack.hot.js | webpack.hot.js | /*global require: false, module: false */
'use strict';
var webpack = require('webpack');
var config = require('./webpack.config');
function wrapEntry(entry) {
if (entry instanceof Array) {
return entry;
}
return [entry];
}
config.entry = [
'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port
'webpack/hot/only-dev-server' // "only" prevents reload on syntax errors
].concat(wrapEntry(config.entry));
var jsLoader = config.module.loaders
.find(function (l) { return l.type === 'js'; });
jsLoader.loaders = ['react-hot'].concat(jsLoader.loaders);
config.plugins = config.plugins.concat([
new webpack.HotModuleReplacementPlugin()
]);
module.exports = config;
| /*global require: false, module: false */
'use strict';
var webpack = require('webpack');
var config = require('./webpack.config');
function wrapEntry(entry) {
if (entry instanceof Array) {
return entry;
}
return [entry];
}
config.entry = [
'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port
'webpack/hot/only-dev-server' // "only" prevents reload on syntax errors
].concat(wrapEntry(config.entry));
function find(arr, fn) {
for (var i = 0; i < arr.length; ++i) {
if (fn(arr[i])) {
return arr[i];
}
}
return undefined;
}
var jsLoader = find(config.module.loaders,
function (l) { return l.type === 'js'; });
jsLoader.loaders = ['react-hot'].concat(jsLoader.loaders);
config.plugins = config.plugins.concat([
new webpack.HotModuleReplacementPlugin()
]);
module.exports = config;
| Implement find for older node. | Implement find for older node.
| JavaScript | apache-2.0 | ucscXena/ucsc-xena-client,ucscXena/ucsc-xena-client,acthp/ucsc-xena-client,ucscXena/ucsc-xena-client,acthp/ucsc-xena-client,acthp/ucsc-xena-client,ucscXena/ucsc-xena-client,ucscXena/ucsc-xena-client | ---
+++
@@ -16,9 +16,17 @@
].concat(wrapEntry(config.entry));
+function find(arr, fn) {
+ for (var i = 0; i < arr.length; ++i) {
+ if (fn(arr[i])) {
+ return arr[i];
+ }
+ }
+ return undefined;
+}
-var jsLoader = config.module.loaders
- .find(function (l) { return l.type === 'js'; });
+var jsLoader = find(config.module.loaders,
+ function (l) { return l.type === 'js'; });
jsLoader.loaders = ['react-hot'].concat(jsLoader.loaders);
config.plugins = config.plugins.concat([ |
f31b2231d992271c598ae9be74e55c2f4e4f4a79 | src/Cache/BaseCache.js | src/Cache/BaseCache.js | /**
* BaseCache it's a simple static cache
*
* @namespace Barba.BaseCache
* @type {Object}
*/
var BaseCache = {
/**
* The array that keeps everything.
*
* @memberOf Barba.BaseCache
* @type {Array}
*/
data: [],
/**
* Helper to extend the object
*
* @memberOf Barba.BaseCache
* @private
* @param {Object} newObject
* @return {Object} newInheritObject
*/
extend: function(obj) {
return Utils.extend(this, obj);
},
/**
* Set a key, value data, mainly Barba is going to save Ajax
* promise object.
*
* @memberOf Barba.BaseCache
* @param {String} key
* @param {*} value
*/
set: function(key, val) {
this.data[key] = val;
},
/**
* Retrieve the data by the key
*
* @memberOf Barba.BaseCache
* @param {String} key
* @return {*}
*/
get: function(key) {
return this.data[key];
},
/**
* Reset all the cache stored
*
* @memberOf Barba.BaseCache
*/
reset: function() {
this.data = [];
}
};
module.exports = BaseCache;
| /**
* BaseCache it's a simple static cache
*
* @namespace Barba.BaseCache
* @type {Object}
*/
var BaseCache = {
/**
* The array that keeps everything.
*
* @memberOf Barba.BaseCache
* @type {Array}
*/
data: {},
/**
* Helper to extend the object
*
* @memberOf Barba.BaseCache
* @private
* @param {Object} newObject
* @return {Object} newInheritObject
*/
extend: function(obj) {
return Utils.extend(this, obj);
},
/**
* Set a key, value data, mainly Barba is going to save Ajax
* promise object.
*
* @memberOf Barba.BaseCache
* @param {String} key
* @param {*} value
*/
set: function(key, val) {
this.data[key] = val;
},
/**
* Retrieve the data by the key
*
* @memberOf Barba.BaseCache
* @param {String} key
* @return {*}
*/
get: function(key) {
return this.data[key];
},
/**
* Reset all the cache stored
*
* @memberOf Barba.BaseCache
*/
reset: function() {
this.data = {};
}
};
module.exports = BaseCache;
| Change array to object for data | Change array to object for data
| JavaScript | mit | luruke/barba.js,luruke/barba.js | ---
+++
@@ -11,7 +11,7 @@
* @memberOf Barba.BaseCache
* @type {Array}
*/
- data: [],
+ data: {},
/**
* Helper to extend the object
@@ -54,7 +54,7 @@
* @memberOf Barba.BaseCache
*/
reset: function() {
- this.data = [];
+ this.data = {};
}
};
|
ce4b95359c29b42431a836888b83203f05cb5089 | patch.js | patch.js | patch();
function patch() {
var ensure = __webpack_require__.e;
var head = document.querySelector('head');
__webpack_require__.e = function(chunkId, callback) {
var loaded = false;
var handler = function(error) {
if (loaded) return;
loaded = true;
callback(error);
};
ensure(chunkId, function() {
handler();
});
onError(function() {
handler(true);
});
};
function onError(callback) {
var script = head.lastChild;
if (script.tagName !== 'SCRIPT') {
// throw new Error('Script is not a script');
console.warn('Script is not a script', script);
return;
}
script.onload = script.onerror = function() {
script.onload = script.onerror = null;
callback();
};
};
}; | patch();
function patch() {
var ensure = __webpack_require__.e;
var head = document.querySelector('head');
__webpack_require__.e = function(chunkId, callback) {
var loaded = false;
var handler = function(error) {
if (loaded) return;
loaded = true;
callback(error);
};
ensure(chunkId, function() {
handler();
});
onError(function() {
if (__webpack_require__.s) {
__webpack_require__.s[chunkId] = void 0;
}
handler(true);
});
};
function onError(callback) {
var script = head.lastChild;
if (script.tagName !== 'SCRIPT') {
// throw new Error('Script is not a script');
console.warn('Script is not a script', script);
return;
}
script.onload = script.onerror = function() {
script.onload = script.onerror = null;
callback();
};
};
}; | Support cleaning of installedChunks callbacks | Support cleaning of installedChunks callbacks
It requires this PR https://github.com/webpack/webpack/pull/1380
to be approved. Or using custom webpack build with that PR. Otherwise,
stuck callback may cause memory leaks.
| JavaScript | mit | NekR/async-module-loader | ---
+++
@@ -19,6 +19,10 @@
});
onError(function() {
+ if (__webpack_require__.s) {
+ __webpack_require__.s[chunkId] = void 0;
+ }
+
handler(true);
});
}; |
1bb8e4e05766ed4ab73d4a8ad5424d238eb6c19a | examples/realworld/src/util/view.js | examples/realworld/src/util/view.js | /* mithril
import m from "mithril"
import { h } from "seview/mithril"
export const render = (view, element) => m.render(element, h(view))
end mithril */
/* preact */
import preact from "preact"
import { h } from "seview/preact"
export const render = (view, element) => preact.render(h(view), element, element.lastElementChild)
/* end preact */
/* react
import ReactDOM from "react-dom"
import { h } from "seview/react"
export const render = (view, element) => ReactDOM.render(h(view), element)
end react */
export const defaultImage = "/assets/smiley-cyrus.jpg"
| /* mithril
import m from "mithril"
import { h } from "seview/mithril"
export const render = (view, element) => m.render(element, h(view))
end mithril */
/* preact */
import preact from "preact"
import { h } from "seview/preact"
export const render = (view, element) => preact.render(h(view), element, element.lastElementChild)
/* end preact */
/* react
import ReactDOM from "react-dom"
import { h } from "seview/react"
export const render = (view, element) => ReactDOM.render(h(view), element)
end react */
export const defaultImage = "assets/smiley-cyrus.jpg"
| Fix reference to image in realworld example. | Fix reference to image in realworld example.
| JavaScript | mit | foxdonut/meiosis-examples,foxdonut/meiosis-examples | ---
+++
@@ -19,4 +19,4 @@
export const render = (view, element) => ReactDOM.render(h(view), element)
end react */
-export const defaultImage = "/assets/smiley-cyrus.jpg"
+export const defaultImage = "assets/smiley-cyrus.jpg" |
98d2fbae57cd1c4071aa0c1613e979c1f2d29de0 | grunt/tasks/jasmine.js | grunt/tasks/jasmine.js | var _ = require('underscore');
var defaultOptions = {
keepRunner: true,
summary: true,
display: 'short',
vendor: [
// Load & install the source-map-support lib (get proper stack traces from inlined source-maps)
'node_modules/source-map-support/browser-source-map-support.js',
'test/install-source-map-support.js',
'http://maps.googleapis.com/maps/api/js?key=AIzaSyA4KzmztukvT7C49NSlzWkz75Xg3J_UyFI',
'node_modules/jasmine-ajax/lib/mock-ajax.js',
'http://cdn.rawgit.com/CartoDB/tangram-1/point-experiment/dist/tangram.min.js'
]
};
/**
* Jasmine grunt task for CartoDB.js tests
* https://github.com/gruntjs/grunt-contrib-jasmine#options
* Load order: vendor, helpers, source, specs,
*/
module.exports = {
'cartodb-src': {
src: [], // actual src files are require'd in the *.spec.js files
options: _.defaults({
outfile: 'test/SpecRunner-src.html',
specs: '<%= config.tmp %>/src-specs.js',
'--web-security': 'no'
}, defaultOptions)
}
};
| var _ = require('underscore');
var defaultOptions = {
keepRunner: true,
summary: true,
display: 'short',
vendor: [
// Load & install the source-map-support lib (get proper stack traces from inlined source-maps)
'node_modules/source-map-support/browser-source-map-support.js',
'test/install-source-map-support.js',
'http://maps.googleapis.com/maps/api/js?key=AIzaSyA4KzmztukvT7C49NSlzWkz75Xg3J_UyFI',
'node_modules/jasmine-ajax/lib/mock-ajax.js',
'node_modules/leaflet/dist/leaflet-src.js',
'http://cdn.rawgit.com/CartoDB/tangram-1/point-experiment/dist/tangram.min.js'
]
};
/**
* Jasmine grunt task for CartoDB.js tests
* https://github.com/gruntjs/grunt-contrib-jasmine#options
* Load order: vendor, helpers, source, specs,
*/
module.exports = {
'cartodb-src': {
src: [], // actual src files are require'd in the *.spec.js files
options: _.defaults({
outfile: 'test/SpecRunner-src.html',
specs: '<%= config.tmp %>/src-specs.js',
'--web-security': 'no'
}, defaultOptions)
}
};
| Add Leaflet to vendor for specs | Add Leaflet to vendor for specs
| JavaScript | bsd-3-clause | splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js | ---
+++
@@ -10,6 +10,7 @@
'test/install-source-map-support.js',
'http://maps.googleapis.com/maps/api/js?key=AIzaSyA4KzmztukvT7C49NSlzWkz75Xg3J_UyFI',
'node_modules/jasmine-ajax/lib/mock-ajax.js',
+ 'node_modules/leaflet/dist/leaflet-src.js',
'http://cdn.rawgit.com/CartoDB/tangram-1/point-experiment/dist/tangram.min.js'
]
}; |
4429894621ebd450d50a85ff23fb393f7b5564a5 | src/__mocks__/mongooseCommon.js | src/__mocks__/mongooseCommon.js | /* @flow */
/* eslint-disable no-param-reassign, no-console */
import mongoose, { Schema } from 'mongoose';
import MongodbMemoryServer from 'mongodb-memory-server';
mongoose.Promise = Promise;
const mongoServer = new MongodbMemoryServer();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
mongoServer.getConnectionString().then(mongoUri => {
mongoose.connect(mongoUri);
mongoose.connection.on('error', e => {
if (e.message.code === 'ETIMEDOUT') {
console.error(e);
mongoose.connect(mongoUri);
} else {
throw e;
}
});
mongoose.connection.once('open', () => {
// console.log(`MongoDB successfully connected to ${mongoUri}`);
});
});
afterAll(() => {
mongoose.disconnect();
mongoServer.stop();
});
export { mongoose, Schema };
| /* @flow */
/* eslint-disable no-param-reassign, no-console */
import mongoose, { Schema } from 'mongoose';
import MongodbMemoryServer from 'mongodb-memory-server';
mongoose.Promise = Promise;
const mongoServer = new MongodbMemoryServer({ debug: true });
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
mongoServer.getConnectionString().then(mongoUri => {
mongoose.connect(mongoUri);
mongoose.connection.on('error', e => {
if (e.message.code === 'ETIMEDOUT') {
console.error(e);
mongoose.connect(mongoUri);
} else {
throw e;
}
});
mongoose.connection.once('open', () => {
// console.log(`MongoDB successfully connected to ${mongoUri}`);
});
});
afterAll(() => {
mongoose.disconnect();
mongoServer.stop();
});
export { mongoose, Schema };
| Add debug mode in mongodb-memory-server | ci(Travis): Add debug mode in mongodb-memory-server
| JavaScript | mit | nodkz/graphql-compose-mongoose | ---
+++
@@ -6,7 +6,7 @@
mongoose.Promise = Promise;
-const mongoServer = new MongodbMemoryServer();
+const mongoServer = new MongodbMemoryServer({ debug: true });
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
|
14dffa3796224e9c5704c6645ebcdfe47d66694a | frontend/src/plugins/store/index.js | frontend/src/plugins/store/index.js | import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
import HalJsonVuex from 'hal-json-vuex'
import lang from './lang'
class StorePlugin {
install (Vue, options) {
Vue.use(Vuex)
store = new Vuex.Store({
modules: {
lang
},
strict: process.env.NODE_ENV !== 'production'
})
axios.defaults.withCredentials = true
axios.defaults.baseURL = window.environment.API_ROOT_URL
Vue.use(VueAxios, axios)
let halJsonVuex = HalJsonVuex
if (typeof halJsonVuex !== 'function') {
halJsonVuex = HalJsonVuex.default
}
apiStore = halJsonVuex(store, axios, { forceRequestedSelfLink: true })
Vue.use(apiStore)
}
}
export let apiStore
export let store
export default new StorePlugin()
| import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
import HalJsonVuex from 'hal-json-vuex'
import lang from './lang'
class StorePlugin {
install (Vue, options) {
Vue.use(Vuex)
store = new Vuex.Store({
modules: {
lang
},
strict: process.env.NODE_ENV !== 'production'
})
axios.defaults.withCredentials = true
axios.defaults.baseURL = window.environment.API_ROOT_URL
axios.defaults.headers.common.Accept = 'application/hal+json'
Vue.use(VueAxios, axios)
let halJsonVuex = HalJsonVuex
if (typeof halJsonVuex !== 'function') {
halJsonVuex = HalJsonVuex.default
}
apiStore = halJsonVuex(store, axios, { forceRequestedSelfLink: true })
Vue.use(apiStore)
}
}
export let apiStore
export let store
export default new StorePlugin()
| Add the Accept header to all API calls | Add the Accept header to all API calls
| JavaScript | agpl-3.0 | ecamp/ecamp3,usu/ecamp3,usu/ecamp3,ecamp/ecamp3,pmattmann/ecamp3,usu/ecamp3,ecamp/ecamp3,usu/ecamp3,pmattmann/ecamp3,pmattmann/ecamp3,ecamp/ecamp3,pmattmann/ecamp3 | ---
+++
@@ -17,6 +17,7 @@
axios.defaults.withCredentials = true
axios.defaults.baseURL = window.environment.API_ROOT_URL
+ axios.defaults.headers.common.Accept = 'application/hal+json'
Vue.use(VueAxios, axios)
let halJsonVuex = HalJsonVuex |
791d6cec734a682a4ed1bafec233398097775e38 | src/scripts/item-review/item-review.component.js | src/scripts/item-review/item-review.component.js | import template from './item-review.html';
import './item-review.scss';
function ItemReviewController($rootScope, dimSettingsService) {
'ngInject';
const vm = this;
vm.canReview = dimSettingsService.allowIdPostToDtr;
vm.expandReview = false;
vm.submitted = false;
vm.hasUserReview = vm.item.userRating;
vm.procon = false; // TODO: turn this back on..
vm.aggregate = {
pros: ['fast', 'lol'],
cons: ['ok']
};
// vm.item.writtenReviews.forEach((review) => {
// aggregate.pros.push(review.pros);
// aggregate.cons.push(review.cons);
// });
vm.toggleEdit = function() {
vm.expandReview = !vm.expandReview;
};
vm.submitReview = function() {
$rootScope.$broadcast('review-submitted', vm.item);
vm.expandReview = false;
vm.submitted = true;
};
vm.setRating = function(rating) {
if (rating) {
vm.item.userRating = rating;
}
vm.expandReview = true;
};
}
export const ItemReviewComponent = {
bindings: {
item: '<'
},
controller: ItemReviewController,
template: template
};
| import template from './item-review.html';
import './item-review.scss';
function ItemReviewController($rootScope, dimSettingsService) {
'ngInject';
const vm = this;
vm.canReview = dimSettingsService.allowIdPostToDtr;
vm.submitted = false;
vm.hasUserReview = vm.item.userRating;
vm.expandReview = vm.hasUserReview;
vm.procon = false; // TODO: turn this back on..
vm.aggregate = {
pros: ['fast', 'lol'],
cons: ['ok']
};
// vm.item.writtenReviews.forEach((review) => {
// aggregate.pros.push(review.pros);
// aggregate.cons.push(review.cons);
// });
vm.toggleEdit = function() {
vm.expandReview = !vm.expandReview;
};
vm.submitReview = function() {
$rootScope.$broadcast('review-submitted', vm.item);
vm.expandReview = false;
vm.submitted = true;
};
vm.setRating = function(rating) {
if (rating) {
vm.item.userRating = rating;
}
vm.expandReview = true;
};
}
export const ItemReviewComponent = {
bindings: {
item: '<'
},
controller: ItemReviewController,
template: template
};
| Expand the review if the user's at least entered a rating. | Expand the review if the user's at least entered a rating.
| JavaScript | mit | delphiactual/DIM,DestinyItemManager/DIM,bhollis/DIM,DestinyItemManager/DIM,delphiactual/DIM,bhollis/DIM,bhollis/DIM,chrisfried/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,bhollis/DIM,delphiactual/DIM,delphiactual/DIM,chrisfried/DIM,chrisfried/DIM,chrisfried/DIM | ---
+++
@@ -6,9 +6,9 @@
const vm = this;
vm.canReview = dimSettingsService.allowIdPostToDtr;
- vm.expandReview = false;
vm.submitted = false;
vm.hasUserReview = vm.item.userRating;
+ vm.expandReview = vm.hasUserReview;
vm.procon = false; // TODO: turn this back on..
vm.aggregate = { |
4ad1ddda54fc4581c1efbd2d8fe33f0b3d14c20a | popup.js | popup.js | function copyToClipboard(str){
'use strict';
// Copy str to clipboard
var textArea = document.createElement('textarea');
document.body.appendChild(textArea);
textArea.value = str;
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
window.addEventListener('load', function(){
'use strict';
// Get elements
var title = document.getElementById('page_title');
var url = document.getElementById('page_url');
var copyTitle = document.getElementById('copy_title');
var copyUrl = document.getElementById('copy_url');
// Get tab info
chrome.tabs.query({ active: true }, function(tabs){
'use strict';
// Show title and url
title.innerHTML = tabs[0].title;
url.innerHTML = tabs[0].url;
// Add click listener to copy button
copyTitle.addEventListener('click', function(){
'use strict';
// Copy title to clipboard
copyToClipboard(tabs[0].title);
});
copyUrl.addEventListener('click', function(){
'use strict';
// Copy title to clipboard
copyToClipboard(tabs[0].url);
});
});
});
| function copyToClipboard(str){
'use strict';
// Copy str to clipboard
var textArea = document.createElement('textarea');
document.body.appendChild(textArea);
textArea.value = str;
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
window.addEventListener('load', function(){
'use strict';
// Get elements
var title = document.getElementById('page_title');
var url = document.getElementById('page_url');
var copyTitle = document.getElementById('copy_title');
var copyUrl = document.getElementById('copy_url');
var copyAll = document.getElementById('copy_all');
// Get tab info
chrome.tabs.query({ active: true }, function(tabs){
'use strict';
// Show title and url
title.innerHTML = tabs[0].title;
url.innerHTML = tabs[0].url;
// Add click listener to copy button
copyTitle.addEventListener('click', function(){
'use strict';
// Copy title to clipboard
copyToClipboard(tabs[0].title);
});
copyUrl.addEventListener('click', function(){
'use strict';
// Copy title to clipboard
copyToClipboard(tabs[0].url);
});
copyAll.addEventListener('click', function(){
'use strict';
copyToClipboard(tabs[0].title + ' ' + tabs[0].url);
});
});
});
| Copy space separeted title and url to clipboard | Copy space separeted title and url to clipboard
| JavaScript | mit | Roadagain/TitleViewer,Roadagain/TitleViewer | ---
+++
@@ -18,6 +18,7 @@
var url = document.getElementById('page_url');
var copyTitle = document.getElementById('copy_title');
var copyUrl = document.getElementById('copy_url');
+ var copyAll = document.getElementById('copy_all');
// Get tab info
chrome.tabs.query({ active: true }, function(tabs){
@@ -40,5 +41,10 @@
// Copy title to clipboard
copyToClipboard(tabs[0].url);
});
+ copyAll.addEventListener('click', function(){
+ 'use strict';
+
+ copyToClipboard(tabs[0].title + ' ' + tabs[0].url);
+ });
});
}); |
6b0dc9bf664dfe6d037e1c8278c857127c591d8a | popup.js | popup.js | document.addEventListener('DOMContentLoaded', function() {
getSource();
});
function getSource() {
document.getElementById('source').innerText = "Loading";
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "GetEmailSource"}, function(response) {
var textarea = document.getElementById('source');
if(!response.source) {
textarea.innerText = "Uh, oh! Something went wrong!";
return;
}
var html_start = response.source.indexOf('<!DOCTYPE html');
if(html_start == -1) {
textarea.innerText = "Couldn't find message HTML. Please make sure you have opened a Gmail email. ";
return;
}
//extract the source HTML
var html_end = response.source.indexOf('--_=_swift', html_start);
var source = response.source.substr(html_start, html_end - html_start);
//decode it and display it
textarea.innerHTML = quotedPrintable.decode(source);
});
});
} | document.addEventListener('DOMContentLoaded', function() {
getSource();
});
function getSource() {
document.getElementById('source').innerText = "Loading";
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "GetEmailSource"}, function(response) {
var textarea = document.getElementById('source');
if(!response.source) {
textarea.innerText = "Uh, oh! Something went wrong!";
return;
}
var html_start = response.source.indexOf('<!DOCTYPE html');
if(html_start == -1) {
textarea.innerText = "Couldn't find message HTML. Please make sure you have opened a Gmail email. ";
return;
}
//extract the source HTML
var html_end = response.source.indexOf('--_=_swift', html_start);
var source = response.source.substr(html_start, html_end - html_start);
//decode it and display it
textarea.innerText = quotedPrintable.decode(source);
});
});
} | Switch back to using innerText | Switch back to using innerText
I thought innerHTML might preserve spaces better, but the encoding is
actually working fine without innerText
| JavaScript | mit | jammaloo/decode-gmail,jammaloo/decode-gmail,jammaloo/decode-gmail | ---
+++
@@ -23,7 +23,7 @@
var source = response.source.substr(html_start, html_end - html_start);
//decode it and display it
- textarea.innerHTML = quotedPrintable.decode(source);
+ textarea.innerText = quotedPrintable.decode(source);
});
});
} |
1814afba39af2e9ad87adb1cca5907a727007adf | teknologr/registration/static/js/registration.js | teknologr/registration/static/js/registration.js | $(document).ready(function() {
// There is no default option for setting readonly a field with django-bootstrap4
$('#id_mother_tongue').prop('readonly', true);
// Set tooltips
$('[data-toggle="tooltip"]').tooltip();
});
$('#id_degree_programme_options').change(function() {
if (this.value === 'extra') {
$('#unknown_degree').show();
$('#unknown_degree input').val('');
} else {
$('#unknown_degree').hide();
$('#unknown_degree input').val(this.value);
}
});
$('input:radio[name="language"]').change(function() {
if ($(this).is(':checked')) {
if ($(this).val() == 'extra') {
$('#id_mother_tongue').prop('readonly', false);
$('#id_mother_tongue').val('');
} else {
$('#id_mother_tongue').prop('readonly', true);
$('#id_mother_tongue').val(this.value);
}
}
});
| /* Some browsers (e.g. desktop Safari) does not have built-in datepickers (e.g. Firefox).
* Thus we check first if the browser supports this, in case not we inject jQuery UI into the DOM.
* This enables a jQuery datepicker.
*/
const datefield = document.createElement('input');
datefield.setAttribute('type', 'date');
if (datefield.type != 'date') {
const jQueryUIurl = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1';
document.write(`<link href="${jQueryUIurl}/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n`)
document.write(`<script src="${jQueryUIurl}/jquery-ui.min.js"><\/script>\n`)
}
$(document).ready(function() {
// There is no default option for setting readonly a field with django-bootstrap4
$('#id_mother_tongue').prop('readonly', true);
// Set tooltips
$('[data-toggle="tooltip"]').tooltip();
// Set the datepicker on birth date, in case input type of date is not supported
if (datefield.type != 'date') {
const currentYear = new Date().getFullYear();
$('id_birth_date').datepicker({
changeMonth: true,
changeYear: true,
yearRange: `1930:${currentYear}`,
});
}
});
$('#id_degree_programme_options').change(function() {
if (this.value === 'extra') {
$('#unknown_degree').show();
$('#unknown_degree input').val('');
} else {
$('#unknown_degree').hide();
$('#unknown_degree input').val(this.value);
}
});
$('input:radio[name="language"]').change(function() {
if ($(this).is(':checked')) {
if ($(this).val() == 'extra') {
$('#id_mother_tongue').prop('readonly', false);
$('#id_mother_tongue').val('');
} else {
$('#id_mother_tongue').prop('readonly', true);
$('#id_mother_tongue').val(this.value);
}
}
});
| Add support for browsers without datepicker for input types of date | Add support for browsers without datepicker for input types of date
| JavaScript | mit | Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io | ---
+++
@@ -1,9 +1,34 @@
+/* Some browsers (e.g. desktop Safari) does not have built-in datepickers (e.g. Firefox).
+ * Thus we check first if the browser supports this, in case not we inject jQuery UI into the DOM.
+ * This enables a jQuery datepicker.
+ */
+
+const datefield = document.createElement('input');
+datefield.setAttribute('type', 'date');
+
+if (datefield.type != 'date') {
+ const jQueryUIurl = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1';
+ document.write(`<link href="${jQueryUIurl}/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n`)
+ document.write(`<script src="${jQueryUIurl}/jquery-ui.min.js"><\/script>\n`)
+}
+
$(document).ready(function() {
// There is no default option for setting readonly a field with django-bootstrap4
$('#id_mother_tongue').prop('readonly', true);
// Set tooltips
$('[data-toggle="tooltip"]').tooltip();
+
+ // Set the datepicker on birth date, in case input type of date is not supported
+ if (datefield.type != 'date') {
+ const currentYear = new Date().getFullYear();
+
+ $('id_birth_date').datepicker({
+ changeMonth: true,
+ changeYear: true,
+ yearRange: `1930:${currentYear}`,
+ });
+ }
});
$('#id_degree_programme_options').change(function() { |
bfb2396d57837298e43a55c6ae6c922f2cb46bd0 | src/js/components/AlertPanel.js | src/js/components/AlertPanel.js | var classNames = require('classnames');
var React = require('react');
var Panel = require('./Panel');
var AlertPanel = React.createClass({
displayName: 'AlertPanel',
defaultProps: {
icon: null
},
propTypes: {
title: React.PropTypes.string,
icon: React.PropTypes.node,
iconClassName: React.PropTypes.string
},
getTitle: function () {
return (
<h3 className="inverse flush-top">
{this.props.title}
</h3>
);
},
getIcon: function () {
let {icon, iconClassName} = this.props;
if (!!icon) {
return icon;
}
if (!iconClassName) {
return null;
}
return (
<i className={iconClassName}></i>
);
},
render: function () {
var classes = {
'container container-fluid container-pod': true
};
if (this.props.className) {
classes[this.props.className] = true;
}
var classSet = classNames(classes);
return (
<div className={classSet}>
<Panel ref="panel"
className="panel panel-inverse vertical-center horizontal-center
text-align-center flush-bottom alert-panel"
footer={this.props.footer}
footerClass="panel-footer flush-top"
heading={this.getIcon()}
headingClass="panel-header no-border flush-bottom">
{this.getTitle()}
{this.props.children}
</Panel>
</div>
);
}
});
module.exports = AlertPanel;
| var classNames = require('classnames');
var React = require('react');
var Panel = require('./Panel');
var AlertPanel = React.createClass({
displayName: 'AlertPanel',
defaultProps: {
className: '',
icon: null
},
propTypes: {
title: React.PropTypes.string,
icon: React.PropTypes.node,
iconClassName: React.PropTypes.string
},
getTitle: function () {
return (
<h3 className="inverse flush-top">
{this.props.title}
</h3>
);
},
getIcon: function () {
let {icon, iconClassName} = this.props;
if (!!icon) {
return icon;
}
if (!iconClassName) {
return null;
}
return (
<i className={iconClassName}></i>
);
},
render: function () {
let classes = classNames('container container-fluid container-pod',
'flush-bottom', this.props.className);
return (
<div className={classes}>
<Panel ref="panel"
className="panel panel-inverse vertical-center horizontal-center
text-align-center flush-bottom alert-panel"
footer={this.props.footer}
footerClass="panel-footer flush-top"
heading={this.getIcon()}
headingClass="panel-header no-border flush-bottom">
{this.getTitle()}
{this.props.children}
</Panel>
</div>
);
}
});
module.exports = AlertPanel;
| Reduce bottom padding on alert panel | Reduce bottom padding on alert panel
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -8,6 +8,7 @@
displayName: 'AlertPanel',
defaultProps: {
+ className: '',
icon: null
},
@@ -42,17 +43,11 @@
},
render: function () {
- var classes = {
- 'container container-fluid container-pod': true
- };
- if (this.props.className) {
- classes[this.props.className] = true;
- }
-
- var classSet = classNames(classes);
+ let classes = classNames('container container-fluid container-pod',
+ 'flush-bottom', this.props.className);
return (
- <div className={classSet}>
+ <div className={classes}>
<Panel ref="panel"
className="panel panel-inverse vertical-center horizontal-center
text-align-center flush-bottom alert-panel" |
39959eb5b7c80ead491097b0581ba155191152fe | cli/commands/install.js | cli/commands/install.js | var p = require('path')
, helper = require('../helpers/promise')
, scripts_path = p.resolve(__dirname, '../../scripts')
module.exports = {
client: function(client) {
return function() {
return helper.runasroot(require('ezseed-'+client)('install'))
}
},
server: function(host) {
return function() {
return helper.runasroot(p.join(scripts_path, 'server.sh') + ' ' +host)
}
}
}
| var p = require('path')
, helper = require('../helpers/promise')
, scripts_path = p.resolve(__dirname, '../../scripts')
, logger = require('ezseed-logger')('server')
, os = require('os')
module.exports = {
client: function(client) {
return function() {
return helper.runasroot(require('ezseed-'+client)('install'))
}
},
server: function(host) {
return function() {
return helper.condition(os.platform() == 'linux', function() {
return helper.runasroot(p.join(scripts_path, 'server.sh') + ' ' +host)
}, function() {
logger.warn('System user not supported')
return helper.next(0)
})
}
}
}
| Install only available for linux | fix(server): Install only available for linux
| JavaScript | bsd-3-clause | ezseed/ezseed,ezseed/ezseed | ---
+++
@@ -1,6 +1,8 @@
var p = require('path')
, helper = require('../helpers/promise')
, scripts_path = p.resolve(__dirname, '../../scripts')
+ , logger = require('ezseed-logger')('server')
+ , os = require('os')
module.exports = {
client: function(client) {
@@ -10,7 +12,12 @@
},
server: function(host) {
return function() {
- return helper.runasroot(p.join(scripts_path, 'server.sh') + ' ' +host)
+ return helper.condition(os.platform() == 'linux', function() {
+ return helper.runasroot(p.join(scripts_path, 'server.sh') + ' ' +host)
+ }, function() {
+ logger.warn('System user not supported')
+ return helper.next(0)
+ })
}
}
} |
41d7fab27e1b405a62cae14424ab9be9d19be53d | Kinect2Scratch.js | Kinect2Scratch.js | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
]
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({}); | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
ext.wait_random = function(callback) {
wait = Math.random();
console.log('Waiting for ' + wait + ' seconds');
window.setTimeout(function() {
callback();
}, wait*1000);
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
]
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({}); | Make command block actually do something | Make command block actually do something
| JavaScript | bsd-3-clause | visor841/SkelScratch,Calvin-CS/SkelScratch | ---
+++
@@ -8,6 +8,14 @@
return {status: 2, msg: 'Ready'};
};
+ ext.wait_random = function(callback) {
+ wait = Math.random();
+ console.log('Waiting for ' + wait + ' seconds');
+ window.setTimeout(function() {
+ callback();
+ }, wait*1000);
+ };
+
// Block and block menu descriptions
var descriptor = {
blocks: [ |
94393f587dd1433a48d440e053f6012379f4ca47 | src/bindToSelection.js | src/bindToSelection.js | import { flow, curry, get, mapValues } from 'lodash/fp'
import { bind } from 'lodash'
const _bindSelector = curry((selectionName, selector) =>
flow(
get(selectionName),
selector
)
)
const bindToSelection = (actions, selectors) => (_selectionName) => {
let selectionName = _selectionName
if (!selectionName) {
selectionName = 'selection'
}
const boundActions = mapValues(
(actionCreator) => bind(actionCreator, null, selectionName),
actions
)
const boundSelectors = mapValues(
_bindSelector(selectionName),
selectors
)
return {
actions: boundActions,
selectors: boundSelectors,
}
}
export default bindToSelection
| import { flow, curry, get, mapValues } from 'lodash/fp'
import { bind } from 'lodash'
const _bindSelector = curry((selectionName, selector) =>
flow(
get(selectionName),
selector
)
)
const bindToSelection = (actions, selectors) => (selectionName = 'selection') => {
const boundActions = mapValues(
(actionCreator) => bind(actionCreator, null, selectionName),
actions
)
const boundSelectors = mapValues(
_bindSelector(selectionName),
selectors
)
return {
actions: boundActions,
selectors: boundSelectors,
}
}
export default bindToSelection
| Use ES6 syntax of default parameter value | Refactor: Use ES6 syntax of default parameter value
| JavaScript | mit | actano/yourchoice-redux | ---
+++
@@ -8,11 +8,7 @@
)
)
-const bindToSelection = (actions, selectors) => (_selectionName) => {
- let selectionName = _selectionName
- if (!selectionName) {
- selectionName = 'selection'
- }
+const bindToSelection = (actions, selectors) => (selectionName = 'selection') => {
const boundActions = mapValues(
(actionCreator) => bind(actionCreator, null, selectionName),
actions |
70cc46d66fd5183eaa0d7e0a1f3c1897b0a0761c | server/src/data/connectors.js | server/src/data/connectors.js | import mongoose from 'mongoose';
const uri = `mongodb://${process.env.MONGO_USERNAME}:${process.env
.MONGO_PASSWORD}@${process.env.MONGO_ADDRESS}`;
mongoose.Promise = global.Promise;
mongoose.connect(uri, { useMongoClient: true, reconnectTries: 30 });
mongoose.connection.on('connecting', () => {
console.dir({ Mongo: 'connecting..' }, { colors: true });
});
mongoose.connection.on('connected', () => {
console.dir({ Mongo: 'connected' }, { colors: true });
});
mongoose.connection.on('reconnected', () => {
console.dir({ Mongo: 'reconnected' }, { colors: true });
});
mongoose.connection.on('disconnected', () => {
console.dir({ Mongo: 'disconnected' }, { colors: true });
});
mongoose.connection.on('error', err => {
console.log('Mongoose failed to connect: ', err);
});
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('DB disconnected through terminal');
process.exit(0);
});
});
export default mongoose;
| import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config();
const uri = `mongodb://${process.env.MONGO_USERNAME}:${process.env
.MONGO_PASSWORD}@${process.env.MONGO_ADDRESS}`;
mongoose.Promise = global.Promise;
mongoose.connect(uri, { useMongoClient: true, reconnectTries: 30 });
mongoose.connection.on('connecting', () => {
console.dir({ Mongo: 'connecting..' }, { colors: true });
});
mongoose.connection.on('connected', () => {
console.dir({ Mongo: 'connected' }, { colors: true });
});
mongoose.connection.on('reconnected', () => {
console.dir({ Mongo: 'reconnected' }, { colors: true });
});
mongoose.connection.on('disconnected', () => {
console.dir({ Mongo: 'disconnected' }, { colors: true });
});
mongoose.connection.on('error', err => {
console.log('Mongoose failed to connect: ', err);
});
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('DB disconnected through terminal');
process.exit(0);
});
});
export default mongoose;
| Use dotenv to access env vars with process env | Use dotenv to access env vars with process env
| JavaScript | mit | nnnoel/graphql-apollo-resource-manager,nnnoel/graphql-apollo-resource-manager | ---
+++
@@ -1,4 +1,6 @@
import mongoose from 'mongoose';
+import dotenv from 'dotenv';
+dotenv.config();
const uri = `mongodb://${process.env.MONGO_USERNAME}:${process.env
.MONGO_PASSWORD}@${process.env.MONGO_ADDRESS}`; |
0b194091101c173ee8505eb4a7f711b9c43973a3 | js/forum/src/main.js | js/forum/src/main.js | /*global twemoji, s9e*/
import { override } from 'flarum/extend';
import app from 'flarum/app';
import Post from 'flarum/models/Post';
import Formatter from 'flarum/utils/Formatter';
app.initializers.add('emoji', () => {
override(Post.prototype, 'contentHtml', original => {
return twemoji.parse(original());
});
override(Formatter, 'format', (original, text) => {
return twemoji.parse(original(text));
});
});
| /*global twemoji, s9e*/
import { override } from 'flarum/extend';
import app from 'flarum/app';
import Post from 'flarum/models/Post';
app.initializers.add('emoji', () => {
override(Post.prototype, 'contentHtml', original => {
return twemoji.parse(original());
});
override(s9e.TextFormatter, 'preview', (original, text, element) => {
original(text, element);
twemoji.parse(element);
});
});
| Update for live preview refactor | Update for live preview refactor
| JavaScript | mit | flarum/emoji,flarum/emoji,flarum/flarum-ext-emoji,flarum/flarum-ext-emoji | ---
+++
@@ -3,14 +3,15 @@
import { override } from 'flarum/extend';
import app from 'flarum/app';
import Post from 'flarum/models/Post';
-import Formatter from 'flarum/utils/Formatter';
app.initializers.add('emoji', () => {
override(Post.prototype, 'contentHtml', original => {
return twemoji.parse(original());
});
- override(Formatter, 'format', (original, text) => {
- return twemoji.parse(original(text));
+ override(s9e.TextFormatter, 'preview', (original, text, element) => {
+ original(text, element);
+
+ twemoji.parse(element);
});
}); |
0700800eabf4592711c5979b80dafa503f073153 | js/main.js | js/main.js | $(document).ready(function() {
$(".tooltip-link").tooltip( {placement: "right"} );
});
if($(".email").length){
// variables, which will be replaced
var at = / AT /;
var dot = / DOT /g;
// function, which replaces pre-made class
$(".email a").each(function () {
var address = "mailto:" + $(this).data("email").replace(at, "@").replace(dot, ".");
$(this).attr("href",address);
});
$(".email").show();
};
| if($(".email").length){
// variables, which will be replaced
var at = / AT /;
var dot = / DOT /g;
// function, which replaces pre-made class
$(".email a").each(function () {
var address = "mailto:" + $(this).data("email").replace(at, "@").replace(dot, ".");
$(this).attr("href",address);
});
$(".email").show();
};
| Remove JavaScript code for initializing tooltips (they aren't used anymore) | Remove JavaScript code for initializing tooltips (they aren't used anymore)
| JavaScript | mit | nicolasmccurdy/nicolasmccurdy.github.io,nicolasmccurdy/nicolasmccurdy.github.io | ---
+++
@@ -1,7 +1,3 @@
-$(document).ready(function() {
- $(".tooltip-link").tooltip( {placement: "right"} );
-});
-
if($(".email").length){
// variables, which will be replaced
var at = / AT /; |
e29485ea7f284c93414df9c7f75a60e56ee92aed | lib/components/modifications-map/adjust-speed-layer.js | lib/components/modifications-map/adjust-speed-layer.js | /** A layer for an adjust speed modification */
import React from 'react'
import colors from 'lib/constants/colors'
import PatternLayer from './pattern-layer'
import HopLayer from './hop-layer'
export default function AdjustSpeedLayer(p) {
if (p.modification.hops) {
return (
<>
<PatternLayer
color={colors.NEUTRAL}
dim={p.dim}
feed={p.feed}
modification={p.modification}
/>
<HopLayer
color={colors.MODIFIED}
dim={p.dim}
feed={p.feed}
modification={p.modification}
/>
</>
)
} else {
return (
<PatternLayer
color={colors.MODIFIED}
dim={p.dim}
feed={p.feed}
modification={p.modification}
/>
)
}
}
| /** A layer for an adjust speed modification */
import React from 'react'
import {Pane} from 'react-leaflet'
import colors from 'lib/constants/colors'
import PatternLayer from './pattern-layer'
import HopLayer from './hop-layer'
export default function AdjustSpeedLayer(p) {
if (p.modification.hops) {
return (
<>
<Pane zIndex={500}>
<PatternLayer
color={colors.NEUTRAL}
dim={p.dim}
feed={p.feed}
modification={p.modification}
/>
</Pane>
<Pane zIndex={501}>
<HopLayer
color={colors.MODIFIED}
dim={p.dim}
feed={p.feed}
modification={p.modification}
/>
</Pane>
</>
)
} else {
return (
<PatternLayer
color={colors.MODIFIED}
dim={p.dim}
feed={p.feed}
modification={p.modification}
/>
)
}
}
| Add Panes for the display only component also | Add Panes for the display only component also
| JavaScript | mit | conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui | ---
+++
@@ -1,5 +1,6 @@
/** A layer for an adjust speed modification */
import React from 'react'
+import {Pane} from 'react-leaflet'
import colors from 'lib/constants/colors'
@@ -10,18 +11,22 @@
if (p.modification.hops) {
return (
<>
- <PatternLayer
- color={colors.NEUTRAL}
- dim={p.dim}
- feed={p.feed}
- modification={p.modification}
- />
- <HopLayer
- color={colors.MODIFIED}
- dim={p.dim}
- feed={p.feed}
- modification={p.modification}
- />
+ <Pane zIndex={500}>
+ <PatternLayer
+ color={colors.NEUTRAL}
+ dim={p.dim}
+ feed={p.feed}
+ modification={p.modification}
+ />
+ </Pane>
+ <Pane zIndex={501}>
+ <HopLayer
+ color={colors.MODIFIED}
+ dim={p.dim}
+ feed={p.feed}
+ modification={p.modification}
+ />
+ </Pane>
</>
)
} else { |
57e961138975b510c900b297d65784e1b14c2898 | server/app.js | server/app.js | var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
//var models = require("./models");
var PORT = process.env.PORT || 3000;
// app.get('/', function (req, res) {
// res.sendFile(__dirname + '/socketTest.html');
// })
//models.sequelize.sync().then(function () {
io.on('connection', function(client) {
console.log('Someone connected!');
client.on('join', function(data) {
if(data === 'This is your teacher speaking') {
client.emit('greeting', 'Hiya, Teach!');
} else{
client.emit('greeting', 'Hello, student. Please wait for your instructor to open a new poll.');
}
//client.emit('openPoll', 'hello, its me');
});
client.on('newPoll', function(data) {
console.log('>>>>>>>>>',data);
io.sockets.emit('openPoll', data);
});
client.on('disconnect', function(client) {
console.log('Bye!\n');
});
});
require('./config/routes.js')(app, express);
server.listen(PORT, function (){
console.log('listening on port', PORT);
});
// }; | var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
//var models = require("./models");
var PORT = process.env.PORT || 3000;
//models.sequelize.sync().then(function () {
io.on('connection', function(client) {
console.log('Someone connected!');
client.on('join', function(data) {
if(data === 'This is your teacher speaking') {
client.emit('greeting', 'Hiya, Teach!');
} else{
client.emit('greeting', 'Hello, student. Please wait for your instructor to open a new poll.');
}
});
client.on('newPoll', function(data) {
io.sockets.emit('openPoll', data);
});
client.on('disconnect', function(client) {
console.log('Bye!\n');
});
});
require('./config/routes.js')(app, express);
server.listen(PORT, function (){
console.log('listening on port', PORT);
});
// }; | Delete zombie code from socket testing | Delete zombie code from socket testing
| JavaScript | mit | Jakeyrob/thumbroll,absurdSquid/thumbroll,absurdSquid/thumbroll,shanemcgraw/thumbroll,Jakeyrob/thumbroll,Jakeyrob/thumbroll,shanemcgraw/thumbroll,shanemcgraw/thumbroll | ---
+++
@@ -6,10 +6,6 @@
var PORT = process.env.PORT || 3000;
-
-// app.get('/', function (req, res) {
-// res.sendFile(__dirname + '/socketTest.html');
-// })
//models.sequelize.sync().then(function () {
@@ -22,11 +18,9 @@
} else{
client.emit('greeting', 'Hello, student. Please wait for your instructor to open a new poll.');
}
- //client.emit('openPoll', 'hello, its me');
});
client.on('newPoll', function(data) {
- console.log('>>>>>>>>>',data);
io.sockets.emit('openPoll', data);
});
|
35d4403dc32ead2f1f106e66eacfc43c8de7397e | src/main/web/florence/js/functions/_viewTeams.js | src/main/web/florence/js/functions/_viewTeams.js | function viewTeams() {
getTeams(
success = function (data) {
populateTeamsTable(data.teams);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateTeamsTable(data) {
var teamsHtml = templates.teamList(teams);
$('.section').html(teamsHtml);
$('.js-selectable-table tbody tr').click(function () {
var teamId = $(this).attr('data-id');
viewTeamDetails(teamId, $(this));
});
$('.form-create-team').submit(function (e) {
e.preventDefault();
var teamName = $('#create-team-name').val();
if (teamName.length < 1) {
sweetAlert("Please enter a user name.");
return;
}
teamName = teamName.trim();
postTeam(teamName);
});
}
}
| function viewTeams() {
getTeams(
success = function (data) {
populateTeamsTable(data.teams);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateTeamsTable(data) {
var teamsHtml = templates.teamList(data);
$('.section').html(teamsHtml);
$('.js-selectable-table tbody tr').click(function () {
var teamId = $(this).attr('data-id');
viewTeamDetails(teamId, $(this));
});
$('.form-create-team').submit(function (e) {
e.preventDefault();
var teamName = $('#create-team-name').val();
if (teamName.length < 1) {
sweetAlert("Please enter a user name.");
return;
}
teamName = teamName.trim();
postTeam(teamName);
});
}
}
| Fix teams screen throwing error and not loading | Fix teams screen throwing error and not loading
Former-commit-id: cfd3266412adf3acb59b8cd4fd96725b8d95d218 | JavaScript | mit | ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence | ---
+++
@@ -10,7 +10,7 @@
);
function populateTeamsTable(data) {
- var teamsHtml = templates.teamList(teams);
+ var teamsHtml = templates.teamList(data);
$('.section').html(teamsHtml);
$('.js-selectable-table tbody tr').click(function () { |
e8af184a67e78d24e297a800a03d5044e90b69fd | src/disco/constants.js | src/disco/constants.js | // Tracking categories.
export const VIDEO_CATEGORY = 'Discovery Video';
export const NAVIGATION_CATEGORY = 'Discovery Navigation';
// Action types.
export const DISCO_RESULTS = 'DISCO_RESULTS';
// Keys for extensions and theme data in the discovery pane JSON blob.
export const DISCO_DATA_THEME = 'theme';
export const DISCO_DATA_EXTENSION = 'extension';
export const DISCO_DATA_UNKNOWN = 'unknown';
// Built-in extensions and themes to ignore.
export const DISCO_DATA_GUID_IGNORE_LIST = [
'{972ce4c6-7e08-4474-a285-3208198ce6fd}', // Default theme.
'e10srollout@mozilla.org', // e10s
'firefox@getpocket.com', // Pocket
'loop@mozilla.org', // Firefox Hello
'aushelper@mozilla.org', // Application Update Service Helper
'webcompat@mozilla.org', // Web Compat
'flyweb@mozilla.org', // FlyWeb
'formautofill@mozilla.org', // Form Autofill
'presentation@mozilla.org', // Presentation
'shield-recipe-client@mozilla.org', // Shield Recipe Client
];
| // Tracking categories.
export const VIDEO_CATEGORY = 'Discovery Video';
export const NAVIGATION_CATEGORY = 'Discovery Navigation';
// Action types.
export const DISCO_RESULTS = 'DISCO_RESULTS';
// Keys for extensions and theme data in the discovery pane JSON blob.
export const DISCO_DATA_THEME = 'theme';
export const DISCO_DATA_EXTENSION = 'extension';
export const DISCO_DATA_UNKNOWN = 'unknown';
// Built-in extensions and themes to ignore.
export const DISCO_DATA_GUID_IGNORE_LIST = [
'{972ce4c6-7e08-4474-a285-3208198ce6fd}', // Default theme.
'e10srollout@mozilla.org', // e10s
'firefox@getpocket.com', // Pocket
'loop@mozilla.org', // Firefox Hello
'aushelper@mozilla.org', // Application Update Service Helper
'webcompat@mozilla.org', // Web Compat
];
| Revert "Adding Nightly System Add-ons to the ignore list" | Revert "Adding Nightly System Add-ons to the ignore list"
This reverts commit 7aa255b4fa5ed7c5815eb5a1ba1432ce0b53453a.
| JavaScript | mpl-2.0 | mozilla/addons-frontend,kumar303/addons-frontend,tsl143/addons-frontend,mozilla/addons-frontend,squarewave/addons-frontend,mozilla/addons-frontend,kumar303/addons-frontend,aviarypl/mozilla-l10n-addons-frontend,kumar303/addons-frontend,mozilla/addons-frontend,aviarypl/mozilla-l10n-addons-frontend,aviarypl/mozilla-l10n-addons-frontend,tsl143/addons-frontend,aviarypl/mozilla-l10n-addons-frontend,squarewave/addons-frontend,tsl143/addons-frontend,squarewave/addons-frontend,kumar303/addons-frontend,tsl143/addons-frontend | ---
+++
@@ -17,8 +17,4 @@
'loop@mozilla.org', // Firefox Hello
'aushelper@mozilla.org', // Application Update Service Helper
'webcompat@mozilla.org', // Web Compat
- 'flyweb@mozilla.org', // FlyWeb
- 'formautofill@mozilla.org', // Form Autofill
- 'presentation@mozilla.org', // Presentation
- 'shield-recipe-client@mozilla.org', // Shield Recipe Client
]; |
9e58bf443f0c37c79542677ba9512053a202f31b | src/components/token/token-routes.js | src/components/token/token-routes.js | import express from 'express';
import jwt from 'jsonwebtoken';
const router = express.Router(); // eslint-disable-line new-cap
router.post('/token', (req, res) => {
const authentication = {
authenticationProvider: 'github',
authenticationId: '4321'
};
const token = jwt.sign(authentication, process.env.CSBLOGS_JWT_SECRET);
res.json({
token
});
});
| import express from 'express';
import jwt from 'jsonwebtoken';
const router = express.Router(); // eslint-disable-line new-cap
router.post('/', (req, res) => {
const authentication = {
authenticationProvider: 'github',
authenticationId: '4321'
};
const token = jwt.sign(authentication, process.env.CSBLOGS_JWT_SECRET);
res.json({
token
});
});
export default router;
| Fix token/ url and remember to actually export the router... | Fix token/ url and remember to actually export the router...
| JavaScript | mit | csblogs/api-server,csblogs/api-server | ---
+++
@@ -3,7 +3,7 @@
const router = express.Router(); // eslint-disable-line new-cap
-router.post('/token', (req, res) => {
+router.post('/', (req, res) => {
const authentication = {
authenticationProvider: 'github',
authenticationId: '4321'
@@ -15,3 +15,5 @@
token
});
});
+
+export default router; |
982a908bae99c14a72fd28ed2d3e5dc25106f707 | lib/cfg.js | lib/cfg.js | var fs = require('fs')
, path = require('path')
function read(dir) {
var f = path.resolve(dir, '.node-dev.json')
return fs.existsSync(f) ? JSON.parse(fs.readFileSync(f)) : {}
}
var c = read('.')
c.__proto__ = read(process.env.HOME)
module.exports = {
vm : c.vm !== false,
fork : c.fork !== false,
notify : c.notify !== false,
timestamp : c.timestamp || (c.timestamp !== false && 'HH:MM:ss'),
clear : !!c.clear,
extensions : c.extensions || {
coffee: "coffee-script",
ls: "LiveScript"
}
}
| var fs = require('fs')
, path = require('path')
function read(dir) {
var f = path.resolve(dir, '.node-dev.json')
return fs.existsSync(f) ? JSON.parse(fs.readFileSync(f)) : {}
}
var c = read('.')
c.__proto__ = read(process.env.HOME || process.env.USERPROFILE)
module.exports = {
vm : c.vm !== false,
fork : c.fork !== false,
notify : c.notify !== false,
timestamp : c.timestamp || (c.timestamp !== false && 'HH:MM:ss'),
clear : !!c.clear,
extensions : c.extensions || {
coffee: "coffee-script",
ls: "LiveScript"
}
}
| Fix for home directory on Windows | Fix for home directory on Windows
| JavaScript | mit | shinygang/node-dev,jiyinyiyong/node-dev,fgnass/node-dev,whitecolor/ts-node-dev,Casear/node-dev,whitecolor/ts-node-dev,SwoopCMI/node-dev,fgnass/node-dev,fgnass/node-dev | ---
+++
@@ -7,7 +7,7 @@
}
var c = read('.')
-c.__proto__ = read(process.env.HOME)
+c.__proto__ = read(process.env.HOME || process.env.USERPROFILE)
module.exports = {
vm : c.vm !== false, |
7dde6f8dd6495b6993f34ea4fcdb5cdc9158a2e7 | library.js | library.js | 'use strict';
// Requirements
var User = module.parent.require('./user'),
winston = module.parent.require('winston'),
watsonDev = require('watson-developer-cloud'),
// Methods
Watson = {};
Watson.response = function(postData) {
var conversation = watsonDev.conversation({
username: 'c9d9cc99-b3e5-44f5-a234-ccae1578e8ae',
password: 'xUtHqarwWpUk',
version: 'v1',
version_date: '2016-09-20'
}),
context = {},
params = {
workspace_id: '25dfa8a0-0263-471b-8980-317e68c30488',
input: {'text': 'hahaha'},
context: context
};
conversation.message(params, function
(err, response) {
if (err)
return winston.error(err);
else
winston.log(JSON.stringify(response, null, 2));
});
}
module.exports = Watson;
| 'use strict';
// Requirements
var User = module.parent.require('./user'),
var winston = module.parent.require('winston'),
var watsonDev = require('watson-developer-cloud');
// Methods
var Watson = {};
Watson.response = function(postData) {
var conversation = watsonDev.conversation({
username: 'c9d9cc99-b3e5-44f5-a234-ccae1578e8ae',
password: 'xUtHqarwWpUk',
version: 'v1',
version_date: '2016-09-20'
});
var context = {};
var params = {
workspace_id: 'a05393b7-d022-4bed-ba76-012042930893',
input: {'text': 'hahaha'},
context: context
};
conversation.message(params, function
(err, response) {
if (err)
return console.log(err);
else
console.log(JSON.stringify(response, null, 2));
});
}
module.exports = Watson;
| Replace of the content in workspace id | Replace of the content in workspace id
| JavaScript | mit | gmochi56/nodebb-plugin-watson | ---
+++
@@ -2,11 +2,11 @@
// Requirements
var User = module.parent.require('./user'),
- winston = module.parent.require('winston'),
- watsonDev = require('watson-developer-cloud'),
+var winston = module.parent.require('winston'),
+var watsonDev = require('watson-developer-cloud');
// Methods
- Watson = {};
+var Watson = {};
Watson.response = function(postData) {
var conversation = watsonDev.conversation({
@@ -14,20 +14,22 @@
password: 'xUtHqarwWpUk',
version: 'v1',
version_date: '2016-09-20'
- }),
- context = {},
- params = {
- workspace_id: '25dfa8a0-0263-471b-8980-317e68c30488',
- input: {'text': 'hahaha'},
- context: context
- };
+ });
+
+ var context = {};
+
+ var params = {
+ workspace_id: 'a05393b7-d022-4bed-ba76-012042930893',
+ input: {'text': 'hahaha'},
+ context: context
+ };
conversation.message(params, function
(err, response) {
if (err)
- return winston.error(err);
+ return console.log(err);
else
- winston.log(JSON.stringify(response, null, 2));
+ console.log(JSON.stringify(response, null, 2));
});
}
|
e9f6c13b1dfd21bf9e315ce04c5e1ea7323f12ca | components/HeaderImg.js | components/HeaderImg.js | import React from 'react';
class HeaderImg extends React.Component {
render() {
const style = {
width: '98%',
height: '500px',
clear: 'both',
margin: '0 1% .5em',
text-align: 'center',
overflow: 'hidden'
};
const src = 'https://wordanddeedindia.imgix.net/images/child.jpg?fit=crop&crop=faces';
return (
<div style={style}>
<img className="imgix-fluid" data-src={src} />
</div>
);
}
}
export default HeaderImg;
| import React from 'react';
class HeaderImg extends React.Component {
render() {
const style = {
width: '100%',
height: '500px',
clear: 'both',
margin: '0',
text-align: 'center',
overflow: 'hidden'
};
const src = 'https://wordanddeedindia.imgix.net/images/child.jpg?fit=crop&crop=faces';
return (
<div style={style}>
<img className="imgix-fluid" data-src={src} />
</div>
);
}
}
export default HeaderImg;
| Remove margin, full bleed image (headerimg comp) | Remove margin, full bleed image (headerimg comp) | JavaScript | mit | arpith/wordanddeedindia,arpith/wordanddeedindia | ---
+++
@@ -3,10 +3,10 @@
class HeaderImg extends React.Component {
render() {
const style = {
- width: '98%',
+ width: '100%',
height: '500px',
clear: 'both',
- margin: '0 1% .5em',
+ margin: '0',
text-align: 'center',
overflow: 'hidden'
}; |
96f5e341a47cf3cbde9222ed72f44d716acb9aa0 | src/js/common/helpers/environment.js | src/js/common/helpers/environment.js | const _Environments = {
production: { API_URL: 'https://dev-api.vets.gov', BASE_URL: 'https://www.vets.gov' },
staging: { API_URL: 'https://staging-api.vets.gov', BASE_URL: 'https://staging.vets.gov' },
development: { API_URL: 'https://dev-api.vets.gov', BASE_URL: 'https://dev.vets.gov' },
local: { API_URL: 'http://localhost:3000', BASE_URL: 'http://localhost:3001' },
e2e: { API_URL: 'http://localhost:4000', BASE_URL: 'http://localhost:3333' }
};
function getEnvironment() {
let platform;
if (location.host === 'localhost:3001') {
platform = 'local';
} else if (location.host === 'localhost:3333') {
platform = 'e2e';
} else {
platform = __BUILDTYPE__;
}
return _Environments[platform];
}
const environment = getEnvironment();
module.exports = environment;
| const _Environments = {
production: { API_URL: 'https://api.vets.gov', BASE_URL: 'https://www.vets.gov' },
staging: { API_URL: 'https://staging-api.vets.gov', BASE_URL: 'https://staging.vets.gov' },
development: { API_URL: 'https://dev-api.vets.gov', BASE_URL: 'https://dev.vets.gov' },
local: { API_URL: 'http://localhost:3000', BASE_URL: 'http://localhost:3001' },
e2e: { API_URL: 'http://localhost:4000', BASE_URL: 'http://localhost:3333' }
};
function getEnvironment() {
let platform;
if (location.host === 'localhost:3001') {
platform = 'local';
} else if (location.host === 'localhost:3333') {
platform = 'e2e';
} else {
platform = __BUILDTYPE__;
}
return _Environments[platform];
}
const environment = getEnvironment();
module.exports = environment;
| Use the production backend in production | Use the production backend in production | JavaScript | cc0-1.0 | department-of-veterans-affairs/vets-website,department-of-veterans-affairs/vets-website | ---
+++
@@ -1,5 +1,5 @@
const _Environments = {
- production: { API_URL: 'https://dev-api.vets.gov', BASE_URL: 'https://www.vets.gov' },
+ production: { API_URL: 'https://api.vets.gov', BASE_URL: 'https://www.vets.gov' },
staging: { API_URL: 'https://staging-api.vets.gov', BASE_URL: 'https://staging.vets.gov' },
development: { API_URL: 'https://dev-api.vets.gov', BASE_URL: 'https://dev.vets.gov' },
local: { API_URL: 'http://localhost:3000', BASE_URL: 'http://localhost:3001' }, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.