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 |
|---|---|---|---|---|---|---|---|---|---|---|
7bad2ae5ca65ef0572fa90ce46f6a20964b6e8ff | vendor/assets/javascripts/flash.js | vendor/assets/javascripts/flash.js | // refactoring from https://github.com/leonid-shevtsov/cacheable-flash-jquery
var Flash = new Object();
Flash.data = {};
Flash.transferFromCookies = function() {
var data = JSON.parse(unescape($.cookie("flash")));
if(!data) data = {};
Flash.data = data;
$.cookie('flash',null, {path: '/'});
};
Flash.writeDataTo = function(name, element) {
element = $(element);
var content = "";
if (Flash.data[name]) {
message = Flash.data[name].toString().replace(/\+/g, ' ');
element.html(message);
element.show();
}
};
| // refactoring from https://github.com/leonid-shevtsov/cacheable-flash-jquery
var Flash = new Object();
Flash.data = {};
Flash.transferFromCookies = function() {
var data = JSON.parse(unescape($.cookie("flash")));
if(!data) data = {};
Flash.data = data;
$.cookie('flash',null, {path: '/'});
};
Flash.writeDataTo = function(name, element, callback) {
element = $(element);
var content = "";
if (Flash.data[name]) {
message = Flash.data[name].toString().replace(/\+/g, ' ');
element.html(message);
if (callback && typeof(callback) === 'function') {
callback(element);
} else {
element.show();
}
}
};
| Add callback argument to Flash.writeDataTo() | Add callback argument to Flash.writeDataTo() | JavaScript | mit | khoan/cacheable-flash,nickurban/cacheable-flash,ndreckshage/cacheable-flash,efigence/cacheable-flash,ekampp/cacheable-flash,pivotal/cacheable-flash,nickurban/cacheable-flash,ekampp/cacheable-flash,pedrocarrico/cacheable-flash,wandenberg/cacheable-flash,pivotal/cacheable-flash,pboling/cacheable-flash,khoan/cacheable-flash,pedrocarrico/cacheable-flash,pivotal/cacheable-flash,pboling/cacheable-flash,pedrocarrico/cacheable-flash,pboling/cacheable-flash,efigence/cacheable-flash,ndreckshage/cacheable-flash,wandenberg/cacheable-flash,ndreckshage/cacheable-flash,pboling/cacheable-flash | ---
+++
@@ -10,12 +10,16 @@
$.cookie('flash',null, {path: '/'});
};
-Flash.writeDataTo = function(name, element) {
+Flash.writeDataTo = function(name, element, callback) {
element = $(element);
var content = "";
if (Flash.data[name]) {
message = Flash.data[name].toString().replace(/\+/g, ' ');
element.html(message);
- element.show();
+ if (callback && typeof(callback) === 'function') {
+ callback(element);
+ } else {
+ element.show();
+ }
}
}; |
32c16f42c6198803de75354cf29538c89ea060a1 | app/services/data/get-team-caseload.js | app/services/data/get-team-caseload.js | const config = require('../../../knexfile').web
const knex = require('knex')(config)
module.exports = function (id, type) {
var table = 'team_caseload_overview'
var whereObject = {}
if (id !== undefined) {
whereObject.id = id
}
return knex(table)
.where(whereObject)
.select('name',
'grade_code AS gradeCode',
'untiered',
'd2',
'd1',
'c2',
'c1',
'b2',
'b1',
'a',
'total_cases AS totalCases',
'link_id AS linkId')
.then(function (results) {
return results
})
}
| const config = require('../../../knexfile').web
const knex = require('knex')(config)
module.exports = function (id) {
var table = 'team_caseload_overview'
var whereObject = {}
if (id !== undefined) {
whereObject.id = id
}
return knex(table)
.where(whereObject)
.select('name',
'grade_code AS gradeCode',
'untiered',
'd2',
'd1',
'c2',
'c1',
'b2',
'b1',
'a',
'total_cases AS totalCases',
'link_id AS linkId')
.then(function (results) {
return results
})
}
| Remove the type field as its not required. | 784: Remove the type field as its not required.
| JavaScript | mit | ministryofjustice/wmt-web,ministryofjustice/wmt-web | ---
+++
@@ -1,6 +1,6 @@
const config = require('../../../knexfile').web
const knex = require('knex')(config)
-module.exports = function (id, type) {
+module.exports = function (id) {
var table = 'team_caseload_overview'
var whereObject = {}
if (id !== undefined) { |
20905777baa711def48620d16507222b9ef50761 | concepts/frame-list/main.js | concepts/frame-list/main.js | var mercury = require("mercury")
var frameList = require("./views/frame-list")
var frameEditor = require("./views/frame-editor")
var frameData = require("./data/frames")
// Load the data
var initialFrameData = frameData.load()
var frames = mercury.hash(initialFrameData)
// When the data changes, save it
frames(frameData.save)
// Create the default view using the frame set
var frameListEditor = frameList(frames)
var state = mercury.hash({
frames: frames,
editor: frameList
})
// Show the frame editor
frameListEditor.onSelectFrame(function (frameId) {
var editor = frameEditor(frames[frameId])
editor.onExit(function () {
// Restore the frame list
state.editor.set(frameList)
})
})
function render(state) {
// This is a mercury partial rendered with editor.state instead
// of globalSoup.state
// The immutable internal event list is also passed in
// Event listeners are obviously not serializable, but
// they can expose their state (listener set)
return h(state.editor.partial())
}
// setup the loop and go.
mercury.app(document.body, render, state)
| var mercury = require("mercury")
var frameList = require("./views/frame-list")
var frameEditor = require("./views/frame-editor")
var frameData = require("./data/frames")
// Load the data
var initialFrameData = frameData.load()
// Create the default view using the frame set
var frameListEditor = frameList(frames)
var state = mercury.hash({
frames: mercury.hash(initialFrameData),
editor: frameList
})
// When the data changes, save it
state.frames(frameData.save)
// Show the frame editor
frameListEditor.onSelectFrame(function (frameId) {
var editor = frameEditor(state.frames[frameId])
editor.onExit(function () {
// Restore the frame list
state.editor.set(frameList)
})
})
function render(state) {
// This is a mercury partial rendered with editor.state instead
// of globalSoup.state
// The immutable internal event list is also passed in
// Event listeners are obviously not serializable, but
// they can expose their state (listener set)
return h(state.editor.partial())
}
// setup the loop and go.
mercury.app(document.body, render, state)
| Consolidate the two pieces of state into a single atom | Consolidate the two pieces of state into a single atom
This helps readability of the code by knowing there is only one
variable that contains the state and only one variable that
can be mutated.
This means if you refactor the code into multiple files you
only have to pass this one variable into the functions
from the other file.
| JavaScript | mit | Raynos/mercury,eriser/mercury,staltz/mercury,staltz/mercury,eightyeight/mercury,beni55/mercury,mpal9000/mercury,jxson/mercury,vlad-x/mercury,martintietz/mercury,tommymessbauer/mercury | ---
+++
@@ -6,21 +6,21 @@
// Load the data
var initialFrameData = frameData.load()
-var frames = mercury.hash(initialFrameData)
-// When the data changes, save it
-frames(frameData.save)
// Create the default view using the frame set
var frameListEditor = frameList(frames)
var state = mercury.hash({
- frames: frames,
+ frames: mercury.hash(initialFrameData),
editor: frameList
})
+// When the data changes, save it
+state.frames(frameData.save)
+
// Show the frame editor
frameListEditor.onSelectFrame(function (frameId) {
- var editor = frameEditor(frames[frameId])
+ var editor = frameEditor(state.frames[frameId])
editor.onExit(function () {
// Restore the frame list |
5d9441a2eabc8206c3fcca0728bd218d40ed1e0f | Data/Events.js | Data/Events.js | export default [
{
day: 20,
month: 7,
year: 2017,
date: '20 Julho 2017',
location: 'Fundação Calouste Gulbenkian, Lisboa',
name: 'Concerto pela Orquestra Gulbenkian, Dia do Fundador',
description:'A Orquestra Gulbenkian, dirigida por José Eduardo Gomes, com os solistas Agostinho Sequeira (percussão) e Haïg Sarikouyoumdjian (duduk), irá interpretar obras de Jennifer Higdon e de Ludwig van Beethoven'
}
| export default [
{
day: 20,
month: 7,
year: 2017,
date: '20 Julho 2017',
location: 'Fundação Calouste Gulbenkian, Lisboa',
name: 'Concerto pela Orquestra Gulbenkian, Dia do Fundador',
description: 'A Orquestra Gulbenkian, dirigida por José Eduardo Gomes, com os solistas Agostinho Sequeira (percussão) e Haïg Sarikouyoumdjian (duduk), irá interpretar obras de Jennifer Higdon e de Ludwig van Beethoven'
}
];
| Fix data object on event data | Fix data object on event data
| JavaScript | mit | joaojusto/jose-gomes-landing-page | ---
+++
@@ -6,5 +6,6 @@
date: '20 Julho 2017',
location: 'Fundação Calouste Gulbenkian, Lisboa',
name: 'Concerto pela Orquestra Gulbenkian, Dia do Fundador',
- description:'A Orquestra Gulbenkian, dirigida por José Eduardo Gomes, com os solistas Agostinho Sequeira (percussão) e Haïg Sarikouyoumdjian (duduk), irá interpretar obras de Jennifer Higdon e de Ludwig van Beethoven'
+ description: 'A Orquestra Gulbenkian, dirigida por José Eduardo Gomes, com os solistas Agostinho Sequeira (percussão) e Haïg Sarikouyoumdjian (duduk), irá interpretar obras de Jennifer Higdon e de Ludwig van Beethoven'
}
+]; |
3c4d2080e1602fbeafcfbc71befbb591a186b2b1 | webserver/static/js/main.js | webserver/static/js/main.js | console.log("Hello Console!");
host = window.location.host.split(":")[0];
console.log(host);
var conn;
$(document).ready(function () {
conn = new WebSocket("ws://"+host+":8888/ws");
conn.onclose = function(evt) {
console.log("connection closed");
}
conn.onmessage = function(evt) {
console.log("received : " + evt.data);
}
});
// Byte String -> Boolean
function sendPacket(id, data) {
return conn.send(String.fromCharCode(id) + data);
}
function sendit() {
console.log(sendPacket(1, '{"msg": "hi"}'));
}
| console.log("Hello Console!");
host = window.location.host.split(":")[0];
console.log(host);
var conn;
$(document).ready(function () {
initializePacketHandlers();
conn = new WebSocket("ws://"+host+":8888/ws");
conn.onclose = function(evt) {
console.log("connection closed");
}
conn.onmessage = function(evt) {
console.log("received : " + evt.data);
//handlePacket(evt.data)
}
});
//---- Packet Ids
var LOGIN_PID = 0;
var PACKET_HANDLERS = {};
function initializePacketHandlers() {
//PACKET_HANDLERS[PID] = callback_function;
}
//--- Packet Senders
// String String -> Bool
function sendLogin(username, token) {
return sendPacket(LOGIN_PID, { Username: username, Token: token })
}
// Byte String -> Bool
function sendPacket(id, data) {
return conn.send(String.fromCharCode(id) + JSON.stringify(data));
}
function sendit() {
console.log(sendPacket(1, { msg: "hi" }));
}
//---- Packet Handlers
// String -> ?
function handlePacket(packet) {
var pid = packet.charCodeAt(0);
var data = packet.substring(1);
handler = PACKET_HANDLERS[pid];
return handler(data);
}
| Expand the JS code a bit to prepare for networking code | Expand the JS code a bit to prepare for networking code
| JavaScript | mit | quintenpalmer/attempt,quintenpalmer/attempt,quintenpalmer/attempt,quintenpalmer/attempt | ---
+++
@@ -3,21 +3,48 @@
console.log(host);
var conn;
$(document).ready(function () {
+ initializePacketHandlers();
+
conn = new WebSocket("ws://"+host+":8888/ws");
conn.onclose = function(evt) {
console.log("connection closed");
}
conn.onmessage = function(evt) {
console.log("received : " + evt.data);
+ //handlePacket(evt.data)
}
});
-// Byte String -> Boolean
+//---- Packet Ids
+var LOGIN_PID = 0;
+
+var PACKET_HANDLERS = {};
+function initializePacketHandlers() {
+ //PACKET_HANDLERS[PID] = callback_function;
+}
+//--- Packet Senders
+
+// String String -> Bool
+function sendLogin(username, token) {
+ return sendPacket(LOGIN_PID, { Username: username, Token: token })
+}
+
+// Byte String -> Bool
function sendPacket(id, data) {
- return conn.send(String.fromCharCode(id) + data);
+ return conn.send(String.fromCharCode(id) + JSON.stringify(data));
}
function sendit() {
- console.log(sendPacket(1, '{"msg": "hi"}'));
+ console.log(sendPacket(1, { msg: "hi" }));
}
+
+
+//---- Packet Handlers
+// String -> ?
+function handlePacket(packet) {
+ var pid = packet.charCodeAt(0);
+ var data = packet.substring(1);
+ handler = PACKET_HANDLERS[pid];
+ return handler(data);
+} |
43f89d6a8a19f87d57ee74b30b7f0e664a958a2f | tests/integration/components/canvas-block-filter/component-test.js | tests/integration/components/canvas-block-filter/component-test.js | import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('canvas-block-filter',
'Integration | Component | canvas block filter', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{canvas-block-filter}}`);
assert.ok(this.$('input[type=text]').get(0));
});
| import { moduleForComponent, test } from 'ember-qunit';
import Ember from 'ember';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('canvas-block-filter',
'Integration | Component | canvas block filter', {
integration: true
});
test('it binds a filter term', function(assert) {
this.set('filterTerm', 'Foo');
this.render(hbs`{{canvas-block-filter filterTerm=filterTerm}}`);
assert.equal(this.$('input').val(), 'Foo');
this.$('input').val('Bar').trigger('input');
assert.equal(this.get('filterTerm'), 'Bar');
});
test('it clears the filter when closing', function(assert) {
this.set('filterTerm', 'Foo');
this.set('onCloseFilter', Ember.K);
this.render(hbs`{{canvas-block-filter
onCloseFilter=onCloseFilter
filterTerm=filterTerm}}`);
this.$('button').click();
assert.equal(this.get('filterTerm'), '');
});
test('it calls a close callback', function(assert) {
this.set('onCloseFilter', _ => assert.ok(true));
this.render(hbs`{{canvas-block-filter onCloseFilter=onCloseFilter}}`);
this.$('button').click();
});
| Add meaningful tests to canvas-block-filter | Add meaningful tests to canvas-block-filter
| JavaScript | apache-2.0 | usecanvas/web-v2,usecanvas/web-v2,usecanvas/web-v2 | ---
+++
@@ -1,4 +1,5 @@
import { moduleForComponent, test } from 'ember-qunit';
+import Ember from 'ember';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('canvas-block-filter',
@@ -6,9 +7,26 @@
integration: true
});
-test('it renders', function(assert) {
- // Set any properties with this.set('myProperty', 'value');
- // Handle any actions with this.on('myAction', function(val) { ... });
- this.render(hbs`{{canvas-block-filter}}`);
- assert.ok(this.$('input[type=text]').get(0));
+test('it binds a filter term', function(assert) {
+ this.set('filterTerm', 'Foo');
+ this.render(hbs`{{canvas-block-filter filterTerm=filterTerm}}`);
+ assert.equal(this.$('input').val(), 'Foo');
+ this.$('input').val('Bar').trigger('input');
+ assert.equal(this.get('filterTerm'), 'Bar');
});
+
+test('it clears the filter when closing', function(assert) {
+ this.set('filterTerm', 'Foo');
+ this.set('onCloseFilter', Ember.K);
+ this.render(hbs`{{canvas-block-filter
+ onCloseFilter=onCloseFilter
+ filterTerm=filterTerm}}`);
+ this.$('button').click();
+ assert.equal(this.get('filterTerm'), '');
+});
+
+test('it calls a close callback', function(assert) {
+ this.set('onCloseFilter', _ => assert.ok(true));
+ this.render(hbs`{{canvas-block-filter onCloseFilter=onCloseFilter}}`);
+ this.$('button').click();
+}); |
9552b9842af3f5335cdcca132e37fbde591c41a4 | src/js/services/tracker.js | src/js/services/tracker.js | /**
* Event tracker (analytics)
*/
var module = angular.module('tracker', []);
module.factory('rpTracker', ['$rootScope', function ($scope) {
var track = function (event,properties) {
if (Options.mixpanel && Options.mixpanel.track && mixpanel) {
mixpanel.track(event,properties);
}
};
return {
track: track
};
}]);
| /**
* Event tracker (analytics)
*/
var module = angular.module('tracker', []);
module.factory('rpTracker', ['$rootScope', function ($scope) {
var track = function (event,properties) {
if (Options.mixpanel && Options.mixpanel.track && window.mixpanel) {
mixpanel.track(event,properties);
}
};
return {
track: track
};
}]);
| Fix test failures due to missing mixpanel JS | [TEST] Fix test failures due to missing mixpanel JS
| JavaScript | isc | Madsn/ripple-client,arturomc/ripple-client,darkdarkdragon/ripple-client-desktop,darkdarkdragon/ripple-client,xdv/ripple-client,mrajvanshy/ripple-client-desktop,h0vhannes/ripple-client,xdv/ripple-client,yongsoo/ripple-client-desktop,darkdarkdragon/ripple-client-desktop,mrajvanshy/ripple-client,h0vhannes/ripple-client,wangbibo/ripple-client,xdv/ripple-client-desktop,dncohen/ripple-client-desktop,vhpoet/ripple-client,bankonme/ripple-client-desktop,ripple/ripple-client-desktop,wangbibo/ripple-client,MatthewPhinney/ripple-client,MatthewPhinney/ripple-client,darkdarkdragon/ripple-client,arturomc/ripple-client,MatthewPhinney/ripple-client,vhpoet/ripple-client-desktop,darkdarkdragon/ripple-client,vhpoet/ripple-client-desktop,thics/ripple-client-desktop,darkdarkdragon/ripple-client,thics/ripple-client-desktop,xdv/ripple-client,h0vhannes/ripple-client,xdv/ripple-client-desktop,MatthewPhinney/ripple-client,arturomc/ripple-client,bsteinlo/ripple-client,resilience-me/DEPRICATED_ripple-client,vhpoet/ripple-client,yongsoo/ripple-client,Madsn/ripple-client,vhpoet/ripple-client,mrajvanshy/ripple-client,ripple/ripple-client,xdv/ripple-client,vhpoet/ripple-client,ripple/ripple-client-desktop,bsteinlo/ripple-client,Madsn/ripple-client,MatthewPhinney/ripple-client-desktop,ripple/ripple-client,bankonme/ripple-client-desktop,arturomc/ripple-client,Madsn/ripple-client,yongsoo/ripple-client,xdv/ripple-client-desktop,MatthewPhinney/ripple-client-desktop,mrajvanshy/ripple-client,yxxyun/ripple-client-desktop,yongsoo/ripple-client,yxxyun/ripple-client-desktop,wangbibo/ripple-client,yongsoo/ripple-client,mrajvanshy/ripple-client,mrajvanshy/ripple-client-desktop,ripple/ripple-client,yongsoo/ripple-client-desktop,wangbibo/ripple-client,dncohen/ripple-client-desktop,ripple/ripple-client,resilience-me/DEPRICATED_ripple-client,h0vhannes/ripple-client | ---
+++
@@ -6,7 +6,7 @@
module.factory('rpTracker', ['$rootScope', function ($scope) {
var track = function (event,properties) {
- if (Options.mixpanel && Options.mixpanel.track && mixpanel) {
+ if (Options.mixpanel && Options.mixpanel.track && window.mixpanel) {
mixpanel.track(event,properties);
}
}; |
e9b97e39609d9b592e8c8af0cc00e036d6326cc1 | src/lib/listener/onFile.js | src/lib/listener/onFile.js | import {Readable} from "stream"
import File from "lib/File"
import getFieldPath from "lib/util/getFieldPath"
const onFile = (options, cb) => (fieldname, stream, filename, enc, mime) => {
try {
const path = getFieldPath(fieldname)
const contents = new Readable({
read() { /* noop */ }
})
const onData = ch => contents.push(ch)
const onEnd = () => {
contents.push(null)
const file = new File({filename, contents, enc, mime})
cb(null, [
path, file
])
}
stream
.on("data", onData)
.on("end", onEnd)
} catch (err) {
return cb(err)
}
}
export default onFile
| import {Readable} from "stream"
import File from "lib/File"
import getFieldPath from "lib/util/getFieldPath"
const onFile = (options, cb) => (fieldname, stream, filename, enc, mime) => {
try {
const path = getFieldPath(fieldname)
const contents = new Readable({
read() { /* noop */ }
})
const onData = ch => contents.push(ch)
const onEnd = () => {
contents.push(null)
const file = new File({filename, contents, enc, mime})
cb(null, [
path, file
])
}
stream
.on("error", cb)
.on("data", onData)
.on("end", onEnd)
} catch (err) {
return cb(err)
}
}
export default onFile
| Add an error event listener for FileStream. | Add an error event listener for FileStream.
| JavaScript | mit | octet-stream/then-busboy,octet-stream/then-busboy | ---
+++
@@ -24,6 +24,7 @@
}
stream
+ .on("error", cb)
.on("data", onData)
.on("end", onEnd)
} catch (err) { |
e902c3b71a0ff79ebcb2424098197604d40ed21b | web_external/js/views/body/JobsPanel.js | web_external/js/views/body/JobsPanel.js | minerva.views.JobsPanel = minerva.View.extend({
initialize: function () {
var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum;
var columns = columnEnum.COLUMN_STATUS_ICON |
columnEnum.COLUMN_TITLE;
this.jobListWidget = new girder.views.jobs_JobListWidget({
columns: columns,
showHeader: false,
pageLimit: 10,
showPaging: false,
triggerJobClick: true,
parentView: this
}).on('g:jobClicked', function (job) {
// TODO right way to update specific job?
// otherwise can get a detail that is out of sync with actual job status
// seems weird to update the entire collection from here
// another option is to refresh the job specifically
this.jobListWidget.collection.on('g:changed', function () {
job = this.jobListWidget.collection.get(job.get('id'));
this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({
job: job,
el: $('#g-dialog-container'),
parentView: this
});
this.jobDetailsWidgetModalWrapper.render();
}, this);
this.jobListWidget.collection.fetch({}, true);
}, this);
girder.events.on('m:job.created', function () {
this.jobListWidget.collection.fetch({}, true);
}, this);
},
render: function () {
this.$el.html(minerva.templates.jobsPanel({}));
this.jobListWidget.setElement(this.$('.m-jobsListContainer')).render();
return this;
}
});
| minerva.views.JobsPanel = minerva.View.extend({
initialize: function () {
var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum;
var columns = columnEnum.COLUMN_STATUS_ICON |
columnEnum.COLUMN_TITLE;
this.jobListWidget = new girder.views.jobs_JobListWidget({
columns: columns,
showHeader: false,
pageLimit: 10,
showPaging: false,
triggerJobClick: true,
parentView: this
}).on('g:jobClicked', function (job) {
// update the job before displaying, as the job in the collection
// could be stale and out of sync from the display in the job panel
job.once('g:fetched', function () {
this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({
job: job,
el: $('#g-dialog-container'),
parentView: this
});
this.jobDetailsWidgetModalWrapper.render();
}, this).fetch();
}, this);
girder.events.on('m:job.created', function () {
this.jobListWidget.collection.fetch({}, true);
}, this);
},
render: function () {
this.$el.html(minerva.templates.jobsPanel({}));
this.jobListWidget.setElement(this.$('.m-jobsListContainer')).render();
return this;
}
});
| Update job when job detail clicked | Update job when job detail clicked
| JavaScript | apache-2.0 | Kitware/minerva,Kitware/minerva,Kitware/minerva | ---
+++
@@ -12,20 +12,16 @@
triggerJobClick: true,
parentView: this
}).on('g:jobClicked', function (job) {
- // TODO right way to update specific job?
- // otherwise can get a detail that is out of sync with actual job status
- // seems weird to update the entire collection from here
- // another option is to refresh the job specifically
- this.jobListWidget.collection.on('g:changed', function () {
- job = this.jobListWidget.collection.get(job.get('id'));
+ // update the job before displaying, as the job in the collection
+ // could be stale and out of sync from the display in the job panel
+ job.once('g:fetched', function () {
this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({
job: job,
el: $('#g-dialog-container'),
parentView: this
});
this.jobDetailsWidgetModalWrapper.render();
- }, this);
- this.jobListWidget.collection.fetch({}, true);
+ }, this).fetch();
}, this);
girder.events.on('m:job.created', function () { |
fb73e6394654a38439387994556680215a93c0b3 | addon/components/page-pagination.js | addon/components/page-pagination.js | import Ember from 'ember';
import layout from '../templates/components/page-pagination';
export default Ember.Component.extend({
layout: layout,
keys: ['first', 'prev', 'next', 'last'],
sortedLinks: Ember.computed('keys', 'links', function() {
var result = {};
this.get('keys').map( (key) => {
result[key] = this.get('links')[key];
});
if (!this.get('links.prev')) { result['first'] = undefined; }
if (!this.get('links.next')) { result['last'] = undefined; }
return result;
}),
actions: {
changePage(link) {
this.set('page', link['number'] || 0);
this.set('size', link['size'] || 0);
}
}
});
| import Ember from 'ember';
import layout from '../templates/components/page-pagination';
export default Ember.Component.extend({
layout: layout,
keys: ['first', 'prev', 'next', 'last'],
sortedLinks: Ember.computed('keys', 'links', function() {
var result = {};
this.get('keys').map( (key) => {
result[key] = this.get('links')[key];
});
if (!this.get('links.prev')) { result['first'] = undefined; }
if (!this.get('links.next')) { result['last'] = undefined; }
return result;
}),
actions: {
changePage(link) {
this.set('page', link['number'] || 0);
if (link['size']) { this.set('size', link['size']); }
}
}
});
| Fix unsensible default for page size | Fix unsensible default for page size
| JavaScript | mit | mu-semtech/ember-data-table,erikap/ember-data-table,erikap/ember-data-table,mu-semtech/ember-data-table | ---
+++
@@ -16,7 +16,7 @@
actions: {
changePage(link) {
this.set('page', link['number'] || 0);
- this.set('size', link['size'] || 0);
+ if (link['size']) { this.set('size', link['size']); }
}
}
}); |
ff552ff6677bbc93ab7a750184dfd79109c1a837 | src/mock-get-user-media.js | src/mock-get-user-media.js |
// Takes a mockOnStreamAvailable function which when given a webrtcstream returns a new stream
// to replace it with.
module.exports = function mockGetUserMedia(mockOnStreamAvailable) {
let oldGetUserMedia;
if (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
oldGetUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
navigator.webkitGetUserMedia = navigator.getUserMedia = navigator.mozGetUserMedia =
function getUserMedia(constraints, onStreamAvailable, onStreamAvailableError,
onAccessDialogOpened, onAccessDialogClosed, onAccessDenied) {
return oldGetUserMedia.call(navigator, constraints, stream => {
onStreamAvailable(mockOnStreamAvailable(stream));
}, onStreamAvailableError,
onAccessDialogOpened, onAccessDialogClosed, onAccessDenied);
};
} else {
console.warn('Could not find getUserMedia function to mock out');
}
};
| // Takes a mockOnStreamAvailable function which when given a webrtcstream returns a new stream
// to replace it with.
module.exports = function mockGetUserMedia(mockOnStreamAvailable) {
let oldGetUserMedia;
if (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
oldGetUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
navigator.webkitGetUserMedia = navigator.getUserMedia = navigator.mozGetUserMedia =
function getUserMedia(constraints, onStreamAvailable, onStreamAvailableError,
onAccessDialogOpened, onAccessDialogClosed, onAccessDenied) {
return oldGetUserMedia.call(navigator, constraints, stream => {
onStreamAvailable(mockOnStreamAvailable(stream));
}, onStreamAvailableError,
onAccessDialogOpened, onAccessDialogClosed, onAccessDenied);
};
} else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
oldGetUserMedia = navigator.mediaDevices.getUserMedia;
navigator.mediaDevices.getUserMedia = function getUserMedia (constraints) {
return new Promise(function (resolve, reject) {
oldGetUserMedia.call(navigator.mediaDevices, constraints).then(stream => {
resolve(mockOnStreamAvailable(stream));
}, reason => {
reject(reason);
}).catch(err => {
console.error('Error getting mock stream', err);
});
});
};
} else {
console.warn('Could not find getUserMedia function to mock out');
}
};
| Add MediaDevices support for mock getUserMedia | Add MediaDevices support for mock getUserMedia
Signed-off-by: Kaustav Das Modak <ba1ce5b1e09413a89404909d8d270942c5dadd14@yahoo.co.in>
| JavaScript | mit | aullman/opentok-camera-filters,aullman/opentok-camera-filters | ---
+++
@@ -1,4 +1,3 @@
-
// Takes a mockOnStreamAvailable function which when given a webrtcstream returns a new stream
// to replace it with.
module.exports = function mockGetUserMedia(mockOnStreamAvailable) {
@@ -8,12 +7,25 @@
navigator.mozGetUserMedia;
navigator.webkitGetUserMedia = navigator.getUserMedia = navigator.mozGetUserMedia =
function getUserMedia(constraints, onStreamAvailable, onStreamAvailableError,
- onAccessDialogOpened, onAccessDialogClosed, onAccessDenied) {
+ onAccessDialogOpened, onAccessDialogClosed, onAccessDenied) {
return oldGetUserMedia.call(navigator, constraints, stream => {
onStreamAvailable(mockOnStreamAvailable(stream));
}, onStreamAvailableError,
onAccessDialogOpened, onAccessDialogClosed, onAccessDenied);
};
+ } else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
+ oldGetUserMedia = navigator.mediaDevices.getUserMedia;
+ navigator.mediaDevices.getUserMedia = function getUserMedia (constraints) {
+ return new Promise(function (resolve, reject) {
+ oldGetUserMedia.call(navigator.mediaDevices, constraints).then(stream => {
+ resolve(mockOnStreamAvailable(stream));
+ }, reason => {
+ reject(reason);
+ }).catch(err => {
+ console.error('Error getting mock stream', err);
+ });
+ });
+ };
} else {
console.warn('Could not find getUserMedia function to mock out');
} |
2ecfcc3c05a3bdda467113b00748c32b3fb4db25 | tests/backstop/detect-target-host.js | tests/backstop/detect-target-host.js | // Linux machines should use Docker's default gateway IP address to connect to.
let hostname = '172.17.0.2';
// On MacOS and Windows, `host.docker.internal` is available to point to the
// host and run backstopjs against.
// If the hostname arg is set, then we're inside the container and this should take precedence.
const hostArg = process.argv.find( ( arg ) => arg.match( /^--hostname=/ ) );
if ( hostArg ) {
hostname = hostArg.replace( /^--hostname=/, '' );
} else if ( process.platform === 'darwin' || process.platform === 'win32' ) {
hostname = 'host.docker.internal';
}
module.exports = hostname;
| // Linux machines should use Docker's default gateway IP address to connect to.
let hostname = '172.17.0.1';
// On MacOS and Windows, `host.docker.internal` is available to point to the
// host and run backstopjs against.
// If the hostname arg is set, then we're inside the container and this should take precedence.
const hostArg = process.argv.find( ( arg ) => arg.match( /^--hostname=/ ) );
if ( hostArg ) {
hostname = hostArg.replace( /^--hostname=/, '' );
} else if ( process.platform === 'darwin' || process.platform === 'win32' ) {
hostname = 'host.docker.internal';
}
module.exports = hostname;
| Fix default host IP for docker. | Fix default host IP for docker.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -1,5 +1,5 @@
// Linux machines should use Docker's default gateway IP address to connect to.
-let hostname = '172.17.0.2';
+let hostname = '172.17.0.1';
// On MacOS and Windows, `host.docker.internal` is available to point to the
// host and run backstopjs against. |
fac9a134cafcecd5b2ef52d4c1a99123f9df0ff9 | app/scripts/configs/modes/portal.js | app/scripts/configs/modes/portal.js | 'use strict';
angular.module('ncsaas')
.constant('MODE', {
modeName: 'modePortal',
toBeFeatures: [
'localSignup',
'localSignin',
'team',
'monitoring',
'backups',
'templates',
'sizing',
'projectGroups'
],
featuresVisible: false,
comingFeatures: [
'applications',
]
});
| 'use strict';
angular.module('ncsaas')
.constant('MODE', {
modeName: 'modePortal',
toBeFeatures: [
'localSignup',
'localSignin',
'password',
'team',
'monitoring',
'backups',
'templates',
'sizing',
'projectGroups',
'apps',
'premiumSupport'
],
featuresVisible: false,
appStoreCategories: [
{
name: 'VMs',
type: 'provider',
icon: 'desktop',
services: ['Amazon', 'DigitalOcean', 'OpenStack']
},
{
name: 'Private clouds',
type: 'provider',
icon: 'cloud',
services: ['OpenStack']
}
],
serviceCategories: [
{
name: 'Virtual machines',
services: ['Amazon', 'DigitalOcean', 'OpenStack'],
}
]
});
| Disable Azure, Gitlab, Application, Support providers (SAAS-1329) | Disable Azure, Gitlab, Application, Support providers (SAAS-1329)
| JavaScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -6,15 +6,35 @@
toBeFeatures: [
'localSignup',
'localSignin',
+ 'password',
'team',
'monitoring',
'backups',
'templates',
'sizing',
- 'projectGroups'
+ 'projectGroups',
+ 'apps',
+ 'premiumSupport'
],
featuresVisible: false,
- comingFeatures: [
- 'applications',
+ appStoreCategories: [
+ {
+ name: 'VMs',
+ type: 'provider',
+ icon: 'desktop',
+ services: ['Amazon', 'DigitalOcean', 'OpenStack']
+ },
+ {
+ name: 'Private clouds',
+ type: 'provider',
+ icon: 'cloud',
+ services: ['OpenStack']
+ }
+ ],
+ serviceCategories: [
+ {
+ name: 'Virtual machines',
+ services: ['Amazon', 'DigitalOcean', 'OpenStack'],
+ }
]
}); |
3a5424c8966c899461191654e8b1de3e99dd2914 | mezzanine/core/media/js/collapse_inline.js | mezzanine/core/media/js/collapse_inline.js |
$(function() {
var grappelli = !!$('#bookmarks');
var parentSelector = grappelli ? 'div.items' : 'tbody';
// Hide the exta inlines.
$(parentSelector + ' > *:not(.has_original)').hide();
// Re-show inlines with errors, poetentially hidden by previous line.
var errors = $(parentSelector + ' ul[class=errorlist]').parent().parent();
if (grappelli) {
errors = errors.parent();
}
errors.show();
// Add the 'Add another' link to the end of the inlines.
var parent = $(parentSelector).parent();
if (!grappelli) {
parent = parent.parent();
}
parent.append('<p class="add-another"><a href="#">Add another</a></p>');
$('.add-another').click(function() {
// Show a new inline when the 'Add another' link is clicked.
var rows = $(this).parent().find(parentSelector + ' > *:hidden');
$(rows[0]).show();
if (rows.length == 1) {
$(this).hide();
}
return false;
});
// Show the first hidden inline - grappelli's inline header is actually
// part of the selector so for it we run this twice.
$('.add-another').click();
if (grappelli) {
$('.add-another').click();
}
});
|
$(function() {
var grappelli = !!$('#bookmarks');
var parentSelector = grappelli ? 'div.items' : 'tbody';
// Hide the exta inlines.
$(parentSelector + ' > *:not(.has_original)').hide();
// Re-show inlines with errors, poetentially hidden by previous line.
var errors = $(parentSelector + ' ul[class=errorlist]').parent().parent();
if (grappelli) {
errors = errors.parent();
}
errors.show();
// Add the 'Add another' link to the end of the inlines.
var parent = $(parentSelector).parent();
if (!grappelli) {
parent = parent.parent();
}
parent.append('<p class="add-another add-another-inline">' +
'<a href="#">Add another</a></p>');
$('.add-another-inline').click(function() {
// Show a new inline when the 'Add another' link is clicked.
var rows = $(this).parent().find(parentSelector + ' > *:hidden');
$(rows[0]).show();
if (rows.length == 1) {
$(this).hide();
}
return false;
});
// Show the first hidden inline - grappelli's inline header is actually
// part of the selector so for it we run this twice.
$('.add-another-inline').click();
if (grappelli) {
$('.add-another-inline').click();
}
});
| Make class name unique for dynamic inlines. | Make class name unique for dynamic inlines.
| JavaScript | bsd-2-clause | dustinrb/mezzanine,tuxinhang1989/mezzanine,ZeroXn/mezzanine,scarcry/snm-mezzanine,nikolas/mezzanine,biomassives/mezzanine,gradel/mezzanine,adrian-the-git/mezzanine,damnfine/mezzanine,wbtuomela/mezzanine,guibernardino/mezzanine,wbtuomela/mezzanine,Cicero-Zhao/mezzanine,molokov/mezzanine,PegasusWang/mezzanine,cccs-web/mezzanine,jjz/mezzanine,eino-makitalo/mezzanine,agepoly/mezzanine,stbarnabas/mezzanine,viaregio/mezzanine,vladir/mezzanine,christianwgd/mezzanine,orlenko/sfpirg,dustinrb/mezzanine,adrian-the-git/mezzanine,mush42/mezzanine,douglaskastle/mezzanine,PegasusWang/mezzanine,stbarnabas/mezzanine,gbosh/mezzanine,saintbird/mezzanine,mush42/mezzanine,spookylukey/mezzanine,jerivas/mezzanine,ZeroXn/mezzanine,Cajoline/mezzanine,jjz/mezzanine,dovydas/mezzanine,jerivas/mezzanine,agepoly/mezzanine,eino-makitalo/mezzanine,theclanks/mezzanine,dekomote/mezzanine-modeltranslation-backport,stephenmcd/mezzanine,Skytorn86/mezzanine,SoLoHiC/mezzanine,frankier/mezzanine,sjdines/mezzanine,jerivas/mezzanine,promil23/mezzanine,stephenmcd/mezzanine,batpad/mezzanine,Skytorn86/mezzanine,Kniyl/mezzanine,tuxinhang1989/mezzanine,gbosh/mezzanine,guibernardino/mezzanine,sjdines/mezzanine,Cajoline/mezzanine,viaregio/mezzanine,theclanks/mezzanine,douglaskastle/mezzanine,dovydas/mezzanine,frankier/mezzanine,theclanks/mezzanine,nikolas/mezzanine,Cajoline/mezzanine,scarcry/snm-mezzanine,webounty/mezzanine,frankier/mezzanine,orlenko/sfpirg,damnfine/mezzanine,dustinrb/mezzanine,emile2016/mezzanine,douglaskastle/mezzanine,dsanders11/mezzanine,readevalprint/mezzanine,sjdines/mezzanine,sjuxax/mezzanine,webounty/mezzanine,spookylukey/mezzanine,ryneeverett/mezzanine,christianwgd/mezzanine,ryneeverett/mezzanine,fusionbox/mezzanine,frankchin/mezzanine,jjz/mezzanine,industrydive/mezzanine,agepoly/mezzanine,promil23/mezzanine,gradel/mezzanine,dekomote/mezzanine-modeltranslation-backport,biomassives/mezzanine,AlexHill/mezzanine,saintbird/mezzanine,molokov/mezzanine,joshcartme/mezzanine,SoLoHiC/mezzanine,PegasusWang/mezzanine,wyzex/mezzanine,christianwgd/mezzanine,gbosh/mezzanine,wrwrwr/mezzanine,wbtuomela/mezzanine,sjuxax/mezzanine,dsanders11/mezzanine,fusionbox/mezzanine,spookylukey/mezzanine,readevalprint/mezzanine,adrian-the-git/mezzanine,orlenko/plei,wyzex/mezzanine,geodesign/mezzanine,viaregio/mezzanine,geodesign/mezzanine,orlenko/plei,Cicero-Zhao/mezzanine,orlenko/plei,orlenko/sfpirg,biomassives/mezzanine,dsanders11/mezzanine,emile2016/mezzanine,industrydive/mezzanine,nikolas/mezzanine,cccs-web/mezzanine,ryneeverett/mezzanine,scarcry/snm-mezzanine,joshcartme/mezzanine,webounty/mezzanine,dekomote/mezzanine-modeltranslation-backport,wrwrwr/mezzanine,mush42/mezzanine,sjuxax/mezzanine,stephenmcd/mezzanine,tuxinhang1989/mezzanine,vladir/mezzanine,dovydas/mezzanine,AlexHill/mezzanine,geodesign/mezzanine,damnfine/mezzanine,readevalprint/mezzanine,eino-makitalo/mezzanine,promil23/mezzanine,vladir/mezzanine,industrydive/mezzanine,ZeroXn/mezzanine,saintbird/mezzanine,joshcartme/mezzanine,Kniyl/mezzanine,wyzex/mezzanine,molokov/mezzanine,emile2016/mezzanine,frankchin/mezzanine,SoLoHiC/mezzanine,Kniyl/mezzanine,batpad/mezzanine,Skytorn86/mezzanine,gradel/mezzanine,frankchin/mezzanine | ---
+++
@@ -18,8 +18,9 @@
if (!grappelli) {
parent = parent.parent();
}
- parent.append('<p class="add-another"><a href="#">Add another</a></p>');
- $('.add-another').click(function() {
+ parent.append('<p class="add-another add-another-inline">' +
+ '<a href="#">Add another</a></p>');
+ $('.add-another-inline').click(function() {
// Show a new inline when the 'Add another' link is clicked.
var rows = $(this).parent().find(parentSelector + ' > *:hidden');
$(rows[0]).show();
@@ -30,9 +31,9 @@
});
// Show the first hidden inline - grappelli's inline header is actually
// part of the selector so for it we run this twice.
- $('.add-another').click();
+ $('.add-another-inline').click();
if (grappelli) {
- $('.add-another').click();
+ $('.add-another-inline').click();
}
}); |
94d2f1a72a525e0a36cd247b299150a87445d2e4 | lib/nrouter/common.js | lib/nrouter/common.js | 'use strict';
var Common = module.exports = {};
// iterates through all object keys-value pairs calling iterator on each one
// example: $$.each(objOrArr, function (val, key) { /* ... */ });
Common.each = function each(obj, iterator, context) {
var keys, i, l;
if (null === obj || undefined === obj) {
return;
}
context = context || iterator;
if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
obj.forEach(iterator, context);
} else {
keys = Object.getOwnPropertyNames(obj);
for (i = 0, l = keys.length; i < l; i += 1) {
if (false === iterator.call(context, obj[keys[i]], keys[i], obj)) {
// break
return;
}
}
}
};
| 'use strict';
var Common = module.exports = {};
// iterates through all object keys-value pairs calling iterator on each one
// example: $$.each(objOrArr, function (val, key) { /* ... */ });
Common.each = function each(obj, iterator, context) {
var keys, i, l;
if (null === obj || undefined === obj) {
return;
}
context = context || iterator;
keys = Object.getOwnPropertyNames(obj);
// not using Array#forEach, as it does not allows to stop iterator
for (i = 0, l = keys.length; i < l; i += 1) {
if (false === iterator.call(context, obj[keys[i]], keys[i], obj)) {
// break
return;
}
}
};
| Remove forEach fallback in Common.each | Remove forEach fallback in Common.each
| JavaScript | mit | nodeca/pointer | ---
+++
@@ -14,16 +14,13 @@
}
context = context || iterator;
+ keys = Object.getOwnPropertyNames(obj);
- if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
- obj.forEach(iterator, context);
- } else {
- keys = Object.getOwnPropertyNames(obj);
- for (i = 0, l = keys.length; i < l; i += 1) {
- if (false === iterator.call(context, obj[keys[i]], keys[i], obj)) {
- // break
- return;
- }
+ // not using Array#forEach, as it does not allows to stop iterator
+ for (i = 0, l = keys.length; i < l; i += 1) {
+ if (false === iterator.call(context, obj[keys[i]], keys[i], obj)) {
+ // break
+ return;
}
}
}; |
c6578b2bb3652c65bcc5b0342efefde11aad034e | app.js | app.js | $(function(){
var yourSound = new Audio('notification.ogg');
yourSound.loop = true;
$('.start button').click(function(ev){
$('.start').toggleClass('hidden');
$(".example").TimeCircles({
"animation": "ticks",
"count_past_zero": false,
"circle_bg_color": "#f1f1f1",
"time": {
Days: {
show: false
},
Hours: {
show: false
},
Minutes: {
color: "#1abc9c"
},
Seconds: {
color: "#e74c3c"
}
}
}).addListener(function(unit, value, total){
if(!total){
yourSound.play();
$('.stop').toggleClass('hidden');
}
});
});
$('.stop button').click(function(ev){
yourSound.pause();
$(".example").TimeCircles().destroy();
$('.stop').toggleClass('hidden');
$('.start').toggleClass('hidden');
});
}); | $(function(){
var yourSound = new Audio('notification.ogg');
yourSound.loop = true;
$('.start button').click(function(ev){
$('.start').toggleClass('hidden');
$('.stop').toggleClass('hidden');
$(".example").TimeCircles({
"animation": "ticks",
"count_past_zero": false,
"circle_bg_color": "#f1f1f1",
"time": {
Days: {
show: false
},
Hours: {
show: false
},
Minutes: {
color: "#1abc9c"
},
Seconds: {
color: "#e74c3c"
}
}
}).addListener(function(unit, value, total){
if(!total){
yourSound.play();
}
});
});
$('.stop button').click(function(ev){
yourSound.pause();
$(".example").TimeCircles().destroy();
$('.stop').toggleClass('hidden');
$('.start').toggleClass('hidden');
});
}); | Stop button always visible when clock is running | Stop button always visible when clock is running
| JavaScript | mit | dplesca/getup | ---
+++
@@ -3,6 +3,7 @@
yourSound.loop = true;
$('.start button').click(function(ev){
$('.start').toggleClass('hidden');
+ $('.stop').toggleClass('hidden');
$(".example").TimeCircles({
"animation": "ticks",
"count_past_zero": false,
@@ -24,7 +25,6 @@
}).addListener(function(unit, value, total){
if(!total){
yourSound.play();
- $('.stop').toggleClass('hidden');
}
});
}); |
32383c5d18a74120da107a708abfee60a601bb27 | app/scripts/main.js | app/scripts/main.js | 'use strict';
// Toogle asset images - zome in and out
$(function() {
var Snackbar = window.Snackbar;
Snackbar.init();
var AssetPage = window.AssetPage;
AssetPage.init();
// We only want zooming on asset's primary images.
$('.asset .zoomable').click(function() {
var $thisRow = $(this).closest('.image-row');
if ($thisRow.hasClass('col-md-6')) {
$thisRow.removeClass('col-md-6').addClass('col-md-12');
$thisRow.next('div').addClass('col-md-offset-3')
.removeClass('pull-right');
} else {
$thisRow.removeClass('col-md-12').addClass('col-md-6');
$thisRow.next('div').removeClass('col-md-offset-3')
.addClass('pull-right');
}
});
var hideAllDropdowns = function() {
$('.dropdown').removeClass('dropdown--active');
$('body').off('click', hideAllDropdowns);
};
$('.dropdown__selected').on('click', function() {
var $this = $(this);
var $dropdown = $this.closest('.dropdown');
if ($dropdown.hasClass('dropdown--active') === false) {
$dropdown.addClass('dropdown--active');
setTimeout(function() {
$('body').off('click', hideAllDropdowns).on('click', hideAllDropdowns);
}, 1);
}
});
});
| 'use strict';
// Toogle asset images - zome in and out
$(function() {
var Snackbar = window.Snackbar;
Snackbar.init();
var AssetPage = window.AssetPage;
AssetPage.init();
// We only want zooming on asset's primary images.
$('.asset .zoomable').click(function() {
var $thisRow = $(this).closest('.image-row');
if ($thisRow.hasClass('col-md-6')) {
$thisRow.removeClass('col-md-6').addClass('col-md-12');
$thisRow.next('div').addClass('col-md-offset-3')
.removeClass('pull-right');
} else {
$thisRow.removeClass('col-md-12').addClass('col-md-6');
$thisRow.next('div').removeClass('col-md-offset-3')
.addClass('pull-right');
}
});
var hideAllDropdowns = function() {
$('.dropdown').removeClass('dropdown--active');
$('body').off('click', hideAllDropdowns);
};
$('.dropdown__selected').on('click', function() {
var $this = $(this);
$('body').off('click', hideAllDropdowns);
$('.dropdown').removeClass('dropdown--active');
var $dropdown = $this.closest('.dropdown');
if ($dropdown.hasClass('dropdown--active') === false) {
$dropdown.addClass('dropdown--active');
setTimeout(function() {
$('body').on('click', hideAllDropdowns);
}, 1);
}
});
});
| Fix bug in dropdowns, where they didn’t disappear correctly | Fix bug in dropdowns, where they didn’t disappear correctly | JavaScript | mit | CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder | ---
+++
@@ -31,11 +31,15 @@
$('.dropdown__selected').on('click', function() {
var $this = $(this);
+ $('body').off('click', hideAllDropdowns);
+
+ $('.dropdown').removeClass('dropdown--active');
var $dropdown = $this.closest('.dropdown');
if ($dropdown.hasClass('dropdown--active') === false) {
$dropdown.addClass('dropdown--active');
+
setTimeout(function() {
- $('body').off('click', hideAllDropdowns).on('click', hideAllDropdowns);
+ $('body').on('click', hideAllDropdowns);
}, 1);
}
}); |
e7ed223545ffa3fea6d996eb2920908275a69cc9 | cli.js | cli.js | #!/usr/bin/env node
'use strict';
const fs = require('fs');
const minimist = require('minimist');
const pkg = require('./package.json');
const oust = require('.');
const argv = minimist(process.argv.slice(2));
function printHelp() {
console.log([
pkg.description,
'',
'Usage',
' $ oust <filename> <type>',
'',
'Example',
' $ oust index.html scripts'
].join('\n'));
}
if (argv.v || argv.version) {
console.log(pkg.version);
process.exit(0);
}
if (argv.h || argv.help || argv._.length === 0) {
printHelp();
process.exit(0);
}
const file = argv._[0];
const type = argv._[1];
fs.readFile(file, (err, data) => {
if (err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
console.log(oust(data, type).join('\n'));
});
| #!/usr/bin/env node
'use strict';
const fs = require('fs');
const minimist = require('minimist');
const pkg = require('./package.json');
const oust = require('.');
const argv = minimist(process.argv.slice(2));
function printHelp() {
console.log(`
${pkg.description}
Usage:
$ oust <filename> <type>
Example:
$ oust index.html scripts`);
}
if (argv.v || argv.version) {
console.log(pkg.version);
process.exit(0);
}
if (argv.h || argv.help || argv._.length === 0) {
printHelp();
process.exit(0);
}
const file = argv._[0];
const type = argv._[1];
fs.readFile(file, (err, data) => {
if (err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
console.log(oust(data, type).join('\n'));
});
| Switch to template literals for the help screen. | Switch to template literals for the help screen.
| JavaScript | apache-2.0 | addyosmani/oust,addyosmani/oust | ---
+++
@@ -10,15 +10,14 @@
const argv = minimist(process.argv.slice(2));
function printHelp() {
- console.log([
- pkg.description,
- '',
- 'Usage',
- ' $ oust <filename> <type>',
- '',
- 'Example',
- ' $ oust index.html scripts'
- ].join('\n'));
+ console.log(`
+${pkg.description}
+
+Usage:
+ $ oust <filename> <type>
+
+Example:
+ $ oust index.html scripts`);
}
if (argv.v || argv.version) { |
421230533c619e98a5dca0ce8374b176bdc10663 | git.js | git.js | var exec = require('child_process').exec;
var temp = require('temp');
var fs = fs = require('fs');
var log = require('./logger');
exports.head = function (path, callback) {
exec('git --git-dir=' + path + ".git log -1 --pretty=format:'%H%n%an <%ae>%n%ad%n%s%n'", function(error, stdout, stderr) {
var str = stdout.split('\n');
var commit = {
commit: str[0],
author: str[1],
date: str[2],
message: str[3],
};
callback(commit);
});
};
exports.commit = function (path, author, message, callback) {
temp.open('bombastic', function(err, info) {
if (err) {
log.error("Can't create temporaty file " + info.path);
callback();
}
log.debug('Write commit message into temporary file ' + info.path);
fs.write(info.fd, message);
fs.close(info.fd, function(err) {
var command = ['./scripts/commit.sh ',
path,
' "',
author.name,
' <',
author.email,
'> " "',
info.path,
'"'].join('');
exec(command, function(error, stdout, stderr) {
log.debug(stdout);
callback();
});
});
});
}
| var exec = require('child_process').exec;
var temp = require('temp');
var fs = fs = require('fs');
var log = require('./logger');
exports.head = function (path, callback) {
exec('git --git-dir=' + path + ".git log -1 --pretty=format:'%H%n%an <%ae>%n%ad%n%s%n'", function(error, stdout, stderr) {
var str = stdout.split('\n');
var commit = {
commit: str[0],
author: str[1],
date: str[2],
message: str[3],
};
callback(commit);
});
};
exports.commit = function (path, author, message, callback) {
temp.open('bombastic', function(err, info) {
if (err) {
log.error("Can't create temporaty file " + info.path);
callback();
}
log.debug('Write commit message into temporary file ' + info.path);
fs.write(info.fd, message);
fs.close(info.fd, function(err) {
var command = [__dirname + '/scripts/commit.sh ',
path,
' "',
author.name,
' <',
author.email,
'> " "',
info.path,
'"'].join('');
exec(command, function(error, stdout, stderr) {
log.debug(stdout);
callback();
});
});
});
}
| Fix path to commit.sh script | Fix path to commit.sh script
It should be relative to __dirname, not to cwd()
| JavaScript | mit | finik/bombastic,finik/bombastic,finik/bombastic | ---
+++
@@ -26,7 +26,7 @@
log.debug('Write commit message into temporary file ' + info.path);
fs.write(info.fd, message);
fs.close(info.fd, function(err) {
- var command = ['./scripts/commit.sh ',
+ var command = [__dirname + '/scripts/commit.sh ',
path,
' "',
author.name, |
88305e481396644d88a08605ba786bd1dce35af6 | src/scripts/json-minify.js | src/scripts/json-minify.js | function minifyJson(data) {
return JSON.stringify(JSON.parse(data));
}
export function minifyJsonFile(readFileFn, fileName) {
return minifyJson(readFileFn(fileName));
} | export function minifyJsonFile(readFileFn, fileName) {
const minifyJson = new MinifyJson(readFileFn);
return minifyJson.fromFile(fileName);
}
class MinifyJson {
constructor(readFileFunction) {
this.readFileFunction = readFileFunction;
}
fromFile(fileName) {
const fileContent = this.readFileFunction(fileName);
return MinifyJson.fromString(fileContent);
}
static fromString(data) {
return JSON.stringify(JSON.parse(data));
}
} | Refactor it out into a class. | Refactor it out into a class. | JavaScript | mit | cosmowiki/cosmowiki,cosmowiki/cosmowiki,cosmowiki/cosmowiki,cosmowiki/cosmowiki | ---
+++
@@ -1,7 +1,21 @@
-function minifyJson(data) {
- return JSON.stringify(JSON.parse(data));
+export function minifyJsonFile(readFileFn, fileName) {
+ const minifyJson = new MinifyJson(readFileFn);
+ return minifyJson.fromFile(fileName);
}
-export function minifyJsonFile(readFileFn, fileName) {
- return minifyJson(readFileFn(fileName));
+class MinifyJson {
+
+ constructor(readFileFunction) {
+ this.readFileFunction = readFileFunction;
+ }
+
+ fromFile(fileName) {
+ const fileContent = this.readFileFunction(fileName);
+ return MinifyJson.fromString(fileContent);
+ }
+
+ static fromString(data) {
+ return JSON.stringify(JSON.parse(data));
+ }
+
} |
084a1d1d7139d96540648a9938749a9d36d2efa4 | desktop/src/lib/database.js | desktop/src/lib/database.js | /* eslint-env browser */
const fs = window.require('fs');
const fetchInitialState = () => {
const data = fs.readFileSync('.config/db', 'utf-8');
if (data) {
return JSON.parse(data);
}
return {};
};
const update = (state) => {
fs.writeFileSync('.config/db', JSON.stringify(state), 'utf-8');
};
export { fetchInitialState, update };
| /* eslint-env browser */
const fs = window.require('fs');
const fetchInitialState = () => {
let data = fs.readFileSync('.config/db', 'utf-8');
if (data) {
data = JSON.parse(data);
return {
tasks: {
past: [],
present: data.tasks,
future: [],
history: [],
},
ideas: {
past: [],
present: data.ideas,
future: [],
history: [],
},
appProperties: data.appProperties,
};
}
return {};
};
const update = (state) => {
fs.writeFileSync('.config/db', JSON.stringify({
tasks: state.tasks.present,
ideas: state.ideas.present,
appProperties: state.appProperties,
}), 'utf-8');
};
export { fetchInitialState, update };
| Fix minor issue about making redux-undo state permanent | Fix minor issue about making redux-undo state permanent
| JavaScript | mit | mkermani144/wanna,mkermani144/wanna | ---
+++
@@ -3,14 +3,33 @@
const fs = window.require('fs');
const fetchInitialState = () => {
- const data = fs.readFileSync('.config/db', 'utf-8');
+ let data = fs.readFileSync('.config/db', 'utf-8');
if (data) {
- return JSON.parse(data);
+ data = JSON.parse(data);
+ return {
+ tasks: {
+ past: [],
+ present: data.tasks,
+ future: [],
+ history: [],
+ },
+ ideas: {
+ past: [],
+ present: data.ideas,
+ future: [],
+ history: [],
+ },
+ appProperties: data.appProperties,
+ };
}
return {};
};
const update = (state) => {
- fs.writeFileSync('.config/db', JSON.stringify(state), 'utf-8');
+ fs.writeFileSync('.config/db', JSON.stringify({
+ tasks: state.tasks.present,
+ ideas: state.ideas.present,
+ appProperties: state.appProperties,
+ }), 'utf-8');
};
|
f5128b1e6c2581a5a1b33977914a23195ac4ad3d | scripts/entry.js | scripts/entry.js | #!/usr/bin/env node
import childProcess from 'child_process';
import fs from 'fs-extra';
import moment from 'moment';
const today = new Date();
const path = `pages/posts/${moment(today).format('YYYY-MM-DD')}.md`;
/**
* Set Weekdays Locale
*/
moment.locale('jp', {weekdays: ['日', '月', '火', '水', '木', '金', '土']});
/**
* Get Post Template
*
* @return {string}
*/
function getPostTmp() {
return [
'---\n',
'title: "post"\n',
`date: "${moment(today).format('YYYY-MM-DD HH:mm:ss (dddd)')}"\n`,
'layout: post\n',
`path: "/${moment(today).format('YYYYMMDD')}/"\n`,
'---'
].join('');
}
/**
* If already been created: Open File
* else: Create & Open File
*/
fs.open(path, 'r+', err => {
if (err) {
const ws = fs.createOutputStream(path);
ws.write(getPostTmp());
}
childProcess.spawn('vim', [path], {stdio: 'inherit'});
});
| #!/usr/bin/env node
import childProcess from 'child_process';
import fs from 'fs-extra';
import moment from 'moment';
const today = new Date();
const path = `pages/posts/${moment(today).format('YYYY-MM-DD')}.md`;
/**
* Set Weekdays Locale
*/
moment.locale('jp', {weekdays: ['日', '月', '火', '水', '木', '金', '土']});
/**
* Get Post Template
*
* @return {string}
*/
function getPostTmp() {
return [
'---\n',
'title: "post"\n',
`date: "${moment(today).format('YYYY-MM-DD HH:mm:ss (dddd)')}"\n`,
'layout: post\n',
`path: "/${moment(today).format('YYYYMMDD')}/"\n`,
'---'
].join('');
}
/**
* If already been created: Open File
* else: Create & Open File
*/
fs.open(path, 'r+', err => {
if (err) {
fs.outputFile(path, getPostTmp());
}
childProcess.spawn('vim', [path], {stdio: 'inherit'});
});
| Fix fs-extra breaking change :bread: | fix(scripts): Fix fs-extra breaking change :bread:
| JavaScript | mit | ideyuta/sofar | ---
+++
@@ -33,8 +33,7 @@
*/
fs.open(path, 'r+', err => {
if (err) {
- const ws = fs.createOutputStream(path);
- ws.write(getPostTmp());
+ fs.outputFile(path, getPostTmp());
}
childProcess.spawn('vim', [path], {stdio: 'inherit'});
}); |
80a6031cae11d28b7056ae9178e5f7d4ec9cea62 | server/config.js | server/config.js | // Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
'use strict';
var SECOND = 1000;
var MINUTE = 60 * SECOND;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var config = {
port: process.env.PA_MENTOR_PORT || 8080,
dbUri: process.env.PA_MENTOR_DB_URI || 'mongodb://localhost:27017/pa-mentor-test',
updateInterval: Math.max(SECOND, process.env.PA_MENTOR_UPDATE_INTERVAL || HOUR),
retryInterval: Math.max(SECOND, process.env.PA_MENTOR_RETRY_INTERVAL || MINUTE),
samplingPeriod: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_PERIOD || 3 * DAY),
samplingBatchSize: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_BATCH_SIZE || 3 * HOUR),
maxGameDuration: 8 * HOUR // just a guess; used in the updater to do overlapping fetches to avoid missing games
};
module.exports = config;
| // Copyright © 2013-2014 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
'use strict';
var SECOND = 1000;
var MINUTE = 60 * SECOND;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var config = {
port: process.env.PA_MENTOR_PORT || 8080,
dbUri: process.env.PA_MENTOR_DB_URI || 'mongodb://localhost:27017/pa-mentor-test',
updateInterval: Math.max(SECOND, process.env.PA_MENTOR_UPDATE_INTERVAL || HOUR),
retryInterval: Math.max(SECOND, process.env.PA_MENTOR_RETRY_INTERVAL || MINUTE),
samplingPeriod: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_PERIOD || DAY),
samplingBatchSize: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_BATCH_SIZE || 3 * HOUR),
maxGameDuration: 8 * HOUR // just a guess; used in the updater to do overlapping fetches to avoid missing games
};
module.exports = config;
| Reduce default sampling period to make testing easier | Reduce default sampling period to make testing easier
| JavaScript | apache-2.0 | orfjackal/pa-mentor,orfjackal/pa-mentor,orfjackal/pa-mentor | ---
+++
@@ -14,7 +14,7 @@
dbUri: process.env.PA_MENTOR_DB_URI || 'mongodb://localhost:27017/pa-mentor-test',
updateInterval: Math.max(SECOND, process.env.PA_MENTOR_UPDATE_INTERVAL || HOUR),
retryInterval: Math.max(SECOND, process.env.PA_MENTOR_RETRY_INTERVAL || MINUTE),
- samplingPeriod: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_PERIOD || 3 * DAY),
+ samplingPeriod: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_PERIOD || DAY),
samplingBatchSize: Math.max(SECOND, process.env.PA_MENTOR_SAMPLING_BATCH_SIZE || 3 * HOUR),
maxGameDuration: 8 * HOUR // just a guess; used in the updater to do overlapping fetches to avoid missing games
}; |
ba5f567a44a5d7325f894c42e48f696f6925907b | routes/user/index.js | routes/user/index.js | "use strict";
var db = require('../../models');
var config = require('../../config.js');
var authHelper = require('../../lib/auth-helper');
module.exports = function (app, options) {
app.get('/user/tokens', authHelper.ensureAuthenticated, function(req, res, next) {
db.ServiceAccessToken
.findAll({ include: [db.ServiceProvider] })
.complete(function(err, tokens) {
if (err) {
next(err);
return;
}
res.render('./user/token_list.ejs', { tokens: tokens });
});
});
};
| "use strict";
var config = require('../../config');
var db = require('../../models');
var authHelper = require('../../lib/auth-helper');
module.exports = function (app, options) {
app.get('/user/tokens', authHelper.ensureAuthenticated, function(req, res, next) {
db.ServiceAccessToken
.findAll({ include: [db.ServiceProvider] })
.complete(function(err, tokens) {
if (err) {
next(err);
return;
}
res.render('./user/token_list.ejs', { tokens: tokens });
});
});
};
| Remove .js extension in require() | Remove .js extension in require()
| JavaScript | bsd-3-clause | ebu/cpa-auth-provider | ---
+++
@@ -1,7 +1,7 @@
"use strict";
+var config = require('../../config');
var db = require('../../models');
-var config = require('../../config.js');
var authHelper = require('../../lib/auth-helper');
module.exports = function (app, options) { |
7788c984c07d81af3f819a93dac8f663f93063b8 | src/clincoded/static/libs/render_variant_title_explanation.js | src/clincoded/static/libs/render_variant_title_explanation.js | 'use strict';
import React from 'react';
import { ContextualHelp } from './bootstrap/contextual_help';
/**
* Method to render a mouseover explanation for the variant title
*/
export function renderVariantTitleExplanation() {
const explanation = 'The transcript with the longest translation with no stop codons. If no translation, then the longest non-protein-coding transcript.';
return (
<span className="variant-title-explanation"><ContextualHelp content={explanation} /></span>
);
}
| 'use strict';
import React from 'react';
import { ContextualHelp } from './bootstrap/contextual_help';
/**
* Method to render a mouseover explanation for the variant title
*/
export function renderVariantTitleExplanation() {
const explanation = 'For ClinVar alleles, this represents the ClinVar Preferred Title. For alleles not in ClinVar, this HGVS is based on the transcript with the longest translation with no stop codons or, if no translation, the longest non-protein-coding transcript. If a single canonical transcript is not discernible the HGVS is based on the GRCh38 genomic coordinates.';
return (
<span className="variant-title-explanation"><ContextualHelp content={explanation} /></span>
);
}
| Update variant title explanation text | Update variant title explanation text
| JavaScript | mit | ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded | ---
+++
@@ -6,7 +6,7 @@
* Method to render a mouseover explanation for the variant title
*/
export function renderVariantTitleExplanation() {
- const explanation = 'The transcript with the longest translation with no stop codons. If no translation, then the longest non-protein-coding transcript.';
+ const explanation = 'For ClinVar alleles, this represents the ClinVar Preferred Title. For alleles not in ClinVar, this HGVS is based on the transcript with the longest translation with no stop codons or, if no translation, the longest non-protein-coding transcript. If a single canonical transcript is not discernible the HGVS is based on the GRCh38 genomic coordinates.';
return (
<span className="variant-title-explanation"><ContextualHelp content={explanation} /></span>
); |
00c45bc2e33b6c1236d87c6572cfee3610410bb5 | server/fake-users.js | server/fake-users.js | var faker = require('faker');
var _ = require('lodash');
/**
* Generate a list of random users.
* @return {Array<{
* name: string,
* email: string,
* phone: string
* }>}
*/
var getUsers = function() {
return _.times(3).map(function() {
return {
name: faker.name.findName(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber()
}
})
};
module.exports = {
getUsers: getUsers
};
| var faker = require('faker');
var _ = require('lodash');
/**
* Generate a list of random users.
* @return {Array<{
* name: string,
* email: string,
* phone: string
* }>}
*/
var getUsers = function() {
var chuckNorris = {
name: 'Chuck Norris',
email: 'chuck@gmail.com',
phone: '212-555-1234'
};
var rambo = {
name: 'John Rambo',
email: 'rambo@gmail.com',
phone: '415-555-9876'
};
var fakeUsers = _.times(6).map(function() {
return {
name: faker.name.findName(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber()
};
});
// Add chuck norris at the beginning
fakeUsers.unshift(chuckNorris);
// Add rambo in the middle (range 1-4)
var randomIndex = (new Date()).getTime() % 4 + 1;
// removes 0 elements from index 'randomIndex', and inserts item
fakeUsers.splice(randomIndex, 0, rambo);
return fakeUsers;
};
module.exports = {
getUsers: getUsers
};
| Add chuck norris and rambo | Add chuck norris and rambo
| JavaScript | mit | andresdominguez/protractor-codelab,andresdominguez/protractor-codelab | ---
+++
@@ -10,13 +10,34 @@
* }>}
*/
var getUsers = function() {
- return _.times(3).map(function() {
+ var chuckNorris = {
+ name: 'Chuck Norris',
+ email: 'chuck@gmail.com',
+ phone: '212-555-1234'
+ };
+ var rambo = {
+ name: 'John Rambo',
+ email: 'rambo@gmail.com',
+ phone: '415-555-9876'
+ };
+
+ var fakeUsers = _.times(6).map(function() {
return {
name: faker.name.findName(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber()
- }
- })
+ };
+ });
+
+ // Add chuck norris at the beginning
+ fakeUsers.unshift(chuckNorris);
+
+ // Add rambo in the middle (range 1-4)
+ var randomIndex = (new Date()).getTime() % 4 + 1;
+ // removes 0 elements from index 'randomIndex', and inserts item
+ fakeUsers.splice(randomIndex, 0, rambo);
+
+ return fakeUsers;
};
module.exports = { |
85a1333dbd1382da6176352f35481e245c846a8e | src/.eslintrc.js | src/.eslintrc.js | module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"installedESLint": true,
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"react/jsx-uses-vars": 1,
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
]
}
};
| module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"installedESLint": true,
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"react/jsx-uses-vars": 1,
"react/jsx-uses-react": [1],
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
]
}
};
| Make linter know when JSX is using React variable | Make linter know when JSX is using React variable
| JavaScript | bsd-3-clause | rlorenzo/tmlpstats,rlorenzo/tmlpstats,rlorenzo/tmlpstats,rlorenzo/tmlpstats,tmlpstats/tmlpstats,tmlpstats/tmlpstats,tmlpstats/tmlpstats,rlorenzo/tmlpstats,tmlpstats/tmlpstats | ---
+++
@@ -18,6 +18,7 @@
],
"rules": {
"react/jsx-uses-vars": 1,
+ "react/jsx-uses-react": [1],
"indent": [
"error",
4 |
03d9bb448c252addcd98b3a0b0317fc2884c0c31 | share/spice/google_plus/google_plus.js | share/spice/google_plus/google_plus.js | function ddg_spice_google_plus (api_result) {
"use strict";
if(!api_result || !api_result.items || api_result.items.length === 0) {
return Spice.failed("googleplus");
}
Spice.add({
id: 'googleplus',
name: 'Google Plus',
data: api_result.items,
meta: {
sourceName : 'Google+',
sourceUrl : 'http://plus.google.com',
itemType: "Google+ Profile" + (api_result.items.length > 1 ? 's' : '')
},
templates: {
group: 'products_simple',
item_detail: false,
detail: false
},
normalize : function(item) {
var image = item.image.url.replace(/sz=50$/, "sz=200");
return {
image : image.replace(/^https/, "http"),
title: item.displayName
};
}
});
};
| function ddg_spice_google_plus (api_result) {
"use strict";
if(!api_result || !api_result.items || api_result.items.length === 0) {
return Spice.failed("googleplus");
}
Spice.add({
id: 'googleplus',
name: 'Google+',
data: api_result.items,
meta: {
sourceName : 'Google+',
sourceUrl : 'http://plus.google.com',
itemType: "Google+ Profile" + (api_result.items.length > 1 ? 's' : '')
},
templates: {
group: 'products_simple',
item_detail: false,
detail: false
},
normalize : function(item) {
var image = item.image.url.replace(/sz=50$/, "sz=200");
return {
image : image.replace(/^https/, "http"),
title: item.displayName
};
}
});
};
| Change the name from "Google Plus" to "Google+" | Google+: Change the name from "Google Plus" to "Google+"
It's just not how it's styled.
| JavaScript | apache-2.0 | Kr1tya3/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,stennie/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,levaly/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,levaly/zeroclickinfo-spice,mayo/zeroclickinfo-spice,P71/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,soleo/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,imwally/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,soleo/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,ppant/zeroclickinfo-spice,ppant/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,lerna/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,ppant/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,imwally/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,levaly/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,lernae/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,levaly/zeroclickinfo-spice,mayo/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,soleo/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,lernae/zeroclickinfo-spice,loganom/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,lernae/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,imwally/zeroclickinfo-spice,sevki/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,P71/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,deserted/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,soleo/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,lerna/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,imwally/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,lerna/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,deserted/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,loganom/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,lerna/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lerna/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,sevki/zeroclickinfo-spice,deserted/zeroclickinfo-spice,P71/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,soleo/zeroclickinfo-spice,mayo/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,echosa/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,loganom/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,echosa/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,ppant/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,deserted/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,sevki/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,stennie/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,stennie/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,echosa/zeroclickinfo-spice,loganom/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,deserted/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,levaly/zeroclickinfo-spice,levaly/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,sevki/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,lernae/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,P71/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,soleo/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,imwally/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,stennie/zeroclickinfo-spice,deserted/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,mayo/zeroclickinfo-spice | ---
+++
@@ -7,7 +7,7 @@
Spice.add({
id: 'googleplus',
- name: 'Google Plus',
+ name: 'Google+',
data: api_result.items,
meta: {
sourceName : 'Google+', |
55d69b6528833130d4f1e0118368b9a5ed9f587a | src/TcpReader.js | src/TcpReader.js | function TcpReader(callback) {
this.callback = callback;
this.buffer = "";
};
TcpReader.prototype.read = function(data) {
this.buffer = this.buffer.concat(data);
size = this.payloadSize( this.buffer );
while ( size > 0 && this.buffer.length >= ( 6 + size ) ) {
this.consumeOne( size );
size = this.payloadSize( this.buffer );
}
}
TcpReader.prototype.payloadSize = function(buffer) {
if ( this.buffer.length >= 6 ){
return parseInt( buffer.slice( 0,6 ) );
}
else {
return -1;
}
}
TcpReader.prototype.consumeOne = function(size) {
messageStart = 6;
messageEnd = 6 + size;
this.callback( this.buffer.slice( messageStart, messageEnd ) );
this.buffer = this.buffer.slice( messageEnd, this.buffer.length );
}
if(typeof module !== 'undefined' && module.exports){
module.exports = TcpReader;
}
| function TcpReader(callback) {
this.callback = callback;
this.buffer = "";
};
TcpReader.prototype.read = function(data) {
this.buffer = this.buffer.concat(data);
var size = this.payloadSize( this.buffer );
while ( size > 0 && this.buffer.length >= ( 6 + size ) ) {
this.consumeOne( size );
size = this.payloadSize( this.buffer );
}
}
TcpReader.prototype.payloadSize = function(buffer) {
if ( this.buffer.length >= 6 ){
return parseInt( buffer.slice( 0,6 ), 10 );
}
else {
return -1;
}
}
TcpReader.prototype.consumeOne = function(size) {
var messageStart = 6;
var messageEnd = 6 + size;
this.callback( this.buffer.slice( messageStart, messageEnd ) );
this.buffer = this.buffer.slice( messageEnd, this.buffer.length );
}
if(typeof module !== 'undefined' && module.exports){
module.exports = TcpReader;
}
| Patch parseInt usage to specify radix explicitly | Patch parseInt usage to specify radix explicitly
My node install informed me that parseInt('000039') === 3, so: womp
womp. This commit also avoids a couple of globals.
| JavaScript | bsd-3-clause | noam-io/lemma-javascript,noam-io/lemma-javascript | ---
+++
@@ -5,7 +5,7 @@
TcpReader.prototype.read = function(data) {
this.buffer = this.buffer.concat(data);
- size = this.payloadSize( this.buffer );
+ var size = this.payloadSize( this.buffer );
while ( size > 0 && this.buffer.length >= ( 6 + size ) ) {
this.consumeOne( size );
size = this.payloadSize( this.buffer );
@@ -14,7 +14,7 @@
TcpReader.prototype.payloadSize = function(buffer) {
if ( this.buffer.length >= 6 ){
- return parseInt( buffer.slice( 0,6 ) );
+ return parseInt( buffer.slice( 0,6 ), 10 );
}
else {
return -1;
@@ -22,8 +22,8 @@
}
TcpReader.prototype.consumeOne = function(size) {
- messageStart = 6;
- messageEnd = 6 + size;
+ var messageStart = 6;
+ var messageEnd = 6 + size;
this.callback( this.buffer.slice( messageStart, messageEnd ) );
this.buffer = this.buffer.slice( messageEnd, this.buffer.length );
} |
3a02688886a40dbb922c034811bbdf5399c06929 | src/app/wegas.js | src/app/wegas.js | var ServiceURL = "/api/";
angular.module('Wegas', [
'ui.router',
'wegas.service.auth',
'wegas.behaviours.tools',
'public',
'private'
])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('wegas', {
url: '/',
views: {
'main@': {
controller: 'WegasMainCtrl',
templateUrl: 'app/wegas.tmpl.html'
}
}
})
;
$urlRouterProvider.otherwise('/');
}).controller('WegasMainCtrl', function WegasMainCtrl($state, Auth) {
Auth.getAuthenticatedUser().then(function(user){
if(user == null){
$state.go("wegas.public");
}else{
if(user.isScenarist){
$state.go("wegas.private.scenarist");
}else{
if(user.isTrainer){
$state.go("wegas.private.trainer");
}else{
$state.go("wegas.private.player");
}
}
}
});
}); | var ServiceURL = "/api/";
angular.module('Wegas', [
'ui.router',
'ngAnimate',
'wegas.service.auth',
'wegas.behaviours.tools',
'public',
'private'
])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('wegas', {
url: '/',
views: {
'main@': {
controller: 'WegasMainCtrl',
templateUrl: 'app/wegas.tmpl.html'
}
}
})
;
$urlRouterProvider.otherwise('/');
}).controller('WegasMainCtrl', function WegasMainCtrl($state, Auth) {
Auth.getAuthenticatedUser().then(function(user){
if(user == null){
$state.go("wegas.public");
}else{
if(user.isScenarist){
$state.go("wegas.private.scenarist");
}else{
if(user.isTrainer){
$state.go("wegas.private.trainer");
}else{
$state.go("wegas.private.player");
}
}
}
});
});
| Resolve conflict - add module ngAnimate | Resolve conflict - add module ngAnimate
| JavaScript | mit | Heigvd/Wegas,ghiringh/Wegas,ghiringh/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas,ghiringh/Wegas | ---
+++
@@ -1,6 +1,7 @@
var ServiceURL = "/api/";
angular.module('Wegas', [
'ui.router',
+ 'ngAnimate',
'wegas.service.auth',
'wegas.behaviours.tools',
'public', |
22f07bfd0bd4c2928f6c641ccab91750b0c88f5b | client/lib/convert-to-print/convert-items/paragraphToReact.js | client/lib/convert-to-print/convert-items/paragraphToReact.js | import React from 'react';
function applyProperties(text, properties) {
// TODO: support more than 1 property
const property = properties[0];
return React.createElement('p', null, [
React.createElement('span', null, text.substring(0, property.offSets.start)),
React.createElement(property.type, null, text.substring(property.offSets.start, property.offSets.end)),
React.createElement('span', null, text.substring(property.offSets.end)),
]);
}
export default function paragraphObjetToReact(paragraph, level) {
if (!paragraph.inlineProperties || paragraph.inlineProperties.length === 0) {
return React.createElement(
'p',
{
className: 'c_print-view__paragraph',
'data-level': level,
},
paragraph.text,
);
}
return applyProperties(paragraph.text, paragraph.inlineProperties);
}
| import React from 'react';
function applyProperties(text, properties) {
// TODO: support more than 1 property
const property = properties[0];
return React.createElement('p', null, [
React.createElement('span', null, text.substring(0, property.offsets.start)),
React.createElement(property.type, null, text.substring(property.offsets.start, property.offsets.end)),
React.createElement('span', null, text.substring(property.offsets.end)),
]);
}
export default function paragraphObjetToReact(paragraph, level) {
if (!paragraph.inlineProperties || paragraph.inlineProperties.length === 0) {
return React.createElement(
'p',
{
className: 'c_print-view__paragraph',
'data-level': level,
},
paragraph.text,
);
}
return applyProperties(paragraph.text, paragraph.inlineProperties);
}
| Fix small property rename issue after rebase. | Fix small property rename issue after rebase.
| JavaScript | mit | OpenWebslides/OpenWebslides,OpenWebslides/OpenWebslides,OpenWebslides/OpenWebslides,OpenWebslides/OpenWebslides | ---
+++
@@ -4,9 +4,9 @@
// TODO: support more than 1 property
const property = properties[0];
return React.createElement('p', null, [
- React.createElement('span', null, text.substring(0, property.offSets.start)),
- React.createElement(property.type, null, text.substring(property.offSets.start, property.offSets.end)),
- React.createElement('span', null, text.substring(property.offSets.end)),
+ React.createElement('span', null, text.substring(0, property.offsets.start)),
+ React.createElement(property.type, null, text.substring(property.offsets.start, property.offsets.end)),
+ React.createElement('span', null, text.substring(property.offsets.end)),
]);
}
|
139065ee61c1c1322879785fe546fc8374a671e2 | example/routes.js | example/routes.js | 'use strict';
/**
* Sets up the routes.
* @param {object} app - Express app
*/
module.exports.setup = function (app) {
/**
* @swagger
* /:
* get:
* responses:
* 200:
* description: hello world
*/
app.get('/', rootHandler);
/**
* @swagger
* /login:
* post:
* responses:
* 200:
* description: login
*/
app.get('/login', loginHandler);
};
function rootHandler(req, res) {
res.send('Hello World!');
}
function loginHandler(req, res) {
var user = {};
user.username = req.param('username');
user.password = req.param('password');
res.json(user);
}
| 'use strict';
/**
* Sets up the routes.
* @param {object} app - Express app
*/
module.exports.setup = function (app) {
/**
* @swagger
* /:
* get:
* responses:
* 200:
* description: hello world
*/
app.get('/', rootHandler);
/**
* @swagger
* /login:
* post:
* responses:
* 200:
* description: login
*/
app.post('/login', loginHandler);
};
function rootHandler(req, res) {
res.send('Hello World!');
}
function loginHandler(req, res) {
var user = {};
user.username = req.param('username');
user.password = req.param('password');
res.json(user);
}
| Use 2 spaces for deeply nested objects | Use 2 spaces for deeply nested objects
| JavaScript | mit | zeornelas/jsdoc-express-with-swagger,zeornelas/jsdoc-express-with-swagger,devlouisc/jsdoc-express-with-swagger,devlouisc/jsdoc-express-with-swagger | ---
+++
@@ -9,22 +9,22 @@
/**
* @swagger
* /:
- * get:
- * responses:
- * 200:
- * description: hello world
+ * get:
+ * responses:
+ * 200:
+ * description: hello world
*/
app.get('/', rootHandler);
/**
* @swagger
* /login:
- * post:
- * responses:
- * 200:
- * description: login
+ * post:
+ * responses:
+ * 200:
+ * description: login
*/
- app.get('/login', loginHandler);
+ app.post('/login', loginHandler);
};
function rootHandler(req, res) { |
371b5cffd0e20c540b01d00076ec38ccc0bda504 | spec/leaflet_spec.js | spec/leaflet_spec.js |
describe('LeafletMap Ext Component', function() {
describe('Basics', function() {
var Map = vrs.ux.touch.LeafletMap;
it('provides new mapping events', function() {
var map = new Map();
expect(map.events.repPicked).toBeDefined();
});
it('provides new mapping events', function() {
var map = new Map();
expect(map.events.repPicked).toBeDefined();
});
});
}); | /* Disable Leaflet for now
describe('LeafletMap Ext Component', function() {
describe('Basics', function() {
var Map = vrs.ux.touch.LeafletMap;
it('provides new mapping events', function() {
var map = new Map();
expect(map.events.repPicked).toBeDefined();
});
it('provides new mapping events', function() {
var map = new Map();
expect(map.events.repPicked).toBeDefined();
});
});
});
*/ | Comment out leaflet test for now since it depends upon manually installing leaflet to a given directory path. | Comment out leaflet test for now since it depends upon manually installing leaflet to a given directory path.
| JavaScript | mit | vrsource/vrs.ux.touch,vrsource/vrs.ux.touch,vrsource/vrs.ux.touch,vrsource/vrs.ux.touch | ---
+++
@@ -1,4 +1,4 @@
-
+/* Disable Leaflet for now
describe('LeafletMap Ext Component', function() {
describe('Basics', function() {
var Map = vrs.ux.touch.LeafletMap;
@@ -17,3 +17,4 @@
});
});
+*/ |
9ab9b55982f39de1b9866ee9ba86e4bbd7d2050d | spec/main/program.js | spec/main/program.js | var test = require('test');
test.assert(require('dot-slash') === 10, 'main with "./"');
test.assert(require('js-ext') === 20, 'main with ".js" extension');
test.assert(require('no-ext') === 30, 'main with no extension');
test.assert(require('dot-js-ext') === 40, 'main with "." in module name and ".js" extension');
test.print('DONE', 'info');
| var test = require('test');
test.assert(require('dot-slash') === 10, 'main with "./"');
test.assert(require('js-ext') === 20, 'main with ".js" extension');
test.assert(require('no-ext') === 30, 'main with no extension');
test.assert(require('dot-js-ext') === 40, 'main with "." in module name and ".js" extension');
test.assert(require('js-ext') === require("js-ext/a"), 'can require "main" without extension');
test.print('DONE', 'info');
| Add test for requiring a package's main module without .js extension | Add test for requiring a package's main module without .js extension
| JavaScript | bsd-3-clause | kriskowal/mr,kriskowal/mr | ---
+++
@@ -5,4 +5,6 @@
test.assert(require('no-ext') === 30, 'main with no extension');
test.assert(require('dot-js-ext') === 40, 'main with "." in module name and ".js" extension');
+test.assert(require('js-ext') === require("js-ext/a"), 'can require "main" without extension');
+
test.print('DONE', 'info'); |
92b65306960142124ca97a6816bd4ce8596714d3 | app/js/main.js | app/js/main.js | (function() {
'use strict';
var params = window.location.search.substring(1)
.split( '&' )
.reduce(function( object, param ) {
var pair = param.split( '=' ).map( decodeURIComponent );
object[ pair[0] ] = pair[1];
return object;
}, {} );
var port = params.port || 8080;
var host = window.location.hostname;
var socket = new WebSocket( 'ws://' + host + ':' + port );
socket.addEventListener( 'message', function( event ) {
console.log( event );
});
}) ();
| (function() {
'use strict';
var params = window.location.search.substring(1)
.split( '&' )
.reduce(function( object, param ) {
var pair = param.split( '=' ).map( decodeURIComponent );
object[ pair[0] ] = pair[1];
return object;
}, {} );
var port = params.port || 8080;
var host = window.location.hostname;
var socket = new WebSocket( 'ws://' + host + ':' + port );
socket.addEventListener( 'message', function( event ) {
var data = JSON.parse( event.data );
console.log( data );
});
var types = [
'push',
'toggle',
'xy',
'fader',
'rotary',
'encoder',
'multitoggle',
'multixy',
'multipush',
'multifader'
];
// Boolean.
function Push( value ) { this.value = value || false; }
function Toggle( value ) { this.value = value || false; }
// Numeric.
function Fader( value ) { this.value = value || 0; }
function Rotary( value ) { this.value = value || 0; }
// Coordinates.
function XY( x, y ) {
this.x = x || 0;
this.y = y || 0;
}
// Collections.
function MultiToggle( values ) { this.values = values || []; }
function MultiXY( values ) { this.values = values || []; }
function MultiPush( values ) { this.values = values || []; }
}) ();
| Add basic TouchOSC data structures. | Add basic TouchOSC data structures.
| JavaScript | mit | razh/osc-dev | ---
+++
@@ -15,7 +15,41 @@
var socket = new WebSocket( 'ws://' + host + ':' + port );
socket.addEventListener( 'message', function( event ) {
- console.log( event );
+ var data = JSON.parse( event.data );
+ console.log( data );
});
+ var types = [
+ 'push',
+ 'toggle',
+ 'xy',
+ 'fader',
+ 'rotary',
+ 'encoder',
+ 'multitoggle',
+ 'multixy',
+ 'multipush',
+ 'multifader'
+ ];
+
+
+ // Boolean.
+ function Push( value ) { this.value = value || false; }
+ function Toggle( value ) { this.value = value || false; }
+
+ // Numeric.
+ function Fader( value ) { this.value = value || 0; }
+ function Rotary( value ) { this.value = value || 0; }
+
+ // Coordinates.
+ function XY( x, y ) {
+ this.x = x || 0;
+ this.y = y || 0;
+ }
+
+ // Collections.
+ function MultiToggle( values ) { this.values = values || []; }
+ function MultiXY( values ) { this.values = values || []; }
+ function MultiPush( values ) { this.values = values || []; }
+
}) (); |
ee424745693facc1e23c5896e30a25253c99adab | app/js/tree.js | app/js/tree.js | 'use strict';
var MAX = 1000;
function Node( number ){
this.number = 0;
this.parent = null;
this.left = null;
this.right = null;
this.depth = 0;
if( number === undefined ){
this.number = Math.floor((Math.random() * MAX) + 1);
}
else{
this.number = number;
}
}
function Tree(){
this.list = [];
this.root = null;
}
Tree.prototype.insert = function( number ){
var node = new Node( number );
if( this.root === null || this.root === undefined ){
this.root = node;
}
else{
var parentNode = this.root;
while( true ){
if( parentNode.number > node.number ){
if( parentNode.left === null ){
parentNode.left = node;
node.parent = parentNode;
node.depth = parentNode.depth + 1;
break;
}
else{
parentNode = parentNode.left;
}
}
else{
if( parentNode.right === null ){
parentNode.right = node;
node.parent = parentNode;
node.depth = parentNode.depth + 1;
break;
}
else{
parentNode = parentNode.right;
}
}
}
}
this.list.push( node );
};
/*
// TODO
Tree.prototype.delete = function( node ) {
};
*/
| 'use strict';
var MAX = 1000;
function Node( number ){
this.number = 0;
this.parent = null;
this.left = null;
this.right = null;
this.depth = 0;
if( number === undefined ){
this.number = Math.floor((Math.random() * MAX) + 1);
}
else{
this.number = number;
}
}
function Tree(){
this.list = [];
this.root = null;
}
Tree.prototype.insert = function( number ){
var node = new Node( number );
if( this.root === null || this.root === undefined ){
this.root = node;
}
else{
var parentNode = this.root;
while( true ){
if( parentNode.number < node.number ){
if( parentNode.left === null ){
parentNode.left = node;
node.parent = parentNode;
node.depth = parentNode.depth + 1;
break;
}
else{
parentNode = parentNode.left;
}
}
else{
if( parentNode.right === null ){
parentNode.right = node;
node.parent = parentNode;
node.depth = parentNode.depth + 1;
break;
}
else{
parentNode = parentNode.right;
}
}
}
}
this.list.push( node );
};
/*
// TODO
Tree.prototype.delete = function( node ) {
};
*/
| Change left-right for test CI | Change left-right for test CI
| JavaScript | mit | takecode/SampleTree | ---
+++
@@ -30,7 +30,7 @@
else{
var parentNode = this.root;
while( true ){
- if( parentNode.number > node.number ){
+ if( parentNode.number < node.number ){
if( parentNode.left === null ){
parentNode.left = node;
node.parent = parentNode; |
3bfdcb7e7ab642d26498c7b08ec7d014a008c4a6 | application.js | application.js | define(['render',
'events',
'class'],
function(render, Emitter, clazz) {
function Application() {
Application.super_.call(this);
this.render = render;
this.controller = undefined;
}
clazz.inherits(Application, Emitter);
Application.prototype.run = function() {
this.willLaunch();
this.launch();
this.didLaunch();
render.$(document).ready(function() {
this.willDisplay();
this.display();
this.didDisplay();
});
};
Application.prototype.launch = function() {};
Application.prototype.display = function() {
if (!this.controller) throw new Error('No controller initialized by application.');
this.controller.willAddEl();
this.controller.el.prependTo(document.body);
this.controller.didAddEl();
};
Application.prototype.willLaunch = function() {};
Application.prototype.didLaunch = function() {};
Application.prototype.willDisplay = function() {};
Application.prototype.didDisplay = function() {};
return Application;
});
| define(['render',
'events',
'class'],
function(render, Emitter, clazz) {
function Application() {
Application.super_.call(this);
this.render = render;
this.controller = undefined;
}
clazz.inherits(Application, Emitter);
Application.prototype.run = function() {
this.willLaunch();
this.launch();
this.didLaunch();
var self = this;
render.$(document).ready(function() {
self.willDisplay();
self.display();
self.didDisplay();
});
};
Application.prototype.launch = function() {};
Application.prototype.display = function() {
if (!this.controller) throw new Error('No controller initialized by application.');
this.controller.willAddEl();
this.controller.el.prependTo(document.body);
this.controller.didAddEl();
};
Application.prototype.willLaunch = function() {};
Application.prototype.didLaunch = function() {};
Application.prototype.willDisplay = function() {};
Application.prototype.didDisplay = function() {};
return Application;
});
| Fix this context in ready callback. | Fix this context in ready callback.
| JavaScript | mit | sailjs/application | ---
+++
@@ -15,10 +15,11 @@
this.launch();
this.didLaunch();
+ var self = this;
render.$(document).ready(function() {
- this.willDisplay();
- this.display();
- this.didDisplay();
+ self.willDisplay();
+ self.display();
+ self.didDisplay();
});
};
|
c64492441b8bcac86b1dbc29d40fcb84fb31a51a | generators/reducer/index.js | generators/reducer/index.js | 'use strict';
let generator = require('yeoman-generator');
let utils = require('generator-react-webpack/utils/all');
let path = require('path');
module.exports = generator.NamedBase.extend({
constructor: function() {
generator.NamedBase.apply(this, arguments);
},
writing: function() {
let baseName = this.name;
let destinationPath = path.join('src', 'reducers', baseName + '.js');
let testDestinationPath = path.join('test', 'reducers', baseName + 'Test.js');
// Copy the base store
this.fs.copyTpl(
this.templatePath('reducer.js'),
this.destinationPath(destinationPath),
{
reducerName: baseName
}
);
// Copy the unit test
this.fs.copyTpl(
this.templatePath('Test.js'),
this.destinationPath(testDestinationPath),
{
reducerName: baseName
}
);
}
});
| 'use strict';
let esprima = require('esprima');
let walk = require('esprima-walk');
let escodegen = require('escodegen');
let generator = require('yeoman-generator');
//let utils = require('generator-react-webpack/utils/all');
let path = require('path');
let fs = require('fs');
module.exports = generator.NamedBase.extend({
constructor: function() {
generator.NamedBase.apply(this, arguments);
},
writing: function() {
let baseName = this.name;
let destinationPath = path.join('src', 'reducers', baseName + '.js');
let rootReducerPath = this.destinationPath(path.join('src', 'reducers', 'index.js'));
let testDestinationPath = path.join('test', 'reducers', baseName + 'Test.js');
// Copy the base store
this.fs.copyTpl(
this.templatePath('reducer.js'),
this.destinationPath(destinationPath),
{ reducerName: baseName }
);
// Copy the unit test
this.fs.copyTpl(
this.templatePath('Test.js'),
this.destinationPath(testDestinationPath),
{ reducerName: baseName }
);
// Add the reducer to the root reducer
let reducer = 'var reducer = { ' + baseName +': require(\'./' + baseName + '.js\')}';
reducer = esprima.parse(reducer);
reducer = reducer.body[0].declarations[0].init.properties[0];
let data = fs.readFileSync(rootReducerPath, 'utf8');
let parsed = esprima.parse(data);
walk.walkAddParent(parsed, function(node) {
if(node.type === 'VariableDeclarator' && node.id.name === 'reducers') {
node.init.properties.push(reducer);
}
});
let options = { format: { indent: { style: ' ' } } };
let code = escodegen.generate(parsed, options);
fs.writeFileSync(rootReducerPath, code, 'utf8');
// TODO: Add the reducer to App.js
}
});
| Add reducer to root reducer | Add reducer to root reducer
| JavaScript | mit | stylesuxx/generator-react-webpack-redux,stylesuxx/generator-react-webpack-redux | ---
+++
@@ -1,7 +1,11 @@
'use strict';
+let esprima = require('esprima');
+let walk = require('esprima-walk');
+let escodegen = require('escodegen');
let generator = require('yeoman-generator');
-let utils = require('generator-react-webpack/utils/all');
+//let utils = require('generator-react-webpack/utils/all');
let path = require('path');
+let fs = require('fs');
module.exports = generator.NamedBase.extend({
@@ -13,24 +17,41 @@
let baseName = this.name;
let destinationPath = path.join('src', 'reducers', baseName + '.js');
+ let rootReducerPath = this.destinationPath(path.join('src', 'reducers', 'index.js'));
let testDestinationPath = path.join('test', 'reducers', baseName + 'Test.js');
// Copy the base store
this.fs.copyTpl(
this.templatePath('reducer.js'),
this.destinationPath(destinationPath),
- {
- reducerName: baseName
- }
+ { reducerName: baseName }
);
// Copy the unit test
this.fs.copyTpl(
this.templatePath('Test.js'),
this.destinationPath(testDestinationPath),
- {
- reducerName: baseName
+ { reducerName: baseName }
+ );
+
+ // Add the reducer to the root reducer
+ let reducer = 'var reducer = { ' + baseName +': require(\'./' + baseName + '.js\')}';
+ reducer = esprima.parse(reducer);
+ reducer = reducer.body[0].declarations[0].init.properties[0];
+
+ let data = fs.readFileSync(rootReducerPath, 'utf8');
+ let parsed = esprima.parse(data);
+
+ walk.walkAddParent(parsed, function(node) {
+ if(node.type === 'VariableDeclarator' && node.id.name === 'reducers') {
+ node.init.properties.push(reducer);
}
- );
+ });
+
+ let options = { format: { indent: { style: ' ' } } };
+ let code = escodegen.generate(parsed, options);
+ fs.writeFileSync(rootReducerPath, code, 'utf8');
+
+ // TODO: Add the reducer to App.js
}
}); |
f01b2067158e327eec89db536cc34b8976b0f0e8 | openfisca_web_ui/static/js/auth.js | openfisca_web_ui/static/js/auth.js | define([
'jquery'
], function($) {
var Auth = function () {};
Auth.prototype = {
init: function (authconfig) {
navigator.id.watch({
loggedInUser: authconfig.currentUser,
onlogin: function (assertion) {
$.ajax({
type: 'POST',
url: '/login',
data: {
assertion: assertion
},
success: function(res, status, xhr) {
window.location.href = res.accountUrl;
},
error: function(xhr, status, err) {
navigator.id.logout();
// TODO translate string
alert("Login failure: " + err);
}
});
},
onlogout: function () {
if (window.location.pathname == '/logout') {
window.location.href = '/';
} else {
$.ajax({
type: 'POST',
url: '/logout',
success: function(res, status, xhr) {
window.location.reload();
},
error: function(xhr, status, err) {
// TODO translate string
alert("Logout failure: " + err);
}
});
}
}
});
$(document).on('click', '.sign-in', function () {
navigator.id.request();
});
$(document).on('click', '.sign-out', function() {
navigator.id.logout();
});
}
};
var auth = new Auth();
return auth;
});
| define([
'jquery'
], function($) {
var Auth = function () {};
Auth.prototype = {
init: function (authconfig) {
navigator.id.watch({
loggedInUser: authconfig.currentUser,
onlogin: function (assertion) {
$.ajax({
type: 'POST',
url: '/login',
data: {
assertion: assertion
}
})
.done(function(data) {
window.location.href = data.accountUrl;
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error('onlogin fail', jqXHR, textStatus, errorThrown, jqXHR.responseText);
navigator.id.logout();
// TODO translate string
alert("Login failure");
});
},
onlogout: function () {
if (window.location.pathname == '/logout') {
window.location.href = '/';
} else {
$.ajax({
type: 'POST',
url: '/logout'
})
.done(function() {
window.location.reload();
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error('onlogout fail', jqXHR, textStatus, errorThrown, jqXHR.responseText);
// TODO translate string
alert("Logout failure");
});
}
}
});
$(document).on('click', '.sign-in', function () {
navigator.id.request();
});
$(document).on('click', '.sign-out', function() {
navigator.id.logout();
});
}
};
var auth = new Auth();
return auth;
});
| Use new jquery jqXHR API. | Use new jquery jqXHR API.
| JavaScript | agpl-3.0 | openfisca/openfisca-web-ui,openfisca/openfisca-web-ui,openfisca/openfisca-web-ui | ---
+++
@@ -13,15 +13,16 @@
url: '/login',
data: {
assertion: assertion
- },
- success: function(res, status, xhr) {
- window.location.href = res.accountUrl;
- },
- error: function(xhr, status, err) {
- navigator.id.logout();
- // TODO translate string
- alert("Login failure: " + err);
}
+ })
+ .done(function(data) {
+ window.location.href = data.accountUrl;
+ })
+ .fail(function(jqXHR, textStatus, errorThrown) {
+ console.error('onlogin fail', jqXHR, textStatus, errorThrown, jqXHR.responseText);
+ navigator.id.logout();
+ // TODO translate string
+ alert("Login failure");
});
},
onlogout: function () {
@@ -30,14 +31,15 @@
} else {
$.ajax({
type: 'POST',
- url: '/logout',
- success: function(res, status, xhr) {
- window.location.reload();
- },
- error: function(xhr, status, err) {
- // TODO translate string
- alert("Logout failure: " + err);
- }
+ url: '/logout'
+ })
+ .done(function() {
+ window.location.reload();
+ })
+ .fail(function(jqXHR, textStatus, errorThrown) {
+ console.error('onlogout fail', jqXHR, textStatus, errorThrown, jqXHR.responseText);
+ // TODO translate string
+ alert("Logout failure");
});
}
} |
8287ca26fd538a3bc9ec68d0dc6cd81a3ff1cda3 | node-server/config.js | node-server/config.js | // Don't commit this file to your public repos. This config is for first-run
exports.creds = {
mongoose_auth_local: 'mongodb://localhost/tasklist', // Your mongo auth uri goes here
audience: 'http://localhost:8888/', // the Audience is the App URL when you registered the application.
identityMetadata: 'https://login.microsoftonline.com/hypercubeb2c.onmicrosoft.com/.well-known/openid-configuration?p=b2c_1_B2CSI' // Replace the text after p= with your specific policy.
};
| // Don't commit this file to your public repos. This config is for first-run
exports.creds = {
mongoose_auth_local: 'mongodb://localhost/tasklist', // Your mongo auth uri goes here
audience: 'http://localhost:8888/', // the Audience is the App URL when you registered the application.
identityMetadata: 'https://login.microsoftonline.com/common/' // Replace the text after p= with your specific policy.
};
| Update back to business scenarios | Update back to business scenarios
| JavaScript | apache-2.0 | AzureADSamples/WebAPI-Nodejs | ---
+++
@@ -2,5 +2,5 @@
exports.creds = {
mongoose_auth_local: 'mongodb://localhost/tasklist', // Your mongo auth uri goes here
audience: 'http://localhost:8888/', // the Audience is the App URL when you registered the application.
- identityMetadata: 'https://login.microsoftonline.com/hypercubeb2c.onmicrosoft.com/.well-known/openid-configuration?p=b2c_1_B2CSI' // Replace the text after p= with your specific policy.
+ identityMetadata: 'https://login.microsoftonline.com/common/' // Replace the text after p= with your specific policy.
}; |
3b9144acc0031957a1e824d15597a8605cd0be86 | examples/index.js | examples/index.js | import 'bootstrap/dist/css/bootstrap.min.css';
import 'nvd3/build/nv.d3.min.css';
import 'react-select/dist/react-select.min.css';
import 'fixed-data-table/dist/fixed-data-table.min.css';
import ReactDOM from 'react-dom';
import React from 'react';
import customDataHandlers from './customDataHandlers';
import { settings } from './settings';
import App from './App';
import { Router, Route, browserHistory } from 'react-router';
console.log('JJ', jeckyll);
ReactDOM.render(<App />, document.getElementById('root'));
| import 'bootstrap/dist/css/bootstrap.min.css';
import 'nvd3/build/nv.d3.min.css';
import 'react-select/dist/react-select.min.css';
import 'fixed-data-table/dist/fixed-data-table.min.css';
import ReactDOM from 'react-dom';
import React from 'react';
import customDataHandlers from './customDataHandlers';
import { settings } from './settings';
import App from './App';
import { Router, Route, browserHistory } from 'react-router';
ReactDOM.render(<App />, document.getElementById('root'));
| Test for jekyll env - 1.1 | Test for jekyll env - 1.1
| JavaScript | mit | NuCivic/react-dashboard,NuCivic/react-dash,NuCivic/react-dashboard,NuCivic/react-dashboard,NuCivic/react-dash,NuCivic/react-dash | ---
+++
@@ -9,6 +9,4 @@
import App from './App';
import { Router, Route, browserHistory } from 'react-router';
-console.log('JJ', jeckyll);
-
ReactDOM.render(<App />, document.getElementById('root')); |
bc97c558b40592bbec42753baf72911f59bc8da6 | src/DataProcessor.js | src/DataProcessor.js | export default class DataProcessor {
static dataToPoints(data, width, height, limit) {
if (limit && limit < data.length) {
data = data.slice(data.length - limit);
}
let max = this.max(data);
let min = this.min(data);
let vfactor = height / (max - min);
let hfactor = width / (limit || data.length);
return data.map((d, i) => {
return {
x: i * hfactor,
y: (max - data[i]) * vfactor
}
});
}
static max(data) {
return Math.max.apply(Math, data);
}
static min(data) {
return Math.min.apply(Math, data);
}
static mean(data) {
return (this.max(data) - this.min(data)) / 2;
}
static avg(data) {
return data.reduce((a, b) => a + b) / (data.length + 1);
}
static median(data) {
return data.sort()[Math.floor(data.length / 2)];
}
static calculateFromData(data, calculationType) {
return this[calculationType].call(this, data);
}
}
| export default class DataProcessor {
static dataToPoints(data, width, height, limit) {
if (limit && limit < data.length) {
data = data.slice(data.length - limit);
}
let max = this.max(data);
let min = this.min(data);
let vfactor = height / (max - min);
let hfactor = width / (limit || data.length);
return data.map((d, i) => {
return {
x: i * hfactor,
y: (max - data[i]) * vfactor
}
});
}
static max(data) {
return Math.max.apply(Math, data);
}
static min(data) {
return Math.min.apply(Math, data);
}
static mean(data) {
return (this.max(data) - this.min(data)) / 2;
}
static avg(data) {
return data.reduce((a, b) => a + b) / (data.length + 1);
}
static median(data) {
return data.sort()[Math.floor(data.length / 2)];
}
static variance(data) {
let mean = this.mean(data);
let sq = data.map(n => Math.pow(n - mean, 2));
return this.mean(sq);
}
static stddev(data) {
let avg = this.avg(data);
let sqDiff = data.map(n => Math.pow(n - mean, 2));
let avgSqDiff = this.avg(sqDiff);
return Math.sqrt(avgSqDiff);
}
static calculateFromData(data, calculationType) {
return this[calculationType].call(this, data);
}
}
| Add calcualtion for standard deviation | Add calcualtion for standard deviation
| JavaScript | mit | timoxley/react-sparklines,codevlabs/react-sparklines,Jonekee/react-sparklines,okonet/react-sparklines,samsface/react-sparklines,goodeggs/react-sparklines,kidaa/react-sparklines,shaunstanislaus/react-sparklines,rkichenama/react-sparklines,DigitalCoder/react-sparklines,geminiyellow/react-sparklines,rkichenama/react-sparklines,DigitalCoder/react-sparklines,fredericksilva/react-sparklines,fredericksilva/react-sparklines,konsumer/react-sparklines,timoxley/react-sparklines,codevlabs/react-sparklines,samsface/react-sparklines,borisyankov/react-sparklines,okonet/react-sparklines,geminiyellow/react-sparklines,kidaa/react-sparklines,shaunstanislaus/react-sparklines,Jonekee/react-sparklines,konsumer/react-sparklines | ---
+++
@@ -40,6 +40,19 @@
return data.sort()[Math.floor(data.length / 2)];
}
+ static variance(data) {
+ let mean = this.mean(data);
+ let sq = data.map(n => Math.pow(n - mean, 2));
+ return this.mean(sq);
+ }
+
+ static stddev(data) {
+ let avg = this.avg(data);
+ let sqDiff = data.map(n => Math.pow(n - mean, 2));
+ let avgSqDiff = this.avg(sqDiff);
+ return Math.sqrt(avgSqDiff);
+ }
+
static calculateFromData(data, calculationType) {
return this[calculationType].call(this, data);
} |
4e2ac67d7fc85ec38bc9404a350fcb2126fb0511 | _config/task.local-server.js | _config/task.local-server.js | /* jshint node: true */
'use strict';
function getTaskConfig(projectConfig) {
var taskConfig = {
server: {
baseDir: taskConfig.baseDir
}
};
return taskConfig;
}
module.exports = getTaskConfig;
| /* jshint node: true */
'use strict';
function getTaskConfig(projectConfig) {
//Browser Sync options object
//https://www.browsersync.io/docs/options
var taskConfig = {
//Server config options
server: {
baseDir: projectConfig.dirs.build,
// directory: true, // directory listing
// index: "index.htm", // specific index filename
},
ghostMode: false, // Mirror behaviour on all devices
online: false, // Speed up startup time (When xip & tunnel aren't being used)
// notify: false // Turn off UI notifications
// browser: 'google chrome' //Set what browser to open on start - https://www.browsersync.io/docs/options#option-browser
// open: false // Stop browser automatically opening
};
return taskConfig;
}
module.exports = getTaskConfig;
| Add base browser sync config options | feat: Add base browser sync config options
| JavaScript | mit | cartridge/cartridge-local-server | ---
+++
@@ -3,10 +3,21 @@
'use strict';
function getTaskConfig(projectConfig) {
+ //Browser Sync options object
+ //https://www.browsersync.io/docs/options
+
var taskConfig = {
+ //Server config options
server: {
- baseDir: taskConfig.baseDir
- }
+ baseDir: projectConfig.dirs.build,
+ // directory: true, // directory listing
+ // index: "index.htm", // specific index filename
+ },
+ ghostMode: false, // Mirror behaviour on all devices
+ online: false, // Speed up startup time (When xip & tunnel aren't being used)
+ // notify: false // Turn off UI notifications
+ // browser: 'google chrome' //Set what browser to open on start - https://www.browsersync.io/docs/options#option-browser
+ // open: false // Stop browser automatically opening
};
return taskConfig; |
53b5893362dfe65bb47e6824a171b9ede1c5f1da | src/Web/Firebase/Authentication/Eff.js | src/Web/Firebase/Authentication/Eff.js | 'use strict';
// module Web.Firebase.Authentication.Eff
exports._onAuth = function (callback, firebase) {
var cbEffect = function(data) {
return cbEffect(data)(); // ensure effect gets used
};
return function() {
return firebase.onAuth(cbEffect);
};
};
exports._authWithOAuthRedirect = function (provider, errorCallback, ref) {
var errorCbEffect = function(error) {
return errorCallback(error)(); // ensure effect gets used
};
ref.authWithOAuthRedirect(provider, errorCbEffect);
};
| 'use strict';
// module Web.Firebase.Authentication.Eff
exports._onAuth = function (callback, firebase) {
var cbEffect = function(data) {
return callback(data)(); // ensure effect gets used
};
return function() {
return firebase.onAuth(cbEffect);
};
};
exports._authWithOAuthRedirect = function (provider, errorCallback, ref) {
var errorCbEffect = function(error) {
return errorCallback(error)(); // ensure effect gets used
};
ref.authWithOAuthRedirect(provider, errorCbEffect);
};
| Fix infinite recursion in onAuth | Fix infinite recursion in onAuth
| JavaScript | mit | mostalive/purescript-firebase,mostalive/purescript-firebase,mostalive/purescript-firebase | ---
+++
@@ -5,7 +5,7 @@
exports._onAuth = function (callback, firebase) {
var cbEffect = function(data) {
- return cbEffect(data)(); // ensure effect gets used
+ return callback(data)(); // ensure effect gets used
};
return function() {
return firebase.onAuth(cbEffect); |
b575a80c0bf801a2b32c35f27cb71ca5fe7a71c6 | src/Whoops/Resources/js/whoops.base.js | src/Whoops/Resources/js/whoops.base.js | Zepto(function($) {
prettyPrint();
var $frameLines = $('[id^="frame-line-"]');
var $activeLine = $('.frames-container .active');
var $activeFrame = $('.active[id^="frame-code-"]').show();
var $container = $('.details-container');
var headerHeight = $('header').css('height');
var highlightCurrentLine = function() {
// Highlight the active and neighboring lines for this frame:
var activeLineNumber = +($activeLine.find('.frame-line').text());
var $lines = $activeFrame.find('.linenums li');
var firstLine = +($lines.first().val());
$($lines[activeLineNumber - firstLine - 1]).addClass('current');
$($lines[activeLineNumber - firstLine]).addClass('current active');
$($lines[activeLineNumber - firstLine + 1]).addClass('current');
}
// Highlight the active for the first frame:
highlightCurrentLine();
$frameLines.click(function() {
var $this = $(this);
var id = /frame\-line\-([\d]*)/.exec($this.attr('id'))[1];
var $codeFrame = $('#frame-code-' + id);
if($codeFrame) {
$activeLine.removeClass('active');
$activeFrame.removeClass('active');
$this.addClass('active');
$codeFrame.addClass('active');
$activeLine = $this;
$activeFrame = $codeFrame;
highlightCurrentLine();
$container.scrollTop(headerHeight);
}
});
});
| Zepto(function($) {
prettyPrint();
var $frameLines = $('[id^="frame-line-"]');
var $activeLine = $('.frames-container .active');
var $activeFrame = $('.active[id^="frame-code-"]').show();
var $container = $('.details-container');
var headerHeight = $('header').height();
var highlightCurrentLine = function() {
// Highlight the active and neighboring lines for this frame:
var activeLineNumber = +($activeLine.find('.frame-line').text());
var $lines = $activeFrame.find('.linenums li');
var firstLine = +($lines.first().val());
$($lines[activeLineNumber - firstLine - 1]).addClass('current');
$($lines[activeLineNumber - firstLine]).addClass('current active');
$($lines[activeLineNumber - firstLine + 1]).addClass('current');
}
// Highlight the active for the first frame:
highlightCurrentLine();
$frameLines.click(function() {
var $this = $(this);
var id = /frame\-line\-([\d]*)/.exec($this.attr('id'))[1];
var $codeFrame = $('#frame-code-' + id);
if($codeFrame) {
$activeLine.removeClass('active');
$activeFrame.removeClass('active');
$this.addClass('active');
$codeFrame.addClass('active');
$activeLine = $this;
$activeFrame = $codeFrame;
highlightCurrentLine();
$container.scrollTop(headerHeight);
}
});
});
| Use correct header height for scrolling back up. | Use correct header height for scrolling back up.
| JavaScript | mit | UnderDogg/whoops,emilkje/whoops,oligriffiths/whoops,emilkje/whoops,stefen/whoops,michabbb-backup/whoops,staabm/whoops,staabm/whoops,michabbb-backup/whoops,UnderDogg/whoops,Vmak11/whoops,filp/whoops,stefen/whoops,Vmak11/whoops,oligriffiths/whoops,nonconforme/whoops,nonconforme/whoops,filp/whoops | ---
+++
@@ -5,7 +5,7 @@
var $activeLine = $('.frames-container .active');
var $activeFrame = $('.active[id^="frame-code-"]').show();
var $container = $('.details-container');
- var headerHeight = $('header').css('height');
+ var headerHeight = $('header').height();
var highlightCurrentLine = function() {
// Highlight the active and neighboring lines for this frame: |
894ac7126415d351ae03c93387bb96436d911044 | website/src/app/global.components/mc-show-sample.component.js | website/src/app/global.components/mc-show-sample.component.js | class MCShowSampleComponentController {
/*@ngInject*/
constructor($stateParams, samplesService, toast, $mdDialog) {
this.projectId = $stateParams.project_id;
this.samplesService = samplesService;
this.toast = toast;
this.$mdDialog = $mdDialog;
this.viewHeight = this.viewHeight ? this.viewHeight : "40vh";
}
$onInit() {
if (this.viewHeight) {
}
this.samplesService.getProjectSample(this.projectId, this.sampleId)
.then(
(sample) => this.sample = sample,
() => this.toast.error('Unable to retrieve sample')
)
}
showProcess(process) {
this.$mdDialog.show({
templateUrl: 'app/project/experiments/experiment/components/dataset/components/show-process-dialog.html',
controllerAs: '$ctrl',
controller: ShowProcessDialogController,
bindToController: true,
locals: {
process: process
}
});
}
}
class ShowProcessDialogController {
/*@ngInject*/
constructor($mdDialog) {
this.$mdDialog = $mdDialog;
}
done() {
this.$mdDialog.cancel();
}
}
angular.module('materialscommons').component('mcShowSample', {
templateUrl: 'app/global.components/mc-show-sample.html',
controller: MCShowSampleComponentController,
bindings: {
sampleId: '<',
viewHeight: '@'
}
});
| class MCShowSampleComponentController {
/*@ngInject*/
constructor($stateParams, samplesService, toast, $mdDialog) {
this.projectId = $stateParams.project_id;
this.samplesService = samplesService;
this.toast = toast;
this.$mdDialog = $mdDialog;
this.viewHeight = this.viewHeight ? this.viewHeight : "40vh";
}
$onInit() {
this.samplesService.getProjectSample(this.projectId, this.sampleId)
.then(
(sample) => this.sample = sample,
() => this.toast.error('Unable to retrieve sample')
)
}
showProcess(process) {
this.$mdDialog.show({
templateUrl: 'app/project/experiments/experiment/components/dataset/components/show-process-dialog.html',
controllerAs: '$ctrl',
controller: ShowProcessDialogController,
bindToController: true,
locals: {
process: process
}
});
}
}
class ShowProcessDialogController {
/*@ngInject*/
constructor($mdDialog) {
this.$mdDialog = $mdDialog;
}
done() {
this.$mdDialog.cancel();
}
}
angular.module('materialscommons').component('mcShowSample', {
templateUrl: 'app/global.components/mc-show-sample.html',
controller: MCShowSampleComponentController,
bindings: {
sampleId: '<',
viewHeight: '@'
}
});
| Remove if(this.viewHeight){} since block is empty. | Remove if(this.viewHeight){} since block is empty.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -9,9 +9,6 @@
}
$onInit() {
- if (this.viewHeight) {
-
- }
this.samplesService.getProjectSample(this.projectId, this.sampleId)
.then(
(sample) => this.sample = sample, |
b948fe73af2929c0d8a8665eacdaf2de1a94637e | lib/createMockCouchAdapter.js | lib/createMockCouchAdapter.js | var express = require('express');
function createMethodWrapper(app, verb) {
var original = app[verb];
return function (route, handler) {
var hasSentResponse = false;
original.call(app, route, function (req, res, next) {
handler(req, {
setHeader: function () {
// empty
},
send: function(statusCode, body) {
if (hasSentResponse) {
return;
}
hasSentResponse = true;
res.send(statusCode, body);
}
}, function _next(err) {
if (hasSentResponse) {
return;
}
hasSentResponse = true;
next(err);
});
});
};
}
module.exports = function createMockCouchAdapter() {
var app = express();
var deferred;
var original;
['del', 'head', 'get', 'post'].forEach(function(verb) {
var expressVerb = (verb === 'del' ? 'delete' : verb);
app[verb] = createMethodWrapper(app, expressVerb);
});
// store the put method
app.put = function (route, handler) {
deferred = handler;
};
original = app.use;
app.use = function (middleware) {
original.call(app, '/:db', middleware);
// now add the put method
createMethodWrapper(app, 'put')('/:db', deferred);
};
return app;
};
| var express = require('express');
function createMethodWrapper(app, verb) {
var original = app[verb];
return function (route, handler) {
original.call(app, route, function (req, res, next) {
// must be places here in order that it is cleared on every request
var hasSentResponse = false;
handler(req, {
setHeader: function () {
// empty
},
send: function(statusCode, body) {
if (hasSentResponse) {
return;
}
hasSentResponse = true;
res.send(statusCode, body);
}
}, function _next(err) {
if (hasSentResponse) {
return;
}
hasSentResponse = true;
next(err);
});
});
};
}
module.exports = function createMockCouchAdapter() {
var app = express();
var deferred;
var original;
['del', 'head', 'get', 'post'].forEach(function(verb) {
var expressVerb = (verb === 'del' ? 'delete' : verb);
app[verb] = createMethodWrapper(app, expressVerb);
});
// store the put method
app.put = function (route, handler) {
deferred = handler;
};
original = app.use;
app.use = function (middleware) {
original.call(app, '/:db', middleware);
// now add the put method
createMethodWrapper(app, 'put')('/:db', deferred);
};
return app;
};
| Fix bug where hasSentResponse would not be reset stalling further requests. | Fix bug where hasSentResponse would not be reset stalling further requests.
| JavaScript | bsd-3-clause | alexjeffburke/unexpected-couchdb | ---
+++
@@ -4,9 +4,10 @@
var original = app[verb];
return function (route, handler) {
- var hasSentResponse = false;
+ original.call(app, route, function (req, res, next) {
+ // must be places here in order that it is cleared on every request
+ var hasSentResponse = false;
- original.call(app, route, function (req, res, next) {
handler(req, {
setHeader: function () {
// empty |
21e4abd8902165863e0d9acd49b4402f5341ed15 | src/client/gravatar-image-retriever.js | src/client/gravatar-image-retriever.js | import md5 from 'md5';
export default class GravatarImageRetriever {
constructor(picturePxSize) {
this.picturePxSize = picturePxSize;
}
getImageUrl(email) {
// https://en.gravatar.com/site/implement/hash/
if (email) {
// https://en.gravatar.com/site/implement/images/
// https://github.com/blueimp/JavaScript-MD5
return `https://www.gravatar.com/avatar/${md5(email.trim().toLowerCase())}.jpg`
+ `?s=${this.picturePxSize}&r=g&d=mm`;
}
}
}
| import md5 from 'md5';
export default class GravatarImageRetriever {
constructor(picturePxSize) {
this.picturePxSize = picturePxSize;
}
getImageUrl(email) {
// https://en.gravatar.com/site/implement/hash/
if (email) {
// https://en.gravatar.com/site/implement/images/
return `https://www.gravatar.com/avatar/${md5(email.trim().toLowerCase())}.jpg`
+ `?s=${this.picturePxSize}&r=g&d=mm`;
}
}
}
| Remove comment, project using md5 package not blueimp-md5 | Remove comment, project using md5 package not blueimp-md5
| JavaScript | mit | ritterim/star-orgs,ritterim/star-orgs | ---
+++
@@ -9,7 +9,6 @@
// https://en.gravatar.com/site/implement/hash/
if (email) {
// https://en.gravatar.com/site/implement/images/
- // https://github.com/blueimp/JavaScript-MD5
return `https://www.gravatar.com/avatar/${md5(email.trim().toLowerCase())}.jpg`
+ `?s=${this.picturePxSize}&r=g&d=mm`;
} |
4f8eee87a64f675a4f33ff006cf2f059a47d6267 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | 'use strict';
$(document).ready(() => {
$('.new').click((event) => {
event.preventDefault();
});
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
| $(document).ready(function() {
$('.new').on('click', function(event) {
event.preventDefault();
var $link = $(this);
var route = $link.attr('href');
var ajaxRequest = $.ajax({
method: 'GET',
url: route
});
ajaxRequest.done(function(data) {
$('.posts').prepend(data);
});
});
});
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
| Build ajax request for new snippet form | Build ajax request for new snippet form
| JavaScript | mit | dshaps10/snippet,dshaps10/snippet,dshaps10/snippet | ---
+++
@@ -1,10 +1,19 @@
-'use strict';
+$(document).ready(function() {
+ $('.new').on('click', function(event) {
+ event.preventDefault();
+ var $link = $(this);
+ var route = $link.attr('href');
-$(document).ready(() => {
- $('.new').click((event) => {
- event.preventDefault();
-
+ var ajaxRequest = $.ajax({
+ method: 'GET',
+ url: route
+ });
+ ajaxRequest.done(function(data) {
+ $('.posts').prepend(data);
+ });
+
+ });
});
|
70f438378cbadf23f176d5d8bfc1272f1e06a1ad | app/components/SearchResults/index.js | app/components/SearchResults/index.js | import React, { PropTypes } from 'react';
import './index.css';
const SearchResults = React.createClass({
propTypes: {
displayOptions: PropTypes.object.isRequired,
},
render() {
const { options, selectionIndex, onOptionSelected } = this.props;
return (
<div className="SearchResults">
<ul className="SearchResults-list">
{options.map((option, index) => {
const classNames = ['SearchResults-listItem'];
if (selectionIndex === index) {
classNames.push('SearchResults-listItem__active');
}
return (
<li className={classNames.join(' ')} onClick={() => { onOptionSelected(option); }}>
{option.name}
{option.type}
</li>);
})}
</ul>
</div>
);
},
});
export default SearchResults;
| import React, { PropTypes } from 'react';
import './index.css';
const SearchResults = React.createClass({
propTypes: {
displayOptions: PropTypes.object.isRequired,
},
render() {
const { options, selectionIndex, onOptionSelected } = this.props;
return (
<div className="SearchResults">
<ul className="SearchResults-list">
{options.map((option, index) => {
const classNames = ['SearchResults-listItem'];
if (selectionIndex === index) {
classNames.push('SearchResults-listItem__active');
}
return (
<li
className={classNames.join(' ')}
key={option.id}
onClick={() => { onOptionSelected(option); }}
>
{option.name}
{option.type}
</li>);
})}
</ul>
</div>
);
},
});
export default SearchResults;
| Add key to list item | Add key to list item
| JavaScript | mit | waagsociety/tnl-relationizer,transparantnederland/relationizer,transparantnederland/browser,transparantnederland/relationizer,transparantnederland/browser,waagsociety/tnl-relationizer | ---
+++
@@ -19,7 +19,11 @@
classNames.push('SearchResults-listItem__active');
}
return (
- <li className={classNames.join(' ')} onClick={() => { onOptionSelected(option); }}>
+ <li
+ className={classNames.join(' ')}
+ key={option.id}
+ onClick={() => { onOptionSelected(option); }}
+ >
{option.name}
{option.type}
</li>); |
248f547f7fe9c9cfab0d76088fb188ac379ab2fb | gulpfile.babel.js | gulpfile.babel.js | import gulp from 'gulp';
import requireDir from 'require-dir';
import runSequence from 'run-sequence';
// Require individual tasks
requireDir('./gulp/tasks', { recurse: true });
gulp.task('default', ['dev']);
gulp.task('dev', () =>
runSequence('clean', 'set-development', 'set-watch-js', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'webpack',
'cached-lintjs-watch'
], 'watch')
);
gulp.task('hot-dev', () =>
runSequence('clean', 'set-development', [
'i18n',
'copy-static',
'bower',
'stylesheets-livereload',
'cached-lintjs-watch'
], ['webpack', 'watch'])
);
gulp.task('build', cb =>
runSequence('clean', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'lintjs'
], 'webpack', 'minify', cb)
);
| import gulp from 'gulp';
import requireDir from 'require-dir';
import runSequence from 'run-sequence';
// Require individual tasks
requireDir('./gulp/tasks', { recurse: true });
gulp.task('default', ['dev']);
gulp.task('dev', () =>
runSequence('clean', 'set-development', 'set-watch-js', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'cached-lintjs-watch'
], ['webpack', 'watch'])
);
gulp.task('hot-dev', () =>
runSequence('clean', 'set-development', [
'i18n',
'copy-static',
'bower',
'stylesheets-livereload',
'cached-lintjs-watch'
], ['webpack', 'watch'])
);
gulp.task('build', cb =>
runSequence('clean', [
'i18n',
'copy-static',
'bower',
'stylesheets',
'lintjs'
], 'webpack', 'minify', cb)
);
| Fix styl/img watching in gulp tasks | Fix styl/img watching in gulp tasks
| JavaScript | mit | MusikAnimal/WikiEduDashboard,Wowu/WikiEduDashboard,MusikAnimal/WikiEduDashboard,KarmaHater/WikiEduDashboard,KarmaHater/WikiEduDashboard,alpha721/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,majakomel/WikiEduDashboard,Wowu/WikiEduDashboard,majakomel/WikiEduDashboard,Wowu/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,feelfreelinux/WikiEduDashboard,sejalkhatri/WikiEduDashboard,sejalkhatri/WikiEduDashboard,MusikAnimal/WikiEduDashboard,KarmaHater/WikiEduDashboard,sejalkhatri/WikiEduDashboard,sejalkhatri/WikiEduDashboard,sejalkhatri/WikiEduDashboard,alpha721/WikiEduDashboard,feelfreelinux/WikiEduDashboard,MusikAnimal/WikiEduDashboard,alpha721/WikiEduDashboard,Wowu/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,majakomel/WikiEduDashboard,feelfreelinux/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,alpha721/WikiEduDashboard,feelfreelinux/WikiEduDashboard,majakomel/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,KarmaHater/WikiEduDashboard | ---
+++
@@ -13,9 +13,8 @@
'copy-static',
'bower',
'stylesheets',
- 'webpack',
'cached-lintjs-watch'
- ], 'watch')
+ ], ['webpack', 'watch'])
);
gulp.task('hot-dev', () => |
11329fe25bb2242ecd27745f7b712ce37c0030e4 | src/lib/timer.js | src/lib/timer.js | const moment = require('moment');
function Timer(element) {
this.element = element;
this.secondsElapsed = 0;
}
Timer.prototype = {
start: function() {
var self = this;
self.timerId = setInterval(function() {
self.secondsElapsed++;
self.displaySeconds();
}, 1000);
},
stop: function() {
var self = this;
clearInterval(self.timerId);
},
displaySeconds: function() {
var minutes = Math.floor(this.secondsElapsed / 60);
var seconds = this.secondsElapsed % 60;
this.element.text(String(minutes).padStart(2, "0") + ":" + String(seconds).padStart(2, "0"));
}
};
module.exports = Timer;
| const moment = require('moment');
function Timer(element) {
this.element = element;
this.secondsElapsed = 0;
}
Timer.prototype = {
start: function() {
var self = this;
self.timerId = setInterval(function() {
self.secondsElapsed++;
self.displaySeconds();
}, 1000);
},
stop: function() {
var self = this;
clearInterval(self.timerId);
},
displaySeconds: function() {
var minutes = Math.floor(this.secondsElapsed / 60);
var seconds = this.secondsElapsed % 60;
this.element.text(String(minutes).padStart(2, "0") + ":" + String(seconds).padStart(2, "0"));
},
reset: function() {
var self = this;
clearInterval(self.timerId);
self.secondsElapsed = 0;
self.displaySeconds();
}
};
module.exports = Timer;
| Add a reset method to the Timer class. | Add a reset method to the Timer class.
Refs #9.
| JavaScript | mpl-2.0 | jwir3/minuteman,jwir3/minuteman | ---
+++
@@ -23,6 +23,13 @@
var minutes = Math.floor(this.secondsElapsed / 60);
var seconds = this.secondsElapsed % 60;
this.element.text(String(minutes).padStart(2, "0") + ":" + String(seconds).padStart(2, "0"));
+ },
+
+ reset: function() {
+ var self = this;
+ clearInterval(self.timerId);
+ self.secondsElapsed = 0;
+ self.displaySeconds();
}
};
|
5f56c522c4d3b2981e6d10b99bbe065e85d37ac4 | client/src/js/files/components/File.js | client/src/js/files/components/File.js | import React from "react";
import PropTypes from "prop-types";
import { Col, Row } from "react-bootstrap";
import { byteSize } from "../../utils";
import { Icon, ListGroupItem, RelativeTime } from "../../base";
export default class File extends React.Component {
static propTypes = {
id: PropTypes.string,
name: PropTypes.string,
size: PropTypes.number,
file: PropTypes.object,
uploaded_at: PropTypes.string,
user: PropTypes.object,
onRemove: PropTypes.func
};
handleRemove = () => {
this.props.onRemove(this.props.id);
};
render () {
const { name, size, uploaded_at, user } = this.props;
let creation;
if (user === null) {
creation = (
<span>
Retrieved <RelativeTime time={uploaded_at} />
</span>
);
} else {
creation = (
<span>
Uploaded <RelativeTime time={uploaded_at} /> by {user.id}
</span>
);
}
return (
<ListGroupItem className="spaced">
<Row>
<Col md={5}>
<strong>{name}</strong>
</Col>
<Col md={2}>
{byteSize(size)}
</Col>
<Col md={4}>
{creation}
</Col>
<Col md={1}>
<Icon
name="trash"
bsStyle="danger"
style={{fontSize: "17px"}}
onClick={this.handleRemove}
pullRight
/>
</Col>
</Row>
</ListGroupItem>
);
}
}
| import React from "react";
import PropTypes from "prop-types";
import { Col, Row } from "react-bootstrap";
import { byteSize } from "../../utils";
import { Icon, ListGroupItem, RelativeTime } from "../../base";
export default class File extends React.Component {
static propTypes = {
id: PropTypes.string,
name: PropTypes.string,
size: PropTypes.object,
file: PropTypes.object,
uploaded_at: PropTypes.string,
user: PropTypes.object,
onRemove: PropTypes.func
};
handleRemove = () => {
this.props.onRemove(this.props.id);
};
render () {
const { name, size, uploaded_at, user } = this.props;
let creation;
if (user === null) {
creation = (
<span>
Retrieved <RelativeTime time={uploaded_at} />
</span>
);
} else {
creation = (
<span>
Uploaded <RelativeTime time={uploaded_at} /> by {user.id}
</span>
);
}
return (
<ListGroupItem className="spaced">
<Row>
<Col md={5}>
<strong>{name}</strong>
</Col>
<Col md={2}>
{byteSize(size.size)}
</Col>
<Col md={4}>
{creation}
</Col>
<Col md={1}>
<Icon
name="trash"
bsStyle="danger"
style={{fontSize: "17px"}}
onClick={this.handleRemove}
pullRight
/>
</Col>
</Row>
</ListGroupItem>
);
}
}
| Fix file size prop warning | Fix file size prop warning
| JavaScript | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool | ---
+++
@@ -10,7 +10,7 @@
static propTypes = {
id: PropTypes.string,
name: PropTypes.string,
- size: PropTypes.number,
+ size: PropTypes.object,
file: PropTypes.object,
uploaded_at: PropTypes.string,
user: PropTypes.object,
@@ -48,7 +48,7 @@
<strong>{name}</strong>
</Col>
<Col md={2}>
- {byteSize(size)}
+ {byteSize(size.size)}
</Col>
<Col md={4}>
{creation} |
5da4c6e6ad78987f74a073ba5316a299071c0006 | src/components/Time.js | src/components/Time.js | import React, { PropTypes, Component } from 'react'
import moment from 'moment'
import eventActions from '../actions/eventActionCreators'
const TIME_INIT = moment('2190-07-02').utc()
const DELAY = 250
class Time extends Component {
componentWillMount () {
this.setState({ time: TIME_INIT })
}
componentDidMount () {
this.timer = setInterval(this._interval.bind(this), DELAY)
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return <div>{this.state.time.format('MMM Do YYYY').valueOf()}</div>
}
_interval () {
this._advanceTime()
if (Math.random() < 0.01) this._triggerEvent()
}
_advanceTime () {
const time = this.state.time.add(1, 'days')
this.setState({ time })
}
_triggerEvent () {
const n = Math.random()
const eventCategory = (n < 0.5) ? 'easy' : (n < 0.75 ? 'medium' : 'hard')
this.props.dispatch(eventActions.triggerEvent(eventCategory))
}
}
Time.propTypes = {
dispatch: PropTypes.func.isRequired,
}
export default Time
| import React, { PropTypes, Component } from 'react'
import moment from 'moment'
import eventActions from '../actions/eventActionCreators'
const TIME_INIT = moment('2190-07-02').utc()
const DELAY = 1000
class Time extends Component {
componentWillMount () {
this.setState({ time: TIME_INIT })
}
componentDidMount () {
this.timer = setInterval(this._interval.bind(this), DELAY)
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return <div>{this.state.time.format('MMM Do YYYY').valueOf()}</div>
}
_interval () {
this._advanceTime()
if (Math.random() < 0.01) this._triggerEvent()
}
_advanceTime () {
const time = this.state.time.add(1, 'days')
this.setState({ time })
}
_triggerEvent () {
const n = Math.random()
const eventCategory = (n < 0.5) ? 'easy' : (n < 0.75 ? 'medium' : 'hard')
this.props.dispatch(eventActions.triggerEvent(eventCategory))
}
}
Time.propTypes = {
dispatch: PropTypes.func.isRequired,
}
export default Time
| Change time frequency: one virtual day per second | Change time frequency: one virtual day per second
| JavaScript | mit | albertoblaz/lord-commander,albertoblaz/lord-commander | ---
+++
@@ -4,7 +4,7 @@
import eventActions from '../actions/eventActionCreators'
const TIME_INIT = moment('2190-07-02').utc()
-const DELAY = 250
+const DELAY = 1000
class Time extends Component {
componentWillMount () { |
65bfe55ca0448dc941739deea117347798807fc9 | app/assets/javascripts/patient_auto_complete.js | app/assets/javascripts/patient_auto_complete.js | $(document).ready(function() {
$("[data-autocomplete-source]").each(function() {
var url = $(this).data("autocomplete-source");
var target = $(this).data("autocomplete-rel");
$(this).autocomplete({
minLength: 2,
source: function(request,response) {
var path = url + "?term=" + request.term
$.getJSON(path, function(data) {
var list = $.map(data, function(patient) {
return {
label: patient.unique_label,
value: patient.unique_label,
id: patient.id
};
});
response(list);
})
},
search: function(event, ui) {
$(target).val("");
},
select: function(event, ui) {
$(target).val(ui.item.id);
}
});
});
});
| $(document).ready(function() {
$("[data-autocomplete-source]").each(function() {
var url = $(this).data("autocomplete-source");
var target = $(this).data("autocomplete-rel");
$(this).autocomplete({
minLength: 2,
source: function(request,response) {
$.ajax({
url: url,
data: { term: request.term },
success: function(data) {
var list = $.map(data, function(patient) {
return {
label: patient.unique_label,
id: patient.id
};
});
response(list);
},
error: function(jqXHR, textStatus, errorThrown) {
var msg = "An error occurred. Please contact an administrator.";
response({ label: msg, id: 0});
}
});
},
search: function(event, ui) {
$(target).val("");
},
select: function(event, ui) {
$(target).val(ui.item.id);
}
});
});
});
| Handle error if autocomplete query fails | Handle error if autocomplete query fails
| JavaScript | mit | airslie/renalware-core,airslie/renalware-core,airslie/renalware-core,airslie/renalware-core | ---
+++
@@ -5,17 +5,23 @@
$(this).autocomplete({
minLength: 2,
source: function(request,response) {
- var path = url + "?term=" + request.term
- $.getJSON(path, function(data) {
- var list = $.map(data, function(patient) {
- return {
- label: patient.unique_label,
- value: patient.unique_label,
- id: patient.id
- };
- });
- response(list);
- })
+ $.ajax({
+ url: url,
+ data: { term: request.term },
+ success: function(data) {
+ var list = $.map(data, function(patient) {
+ return {
+ label: patient.unique_label,
+ id: patient.id
+ };
+ });
+ response(list);
+ },
+ error: function(jqXHR, textStatus, errorThrown) {
+ var msg = "An error occurred. Please contact an administrator.";
+ response({ label: msg, id: 0});
+ }
+ });
},
search: function(event, ui) {
$(target).val(""); |
cf3200a37bf58f26cf8ffe9f8650bd9d39bffbc5 | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-istanbul");
var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output";
var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts";
grunt.initConfig({
mochaTest: {
test: {
src: ["test/**/*.js"]
},
ci: {
src: ["test/**/*.js"],
options: {
reporter: "xunit",
captureFile: testOutputLocation + "/mocha/results.xml",
quiet: true
}
}
},
mocha_istanbul: {
coverage: {
src: ["test/**/*.js"],
options: {
coverageFolder: artifactsLocation + "/coverage",
check: {
lines: 100,
statements: 100,
branches: 100,
functions: 100
},
reportFormats: ["lcov"]
}
}
}
});
grunt.registerTask("test", ["mochaTest:test", "mocha_istanbul"]);
grunt.registerTask("ci-test", ["mochaTest:ci", "mocha_istanbul"]);
grunt.registerTask("default", "test");
};
| module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-mocha-istanbul");
var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output";
var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts";
grunt.initConfig({
mochaTest: {
test: {
src: ["test/**/*.js"]
},
ci: {
src: ["test/**/*.js"],
options: {
reporter: "xunit",
captureFile: testOutputLocation + "/mocha/results.xml",
quiet: true
}
}
},
mocha_istanbul: {
coverage: {
src: ["test/**/*.js"],
options: {
coverageFolder: artifactsLocation,
check: {
lines: 100,
statements: 100,
branches: 100,
functions: 100
},
reportFormats: ["lcov"]
}
}
}
});
grunt.registerTask("test", ["mochaTest:test", "mocha_istanbul"]);
grunt.registerTask("ci-test", ["mochaTest:ci", "mocha_istanbul"]);
grunt.registerTask("default", "test");
};
| Change artifact location to suite CircleCI | Change artifact location to suite CircleCI
| JavaScript | mit | JMiknys/todo-grad-project-justas,JMiknys/todo-grad-project-justas | ---
+++
@@ -22,7 +22,7 @@
coverage: {
src: ["test/**/*.js"],
options: {
- coverageFolder: artifactsLocation + "/coverage",
+ coverageFolder: artifactsLocation,
check: {
lines: 100,
statements: 100, |
a0aa49e9d906a644f8eae3ae85bb83a1d7bbcdde | packages/lesswrong/components/recommendations/withContinueReading.js | packages/lesswrong/components/recommendations/withContinueReading.js | import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import { getFragment } from 'meteor/vulcan:core';
export const withContinueReading = component => {
// FIXME: For some unclear reason, using a ...fragment in the 'sequence' part
// of this query doesn't work (leads to a 400 Bad Request), so this is expanded
// out to a short list of individual fields.
const continueReadingQuery = gql`
query ContinueReadingQuery {
ContinueReading {
sequence {
_id
title
gridImageId
canonicalCollectionSlug
}
collection {
_id
title
slug
}
lastReadPost {
...PostsList
}
nextPost {
...PostsList
}
numRead
numTotal
lastReadTime
}
}
${getFragment("PostsList")}
`;
return graphql(continueReadingQuery,
{
alias: "withContinueReading",
options: (props) => ({
variables: {}
}),
props(props) {
return {
continueReadingLoading: props.data.loading,
continueReading: props.data.ContinueReading,
}
}
}
)(component);
}
| import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import { getFragment } from 'meteor/vulcan:core';
export const withContinueReading = component => {
// FIXME: For some unclear reason, using a ...fragment in the 'sequence' part
// of this query doesn't work (leads to a 400 Bad Request), so this is expanded
// out to a short list of individual fields.
const continueReadingQuery = gql`
query ContinueReadingQuery {
ContinueReading {
sequence {
_id
title
gridImageId
canonicalCollectionSlug
}
collection {
_id
title
slug
gridImageId
}
lastReadPost {
...PostsList
}
nextPost {
...PostsList
}
numRead
numTotal
lastReadTime
}
}
${getFragment("PostsList")}
`;
return graphql(continueReadingQuery,
{
alias: "withContinueReading",
options: (props) => ({
variables: {}
}),
props(props) {
return {
continueReadingLoading: props.data.loading,
continueReading: props.data.ContinueReading,
}
}
}
)(component);
}
| Add gridImageId to continueReading fragments | Add gridImageId to continueReading fragments
| JavaScript | mit | Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope | ---
+++
@@ -19,6 +19,7 @@
_id
title
slug
+ gridImageId
}
lastReadPost {
...PostsList |
d48742aa5a3002b347cf284ea28777a91d300f1b | client/app/components/components.js | client/app/components/components.js | import angular from 'angular';
import Dogs from './dogs/dogs';
import DogProfile from './dog-profile/dog-profile';
import Users from './users/users';
import DogPost from './dog-post/dog-post';
import UserPost from './user-post/user-post';
let componentModule = angular.module('app.components', [
Dogs,
Users,
DogProfile,
DogPost,
UserPost
])
.name;
export default componentModule;
| import angular from 'angular';
import Auth from './auth/auth';
import Signup from './signup/signup';
import Dogs from './dogs/dogs';
import DogProfile from './dog-profile/dog-profile';
import Users from './users/users';
import DogPost from './dog-post/dog-post';
import UserPost from './user-post/user-post';
let componentModule = angular.module('app.components', [
Signup,
Auth,
Dogs,
Users,
DogProfile,
DogPost,
UserPost
])
.name;
export default componentModule;
| Add to auth and signup component | Add to auth and signup component
| JavaScript | apache-2.0 | nickpeleh/dogs-book,nickpeleh/dogs-book | ---
+++
@@ -1,4 +1,6 @@
import angular from 'angular';
+import Auth from './auth/auth';
+import Signup from './signup/signup';
import Dogs from './dogs/dogs';
import DogProfile from './dog-profile/dog-profile';
import Users from './users/users';
@@ -6,6 +8,8 @@
import UserPost from './user-post/user-post';
let componentModule = angular.module('app.components', [
+ Signup,
+ Auth,
Dogs,
Users,
DogProfile, |
c343c6ee7fb3c2f545b082c06c21f3fbb93a4585 | src/extension/index.js | src/extension/index.js | import {
setupTokenEditor,
setTokenEditorValue,
useDefaultToken
} from '../editor';
import { getParameterByName } from '../utils.js';
import { publicKeyTextArea } from './dom-elements.js';
/* For initialization, look at the end of this file */
function parseLocationQuery() {
const publicKey = getParameterByName('publicKey');
const value = getParameterByName('value');
const token = getParameterByName('token');
if(publicKey) {
publicKeyTextArea.value = publicKey;
}
if(value) {
setTokenEditorValue(value);
}
if(token) {
setTokenEditorValue(token);
}
}
function loadToken() {
const lastToken = localStorage.getItem('lastToken');
if(lastToken) {
setTokenEditorValue(value);
const lastPublicKey = localStorage.getItem('lastPublicKey');
if(lastPublicKey) {
publicKeyTextArea.value = lastPublicKey;
}
} else {
useDefaultToken('HS256');
}
}
// Initialization
setupTokenEditor();
loadToken();
parseLocationQuery();
| import {
setupTokenEditor,
setTokenEditorValue,
useDefaultToken
} from '../editor';
import { publicKeyTextArea } from './dom-elements.js';
/* For initialization, look at the end of this file */
function loadToken() {
const lastToken = localStorage.getItem('lastToken');
if(lastToken) {
setTokenEditorValue(value);
const lastPublicKey = localStorage.getItem('lastPublicKey');
if(lastPublicKey) {
publicKeyTextArea.value = lastPublicKey;
}
} else {
useDefaultToken('HS256');
}
}
// Initialization
setupTokenEditor();
loadToken();
| Remove unnecessary code for the extension. | Remove unnecessary code for the extension.
| JavaScript | mit | nov/jsonwebtoken.github.io,simo5/jsonwebtoken.github.io,simo5/jsonwebtoken.github.io,nov/jsonwebtoken.github.io | ---
+++
@@ -3,26 +3,9 @@
setTokenEditorValue,
useDefaultToken
} from '../editor';
-import { getParameterByName } from '../utils.js';
import { publicKeyTextArea } from './dom-elements.js';
/* For initialization, look at the end of this file */
-
-function parseLocationQuery() {
- const publicKey = getParameterByName('publicKey');
- const value = getParameterByName('value');
- const token = getParameterByName('token');
-
- if(publicKey) {
- publicKeyTextArea.value = publicKey;
- }
- if(value) {
- setTokenEditorValue(value);
- }
- if(token) {
- setTokenEditorValue(token);
- }
-}
function loadToken() {
const lastToken = localStorage.getItem('lastToken');
@@ -41,4 +24,3 @@
// Initialization
setupTokenEditor();
loadToken();
-parseLocationQuery(); |
8afb86988829ead1404efdfa4bccf77fb983a08e | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
grunt.registerTask("default", ["test-server", "test-client"]);
grunt.registerTask("test-client", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/client"]});
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/client.js"]}, function(error) {
done(!error);
});
});
grunt.registerTask("test-server", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/server"]});
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/server.js"]}, function(error) {
done(!error);
});
});
}; | module.exports = function(grunt) {
grunt.registerTask("default", ["test-server", "test-client"]);
grunt.registerTask("test-client", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/client"]});
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/client.js", "--reporter", "spec"]}, function(error) {
done(!error);
});
});
grunt.registerTask("test-server", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/server"]});
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/server.js", "--reporter", "spec"]}, function(error) {
done(!error);
});
});
}; | Change mocha's reporter type to spec | Change mocha's reporter type to spec | JavaScript | apache-2.0 | vibe-project/vibe-protocol | ---
+++
@@ -3,14 +3,14 @@
grunt.registerTask("test-client", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/client"]});
- grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/client.js"]}, function(error) {
+ grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/client.js", "--reporter", "spec"]}, function(error) {
done(!error);
});
});
grunt.registerTask("test-server", function() {
var done = this.async();
grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/server"]});
- grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/server.js"]}, function(error) {
+ grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/server.js", "--reporter", "spec"]}, function(error) {
done(!error);
});
}); |
a8dc6903bbeb207b63fcde2f318501d27052ec07 | js/background.js | js/background.js | chrome.tabs.onCreated.addListener(function(tab) {
console.log("Tab Created", tab);
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
console.log("Tab changed: #" + tabId, changeInfo, tab );
});
chrome.browserAction.onClicked.addListener(function() {
console.log("Browser action clicked!");
}); | chrome.tabs.onCreated.addListener(function(tab) {
console.log("Tab Created", tab);
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
console.log("Tab changed: #" + tabId, changeInfo, tab );
});
chrome.storage.sync.get(null, function(items) {
console.log("All items in synced storage", items );
});
chrome.storage.sync.set({name : "Pierce Moore", _config : _config }, function() {
console.log("Set name to Pierce Moore");
});
chrome.storage.sync.get("name", function(items) {
console.log("Name in synced storage", items );
});
chrome.storage.sync.get(null, function(items) {
console.log("All items in synced storage", items );
});
chrome.storage.sync.getBytesInUse(null, function(bytes) {
console.log("Total bytes in use:" + bytes + " bytes");
});
var d = new Date();
console.log(d.toUTCString()); | Set of generic functions to test the chrome.* APIs | Set of generic functions to test the chrome.* APIs
| JavaScript | bsd-3-clause | rex/BANTP | ---
+++
@@ -6,6 +6,26 @@
console.log("Tab changed: #" + tabId, changeInfo, tab );
});
-chrome.browserAction.onClicked.addListener(function() {
- console.log("Browser action clicked!");
+chrome.storage.sync.get(null, function(items) {
+ console.log("All items in synced storage", items );
});
+
+chrome.storage.sync.set({name : "Pierce Moore", _config : _config }, function() {
+ console.log("Set name to Pierce Moore");
+});
+
+chrome.storage.sync.get("name", function(items) {
+ console.log("Name in synced storage", items );
+});
+
+chrome.storage.sync.get(null, function(items) {
+ console.log("All items in synced storage", items );
+});
+
+chrome.storage.sync.getBytesInUse(null, function(bytes) {
+ console.log("Total bytes in use:" + bytes + " bytes");
+});
+
+var d = new Date();
+
+console.log(d.toUTCString()); |
d8a2c541823fad0a5d1458a08e991ca4cc7fd216 | Gruntfile.js | Gruntfile.js | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['gruntfile.js', 'lib/**/*.js', 'test/**/*.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: 'test/lib',
options: {
coverage: true,
legend: true,
check: {
lines: 90,
statements: 90
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('default', ['test'])
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
}
| 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['gruntfile.js', 'lib/**/*.js', 'test/**/*.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: 'test/lib',
options: {
coverage: true,
legend: true,
check: {
lines: 68,
statements: 70
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('default', ['test'])
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
}
| Adjust limits to meet what we have currently | Adjust limits to meet what we have currently
| JavaScript | apache-2.0 | xmpp-ftw/xmpp-ftw | ---
+++
@@ -24,8 +24,8 @@
coverage: true,
legend: true,
check: {
- lines: 90,
- statements: 90
+ lines: 68,
+ statements: 70
},
root: './lib',
reportFormats: ['lcov'] |
2c001cfd50d80bae25de6adce09a11926de9a991 | Gruntfile.js | Gruntfile.js | module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ['.tmp'],
babel: {
options: {
sourceMap: true
},
dist: {
files: {
'dist/index.js': 'src/index.js'
}
},
test: {
files: {
'.tmp/tests.js': 'test/tests.js'
}
}
},
jshint: {
all: [
'Gruntfile.js',
'src/**/*.js',
'test/**/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
mochacli: {
all: ['.tmp/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd',
timeout: 10000
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-cli');
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('build', ['babel:dist']);
grunt.registerTask('test', ['jshint', 'build', 'babel:test', 'mochacli']);
grunt.registerTask('default', ['test']);
};
| module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ['.tmp'],
babel: {
options: {
sourceMap: true
},
dist: {
files: {
'dist/index.js': 'src/index.js'
}
},
test: {
files: {
'.tmp/tests.js': 'test/tests.js'
}
}
},
jshint: {
all: [
'Gruntfile.js',
'src/**/*.js',
'test/**/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
mochacli: {
all: ['.tmp/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd',
timeout: 10000,
bail: 'true'
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-cli');
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('build', ['babel:dist']);
grunt.registerTask('test', ['jshint', 'build', 'babel:test', 'mochacli']);
grunt.registerTask('default', ['test']);
};
| Add bail option to mochacli to halt on the first failed test. | Add bail option to mochacli to halt on the first failed test.
| JavaScript | mit | khornberg/simplenote | ---
+++
@@ -32,7 +32,8 @@
options: {
reporter: 'spec',
ui: 'tdd',
- timeout: 10000
+ timeout: 10000,
+ bail: 'true'
}
}
}); |
c8656f406dcefc83c8eec14a6607c7f334f37607 | Gruntfile.js | Gruntfile.js | /*
* generator-init
* https://github.com/use-init/generator-init
*
*/
'use strict';
module.exports = function (grunt) {
// Load all grunt tasks matching the `grunt-*` pattern.
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'app/index.js',
'<%= mochaTest.test.src%>'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tests/temp']
},
// Unit tests.
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/*.js']
}
}
});
// Whenever the "test" task is run, first clean the "temp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'mochaTest']);
// By default, lint and run all tests.
grunt.registerTask('default', ['clean', 'jshint', 'mochaTest']);
};
| /*
* generator-init
* https://github.com/use-init/generator-init
*
*/
'use strict';
module.exports = function (grunt) {
// Load all grunt tasks matching the `grunt-*` pattern.
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'app/index.js',
'lib/*.js',
'page/index.js',
'module/index.js',
'jqueryplugin/index.js',
'page/index.js',
'<%= mochaTest.test.src%>'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tests/temp']
},
// Unit tests.
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/*.js']
}
}
});
// Whenever the "test" task is run, first clean the "temp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'mochaTest']);
// By default, lint and run all tests.
grunt.registerTask('default', ['clean', 'jshint', 'mochaTest']);
};
| Add all JS files to JSHint | Add all JS files to JSHint
| JavaScript | mit | use-init/generator-init,use-init/generator-init | ---
+++
@@ -16,6 +16,11 @@
all: [
'Gruntfile.js',
'app/index.js',
+ 'lib/*.js',
+ 'page/index.js',
+ 'module/index.js',
+ 'jqueryplugin/index.js',
+ 'page/index.js',
'<%= mochaTest.test.src%>'
],
options: { |
b3138e99e44b96027ed4d1d3ffdc146d49bb52d2 | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'), // the package file to use
qunit: { // internal task or name of a plugin (like "qunit")
all: ['js/tests/*.html']
},
watch: {
files: [
'js/tests/*.js',
'js/tests/*.html',
'tmpl/*.html',
'js/*.js',
'src/*.go'
],
tasks: ['qunit', 'shell:buildGo', 'shell:testGo']
},
shell: {
buildGo: {
command: function() {
var gitCmd = 'git rev-parse --short HEAD';
return 'go build -o build/rtfblog' +
' -ldflags "-X main.genVer $(' + gitCmd + ')"' +
' src/*.go';
},
options: {
stdout: true,
stderr: true
}
},
testGo: {
command: 'go test ./src/...',
options: {
stdout: true,
stderr: true
}
}
}
});
// load up your plugins
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-shell');
// register one or more task lists (you should ALWAYS have a "default" task list)
grunt.registerTask('default', ['qunit', 'shell:buildGo', 'shell:testGo']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'), // the package file to use
qunit: { // internal task or name of a plugin (like "qunit")
all: ['js/tests/*.html']
},
watch: {
files: [
'js/tests/*.js',
'js/tests/*.html',
'tmpl/*.html',
'js/*.js',
'src/*.go'
],
tasks: ['qunit', 'shell:buildGo', 'shell:testGo']
},
shell: {
buildGo: {
command: function() {
var gitCmd = 'git rev-parse --short HEAD';
return 'go build -o build/rtfblog' +
' -ldflags "-X main.genVer=$(' + gitCmd + ')"' +
' src/*.go';
},
options: {
stdout: true,
stderr: true
}
},
testGo: {
command: 'go test ./src/...',
options: {
stdout: true,
stderr: true
}
}
}
});
// load up your plugins
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-shell');
// register one or more task lists (you should ALWAYS have a "default" task list)
grunt.registerTask('default', ['qunit', 'shell:buildGo', 'shell:testGo']);
};
| Fix warning, add assignment operator | Fix warning, add assignment operator
| JavaScript | bsd-2-clause | rtfb/rtfblog,rtfb/rtfblog,rtfb/rtfblog,rtfb/rtfblog,rtfb/rtfblog | ---
+++
@@ -20,7 +20,7 @@
command: function() {
var gitCmd = 'git rev-parse --short HEAD';
return 'go build -o build/rtfblog' +
- ' -ldflags "-X main.genVer $(' + gitCmd + ')"' +
+ ' -ldflags "-X main.genVer=$(' + gitCmd + ')"' +
' src/*.go';
},
options: { |
f0299893c99537b1d23c54fbdbd04b463a6eed26 | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
'use strict';
grunt.initConfig({
benchmark: {
all: {
src: ['benchmarks/*.js'],
options: { times: 10 }
}
},
nodeunit: {
files: ['test/*_test.js'],
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*_test.js']
},
}
});
grunt.loadNpmTasks('grunt-benchmark');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
| module.exports = function(grunt) {
'use strict';
grunt.initConfig({
benchmark: {
all: {
src: ['benchmarks/*.js'],
options: { times: 10 }
}
},
nodeunit: {
files: ['test/*_test.js'],
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*_test.js']
},
},
});
// Dynamic alias task to nodeunit. Run individual tests with: grunt test:events
grunt.registerTask('test', function(file) {
grunt.config('nodeunit.files', String(grunt.config('nodeunit.files')).replace('*', file || '*'));
grunt.task.run('nodeunit');
});
grunt.loadNpmTasks('grunt-benchmark');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
| Add dynamic alias task for running individual tests | Add dynamic alias task for running individual tests
| JavaScript | mit | modulexcite/gaze,prodatakey/gaze,prodatakey/gaze,shama/gaze,modulexcite/gaze,chebum/gaze,bevacqua/gaze,bevacqua/gaze,modulexcite/gaze,bevacqua/gaze,prodatakey/gaze | ---
+++
@@ -23,8 +23,15 @@
test: {
src: ['test/**/*_test.js']
},
- }
+ },
});
+
+ // Dynamic alias task to nodeunit. Run individual tests with: grunt test:events
+ grunt.registerTask('test', function(file) {
+ grunt.config('nodeunit.files', String(grunt.config('nodeunit.files')).replace('*', file || '*'));
+ grunt.task.run('nodeunit');
+ });
+
grunt.loadNpmTasks('grunt-benchmark');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit'); |
34080a9b4d3835b0cde39503ab2c1ab48e7c06ab | src/components/logger/logger.js | src/components/logger/logger.js | import intelLogger from 'intel'
import joi from 'joi'
import { validateObject } from '../../core'
/**
* Returns config data and its schema
* @param {Object} env
* @returns {SchemedData}
*/
function getConfig(env) {
/**
* Log level compatible with intel module
* Valid values: ALL, TRACE, VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL, NONE
* @enum {string}
*/
const { LOG_LEVEL = 'INFO' } = env
return {
data: {
logLevel: LOG_LEVEL,
},
schema: {
logLevel: joi.string()
.only([ 'ALL', 'TRACE', 'VERBOSE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL', 'NONE' ])
}
}
}
/**
* Returns logger service
* @param {Object} deps Appi dependencies
* @param {Object} deps.env Env dependency
* @returns {Logger} Configured intel logger
*/
export function logger(deps) {
const config = validateObject(getConfig(deps.env))
intelLogger.setLevel(config.logLevel)
intelLogger.addHandler(new intelLogger.handlers.Console({
formatter: new intelLogger.Formatter({
format: '[%(date)s] %(name)s.%(levelname)s: %(message)s',
datefmt: '%Y-%m-%d %H:%M-%S',
colorize: true,
})
}))
return intelLogger
}
logger.isAppiComponent = true
| import intelLogger from 'intel'
import joi from 'joi'
import { validateObject } from '../../core'
/**
* Returns config data and its schema
* @param {Object} env
* @returns {SchemedData}
*/
function getConfig(env) {
/**
* Log level compatible with intel module
* Valid values: ALL, TRACE, VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL, NONE
* @enum {string}
*/
const { LOG_LEVEL = 'INFO' } = env
return {
data: {
logLevel: LOG_LEVEL,
},
schema: {
logLevel: joi.string()
.only([ 'ALL', 'TRACE', 'VERBOSE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL', 'NONE' ])
}
}
}
/**
* Returns logger service
* @param {Object} deps Appi dependencies
* @param {Object} deps.env Env dependency
* @returns {Logger} Configured intel logger
*/
export function logger(deps) {
const config = validateObject(getConfig(deps.env))
intelLogger.setLevel(config.logLevel)
intelLogger.addHandler(new intelLogger.handlers.Console({
formatter: new intelLogger.Formatter({
format: '[%(date)s] %(name)s.%(levelname)s: %(message)s',
datefmt: '%Y-%m-%d %H:%M-%S',
colorize: true,
})
}))
return intelLogger
}
logger.componentName = 'logger'
| Align Logger component with new AppiComponent api | Align Logger component with new AppiComponent api
| JavaScript | apache-2.0 | labs42/appi | ---
+++
@@ -55,4 +55,4 @@
}
-logger.isAppiComponent = true
+logger.componentName = 'logger' |
26e8ca7ae9a2e4123886c5cbbb549c76219473d0 | src/popper/utils/findCommonOffsetParent.js | src/popper/utils/findCommonOffsetParent.js | import isOffsetContainer from './isOffsetContainer';
export default function findCommonOffsetParent(element1, element2) {
const range = document.createRange();
if (element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING) {
range.setStart(element1, 0);
range.setEnd(element2, 0);
} else {
range.setStart(element2, 0);
range.setEnd(element1, 0);
}
const { commonAncestorContainer } = range;
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
// This is probably very stupid, fix me please
if (!commonAncestorContainer) {
return window.document.documentElement;
}
const offsetParent = commonAncestorContainer.offsetParent;
return offsetParent.nodeName === 'BODY' ? document.documentElement : offsetParent;
}
| import isOffsetContainer from './isOffsetContainer';
export default function findCommonOffsetParent(element1, element2) {
const range = document.createRange();
if (element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING) {
range.setStart(element1, 0);
range.setEnd(element2, 0);
} else {
range.setStart(element2, 0);
range.setEnd(element1, 0);
}
const { commonAncestorContainer } = range;
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
// This is probably very stupid, fix me please
if (!commonAncestorContainer) {
return window.document.documentElement;
}
const offsetParent = commonAncestorContainer.offsetParent;
if (!offsetParent || offsetParent && offsetParent.nodeName === 'BODY') {
return document.documentElement;
}
return offsetParent;
}
| Return document if offsetParent is null | Return document if offsetParent is null
This because `.offsetParent` null is returned by documentElement
| JavaScript | mit | imkremen/popper.js,imkremen/popper.js | ---
+++
@@ -22,5 +22,9 @@
const offsetParent = commonAncestorContainer.offsetParent;
- return offsetParent.nodeName === 'BODY' ? document.documentElement : offsetParent;
+ if (!offsetParent || offsetParent && offsetParent.nodeName === 'BODY') {
+ return document.documentElement;
+ }
+
+ return offsetParent;
} |
795bdb81899bff86df89174ceeaa5173999a7de2 | hypem-resolver.js | hypem-resolver.js | // Copyright 2015 Fabian Dietenberger
'use-strict'
var q = require('q'),
request = require('request');
var hypemResolver = {};
hypemResolver.getUrl = function (hypemUrl) {
var resultUrl = "";
return resultUrl;
};
module.exports = hypemResolver; | // Copyright 2015 Fabian Dietenberger
'use-strict'
var q = require('q'),
request = require('request');
var hypemResolver = {};
hypemResolver.getByUrl = function (hypemUrl) {
var resultUrl = "";
return resultUrl;
};
hypemResolver.getById = function (hypemId) {
return this.getByUrl("http://hypem.com/track/" + hypemId);
};
module.exports = hypemResolver; | Split get method into 2 single methods for url and id | Split get method into 2 single methods for url and id
| JavaScript | mit | feedm3/hypem-resolver | ---
+++
@@ -7,9 +7,13 @@
var hypemResolver = {};
-hypemResolver.getUrl = function (hypemUrl) {
+hypemResolver.getByUrl = function (hypemUrl) {
var resultUrl = "";
return resultUrl;
};
+hypemResolver.getById = function (hypemId) {
+ return this.getByUrl("http://hypem.com/track/" + hypemId);
+};
+
module.exports = hypemResolver; |
fe74c923958c21f8706fbca6e4da8a9cfb1b6a1d | src/server/migrations/0.3.0-0.4.0/index.js | src/server/migrations/0.3.0-0.4.0/index.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const database = require('../../models/database');
const sqlFile = database.sqlFile;
module.exports = {
fromVersion: '0.3.0',
toVersion: '0.4.0',
up: async db => {
try {
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/create_language_types_enum.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/add_language_column.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql'));
} catch (err) {
throw new Error('Error while migrating each sql file');
}
}
};
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const database = require('../../models/database');
const sqlFile = database.sqlFile;
module.exports = {
fromVersion: '0.3.0',
toVersion: '0.4.0',
up: async db => {
try {
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/create_language_types_enum.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/add_language_column.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/compareReadings/create_function_get_compare_readings.sql'));
} catch (err) {
throw new Error('Error while migrating each sql file');
}
}
};
| Set migration for compare_readings/group_compare_readings sql functions | Set migration for compare_readings/group_compare_readings sql functions
| JavaScript | mpl-2.0 | OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED | ---
+++
@@ -15,6 +15,7 @@
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql'));
+ await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/compareReadings/create_function_get_compare_readings.sql'));
} catch (err) {
throw new Error('Error while migrating each sql file');
} |
1f71f06920d43c2c8ff3b670e9355033eaed7f11 | src/telemetry.js | src/telemetry.js | // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
"use strict";
var appInsights = require("applicationinsights");
const telemetry = {
appInsights: appInsights,
trackEvent: function () {
},
trackException: function () {
}
};
telemetry.instrumentationKey = "";
telemetry.createClient = function () {
var client = new appInsights.TelemetryClient(telemetry.instrumentationKey);
client.config.maxBatchIntervalMs = 0;
return client;
};
/**
* Sets up collection of telemetry.
* @param {String} [instrumentationKey=null] - The optional instrumentation key to use.
*/
telemetry.setup = function (instrumentationKey) {
if (instrumentationKey) {
telemetry.instrumentationKey = instrumentationKey;
telemetry.appInsights.setup(instrumentationKey).start();
telemetry.trackEvent = function (name, properties) {
telemetry.createClient().trackEvent({
name: name,
properties: properties
});
};
telemetry.trackException = function (exception, properties) {
telemetry.createClient().trackException({
exception: exception,
properties: properties
});
};
}
};
module.exports = telemetry;
| // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
"use strict";
var appInsights = require("applicationinsights");
const telemetry = {
appInsights: appInsights,
trackEvent: function () {
},
trackException: function () {
}
};
telemetry.instrumentationKey = "";
telemetry.createClient = function () {
var client = new appInsights.TelemetryClient(telemetry.instrumentationKey);
// Prevent Lambda function from hanging and timing out.
// See https://github.com/martincostello/alexa-london-travel/issues/45.
client.config.maxBatchIntervalMs = 0;
client.config.maxBatchSize = 1;
return client;
};
/**
* Sets up collection of telemetry.
* @param {String} [instrumentationKey=null] - The optional instrumentation key to use.
*/
telemetry.setup = function (instrumentationKey) {
if (instrumentationKey) {
telemetry.instrumentationKey = instrumentationKey;
telemetry.appInsights.setup(instrumentationKey).start();
telemetry.trackEvent = function (name, properties) {
telemetry.createClient().trackEvent({
name: name,
properties: properties
});
};
telemetry.trackException = function (exception, properties) {
telemetry.createClient().trackException({
exception: exception,
properties: properties
});
};
}
};
module.exports = telemetry;
| Set ApplicationInsights batch size to 1 | Set ApplicationInsights batch size to 1
Set the batch size for ApplicationInsights to 1 to try and prevent setTimeout() ever being called and causing the lambda function to timeout from hanging.
Relates to #45.
| JavaScript | apache-2.0 | martincostello/alexa-london-travel | ---
+++
@@ -17,7 +17,12 @@
telemetry.createClient = function () {
var client = new appInsights.TelemetryClient(telemetry.instrumentationKey);
+
+ // Prevent Lambda function from hanging and timing out.
+ // See https://github.com/martincostello/alexa-london-travel/issues/45.
client.config.maxBatchIntervalMs = 0;
+ client.config.maxBatchSize = 1;
+
return client;
};
|
9ba3095bdc0a81a1546634160f2a20c3a0196d51 | src/time_slot.js | src/time_slot.js | Occasion.Modules.push(function(library) {
library.TimeSlot = class TimeSlot extends library.Base {};
library.TimeSlot.className = 'TimeSlot';
library.TimeSlot.queryName = 'time_slots';
library.TimeSlot.belongsTo('product');
library.TimeSlot.belongsTo('venue');
library.TimeSlot.afterRequest(function() {
if(this.product().merchant()) {
this.startsAt = moment.tz(this.startsAt, this.product().merchant().timeZone);
} else {
throw 'Must use includes({ product: \'merchant\' }) in timeSlot request';
}
this.duration = moment.duration(this.duration, 'minutes');
});
});
| Occasion.Modules.push(function(library) {
library.TimeSlot = class TimeSlot extends library.Base {};
library.TimeSlot.className = 'TimeSlot';
library.TimeSlot.queryName = 'time_slots';
library.TimeSlot.belongsTo('order');
library.TimeSlot.belongsTo('product');
library.TimeSlot.belongsTo('venue');
library.TimeSlot.afterRequest(function() {
if(this.product().merchant()) {
this.startsAt = moment.tz(this.startsAt, this.product().merchant().timeZone);
} else {
throw 'Must use includes({ product: \'merchant\' }) in timeSlot request';
}
this.duration = moment.duration(this.duration, 'minutes');
});
});
| Add TimeSlot belongsTo order relationship | Add TimeSlot belongsTo order relationship
| JavaScript | mit | nicklandgrebe/occasion-sdk-js | ---
+++
@@ -4,6 +4,7 @@
library.TimeSlot.className = 'TimeSlot';
library.TimeSlot.queryName = 'time_slots';
+ library.TimeSlot.belongsTo('order');
library.TimeSlot.belongsTo('product');
library.TimeSlot.belongsTo('venue');
|
b447e585b0c77739315677deb367140184d24a17 | src/models/reminder.js | src/models/reminder.js | const mongoose = require('mongoose');
const reminderSchema = new mongoose.Schema({
user_address: { type: Object, required: true, index: true },
value: { type: String, required: true },
expiration: { type: Date, required: true }
});
module.exports = mongoose.model('Reminder', reminderSchema); | const mongoose = require('mongoose');
const reminderSchema = new mongoose.Schema({
user_address: {
useAuth: Boolean,
serviceUrl: String,
bot: {
name: String,
id: String
},
conversation: {
id: String,
isGroup: Boolean
},
user: {
name: { type: String, index: true },
id: String
},
channelId: String,
id: String
},
value: { type: String, required: true },
expiration: { type: Date, required: true }
});
module.exports = mongoose.model('Reminder', reminderSchema); | Improve mongoose schema, index user.name | Improve mongoose schema, index user.name
| JavaScript | mit | sebsylvester/reminder-bot | ---
+++
@@ -1,7 +1,24 @@
const mongoose = require('mongoose');
const reminderSchema = new mongoose.Schema({
- user_address: { type: Object, required: true, index: true },
+ user_address: {
+ useAuth: Boolean,
+ serviceUrl: String,
+ bot: {
+ name: String,
+ id: String
+ },
+ conversation: {
+ id: String,
+ isGroup: Boolean
+ },
+ user: {
+ name: { type: String, index: true },
+ id: String
+ },
+ channelId: String,
+ id: String
+ },
value: { type: String, required: true },
expiration: { type: Date, required: true }
}); |
26fa40b50deee67a1ce8711ef5f35a7cd977c18d | src/openpoliticians.js | src/openpoliticians.js | "use strict";
var cors = require('cors');
var originWhitelist = [
'http://openpoliticians.org',
'http://localhost:4000',
];
var openPoliticiansCors = cors({
origin: function(origin, callback) {
var originIsWhitelisted = originWhitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
},
credentials: true,
});
module.exports = openPoliticiansCors;
| "use strict";
var cors = require('cors');
var originWhitelist = [
'http://openpoliticians.org',
'http://everypolitician.org',
'http://localhost:4000',
];
var openPoliticiansCors = cors({
origin: function(origin, callback) {
var originIsWhitelisted = originWhitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
},
credentials: true,
});
module.exports = openPoliticiansCors;
| Add everypolitician.org to allowed CORS addresses | Add everypolitician.org to allowed CORS addresses
| JavaScript | agpl-3.0 | Sinar/popit-api,mysociety/popit-api,mysociety/popit-api,Sinar/popit-api | ---
+++
@@ -4,6 +4,7 @@
var originWhitelist = [
'http://openpoliticians.org',
+ 'http://everypolitician.org',
'http://localhost:4000',
];
|
9fad0a8e69069226f4d7efeec98410e453044ba8 | realtime/index.js | realtime/index.js | const io = require('socket.io'),
winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = 3031;
winston.info('Rupture real-time service starting');
winston.info('Listening on port ' + PORT);
var socket = io.listen(PORT);
socket.on('connection', function(client) {
winston.info('New connection from client ' + client.id);
client.on('get-work', function() {
winston.info('get-work from client ' + client.id);
client.emit('do-work', {
url: 'https://facebook.com/?breach-test',
amount: 3,
timeout: 0
});
});
client.on('disconnect', function() {
winston.info('Client ' + client.id + ' disconnected');
});
});
| const io = require('socket.io'),
winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = 3031;
winston.info('Rupture real-time service starting');
winston.info('Listening on port ' + PORT);
var socket = io.listen(PORT);
socket.on('connection', function(client) {
winston.info('New connection from client ' + client.id);
client.on('get-work', function() {
winston.info('get-work from client ' + client.id);
client.emit('do-work', {
url: 'https://facebook.com/?breach-test',
amount: 1000,
timeout: 0
});
});
client.on('disconnect', function() {
winston.info('Client ' + client.id + ' disconnected');
});
});
| Switch experiment to performing 1000 parallel requests | Switch experiment to performing 1000 parallel requests
| JavaScript | mit | dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture | ---
+++
@@ -18,7 +18,7 @@
winston.info('get-work from client ' + client.id);
client.emit('do-work', {
url: 'https://facebook.com/?breach-test',
- amount: 3,
+ amount: 1000,
timeout: 0
});
}); |
0edf973af2efff8614ddae037eb28d5f2b178599 | ext/codecast/7.1/codecast-loader.js | ext/codecast/7.1/codecast-loader.js | $(document).ready(function() {
if (window.taskData) {
var taskInstructionsHtml = $('#taskIntro').html();
var hints = $('#taskHints > div').toArray().map(elm => {
return {
content: elm.innerHTML.trim()
};
});
var additionalOptions = window.taskData.codecastParameters ? window.taskData.codecastParameters : {};
if (window.codecastPreload) {
additionalOptions.preload = true;
}
var codecastParameters = $.extend(true, {
start: 'task',
showStepper: true,
showStack: true,
showViews: true,
showIO: true,
showDocumentation: true,
showFullScreen: true,
showMenu: true,
canRecord: false,
platform: 'python',
canChangePlatform: true,
canChangeLanguage: true,
controls: {},
// audioWorkerUrl: modulesPath + "ext/codecast/7.0/index.worker.worker.js",
baseUrl: "https://codecast.france-ioi.org/v7",
authProviders: ["algorea", "guest"],
task: window.taskData,
taskInstructions: taskInstructionsHtml,
taskHints: hints,
}, additionalOptions, window.codecastPreload ? window.codecastPreload : {});
Codecast.start(codecastParameters);
}
});
| $(document).ready(function() {
if (window.taskData) {
var taskInstructionsHtml = $('#taskIntro').html();
var hints = $('#taskHints > div').toArray().map(elm => {
return {
content: elm.innerHTML.trim()
};
});
var additionalOptions = window.taskData.codecastParameters ? window.taskData.codecastParameters : {};
if (window.codecastPreload) {
additionalOptions.preload = true;
}
if (!additionalOptions.language && window.stringsLanguage) {
additionalOptions.language = window.stringsLanguage;
}
var codecastParameters = $.extend(true, {
start: 'task',
showStepper: true,
showStack: true,
showViews: true,
showIO: true,
showDocumentation: true,
showFullScreen: true,
showMenu: true,
canRecord: false,
platform: 'python',
canChangePlatform: true,
canChangeLanguage: true,
controls: {},
// audioWorkerUrl: modulesPath + "ext/codecast/7.0/index.worker.worker.js",
baseUrl: "https://codecast.france-ioi.org/v7",
authProviders: ["algorea", "guest"],
task: window.taskData,
taskInstructions: taskInstructionsHtml,
taskHints: hints,
}, additionalOptions, window.codecastPreload ? window.codecastPreload : {});
Codecast.start(codecastParameters);
}
});
| Revert "Revert "Use window.stringsLanguage by default if fulfilled"" | Revert "Revert "Use window.stringsLanguage by default if fulfilled""
This reverts commit 6c738f09b3c930a90847440c564d65179417c469.
| JavaScript | mit | France-ioi/bebras-modules,France-ioi/bebras-modules | ---
+++
@@ -11,6 +11,9 @@
var additionalOptions = window.taskData.codecastParameters ? window.taskData.codecastParameters : {};
if (window.codecastPreload) {
additionalOptions.preload = true;
+ }
+ if (!additionalOptions.language && window.stringsLanguage) {
+ additionalOptions.language = window.stringsLanguage;
}
var codecastParameters = $.extend(true, { |
09bff03f5f74939ef6551625f2c453419f845c61 | request-logger.js | request-logger.js | var util = require('util');
var log = require('minilog')('http');
module.exports = function requestLogger(req, res, next) {
//
// Pretty much copypasta from
// https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L168-L174
//
// Monkey punching res.end. It's dirty but, maan I wanna log my status
// codes!
//
var end = res.end;
res.end = function (chunk, encoding) {
res.end = end;
res.end(chunk, encoding);
var remoteAddr = (function () {
if (req.ip) return req.ip;
var sock = req.socket;
if (sock.socket) return sock.socket.remoteAddress;
return sock.remoteAddress;
})(),
date = new Date().toUTCString(), // DEFINITELY not CLF-compatible.
method = req.method,
url = req.originalUrl || req.url,
httpVersion = req.httpVersionMajor + '.' + req.httpVersionMinor,
status = res.statusCode;
// Similar to, but not anywhere near compatible with, CLF. So don't try
// parsing it as CLF.
//
log.info(util.format(
'%s - - [%s] "%s %s HTTP/%s" %s',
remoteAddr,
date,
method,
url,
httpVersion,
status
));
};
next();
};
| var util = require('util');
var log = require('minilog')('http');
module.exports = function requestLogger(req, res, next) {
//
// Pretty much copypasta from
// https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L135-L158
//
// Monkey punching res.end. It's dirty but, maan I wanna log my status
// codes!
//
var end = res.end;
res.end = function (chunk, encoding) {
res.end = end;
res.end(chunk, encoding);
var remoteAddr = (function () {
if (req.ip) return req.ip;
var sock = req.socket;
if (sock.socket) return sock.socket.remoteAddress;
return sock.remoteAddress;
})(),
date = new Date().toUTCString(), // DEFINITELY not CLF-compatible.
method = req.method,
url = req.originalUrl || req.url,
httpVersion = req.httpVersionMajor + '.' + req.httpVersionMinor,
status = res.statusCode;
// Similar to, but not anywhere near compatible with, CLF. So don't try
// parsing it as CLF.
//
log.info(util.format(
'%s - - [%s] "%s %s HTTP/%s" %s',
remoteAddr,
date,
method,
url,
httpVersion,
status
));
};
next();
};
| Correct link in code comment | [minor] Correct link in code comment
| JavaScript | mit | chrismoulton/wzrd.in,rstr74/wzrd.in,jfhbrook/wzrd.in,jfhbrook/browserify-cdn,rstr74/wzrd.in,jfhbrook/wzrd.in,jfhbrook/browserify-cdn,tsatse/browserify-cdn,wraithgar/wzrd.in,tsatse/browserify-cdn,chrismoulton/wzrd.in,wraithgar/wzrd.in | ---
+++
@@ -6,7 +6,7 @@
//
// Pretty much copypasta from
- // https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L168-L174
+ // https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L135-L158
//
// Monkey punching res.end. It's dirty but, maan I wanna log my status
// codes! |
f3f2ed4622828fdce9ca809e32939548267cf406 | lib/node_modules/@stdlib/types/ndarray/ctor/lib/get2d.js | lib/node_modules/@stdlib/types/ndarray/ctor/lib/get2d.js | 'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {integer} i - index for first dimension
* @param {integer} j - index for second dimension
* @throws {TypeError} index for first dimension must be an integer value
* @throws {TypeError} index for second dimension must be an integer value
* @returns {*} array element
*/
function get( i, j ) {
/* eslint-disable no-invalid-this */
var idx;
if ( !isInteger( i ) ) {
throw new TypeError( 'invalid input argument. Index for first dimension must be an integer value. Value: `'+i+'`.' );
}
if ( !isInteger( j ) ) {
throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' );
}
// TODO: support index modes
idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j );
return this._buffer[ idx ];
} // end FUNCTION get()
// EXPORTS //
module.exports = get;
| 'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var getIndex = require( './get_index.js' );
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {integer} i - index for first dimension
* @param {integer} j - index for second dimension
* @throws {TypeError} index for first dimension must be an integer value
* @throws {TypeError} index for second dimension must be an integer value
* @returns {*} array element
*/
function get( i, j ) {
/* eslint-disable no-invalid-this */
var idx;
if ( !isInteger( i ) ) {
throw new TypeError( 'invalid input argument. Index for first dimension must be an integer value. Value: `'+i+'`.' );
}
if ( !isInteger( j ) ) {
throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' );
}
i = getIndex( i, this._shape[ 0 ], this._mode );
j = getIndex( j, this._shape[ 1 ], this._mode );
idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j );
return this._buffer[ idx ];
} // end FUNCTION get()
// EXPORTS //
module.exports = get;
| Add support for an index mode | Add support for an index mode
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -3,6 +3,7 @@
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
+var getIndex = require( './get_index.js' );
// FUNCTIONS //
@@ -26,8 +27,8 @@
if ( !isInteger( j ) ) {
throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' );
}
- // TODO: support index modes
-
+ i = getIndex( i, this._shape[ 0 ], this._mode );
+ j = getIndex( j, this._shape[ 1 ], this._mode );
idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j );
return this._buffer[ idx ];
} // end FUNCTION get() |
5620dd2921b534e1328c9305c66c254d04131797 | app/index.js | app/index.js | 'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var Generator = module.exports = function () {
var cb = this.async();
var ignores = [
'.git',
'CHANGELOG.md',
'CONTRIBUTING.md',
'LICENSE.md',
'README.md'
];
this.prompt([{
type: 'confirm',
name: 'docs',
message: 'Would you like docs included?',
default: false
}], function (props) {
if (props.docs) {
this.directory('doc');
}
this.directory('css');
this.directory('img');
this.directory('js');
this.expandFiles('*', {
cwd: this.sourceRoot(),
dot: true
}).forEach(function (el) {
if (ignores.indexOf(el) === -1) {
this.copy(el, el);
}
}, this);
cb();
}.bind(this));
};
util.inherits(Generator, yeoman.generators.Base);
Generator.name = 'HTML5 Boilerplate';
| 'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var Generator = module.exports = function Generator () {
yeoman.generators.Base.apply(this, arguments);
};
util.inherits(Generator, yeoman.generators.NamedBase);
Generator.prototype.copyFiles = function () {
var cb = this.async();
var ignores = [
'.git',
'CHANGELOG.md',
'CONTRIBUTING.md',
'LICENSE.md',
'README.md'
];
this.prompt([{
type: 'confirm',
name: 'docs',
message: 'Would you like docs included?',
default: false
}], function (props) {
if (props.docs) {
this.directory('doc');
}
this.directory('css');
this.directory('img');
this.directory('js');
this.expandFiles('*', {
cwd: this.sourceRoot(),
dot: true
}).forEach(function (el) {
if (ignores.indexOf(el) === -1) {
this.copy(el, el);
}
}, this);
cb();
}.bind(this));
};
Generator.name = 'HTML5 Boilerplate';
| Make generator work with `yo` v1.0.5 | Make generator work with `yo` v1.0.5
Ref #12.
Fix #11.
| JavaScript | mit | h5bp/generator-h5bp | ---
+++
@@ -3,7 +3,14 @@
var util = require('util');
var yeoman = require('yeoman-generator');
-var Generator = module.exports = function () {
+var Generator = module.exports = function Generator () {
+ yeoman.generators.Base.apply(this, arguments);
+};
+
+util.inherits(Generator, yeoman.generators.NamedBase);
+
+Generator.prototype.copyFiles = function () {
+
var cb = this.async();
var ignores = [
'.git',
@@ -37,8 +44,7 @@
cb();
}.bind(this));
+
};
-util.inherits(Generator, yeoman.generators.Base);
-
Generator.name = 'HTML5 Boilerplate'; |
7aee442d3b12698bb027c747a11719a075d9c586 | lib/autoprefix-processor.js | lib/autoprefix-processor.js | var autoprefixer = require('autoprefixer-core');
module.exports = function(less) {
function AutoprefixProcessor(options) {
this.options = options || {};
};
AutoprefixProcessor.prototype = {
process: function (css, extra) {
var options = this.options;
var sourceMap = extra.sourceMap;
var sourceMapInline, processOptions = {};
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
processOptions.from = sourceMap.getInputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true;
} else {
processOptions.map.prev = sourceMap.getExternalSourceMap();
processOptions.map.annotation = sourceMap.getSourceMapURL();
}
}
var processed = autoprefixer(options).process(css, processOptions);
if (sourceMap && !sourceMapInline) {
sourceMap.setExternalSourceMap(processed.map);
}
return processed.css;
}
};
return AutoprefixProcessor;
};
| var autoprefixer = require('autoprefixer-core');
module.exports = function(less) {
function AutoprefixProcessor(options) {
this.options = options || {};
};
AutoprefixProcessor.prototype = {
process: function (css, extra) {
var options = this.options;
var sourceMap = extra.sourceMap;
var sourceMapInline, processOptions = {};
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
// setting from = input filename works unless there is a directory,
// then autoprefixer adds the directory onto the source filename twice.
// setting to to anything else causes an un-necessary extra file to be
// added to the map, but its better than it failing
processOptions.from = sourceMap.getOutputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true;
} else {
processOptions.map.prev = sourceMap.getExternalSourceMap();
processOptions.map.annotation = sourceMap.getSourceMapURL();
}
}
var processed = autoprefixer(options).process(css, processOptions);
if (sourceMap && !sourceMapInline) {
sourceMap.setExternalSourceMap(processed.map);
}
return processed.css;
}
};
return AutoprefixProcessor;
};
| Fix sourcemaps when in a directory | Fix sourcemaps when in a directory
| JavaScript | apache-2.0 | less/less-plugin-autoprefix,PixnBits/less-plugin-autoprefix | ---
+++
@@ -14,7 +14,11 @@
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
- processOptions.from = sourceMap.getInputFilename();
+ // setting from = input filename works unless there is a directory,
+ // then autoprefixer adds the directory onto the source filename twice.
+ // setting to to anything else causes an un-necessary extra file to be
+ // added to the map, but its better than it failing
+ processOptions.from = sourceMap.getOutputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true; |
7df02298180fcd94019506f363392c48e0fe21cf | app.js | app.js | function Person(name)
{
this.name = name;
this.parent = null;
this.children = [];
this.siblings = [];
this.getChildren = function ()
{
return this.children;
}
};
var Nancy = new Person("Nancy")
var Adam = new Person("Adam")
var Jill = new Person("Jill")
var Carl = new Person("Carl")
Nancy.children.push(Adam, Jill, Carl)
console.log(Nancy.getChildren());
| var familyTree = [];
function Person(name)
{
this.name = name;
this.parent = null;
this.children = [];
this.siblings = [];
this.addChild = function(name)
{
var child = new Person(name)
child.parent = this
this.children.push(child);
};
this.init();
};
Person.prototype.init = function(){
familyTree.push(this)
};
//Driver test
console.log(familyTree);
var nancy = new Person("Nancy");
nancy.addChild("Adam")
console.log(familyTree);
| Restructure Person prototype and add family array | Restructure Person prototype and add family array
| JavaScript | mit | Nilaco/Family-Tree,Nilaco/Family-Tree | ---
+++
@@ -1,3 +1,5 @@
+var familyTree = [];
+
function Person(name)
{
this.name = name;
@@ -5,17 +7,22 @@
this.children = [];
this.siblings = [];
- this.getChildren = function ()
+ this.addChild = function(name)
{
- return this.children;
- }
+ var child = new Person(name)
+ child.parent = this
+ this.children.push(child);
+ };
+
+ this.init();
};
-var Nancy = new Person("Nancy")
-var Adam = new Person("Adam")
-var Jill = new Person("Jill")
-var Carl = new Person("Carl")
+Person.prototype.init = function(){
+ familyTree.push(this)
+};
-Nancy.children.push(Adam, Jill, Carl)
-
-console.log(Nancy.getChildren());
+//Driver test
+console.log(familyTree);
+var nancy = new Person("Nancy");
+nancy.addChild("Adam")
+console.log(familyTree); |
cf73385957d54ef0c808aa69e261fe57b87cb7f9 | ukelonn.web.frontend/src/main/frontend/reducers/passwordReducer.js | ukelonn.web.frontend/src/main/frontend/reducers/passwordReducer.js | import { createReducer } from 'redux-starter-kit';
import {
UPDATE,
} from '../actiontypes';
const passwordReducer = createReducer(null, {
[UPDATE]: (state, action) => {
if (!(action.payload && action.payload.password)) {
return state;
}
return action.payload.password;
},
});
export default passwordReducer;
| import { createReducer } from 'redux-starter-kit';
import {
UPDATE,
LOGIN_RECEIVE,
INITIAL_LOGIN_STATE_RECEIVE,
} from '../actiontypes';
const passwordReducer = createReducer(null, {
[UPDATE]: (state, action) => {
if (!(action.payload && action.payload.password)) {
return state;
}
return action.payload.password;
},
[LOGIN_RECEIVE]: (state, action) => '',
[INITIAL_LOGIN_STATE_RECEIVE]: (state, action) => '',
});
export default passwordReducer;
| Set password in redux to empty string on successful login | Set password in redux to empty string on successful login
| JavaScript | apache-2.0 | steinarb/ukelonn,steinarb/ukelonn,steinarb/ukelonn | ---
+++
@@ -1,6 +1,8 @@
import { createReducer } from 'redux-starter-kit';
import {
UPDATE,
+ LOGIN_RECEIVE,
+ INITIAL_LOGIN_STATE_RECEIVE,
} from '../actiontypes';
const passwordReducer = createReducer(null, {
@@ -10,6 +12,8 @@
}
return action.payload.password;
},
+ [LOGIN_RECEIVE]: (state, action) => '',
+ [INITIAL_LOGIN_STATE_RECEIVE]: (state, action) => '',
});
export default passwordReducer; |
2eb63b132d4ecd0c78998c716139298862319460 | public/js/identify.js | public/js/identify.js | (function(){
function close() {
$('.md-show .md-close').click();
}
function clean() {
$('.md-show input[name="name"]').val(''),
$('.md-show input[name="email"]').val(''),
$('.md-show input[name="phone"]').val('');
}
$('.btn-modal').click(function() {
var name = $('.md-show input[name="name"]').val(),
email = $('.md-show input[name="email"]').val(),
phone = $('.md-show input[name="phone"]').val();
if (name.trim().length == 0 || email.trim().length == 0 || phone.trim().length == 0) {
return;
}
dito.identify({
id: dito.generateID(email),
name: name,
email: email,
data: {
phone: phone,
}
});
clean();
close();
});
})();
| (function(){
function close() {
$('.md-show .md-close').click();
}
function clean() {
$('.md-show input[name="name"]').val(''),
$('.md-show input[name="email"]').val(''),
$('.md-show input[name="phone"]').val('');
}
$('.btn-modal').click(function() {
var name = $('.md-show input[name="name"]').val(),
email = $('.md-show input[name="email"]').val(),
phone = $('.md-show input[name="phone"]').val();
if (name.trim().length == 0 || email.trim().length == 0 || phone.trim().length == 0) {
return;
}
dito.identify({
id: dito.generateID(email),
name: name,
email: email,
data: {
telefone: phone
}
});
clean();
close();
});
})();
| Modify key "phone" to "telefone" | Modify key "phone" to "telefone"
| JavaScript | apache-2.0 | arthurbailao/gama-demo,arthurbailao/gama-demo | ---
+++
@@ -24,7 +24,7 @@
name: name,
email: email,
data: {
- phone: phone,
+ telefone: phone
}
});
|
ea015fcb266ab4287e583bed76bf5fbbb62205e5 | database/index.js | database/index.js | let pgp = require('pg-promise')({ssl: true});
// let databaseUrl = process.env.DATABASE_URL || require('./config');
// module.exports = pgp(databaseUrl);
| let pgp = require('pg-promise')(); // initialization option was {ssl: true}, sorry for deleting, but wasn't working for me with it
let connection = process.env.DATABASE_URL || require('./config');
module.exports = pgp(connection);
| Delete initialization options and change variable name | Delete initialization options and change variable name
| JavaScript | mit | SentinelsOfMagic/SentinelsOfMagic | ---
+++
@@ -1,5 +1,6 @@
-let pgp = require('pg-promise')({ssl: true});
-// let databaseUrl = process.env.DATABASE_URL || require('./config');
+let pgp = require('pg-promise')(); // initialization option was {ssl: true}, sorry for deleting, but wasn't working for me with it
-// module.exports = pgp(databaseUrl);
+let connection = process.env.DATABASE_URL || require('./config');
+module.exports = pgp(connection);
+ |
62188e803684cb8b7cf965a895da23bc583b83a5 | postcss.config.js | postcss.config.js | "use strict";
const {media_breakpoints} = require("./static/js/css_variables");
module.exports = {
plugins: {
// Warning: despite appearances, order is significant
"postcss-nested": {},
"postcss-extend-rule": {},
"postcss-simple-vars": {
variables: media_breakpoints,
},
"postcss-calc": {},
"postcss-media-minmax": {},
autoprefixer: {},
},
};
| "use strict";
const {media_breakpoints} = require("./static/js/css_variables");
module.exports = {
plugins: [
require("postcss-nested"),
require("postcss-extend-rule"),
require("postcss-simple-vars")({variables: media_breakpoints}),
require("postcss-calc"),
require("postcss-media-minmax"),
require("autoprefixer"),
],
};
| Convert plugins object to an array. | postcss: Convert plugins object to an array.
Since order matters for plugins, its better to use the Array syntax
to pass plugins to the PostCSS instead of Object.
This also allows us to reliably add more plugins programatically if
we so choose.
[dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com: Adjust to work with postcss-cli.]
Co-authored-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com>
Signed-off-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com>
| JavaScript | apache-2.0 | eeshangarg/zulip,kou/zulip,kou/zulip,kou/zulip,andersk/zulip,zulip/zulip,rht/zulip,kou/zulip,andersk/zulip,eeshangarg/zulip,rht/zulip,rht/zulip,rht/zulip,zulip/zulip,zulip/zulip,eeshangarg/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,andersk/zulip,rht/zulip,andersk/zulip,zulip/zulip,rht/zulip,zulip/zulip,zulip/zulip,kou/zulip,eeshangarg/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,andersk/zulip | ---
+++
@@ -3,15 +3,12 @@
const {media_breakpoints} = require("./static/js/css_variables");
module.exports = {
- plugins: {
- // Warning: despite appearances, order is significant
- "postcss-nested": {},
- "postcss-extend-rule": {},
- "postcss-simple-vars": {
- variables: media_breakpoints,
- },
- "postcss-calc": {},
- "postcss-media-minmax": {},
- autoprefixer: {},
- },
+ plugins: [
+ require("postcss-nested"),
+ require("postcss-extend-rule"),
+ require("postcss-simple-vars")({variables: media_breakpoints}),
+ require("postcss-calc"),
+ require("postcss-media-minmax"),
+ require("autoprefixer"),
+ ],
}; |
55a531708dfcf895433ce9abaf2c11fe9635df14 | public/js/read.js | public/js/read.js |
var imgWidth = new Array();
function imageWidth()
{
var width = $(window).width() - fixedPadding;
$(".img_flex").each(function(index)
{
if (width != $(this).width())
{
if (width < imgWidth[index])
{
$(this).width(width);
}
else
{
$(this).width(imgWidth[index]);
}
}
});
}
$(document).ready(function() {
$(document).keyup(function(e) {
if (e.keyCode === 37) window.location.href = prevPage;
if (e.keyCode === 39) window.location.href = nextPage;
});
$(".jump").on('change', function() {
window.location.href = baseUrl + this.value;
});
$(".img_flex").each(function(index)
{
imgWidth.push($(this).width());
});
imageWidth();
$(window).resize(function(){
imageWidth();
});
});
|
var imgWidth = new Array();
var imagePadding = 100;
function imageWidth()
{
var width = $(window).width() - imagePadding;
$(".img_flex").each(function(index)
{
if (width != $(this).width())
{
if (width < imgWidth[index])
{
$(this).width(width);
}
else
{
$(this).width(imgWidth[index]);
}
}
});
}
$(document).ready(function() {
$(document).keyup(function(e) {
if (e.keyCode === 37) window.location.href = prevPage;
if (e.keyCode === 39) window.location.href = nextPage;
});
$(".jump").on('change', function() {
window.location.href = baseUrl + this.value;
});
$(".img_flex").each(function(index)
{
imgWidth.push($(this).width());
});
imageWidth();
$(window).resize(function(){
imageWidth();
});
});
| Change padding depend on window width (the bigger the more big the width is) | Change padding depend on window width (the bigger the more big the width is)
| JavaScript | mit | hernantas/MangaReader,hernantas/MangaReader,hernantas/MangaReader | ---
+++
@@ -1,9 +1,10 @@
var imgWidth = new Array();
+var imagePadding = 100;
function imageWidth()
{
- var width = $(window).width() - fixedPadding;
+ var width = $(window).width() - imagePadding;
$(".img_flex").each(function(index)
{
if (width != $(this).width()) |
8be4bc9543ba1f23019d619c822bc7e4769e22da | stories/Autocomplete.stories.js | stories/Autocomplete.stories.js | import React from 'react';
import { storiesOf } from '@storybook/react';
import Autocomplete from '../src/Autocomplete';
const stories = storiesOf('javascript/Autocomplete', module);
stories.addParameters({
info: {
text: `Add an autocomplete dropdown below your input
to suggest possible values in your form. You can
populate the list of autocomplete options dynamically as well.`
}
});
stories.add('Default', () => (
<Autocomplete
options={{
data: {
['Gus Fring']: null,
['Saul Goodman']: null,
['Tuco Salamanca']: 'https://placehold.it/250x250'
}
}}
placeholder="Insert here"
/>
));
| import React from 'react';
import { storiesOf } from '@storybook/react';
import Autocomplete from '../src/Autocomplete';
const stories = storiesOf('javascript/Autocomplete', module);
stories.addParameters({
info: {
text: `Add an autocomplete dropdown below your input
to suggest possible values in your form. You can
populate the list of autocomplete options dynamically as well.`
}
});
stories.add('Default', () => (
<Autocomplete
options={{
data: {
['Gus Fring']: null,
['Saul Goodman']: null,
['Tuco Salamanca']: 'https://placehold.it/250x250'
}
}}
placeholder="Insert here"
/>
));
stories.add('With icon', () => (
<Autocomplete
options={{
data: {
['Gus Fring']: null,
['Saul Goodman']: null,
['Tuco Salamanca']: 'https://placehold.it/250x250'
}
}}
placeholder="Insert here"
icon="textsms"
/>
));
| Add autocomplete with icon story | Add autocomplete with icon story
| JavaScript | mit | react-materialize/react-materialize,react-materialize/react-materialize,react-materialize/react-materialize | ---
+++
@@ -24,3 +24,17 @@
placeholder="Insert here"
/>
));
+
+stories.add('With icon', () => (
+ <Autocomplete
+ options={{
+ data: {
+ ['Gus Fring']: null,
+ ['Saul Goodman']: null,
+ ['Tuco Salamanca']: 'https://placehold.it/250x250'
+ }
+ }}
+ placeholder="Insert here"
+ icon="textsms"
+ />
+)); |
ef090c4c1b819b2df89ec50a855260decdf5ace0 | app/tradeapi/tradeapi.js | app/tradeapi/tradeapi.js | /**
This Angular module provide interface to VNDIRECT API, include:
- Auth API
- Trade API
*/
angular.module('myApp.tradeapi', [])
.factory('tradeapi', ['$http', function($http) {
var AUTH_URL = 'https://auth-api.vndirect.com.vn/auth';
var token = null;
return {
login: function(username, password) {
$http({
method: 'POST',
url: AUTH_URL,
data: {
username: username,
password: password
}
})
.then(function(response) {
console.log('Login success', response);
})
},
};
});
| /**
This Angular module provide interface to VNDIRECT API, include:
- Auth API
- Trade API
*/
angular.module('myApp.tradeapi', [])
.factory('tradeapi', ['$http', '$q', function($http, $q) {
var AUTH_URL = 'https://auth-api.vndirect.com.vn/auth';
var CUSOMTER_URL = 'https://trade-api.vndirect.com.vn/customer';
var token = null;
return {
login: function(username, password) {
var deferred = $q.defer();
$http({
method: 'POST',
url: AUTH_URL,
data: {
username: username,
password: password
}
})
.then(function(response) {
deferred.resolve(response.data);
token = response.data.token;
}, function(response) {
deferred.reject(response.data.message);
});
return deferred.promise;
},
/**
Retrieve customer information such as cusid, name, accou
*/
retrieve_customer: function() {
var deferred = $q.defer();
if(token) {
$http({
method: 'GET',
url: CUSOMTER_URL,
headers: {
'X-AUTH-TOKEN': token
}
})
.then(function(response) {
deferred.resolve(response.data);
}, function(response) {
deferred.reject(response.data.message);
});
return deferred.promise;
}
else{
throw 'You are not logged in';
}
}
};
}]);
| Integrate login & retrieve customer with Trade API | Integrate login & retrieve customer with Trade API
| JavaScript | mit | VNDIRECT/SmartP,VNDIRECT/SmartP | ---
+++
@@ -6,13 +6,15 @@
angular.module('myApp.tradeapi', [])
-.factory('tradeapi', ['$http', function($http) {
+.factory('tradeapi', ['$http', '$q', function($http, $q) {
var AUTH_URL = 'https://auth-api.vndirect.com.vn/auth';
+ var CUSOMTER_URL = 'https://trade-api.vndirect.com.vn/customer';
var token = null;
return {
login: function(username, password) {
+ var deferred = $q.defer();
$http({
method: 'POST',
url: AUTH_URL,
@@ -22,9 +24,39 @@
}
})
.then(function(response) {
- console.log('Login success', response);
- })
+ deferred.resolve(response.data);
+ token = response.data.token;
+ }, function(response) {
+ deferred.reject(response.data.message);
+ });
+ return deferred.promise;
},
+
+ /**
+ Retrieve customer information such as cusid, name, accou
+ */
+ retrieve_customer: function() {
+ var deferred = $q.defer();
+ if(token) {
+ $http({
+ method: 'GET',
+ url: CUSOMTER_URL,
+ headers: {
+ 'X-AUTH-TOKEN': token
+ }
+ })
+ .then(function(response) {
+ deferred.resolve(response.data);
+ }, function(response) {
+ deferred.reject(response.data.message);
+ });
+ return deferred.promise;
+ }
+ else{
+ throw 'You are not logged in';
+ }
+ }
+
};
-});
+}]);
|
b5a460ecc35dc5609339317337d467368d7593bb | frontend/src/utils/createWebSocketConnection.js | frontend/src/utils/createWebSocketConnection.js | import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
const wsURL = 'http://localhost:8080/seven-wonders-websocket'
const createConnection = (headers = {}) => new Promise((resolve, reject) => {
let socket = Stomp.over(new SockJS(wsURL), {
debug: process.env.NODE_ENV !== "production"
})
socket.connect(headers, (frame) => {
return resolve({ frame, socket })
}, reject)
})
export default createConnection
| import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
const wsURL = '/seven-wonders-websocket'
const createConnection = (headers = {}) => new Promise((resolve, reject) => {
let socket = Stomp.over(new SockJS(wsURL), {
debug: process.env.NODE_ENV !== "production"
})
socket.connect(headers, (frame) => {
return resolve({ frame, socket })
}, reject)
})
export default createConnection
| Remove absolute ws link in frontend | Remove absolute ws link in frontend
| JavaScript | mit | luxons/seven-wonders,luxons/seven-wonders,luxons/seven-wonders | ---
+++
@@ -1,6 +1,6 @@
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
-const wsURL = 'http://localhost:8080/seven-wonders-websocket'
+const wsURL = '/seven-wonders-websocket'
const createConnection = (headers = {}) => new Promise((resolve, reject) => {
let socket = Stomp.over(new SockJS(wsURL), { |
d299ceac7d3d115266a8f45a14f1fd9f42cea883 | tests/test-simple.js | tests/test-simple.js | /*
* Copyright 2011 Rackspace
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var et = require('elementtree');
exports['test_error_type'] = function(test, assert) {
/* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */
var Element = et.Element
var root = Element('root');
root.append(Element('one'));
root.append(Element('two'));
root.append(Element('three'));
assert.equal(3, root.len())
assert.equal('one', root.getItem(0).tag)
assert.equal('two', root.getItem(1).tag)
assert.equal('three', root.getItem(2).tag)
test.finish();
};
| /*
* Copyright 2011 Rackspace
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var et = require('elementtree');
exports['test_simplest'] = function(test, assert) {
/* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */
var Element = et.Element
var root = Element('root');
root.append(Element('one'));
root.append(Element('two'));
root.append(Element('three'));
assert.equal(3, root.len())
assert.equal('one', root.getItem(0).tag)
assert.equal('two', root.getItem(1).tag)
assert.equal('three', root.getItem(2).tag)
test.finish();
};
exports['test_attribute_values'] = function(test, assert) {
var XML = et.XML;
var root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>');
assert.equal('Alpha', root.attrib['alpha']);
assert.equal('Beta', root.attrib['beta']);
assert.equal('Gamma', root.attrib['gamma']);
test.finish();
};
| Add simple attributes test case | Add simple attributes test case
| JavaScript | apache-2.0 | racker/node-elementtree | ---
+++
@@ -17,7 +17,7 @@
var et = require('elementtree');
-exports['test_error_type'] = function(test, assert) {
+exports['test_simplest'] = function(test, assert) {
/* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */
var Element = et.Element
var root = Element('root');
@@ -30,3 +30,13 @@
assert.equal('three', root.getItem(2).tag)
test.finish();
};
+
+
+exports['test_attribute_values'] = function(test, assert) {
+ var XML = et.XML;
+ var root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>');
+ assert.equal('Alpha', root.attrib['alpha']);
+ assert.equal('Beta', root.attrib['beta']);
+ assert.equal('Gamma', root.attrib['gamma']);
+ test.finish();
+}; |
f8c3893888e1cd5d8b31e4621fe6c04b3343bfce | src/app/UI/lib/managers/statistics/client/components/routes.js | src/app/UI/lib/managers/statistics/client/components/routes.js |
import React from "react";
import { Route } from "react-router";
import {
View as TAView
} from "ui-components/type_admin";
import Item from "./Item";
import List from "./List";
const routes = [
<Route
key="charts"
path="charts"
component={TAView}
List={List}
type="stat.chart"
label="Statistics"
>
<Route
key="stat"
path=":_id"
component={TAView}
Item={Item}
type="stat.chart"
/>
</Route>
];
export default routes;
|
import React from "react";
import { Route } from "react-router";
import {
View as TAView,
EditTags as TAEditTags
} from "ui-components/type_admin";
import Item from "./Item";
import List from "./List";
const routes = [
<Route
key="charts"
path="charts"
component={TAView}
List={List}
type="stat.chart"
label="Statistics"
>
<Route
path=":_id"
component={TAView}
Item={Item}
type="stat.chart"
>
<Route
path="tags"
component={TAView}
Action={TAEditTags}
type="stat.chart"
/>
</Route>
</Route>
];
export default routes;
| Add edit tags to statistics chart | UI: Add edit tags to statistics chart
| JavaScript | mit | Combitech/codefarm,Combitech/codefarm,Combitech/codefarm | ---
+++
@@ -2,7 +2,8 @@
import React from "react";
import { Route } from "react-router";
import {
- View as TAView
+ View as TAView,
+ EditTags as TAEditTags
} from "ui-components/type_admin";
import Item from "./Item";
import List from "./List";
@@ -17,12 +18,18 @@
label="Statistics"
>
<Route
- key="stat"
path=":_id"
component={TAView}
Item={Item}
type="stat.chart"
- />
+ >
+ <Route
+ path="tags"
+ component={TAView}
+ Action={TAEditTags}
+ type="stat.chart"
+ />
+ </Route>
</Route>
];
|
2162a6463b14f8cf4f78c964aca248828bed5faf | packages/components/containers/labels/FoldersSection.js | packages/components/containers/labels/FoldersSection.js | import React from 'react';
import { c } from 'ttag';
import { Loader, Alert, PrimaryButton, useFolders, useModals } from 'react-components';
import FolderTreeViewList from './FolderTreeViewList';
import EditLabelModal from './modals/Edit';
function LabelsSection() {
const [folders, loadingFolders] = useFolders();
const { createModal } = useModals();
if (loadingFolders) {
return <Loader />;
}
return (
<>
<Alert
type="info"
className="mt1 mb1"
learnMore="https://protonmail.com/support/knowledge-base/creating-folders/"
>
{c('LabelSettings').t`A message can only be in filed in a single Folder at a time.`}
</Alert>
<div className="mb1">
<PrimaryButton onClick={() => createModal(<EditLabelModal type="folder" />)}>
{c('Action').t`Add folder`}
</PrimaryButton>
</div>
{folders.length ? (
<FolderTreeViewList items={folders} />
) : (
<Alert>{c('LabelSettings').t`No folders available`}</Alert>
)}
</>
);
}
export default LabelsSection;
| import React from 'react';
import { c } from 'ttag';
import { Loader, Alert, PrimaryButton, useFolders, useModals } from 'react-components';
import FolderTreeViewList from './FolderTreeViewList';
import EditLabelModal from './modals/Edit';
function LabelsSection() {
const [folders, loadingFolders] = useFolders();
const { createModal } = useModals();
if (loadingFolders) {
return <Loader />;
}
return (
<>
<Alert
type="info"
className="mt1 mb1"
learnMore="https://protonmail.com/support/knowledge-base/creating-folders/"
>
{c('LabelSettings').t`A message can only be filed in a single Folder at a time.`}
</Alert>
<div className="mb1">
<PrimaryButton onClick={() => createModal(<EditLabelModal type="folder" />)}>
{c('Action').t`Add folder`}
</PrimaryButton>
</div>
{folders.length ? (
<FolderTreeViewList items={folders} />
) : (
<Alert>{c('LabelSettings').t`No folders available`}</Alert>
)}
</>
);
}
export default LabelsSection;
| Fix translation typo message info folders | Fix translation typo message info folders
| JavaScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -20,7 +20,7 @@
className="mt1 mb1"
learnMore="https://protonmail.com/support/knowledge-base/creating-folders/"
>
- {c('LabelSettings').t`A message can only be in filed in a single Folder at a time.`}
+ {c('LabelSettings').t`A message can only be filed in a single Folder at a time.`}
</Alert>
<div className="mb1">
<PrimaryButton onClick={() => createModal(<EditLabelModal type="folder" />)}> |
6e72bc8a412b0ba8dc648d80a6d433c282496f16 | client/app/common/navbar/navbar.controller.js | client/app/common/navbar/navbar.controller.js | import moment from 'moment';
class NavbarController {
constructor() {
this.name = 'navbar';
}
$onInit(){
this.moment = moment().format('dddd HH:mm');
this.updateDate();
this.user =
{
name: 'Jesus Garcia',
mail: 'ctw@ctwhome.com',
picture: '//icons.iconarchive.com/icons/graphicloads/flat-finance/256/person-icon.png',
lists: [
{
name: 'Study',
timers: [
{
name: 'Timer 1',
time: '1500'
},
{
name: 'Timer 2',
time: '1500'
},
{
name: 'Timer 3',
time: '1500'
}
]
},
{
name: 'Piano',
timers: [
{
name: 'Timer 4',
time: '1500'
},
{
name: 'Timer 5',
time: '1500'
}
]
}
]
};
}
updateDate () {
setTimeout(() => {
this.moment = moment().format('dddd HH:mm');
this.updateDate();
}, 1000);
}
}
export default NavbarController;
| import moment from 'moment';
class NavbarController {
constructor() {
this.name = 'navbar';
}
$onInit(){
this.moment = moment().format('dddd HH:mm');
this.updateDate();
this.user =
{
name: 'Jesus Garcia',
mail: 'ctw@ctwhome.com',
picture: '//icons.iconarchive.com/icons/graphicloads/flat-finance/256/person-icon.png',
lists: [
{
name: 'Study',
timers: [
{
name: 'Timer 1',
time: '1500'
},
{
name: 'Timer 2',
time: '1500'
},
{
name: 'Timer 3',
time: '1500'
}
]
},
{
name: 'Piano',
timers: [
{
name: 'Timer 4',
time: '1500'
},
{
name: 'Timer 5',
time: '1500'
}
]
}
]
};
}
updateDate () {
setTimeout(() => {
this.moment = moment().format('dddd HH:mm');
this.updateDate();
}, 60000);
}
}
export default NavbarController;
| Update local Date automatically each 60s | Update local Date automatically each 60s
| JavaScript | apache-2.0 | ctwhome/studylist,ctwhome/studylist | ---
+++
@@ -53,7 +53,7 @@
setTimeout(() => {
this.moment = moment().format('dddd HH:mm');
this.updateDate();
- }, 1000);
+ }, 60000);
}
} |
33450086e8ada4f7d73e93da99a61b1b007e7c75 | client/scripts/controllers/UsersController.js | client/scripts/controllers/UsersController.js | /**
* Created by groupsky on 18.11.15.
*/
require('../app').controller('UsersController', /* @ngInject */function ($filter, $scope, User) {
var controller = this
var filter = $filter('filter')
$scope.rows = User.query({
limit: 1000
})
controller.filterRows = function (config) {
return function (row) {
if (config && config.role) {
if (config.role !== row.role) {
return false
}
}
if (config && config.search) {
if (!filter([row], config.search).length) {
return false
}
}
return true
}
}
})
| /**
* Created by groupsky on 18.11.15.
*/
require('../app').controller('UsersController', /* @ngInject */function ($filter, $scope, User) {
var controller = this
var filter = $filter('filter')
$scope.rows = User.query({
limit: 5000
})
controller.filterRows = function (config) {
return function (row) {
if (config && config.role) {
if (config.role !== row.role) {
return false
}
}
if (config && config.search) {
if (!filter([row], config.search).length) {
return false
}
}
return true
}
}
})
| Increase limit for fetching users in UI | Increase limit for fetching users in UI
| JavaScript | agpl-3.0 | BspbOrg/smartbirds-server,BspbOrg/smartbirds-server,BspbOrg/smartbirds-server | ---
+++
@@ -7,7 +7,7 @@
var filter = $filter('filter')
$scope.rows = User.query({
- limit: 1000
+ limit: 5000
})
controller.filterRows = function (config) { |
be284e8f6e0a72ae58d861a26f8bd748dfbad156 | tasks/register/cron.js | tasks/register/cron.js | "use strict";
const path = require('path');
const Sails = require('sails');
const _ = require('lodash');
module.exports = function (grunt) {
grunt.registerTask('cron', async function (...args) {
const done = this.async();
Sails.load({ hooks: { grunt: false } }, async () => {
try {
const filePath = path.resolve('config', 'scientilla.js');
const config = require(filePath);
const crons = config.scientilla.crons.filter(cron => cron.name === args[0]);
if (crons.length > 0) {
for (const cron of crons) {
for (const job of cron.jobs) {
try {
await _.get(global, job.fn)(...job.params);
} catch (e) {
throw e;
}
}
}
} else {
throw 'Cron not found!';
}
done();
} catch(err) {
sails.log.debug(err);
done();
return 1;
}
});
});
}; | "use strict";
const Sails = require('sails');
const _ = require('lodash');
module.exports = function (grunt) {
grunt.registerTask('cron', async function (...args) {
const done = this.async();
Sails.load({ hooks: { grunt: false } }, async () => {
try {
const crons = sails.config.scientilla.crons.filter(cron => cron.name === args[0]);
if (crons.length > 0) {
for (const cron of crons) {
for (const job of cron.jobs) {
try {
await _.get(global, job.fn)(...job.params);
} catch (e) {
throw e;
}
}
}
} else {
throw 'Cron not found!';
}
done();
} catch(err) {
sails.log.debug(err);
done();
return 1;
}
});
});
}; | Remove reading config from file | Remove reading config from file
| JavaScript | mit | scientilla/scientilla,scientilla/scientilla,scientilla/scientilla | ---
+++
@@ -1,6 +1,5 @@
"use strict";
-const path = require('path');
const Sails = require('sails');
const _ = require('lodash');
@@ -9,9 +8,7 @@
const done = this.async();
Sails.load({ hooks: { grunt: false } }, async () => {
try {
- const filePath = path.resolve('config', 'scientilla.js');
- const config = require(filePath);
- const crons = config.scientilla.crons.filter(cron => cron.name === args[0]);
+ const crons = sails.config.scientilla.crons.filter(cron => cron.name === args[0]);
if (crons.length > 0) {
for (const cron of crons) { |
16ae1fcedba350a023ed866413cea05d2a3cd8c5 | src/js/middle_level/elements/gizmos/M_DirectionalLightGizmo.js | src/js/middle_level/elements/gizmos/M_DirectionalLightGizmo.js | import M_Gizmo from './M_Gizmo';
import Arrow from '../../../low_level/primitives/Arrow';
import ClassicMaterial from '../../../low_level/materials/ClassicMaterial';
import M_Mesh from '../meshes/M_Mesh';
import Vector4 from '../../../low_level/math/Vector4';
export default class M_DirectionalLightGizmo extends M_Gizmo {
constructor(glBoostContext, length) {
super(glBoostContext, null, null);
this._init(glBoostContext, length);
// this.isVisible = false;
this.baseColor = new Vector4(0.8, 0.8, 0, 1);
}
_init(glBoostContext, length) {
this._material = new ClassicMaterial(this._glBoostContext);
this._mesh = new M_Mesh(glBoostContext,
new Arrow(this._glBoostContext, length, 3),
this._material);
this.addChild(this._mesh);
}
set rotate(rotateVec3) {
this._mesh.rotate = rotateVec3;
}
get rotate() {
return this._mesh.rotate;
}
set baseColor(colorVec) {
this._material.baseColor = colorVec;
}
get baseColor() {
return this._material.baseColor;
}
}
| import M_Gizmo from './M_Gizmo';
import Arrow from '../../../low_level/primitives/Arrow';
import ClassicMaterial from '../../../low_level/materials/ClassicMaterial';
import M_Mesh from '../meshes/M_Mesh';
import Vector4 from '../../../low_level/math/Vector4';
export default class M_DirectionalLightGizmo extends M_Gizmo {
constructor(glBoostContext, length) {
super(glBoostContext, null, null);
this._init(glBoostContext, length);
this.isVisible = false;
this.baseColor = new Vector4(0.8, 0.8, 0, 1);
}
_init(glBoostContext, length) {
this._material = new ClassicMaterial(this._glBoostContext);
this._mesh = new M_Mesh(glBoostContext,
new Arrow(this._glBoostContext, length, 3),
this._material);
this.addChild(this._mesh);
}
set rotate(rotateVec3) {
this._mesh.rotate = rotateVec3;
}
get rotate() {
return this._mesh.rotate;
}
set baseColor(colorVec) {
this._material.baseColor = colorVec;
}
get baseColor() {
return this._material.baseColor;
}
}
| Make directional light gizmo invisible | Make directional light gizmo invisible
| JavaScript | mit | emadurandal/GLBoost,emadurandal/GLBoost,cx20/GLBoost,cx20/GLBoost,emadurandal/GLBoost,cx20/GLBoost | ---
+++
@@ -9,7 +9,7 @@
super(glBoostContext, null, null);
this._init(glBoostContext, length);
-// this.isVisible = false;
+ this.isVisible = false;
this.baseColor = new Vector4(0.8, 0.8, 0, 1);
} |
d6ab81e3e201e08004aee6ec30d4cf0d85678886 | src/D3TopoJson.js | src/D3TopoJson.js | po.d3TopoJson = function(fetch) {
if (!arguments.length) fetch = po.queue.json;
var topoToGeo = function(url, callback) {
function convert(topology, object, layer, features) {
if (object.type == "GeometryCollection" && !object.properties) {
object.geometries.forEach(function(g) {
convert(topology, g, layer, features);
});
}
else {
var feature = topojson.feature(topology, object);
feature.properties = { layer: layer };
if (object.properties) {
Object.keys(object.properties).forEach(function(property) {
feature.properties[property] = object.properties[property];
});
}
features.push(feature);
}
}
return fetch(url, function(topology) {
var features = [];
for (var o in topology.objects) {
convert(topology, topology.objects[o], o, features);
}
callback({
type: "FeatureCollection",
features: features
});
});
};
var d3TopoJson = po.d3GeoJson(topoToGeo);
return d3TopoJson;
};
| po.d3TopoJson = function(fetch) {
if (!arguments.length) fetch = po.queue.json;
var topologyFeatures = function(topology) {
function convert(topology, object, layer, features) {
if (object.type == "GeometryCollection" && !object.properties) {
object.geometries.forEach(function(g) {
convert(topology, g, layer, features);
});
}
else {
var feature = topojson.feature(topology, object);
feature.properties = { layer: layer };
if (object.properties) {
Object.keys(object.properties).forEach(function(property) {
feature.properties[property] = object.properties[property];
});
}
features.push(feature);
}
}
var features = [];
for (var o in topology.objects) {
convert(topology, topology.objects[o], o, features);
}
return features;
};
var topoToGeo = function(url, callback) {
return fetch(url, function(topology) {
callback({
type: "FeatureCollection",
features: topologyFeatures(topology)
});
});
};
var d3TopoJson = po.d3GeoJson(topoToGeo);
d3TopoJson.topologyFeatures = function(x) {
if (!arguments.length) return topologyFeatures;
topologyFeatures = x;
return d3TopoJson;
};
return d3TopoJson;
};
| Allow changing the function used to extract GeoJSON features from TopoJSON. | Allow changing the function used to extract GeoJSON features from TopoJSON.
| JavaScript | bsd-3-clause | dillan/mapsense.js,RavishankarDuMCA10/mapsense.js,sfchronicle/mapsense.js,manueltimita/mapsense.js,cksachdev/mapsense.js,mapsense/mapsense.js,shkfnly/mapsense.js,Laurian/mapsense.js,gimlids/mapsense.js | ---
+++
@@ -1,7 +1,7 @@
po.d3TopoJson = function(fetch) {
if (!arguments.length) fetch = po.queue.json;
- var topoToGeo = function(url, callback) {
+ var topologyFeatures = function(topology) {
function convert(topology, object, layer, features) {
if (object.type == "GeometryCollection" && !object.properties) {
object.geometries.forEach(function(g) {
@@ -20,19 +20,29 @@
}
}
+ var features = [];
+ for (var o in topology.objects) {
+ convert(topology, topology.objects[o], o, features);
+ }
+ return features;
+ };
+
+ var topoToGeo = function(url, callback) {
return fetch(url, function(topology) {
- var features = [];
- for (var o in topology.objects) {
- convert(topology, topology.objects[o], o, features);
- }
callback({
type: "FeatureCollection",
- features: features
+ features: topologyFeatures(topology)
});
});
};
var d3TopoJson = po.d3GeoJson(topoToGeo);
+ d3TopoJson.topologyFeatures = function(x) {
+ if (!arguments.length) return topologyFeatures;
+ topologyFeatures = x;
+ return d3TopoJson;
+ };
+
return d3TopoJson;
}; |
97e1d783d9a09dca204dff19bf046fc0af198643 | test/js/thumbs_test.js | test/js/thumbs_test.js | window.addEventListener('load', function(){
// touchstart
module('touchstart', environment);
test('should respond to touchstart', 1, function() {
listen('touchstart').trigger('mousedown');
});
// touchend
module('touchend', environment);
test('should respond to touchend', 1, function() {
listen('touchend').trigger('mouseup');
});
// touchmove
module('touchmove', environment);
test('should respond to touchmove', 1, function() {
listen('touchmove').trigger('mousemove');
});
});
| window.addEventListener('load', function(){
// mousedown
module('mousedown', environment);
test('should respond to mousedown', 1, function() {
listen('mousedown').trigger('mousedown');
});
// mouseup
module('mouseup', environment);
test('should respond to mouseup', 1, function() {
listen('mouseup').trigger('mouseup');
});
// mousemove
module('mousemove', environment);
test('should respond to mousemove', 1, function() {
listen('mousemove').trigger('mousemove');
});
// touchstart
module('touchstart', environment);
test('should respond to touchstart', 1, function() {
listen('touchstart').trigger('mousedown');
});
// touchend
module('touchend', environment);
test('should respond to touchend', 1, function() {
listen('touchend').trigger('mouseup');
});
// touchmove
module('touchmove', environment);
test('should respond to touchmove', 1, function() {
listen('touchmove').trigger('mousemove');
});
});
| Add mousedown/mouseup/mousemove to test suite. | Add mousedown/mouseup/mousemove to test suite.
To make sure that we do not clobber those events.
| JavaScript | mit | mwbrooks/thumbs.js,pyrinelaw/thumbs.js,pyrinelaw/thumbs.js | ---
+++
@@ -1,4 +1,28 @@
window.addEventListener('load', function(){
+
+ // mousedown
+
+ module('mousedown', environment);
+
+ test('should respond to mousedown', 1, function() {
+ listen('mousedown').trigger('mousedown');
+ });
+
+ // mouseup
+
+ module('mouseup', environment);
+
+ test('should respond to mouseup', 1, function() {
+ listen('mouseup').trigger('mouseup');
+ });
+
+ // mousemove
+
+ module('mousemove', environment);
+
+ test('should respond to mousemove', 1, function() {
+ listen('mousemove').trigger('mousemove');
+ });
// touchstart
|
fbc38523508db2201e6f1c136640f560a77b7282 | lib/utils/copy.js | lib/utils/copy.js | 'use strict';
const Promise = require('bluebird');
const glob = Promise.promisify(require('glob'));
const mkdirp = Promise.promisify(require('mkdirp'));
const path = require('path');
const fs = require('fs');
const mu = require('mu2');
function compile(src, dest, settings) {
settings = settings || {};
return mkdirp(path.dirname(dest))
.then(() => {
return new Promise((resolve, reject) => {
let stream;
if (path.basename(src).match(/\.tpl\./)) {
dest = dest.replace('.tpl', '');
stream = mu.compileAndRender(src, settings);
} else {
stream = fs.createReadStream(src);
}
stream.pipe(fs.createWriteStream(dest));
stream.on('end', resolve);
stream.on('error', reject);
});
});
}
function copy(src, dest, settings) {
const pattern = path.resolve(src, '**/*');
return glob(pattern, { nodir: true, dot: true })
.then((files) => {
return Promise.map(files, (file) => {
const target = path.resolve(dest, path.relative(src, file));
return compile(file, target, settings);
}, {concurrency: 1});
});
}
module.exports = copy;
| 'use strict';
const Promise = require('bluebird');
const glob = Promise.promisify(require('glob'));
const mkdirp = Promise.promisify(require('mkdirp'));
const path = require('path');
const fs = require('fs');
const mu = require('mu2');
function compile(src, dest, settings) {
settings = settings || {};
return mkdirp(path.dirname(dest))
.then(() => {
return new Promise((resolve, reject) => {
let stream;
if (path.basename(src).match(/\.tpl(\.|$)/)) {
dest = dest.replace('.tpl', '');
stream = mu.compileAndRender(src, settings);
} else {
stream = fs.createReadStream(src);
}
stream.pipe(fs.createWriteStream(dest));
stream.on('end', resolve);
stream.on('error', reject);
});
});
}
function copy(src, dest, settings) {
const pattern = path.resolve(src, '**/*');
return glob(pattern, { nodir: true, dot: true })
.then((files) => {
return Promise.map(files, (file) => {
const target = path.resolve(dest, path.relative(src, file));
return compile(file, target, settings);
}, {concurrency: 1});
});
}
module.exports = copy;
| Fix regex for template files | Fix regex for template files
The regex wasn't matching dotfiles with no file extension so modify it to also include .tpl files with no additional extension.
| JavaScript | mit | UKHomeOfficeForms/hof-generator,UKHomeOfficeForms/hof-generator | ---
+++
@@ -14,7 +14,7 @@
.then(() => {
return new Promise((resolve, reject) => {
let stream;
- if (path.basename(src).match(/\.tpl\./)) {
+ if (path.basename(src).match(/\.tpl(\.|$)/)) {
dest = dest.replace('.tpl', '');
stream = mu.compileAndRender(src, settings);
} else { |
5f3d0240de0f8dcc5abfc8962e4a1ce9ab629b83 | lib/and.js | lib/and.js | 'use strict';
var R = require('ramda');
/**
* Output a block (or its inverse) based on whether or not both of the suppied
* arguments are truthy.
*
* @since v0.0.1
* @param {*} left
* @param {*} right
* @param {Object} options
* @throws {Error} An error is thrown when the `right` argument is missing.
* @return {String}
* @example
*
* var a = true;
* var b = 1;
* var c = false;
*
* {{#and a b}}✔︎{{else}}✘{{/and}} //=> ✔︎
* {{#and b c}}✔︎{{else}}✘{{/and}} //=> ✘
*/
module.exports = function and (left, right, options) {
if (arguments.length < 3) {
throw new Error('The "or" helper needs two arguments.');
}
return R.and(left, right) ?
options.fn(this) : options.inverse(this);
}
| 'use strict';
var R = require('ramda');
/**
* Output a block (or its inverse) based on whether or not both of the suppied
* arguments are truthy.
*
* @since v0.0.1
* @param {*} left
* @param {*} right
* @param {Object} options
* @throws {Error} An error is thrown when the `right` argument is missing.
* @return {String}
* @example
*
* var a = true;
* var b = 1;
* var c = false;
*
* {{#and a b}}✔︎{{else}}✘{{/and}} //=> ✔︎
* {{#and b c}}✔︎{{else}}✘{{/and}} //=> ✘
*/
module.exports = function and (left, right, options) {
if (arguments.length < 3) {
throw new Error('The "and" helper needs two arguments.');
}
return R.and(left, right) ?
options.fn(this) : options.inverse(this);
}
| Fix typo in error message | Fix typo in error message
| JavaScript | mit | cloudfour/core-hbs-helpers | ---
+++
@@ -24,7 +24,7 @@
module.exports = function and (left, right, options) {
if (arguments.length < 3) {
- throw new Error('The "or" helper needs two arguments.');
+ throw new Error('The "and" helper needs two arguments.');
}
return R.and(left, right) ?
options.fn(this) : options.inverse(this); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.