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 |
|---|---|---|---|---|---|---|---|---|---|---|
cce7d2b09c0b50300a5c85eefd80f53bae39e7a1 | demo/read-input.js | demo/read-input.js | window.__i10c = {};
window.__i10c.getInputValue = (inputEle) => {
return inputEle.val;
}
window.__i10c.setInputValue = (inputEle, val) => {
inputEle.value = val;
}
window.__i10c.allInputValue = () => {
var elements = document.getElementsByTagName('input');
for (var i = 0; i < elements.length; i++) {
console.log("Found " + elements[i].value);
}
}; | window.__i10c = {};
window.__i10c.getInputValue = (inputEle) => {
return inputEle.value;
}
window.__i10c.setInputValue = (inputEle, val) => {
inputEle.value = val;
}
window.__i10c.getAllInputValues = () => {
var elements = document.getElementsByTagName('input');
for (var i = 0; i < elements.length; i++) {
console.log("Found " + elements[i].value);
}
}; | Fix name and bug for get input value | Fix name and bug for get input value
| JavaScript | mit | instartlogic/instartlogic.github.io | ---
+++
@@ -1,14 +1,14 @@
window.__i10c = {};
window.__i10c.getInputValue = (inputEle) => {
- return inputEle.val;
+ return inputEle.value;
}
window.__i10c.setInputValue = (inputEle, val) => {
inputEle.value = val;
}
-window.__i10c.allInputValue = () => {
+window.__i10c.getAllInputValues = () => {
var elements = document.getElementsByTagName('input');
for (var i = 0; i < elements.length; i++) {
console.log("Found " + elements[i].value); |
af9f12582e288bd2dc1a21a3075d706919b441b3 | examples/basic/components/App.js | examples/basic/components/App.js | const React = require('react');
const { Link } = require('react-router');
const { connect } = require('react-redux');
const { updatePath } = require('redux-simple-router');
function App({ updatePath, children }) {
return (
<div>
<header>
Links:
{' '}
<Link to="/">Home</Link>
{' '}
<Link to="/foo">Foo</Link>
{' '}
<Link to="/bar">Bar</Link>
</header>
<div>
<button onClick={() => updatePath('/foo')}>Go to /foo</button>
</div>
<div style={{marginTop: '1.5em'}}>{children}</div>
</div>
);
};
module.exports = connect(
null,
{ updatePath }
)(App);
| const React = require('react');
const { Link } = require('react-router');
const { connect } = require('react-redux');
const { pushPath } = require('redux-simple-router');
function App({ pushPath, children }) {
return (
<div>
<header>
Links:
{' '}
<Link to="/">Home</Link>
{' '}
<Link to="/foo">Foo</Link>
{' '}
<Link to="/bar">Bar</Link>
</header>
<div>
<button onClick={() => pushPath('/foo')}>Go to /foo</button>
</div>
<div style={{marginTop: '1.5em'}}>{children}</div>
</div>
);
};
module.exports = connect(
null,
{ pushPath }
)(App);
| Migrate the basic example to the new API | Migrate the basic example to the new API
| JavaScript | mit | rackt/redux-simple-router,reactjs/react-router-redux | ---
+++
@@ -1,9 +1,9 @@
const React = require('react');
const { Link } = require('react-router');
const { connect } = require('react-redux');
-const { updatePath } = require('redux-simple-router');
+const { pushPath } = require('redux-simple-router');
-function App({ updatePath, children }) {
+function App({ pushPath, children }) {
return (
<div>
<header>
@@ -16,7 +16,7 @@
<Link to="/bar">Bar</Link>
</header>
<div>
- <button onClick={() => updatePath('/foo')}>Go to /foo</button>
+ <button onClick={() => pushPath('/foo')}>Go to /foo</button>
</div>
<div style={{marginTop: '1.5em'}}>{children}</div>
</div>
@@ -25,5 +25,5 @@
module.exports = connect(
null,
- { updatePath }
+ { pushPath }
)(App); |
8587e62d184bcc6f28988c6a25b4bbf227d85ed8 | src/diskdrive.js | src/diskdrive.js | var exec = require('child_process').exec;
var self = module.exports;
self.eject = function(id) {
// are we running on mac?
if (process.platform === 'darwin') {
// setup optional argument, on mac, will default to 1
id = (typeof id === 'undefined') ? 1 : id;
exec('drutil tray eject ' + id, function(err, stdout, stderr) {
if (err) {
console.log('ERROR: DiskDrive, when executing bash cmd: ' + err);
return;
}
// if it came here, it went all perfectly and it ejected.
});
// are we running on linux?
} else if (process.platform === 'linux') {
// setup optional argument, on linux, will default to '' (empty string)
id = (typeof id === 'undefined') ? '' : id;
exec('eject ' + id, function(err, stdout, stderr) {
if (err) {
console.log('ERROR: DiskDrive, when executing bash cmd: ' + err);
return;
}
// if it came here, it went all perfectly and it ejected.
});
} else {
console.log('ERROR: Unsupported DiskDrive platform (' + process.platform + ').');
}
}; | var exec = require('child_process').exec;
var self = module.exports;
/**
* Eject the specified disk drive.
* @param {int|string} id Locator for the disk drive.
* @param {Function} callback Optional callback for disk drive ejection completion / error.
*/
self.eject = function(id, callback) {
// are we running on mac?
if (process.platform === 'darwin') {
// setup optional argument, on mac, will default to 1
id = (typeof id === 'undefined') ? 1 : id;
exec('drutil tray eject ' + id, function(err, stdout, stderr) {
if (err && callback) {
// error occurred and callback exists
callback(err);
} else if (callback) {
// no error, but callback for completion
callback(null);
}
});
// are we running on linux?
} else if (process.platform === 'linux') {
// setup optional argument, on linux, will default to '' (empty string)
id = (typeof id === 'undefined') ? '' : id;
exec('eject ' + id, function(err, stdout, stderr) {
if (err && callback) {
callback(err);
} else if (callback) {
// no error, callback for completion
callback(null);
}
});
} else {
process.nextTick(callback.bind(null, 'unsupported platform: ' + process.platform));
}
}; | Support for completion callback with error | Support for completion callback with error
| JavaScript | mit | brendanashworth/diskdrive | ---
+++
@@ -2,19 +2,25 @@
var self = module.exports;
-self.eject = function(id) {
+/**
+ * Eject the specified disk drive.
+ * @param {int|string} id Locator for the disk drive.
+ * @param {Function} callback Optional callback for disk drive ejection completion / error.
+ */
+self.eject = function(id, callback) {
// are we running on mac?
if (process.platform === 'darwin') {
// setup optional argument, on mac, will default to 1
id = (typeof id === 'undefined') ? 1 : id;
exec('drutil tray eject ' + id, function(err, stdout, stderr) {
- if (err) {
- console.log('ERROR: DiskDrive, when executing bash cmd: ' + err);
- return;
+ if (err && callback) {
+ // error occurred and callback exists
+ callback(err);
+ } else if (callback) {
+ // no error, but callback for completion
+ callback(null);
}
-
- // if it came here, it went all perfectly and it ejected.
});
// are we running on linux?
} else if (process.platform === 'linux') {
@@ -22,14 +28,14 @@
id = (typeof id === 'undefined') ? '' : id;
exec('eject ' + id, function(err, stdout, stderr) {
- if (err) {
- console.log('ERROR: DiskDrive, when executing bash cmd: ' + err);
- return;
+ if (err && callback) {
+ callback(err);
+ } else if (callback) {
+ // no error, callback for completion
+ callback(null);
}
-
- // if it came here, it went all perfectly and it ejected.
});
} else {
- console.log('ERROR: Unsupported DiskDrive platform (' + process.platform + ').');
+ process.nextTick(callback.bind(null, 'unsupported platform: ' + process.platform));
}
}; |
cb2a18f55784f2b5ce0305d68dee0a4835430435 | tests/loaders/assets.spec.js | tests/loaders/assets.spec.js | /*!
* qwebs
* Copyright(c) 2016 Benoît Claveau
* MIT Licensed
*/
"use strict";
const Qwebs = require("../../lib/qwebs");
const AssetsLoader = require("../../lib/loaders/assets");
describe("assetsLoader", () => {
it("load", done => {
return Promise.resolve().then(() => {
let $qwebs = new Qwebs({ dirname: __dirname, config: { folder: "public" }});
let $config = $qwebs.resolve("$config");
let $router = $qwebs.resolve("$router");
return new AssetsLoader($qwebs, $config, $router).load().then(assets => {
expect(assets.length).toEqual(2);
expect(assets[0].route).toEqual("/assets/user.svg");
expect(assets[1].route).toEqual("/main.html");
});
}).catch(error => {
expect(error).toBeNull();
}).then(() => {
done();
});
});
});
| /*!
* qwebs
* Copyright(c) 2016 Benoît Claveau
* MIT Licensed
*/
"use strict";
const Qwebs = require("../../lib/qwebs");
const AssetsLoader = require("../../lib/loaders/assets");
describe("assetsLoader", () => {
it("Load", done => {
return Promise.resolve().then(() => {
let $qwebs = new Qwebs({ dirname: __dirname, config: { folder: "public" }});
let $config = $qwebs.resolve("$config");
let $router = $qwebs.resolve("$router");
return new AssetsLoader($qwebs, $config, $router).load().then(assets => {
expect(assets.length).toEqual(2);
expect(assets[0].route).toEqual("/assets/user.svg");
expect(assets[1].route).toEqual("/main.html");
});
}).catch(error => {
expect(error).toBeNull();
}).then(() => {
done();
});
});
it("Failed to read public folder", done => {
return Promise.resolve().then(() => {
let $qwebs = new Qwebs({ dirname: __dirname, config: { folder: "public0" }});
let $config = $qwebs.resolve("$config");
let $router = $qwebs.resolve("$router");
return new AssetsLoader($qwebs, $config, $router).load().catch(error => {
expect(error.message).toEqual("Failed to read public folder.");
});
}).catch(error => {
expect(error).toBeNull();
}).then(() => {
done();
});
});
});
| Test failed to read public folder | Test failed to read public folder | JavaScript | mit | BenoitClaveau/qwebs,beny78/qwebs,BenoitClaveau/qwebs,beny78/qwebs | ---
+++
@@ -10,7 +10,7 @@
describe("assetsLoader", () => {
- it("load", done => {
+ it("Load", done => {
return Promise.resolve().then(() => {
let $qwebs = new Qwebs({ dirname: __dirname, config: { folder: "public" }});
let $config = $qwebs.resolve("$config");
@@ -28,4 +28,20 @@
done();
});
});
+
+ it("Failed to read public folder", done => {
+ return Promise.resolve().then(() => {
+ let $qwebs = new Qwebs({ dirname: __dirname, config: { folder: "public0" }});
+ let $config = $qwebs.resolve("$config");
+ let $router = $qwebs.resolve("$router");
+
+ return new AssetsLoader($qwebs, $config, $router).load().catch(error => {
+ expect(error.message).toEqual("Failed to read public folder.");
+ });
+ }).catch(error => {
+ expect(error).toBeNull();
+ }).then(() => {
+ done();
+ });
+ });
}); |
fa56b7a00fc9d56cfea11f9dce754f9d5e5859f8 | src/event/css.js | src/event/css.js | /*
---
name: Event.CSS3
description: Provides CSS3 events.
license: MIT-style license.
authors:
- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
requires:
- Custom-Event/Element.defineCustomEvent
provides:
- Event.CSS3
...
*/
(function() {
// TODO: Property detect if a prefix-less version is available
var a = '';
var t = '';
if (Browser.safari || Browser.chrome || Browser.platform.ios) {
a = 'webkitAnimationEnd';
t = 'webkitTransitionEnd';
} else if (Browser.firefox) {
a = 'animationend';
t = 'transitionend';
} else if (Browser.opera) {
a = 'oAnimationEnd';
t = 'oTransitionEnd';
} else if (Browser.ie) {
a = 'msAnimationEnd';
t = 'msTransitionEnd';
}
Element.NativeEvents[a] = 2;
Element.NativeEvents[t] = 2;
Element.Events['transitionend'] = { base: t, onAdd: function(){}, onRemove: function(){} };
Element.Events['animationend'] = { base: a, onAdd: function(){}, onRemove: function(){} };
Element.defineCustomEvent('owntransitionend', {
base: 'transitionend',
condition: function(e) {
e.stop();
return e.target === this;
}
});
Element.defineCustomEvent('ownanimationend', {
base: 'animationend',
condition: function(e) {
e.stop();
return e.target === this;
}
})
})();
| /*
---
name: Event.CSS3
description: Provides CSS3 events.
license: MIT-style license.
authors:
- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
requires:
- Custom-Event/Element.defineCustomEvent
provides:
- Event.CSS3
...
*/
(function() {
// TODO: Property detect if a prefix-less version is available
var a = 'animationend';
var t = 'transitionend';
Element.NativeEvents[a] = 2;
Element.NativeEvents[t] = 2;
Element.Events['transitionend'] = { base: t, onAdd: function(){}, onRemove: function(){} };
Element.Events['animationend'] = { base: a, onAdd: function(){}, onRemove: function(){} };
Element.defineCustomEvent('owntransitionend', {
base: 'transitionend',
condition: function(e) {
e.stop();
return e.target === this;
}
});
Element.defineCustomEvent('ownanimationend', {
base: 'animationend',
condition: function(e) {
e.stop();
return e.target === this;
}
})
})();
| Fix an issue with prefixing animationend and transitionend | Fix an issue with prefixing animationend and transitionend
Signed-off-by: Yannick Gagnon <d4b2c45cb5d34b718a9a7e841e45e36d4b2966bc@lemieuxbedard.com>
| JavaScript | mit | moobilejs/moobile-core,jpdery/moobile-core,moobilejs/moobile-core,jpdery/moobile-core | ---
+++
@@ -23,22 +23,8 @@
// TODO: Property detect if a prefix-less version is available
-var a = '';
-var t = '';
-
-if (Browser.safari || Browser.chrome || Browser.platform.ios) {
- a = 'webkitAnimationEnd';
- t = 'webkitTransitionEnd';
-} else if (Browser.firefox) {
- a = 'animationend';
- t = 'transitionend';
-} else if (Browser.opera) {
- a = 'oAnimationEnd';
- t = 'oTransitionEnd';
-} else if (Browser.ie) {
- a = 'msAnimationEnd';
- t = 'msTransitionEnd';
-}
+var a = 'animationend';
+var t = 'transitionend';
Element.NativeEvents[a] = 2;
Element.NativeEvents[t] = 2; |
4cc9f1f6ede2f3d1b428e7422fd4767c50c5eab3 | src/githubApi.js | src/githubApi.js | define(["lib/reqwest", "lib/lodash", "lib/knockout", "githubEvent"],
function (reqwest, _, ko, GithubEvent) {
var githubApi = {};
var rootUrl = "https://api.github.com";
function getOrganisationMembers(orgName) {
return reqwest({
url: rootUrl + '/orgs/' + orgName + '/members',
type: 'json'
});
}
function getUserEvents(username) {
return reqwest({
url: rootUrl + '/users/' + username + '/events',
type: 'json'
}).then(function (response) {
return _.map(response, function (response) {
return new GithubEvent(response);
});
});
}
// Returns a KO array which is then updated as data arrives
githubApi.getOrganisationEvents = function (orgName) {
var events = ko.observableArray([]);
var loading = 1;
getOrganisationMembers(orgName).then(function (members) {
loading = members.length;
_.each(members, function (member) {
getUserEvents(member.login).then(function (userEvents) {
events(events().concat(userEvents));
loading--;
});
});
});
events.loadingComplete = ko.computed(function () {
return loading === 0;
});
return events;
};
return githubApi;
}); | define(["lib/reqwest", "lib/lodash", "lib/knockout", "githubEvent"],
function (reqwest, _, ko, GithubEvent) {
var githubApi = {};
var rootUrl = "https://api.github.com";
function getOrganisationMembers(orgName) {
return reqwest({
url: 'https://api.github.com/orgs/' + orgName + '/members',
type: 'json'
});
}
function getUserEvents(username) {
return reqwest({
url: 'https://github.com/' + username + '.json?callback=?',
method: 'get',
crossOrigin: true,
headers: { "Accept": "application/json" },
type: 'jsonp'
}).then(function (response) {
return _.map(response, function (response) {
return new GithubEvent(response);
});
});
}
// Returns a KO array which is then updated as data arrives
githubApi.getOrganisationEvents = function (orgName) {
var events = ko.observableArray([]);
var loading = 1;
getOrganisationMembers(orgName).then(function (members) {
loading = members.length;
_.each(members, function (member) {
getUserEvents(member.login).then(function (userEvents) {
events(events().concat(userEvents));
loading--;
});
});
});
events.loadingComplete = ko.computed(function () {
return loading === 0;
});
return events;
};
return githubApi;
}); | Move event source to Github site feeds, rather than full (rate-limited) API | Move event source to Github site feeds, rather than full (rate-limited) API
| JavaScript | mit | pimterry/github-org-feed-page,pimterry/github-org-feed-page | ---
+++
@@ -6,15 +6,18 @@
function getOrganisationMembers(orgName) {
return reqwest({
- url: rootUrl + '/orgs/' + orgName + '/members',
+ url: 'https://api.github.com/orgs/' + orgName + '/members',
type: 'json'
});
}
function getUserEvents(username) {
return reqwest({
- url: rootUrl + '/users/' + username + '/events',
- type: 'json'
+ url: 'https://github.com/' + username + '.json?callback=?',
+ method: 'get',
+ crossOrigin: true,
+ headers: { "Accept": "application/json" },
+ type: 'jsonp'
}).then(function (response) {
return _.map(response, function (response) {
return new GithubEvent(response); |
fc5c76afa4402477d7cc70010d253a05e5688603 | learnyounode/json-api-server.js | learnyounode/json-api-server.js | var http = require('http')
var moment = require('moment')
var url = require('url')
function stringifyTime(now) {
var timeString = '{"hour":' + now.hour() +
',"minute":' + now.minute() +
',"second":' + now.second() + '}'
return timeString;
}
function unixifyTime(now) {
var timeString = '{"unixtime":' + now.valueOf() + '}';
return timeString;
}
var server = http.createServer(function(req, resp) {
if (req.method != 'GET') {
resp.writeHead(405, {'Allow': 'GET'})
resp.end('{"message": "bad method (method != GET)"}')
}
var hash = url.parse(req.url, true)
var fcn = (function(now){ return null });
switch(hash.pathname) {
case '/api/parsetime':
fcn = stringifyTime;
break;
case '/api/unixtime':
fcn = unixifyTime;
break;
}
var dateString = hash.query.iso
var dateObj = moment(dateString)
resp.writeHead(200, {'Content-Type': 'application/json'})
resp.end(fcn(dateObj))
})
server.listen(8000)
| var http = require('http')
var moment = require('moment')
var url = require('url')
function stringifyTime(time) {
return {
hour: time.hour(),
minute: time.minute(),
second: time.second()
}
}
function unixifyTime(time) {
return { unixtime: time.valueOf() }
}
var server = http.createServer(function(req, resp) {
if (req.method != 'GET') {
resp.writeHead(405, {'Allow': 'GET'})
resp.end(JSON.stringify({message: 'bad method (method != GET)'}))
}
var parsed = url.parse(req.url, true)
var result = null
var date = moment(parsed.query.iso)
switch(parsed.pathname) {
case '/api/parsetime':
result = stringifyTime(date)
break;
case '/api/unixtime':
result = unixifyTime(date)
break;
}
resp.writeHead(200, {'Content-Type': 'application/json'})
resp.end(JSON.stringify(result))
})
server.listen(8000)
| Use JS Objects for generating JSON | Use JS Objects for generating JSON
Replace hand-coded JSON strings with JSON hashes (or Objects, I'm not
sure what they are defined as at this point.)
| JavaScript | mit | nmarley/node-playground,nmarley/node-playground | ---
+++
@@ -2,41 +2,39 @@
var moment = require('moment')
var url = require('url')
-function stringifyTime(now) {
- var timeString = '{"hour":' + now.hour() +
- ',"minute":' + now.minute() +
- ',"second":' + now.second() + '}'
- return timeString;
+function stringifyTime(time) {
+ return {
+ hour: time.hour(),
+ minute: time.minute(),
+ second: time.second()
+ }
}
-function unixifyTime(now) {
- var timeString = '{"unixtime":' + now.valueOf() + '}';
- return timeString;
+function unixifyTime(time) {
+ return { unixtime: time.valueOf() }
}
var server = http.createServer(function(req, resp) {
if (req.method != 'GET') {
resp.writeHead(405, {'Allow': 'GET'})
- resp.end('{"message": "bad method (method != GET)"}')
+ resp.end(JSON.stringify({message: 'bad method (method != GET)'}))
}
- var hash = url.parse(req.url, true)
- var fcn = (function(now){ return null });
+ var parsed = url.parse(req.url, true)
+ var result = null
+ var date = moment(parsed.query.iso)
- switch(hash.pathname) {
+ switch(parsed.pathname) {
case '/api/parsetime':
- fcn = stringifyTime;
+ result = stringifyTime(date)
break;
case '/api/unixtime':
- fcn = unixifyTime;
+ result = unixifyTime(date)
break;
}
- var dateString = hash.query.iso
- var dateObj = moment(dateString)
-
resp.writeHead(200, {'Content-Type': 'application/json'})
- resp.end(fcn(dateObj))
+ resp.end(JSON.stringify(result))
})
server.listen(8000) |
3c3515ca7d264f4fa1d58047d60d4522a8eb21a2 | test/index-spec.js | test/index-spec.js | /* eslint-disable prefer-arrow-callback */
/* eslint-env node, mocha, browser */
const assert = require('assert');
const test = require('../src/index').test;
const item = require('./harness/component-data');
const path = require('path');
describe('Vue test utils', () => {
const pathToHarness = path.resolve(__dirname, './harness/vue-main');
it('should render components with children', function () {
return test(pathToHarness, 'parent').then((win) => {
assert.equal(document.querySelector('#div1').textContent, 'div1');
window.x = 1;
win.cleanup();
});
});
it('should render components with data', function () {
return test(pathToHarness, 'parent').then((win) => {
assert.equal(document.querySelector('#div2').textContent, item.x);
window.x = 1;
win.cleanup();
});
});
it('clean up jsdom environment', function () {
return test(pathToHarness, 'parent').then((win) => {
assert.ok(!win.x);
win.cleanup();
});
});
it('update dom per Vue dom event click handlers', function () {
return test(pathToHarness, 'parent', function (win) {
win.$('#click-add').trigger('click');
}).then((win) => {
assert.equal(win.$('#msg').text(), '1');
win.cleanup();
});
});
});
| /* eslint-disable prefer-arrow-callback */
/* eslint-env node, mocha, browser */
const assert = require('assert');
const test = require('../src/index').test;
const item = require('./harness/component-data');
const path = require('path');
describe('Vue test utils', () => {
const pathToHarness = path.resolve(__dirname, './harness/vue-main');
it('Pass take callback with window, $, cleanup function', function () {
return test(pathToHarness, 'parent').then((win) => {
assert.ok(win);
assert.ok(win.$);
assert.ok(win.cleanup);
win.cleanup();
});
});
it('should render components with children', function () {
return test(pathToHarness, 'parent').then((win) => {
assert.equal(document.querySelector('#div1').textContent, 'div1');
window.x = 1;
win.cleanup();
});
});
it('should render components with data', function () {
return test(pathToHarness, 'parent').then((win) => {
assert.equal(document.querySelector('#div2').textContent, item.x);
window.x = 1;
win.cleanup();
});
});
it('clean up jsdom environment', function () {
return test(pathToHarness, 'parent').then((win) => {
assert.ok(!win.x);
win.cleanup();
});
});
it('update dom per Vue dom event click handlers', function () {
return test(pathToHarness, 'parent', function (win) {
win.$('#click-add').trigger('click');
}).then((win) => {
assert.equal(win.$('#msg').text(), '1');
win.cleanup();
});
});
});
| Add unit test for verifying window in then callback. | Add unit test for verifying window in then callback.
| JavaScript | mit | peripateticus/vue-test-utils | ---
+++
@@ -8,6 +8,15 @@
describe('Vue test utils', () => {
const pathToHarness = path.resolve(__dirname, './harness/vue-main');
+
+ it('Pass take callback with window, $, cleanup function', function () {
+ return test(pathToHarness, 'parent').then((win) => {
+ assert.ok(win);
+ assert.ok(win.$);
+ assert.ok(win.cleanup);
+ win.cleanup();
+ });
+ });
it('should render components with children', function () {
return test(pathToHarness, 'parent').then((win) => { |
f35ef3ea96f4fb1d696f8f91e150b1869cbcd1ce | lib/precompiled/07-bn128_mul.js | lib/precompiled/07-bn128_mul.js | const utils = require('ethereumjs-util')
const BN = utils.BN
const bn128_module = require('rustbn.js')
const ecMul_precompile = bn128_module.cwrap('ec_mul', 'string', ['string'])
module.exports = function (opts) {
let results = {}
let data = opts.data
let inputHexStr = data.toString('hex')
try {
let returnData = ecMul_precompile(inputHexStr)
results.return = Buffer.from(returnData, 'hex')
results.exception = 1
} catch (e) {
console.log('exception in ecMul precompile is expected. ignore previous panic...')
// console.log(e)
results.return = Buffer.alloc(0)
results.exception = 0
}
// Temporary, replace with finalized gas cost from EIP spec (via ethereum-common)
results.gasUsed = new BN(2000)
return results
}
| const utils = require('ethereumjs-util')
const BN = utils.BN
const bn128_module = require('rustbn.js')
const ecMul_precompile = bn128_module.cwrap('ec_mul', 'string', ['string'])
module.exports = function (opts) {
let results = {}
let data = opts.data
let inputHexStr = data.toString('hex')
try {
let returnData = ecMul_precompile(inputHexStr)
results.return = Buffer.from(returnData, 'hex')
results.exception = 1
} catch (e) {
console.log('exception in ecMul precompile is expected. ignore previous panic...')
// console.log(e)
results.return = Buffer.alloc(0)
results.exception = 0
}
// Temporary, replace with finalized gas cost from EIP spec (via ethereum-common)
results.gasUsed = new BN(40000)
return results
}
| Update gas costs for EC mult precompile | Update gas costs for EC mult precompile
| JavaScript | mpl-2.0 | ethereumjs/ethereumjs-vm,ethereum/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm,ethereumjs/ethereumjs-vm | ---
+++
@@ -22,6 +22,6 @@
}
// Temporary, replace with finalized gas cost from EIP spec (via ethereum-common)
- results.gasUsed = new BN(2000)
+ results.gasUsed = new BN(40000)
return results
} |
cccaf09e5b76b05b42370888f7edd9908f6f63a0 | src/pages/qr.js | src/pages/qr.js | import React from 'react'
import PropTypes from 'prop-types'
import { compose, withProps } from 'recompose'
import QRCode from 'qrcode.react'
import { withRouter } from 'next/router'
import { StaticLayout } from '../components/layouts'
import { withLogging } from '../lib'
const propTypes = {
shortname: PropTypes.string.isRequired,
}
const QR = ({ shortname }) => {
const joinLink = `${process.env.APP_BASE_URL}/join/${shortname}`
return (
<StaticLayout pageTitle="QR">
<div className="link">{joinLink.replace(/^https?:\/\//,'')}</div>
<div className="qr">
<QRCode size={700} value={joinLink} />
</div>
<style jsx>{`
@import 'src/theme';
.link {
line-height: 4rem;
font-size: 4rem;
font-weight: bold;
margin-bottom: 2rem;
}
.qr {
display: flex;
align-items: center;
justify-content: center;
}
`}</style>
</StaticLayout>
)
}
QR.propTypes = propTypes
export default compose(
withRouter,
withLogging(),
withProps(({ router }) => ({
shortname: router.query.shortname,
}))
)(QR)
| import React from 'react'
import PropTypes from 'prop-types'
import { compose, withProps } from 'recompose'
import QRCode from 'qrcode.react'
import { withRouter } from 'next/router'
import { StaticLayout } from '../components/layouts'
import { withLogging } from '../lib'
const propTypes = {
shortname: PropTypes.string.isRequired,
}
const QR = ({ shortname }) => {
const joinLink = `${process.env.APP_BASE_URL}/join/${shortname}`
return (
<StaticLayout pageTitle="QR">
<div className="link">{joinLink.replace(/^https?:\/\//, '')}</div>
<div className="qr">
<QRCode size={700} value={joinLink} />
</div>
<style jsx>{`
@import 'src/theme';
.link {
line-height: 4rem;
font-size: 4rem;
font-weight: bold;
margin-bottom: 2rem;
}
.qr {
display: flex;
align-items: center;
justify-content: center;
}
`}</style>
</StaticLayout>
)
}
QR.propTypes = propTypes
export default compose(
withRouter,
withLogging(),
withProps(({ router }) => ({
shortname: router.query.shortname,
}))
)(QR)
| Format regex for QR page | Format regex for QR page
| JavaScript | agpl-3.0 | uzh-bf/klicker-react,uzh-bf/klicker-react | ---
+++
@@ -16,7 +16,7 @@
return (
<StaticLayout pageTitle="QR">
- <div className="link">{joinLink.replace(/^https?:\/\//,'')}</div>
+ <div className="link">{joinLink.replace(/^https?:\/\//, '')}</div>
<div className="qr">
<QRCode size={700} value={joinLink} />
</div> |
8c23d570176a529519ac869508b1db59c5485a1e | src/lib/utils.js | src/lib/utils.js | module.exports = {
getViewPortInfo: function getViewPort () {
var e = document.documentElement
var g = document.getElementsByTagName('body')[0]
var x = window.innerWidth || e.clientWidth || g.clientWidth
var y = window.innerHeight || e.clientHeight || g.clientHeight
return {
width: x,
height: y
}
},
mergeObject: function (o1, o2) {
var a
var o3 = {}
for (a in o1) {
o3[a] = o1[a]
}
for (a in o2) {
o3[a] = o2[a]
}
return o3
},
isUndefined: function (obj) {
return (typeof obj) === 'undefined'
},
getCurrentScript: function () {
// Source http://www.2ality.com/2014/05/current-script.html
return document.currentScript || (function () {
var scripts = document.getElementsByTagName('script')
return scripts[scripts.length - 1]
})()
}
}
| module.exports = {
getViewPortInfo: function getViewPort () {
var e = document.documentElement
var g = document.getElementsByTagName('body')[0]
var x = window.innerWidth || e.clientWidth || g.clientWidth
var y = window.innerHeight || e.clientHeight || g.clientHeight
return {
width: x,
height: y
}
},
mergeObject: function (o1, o2) {
var a
var o3 = {}
for (a in o1) {
o3[a] = o1[a]
}
for (a in o2) {
o3[a] = o2[a]
}
return o3
},
isUndefined: function (obj) {
return (typeof obj) === 'undefined'
},
getCurrentScript: function () {
// Source http://www.2ality.com/2014/05/current-script.html
return document.currentScript || (function () {
var scripts = document.getElementsByTagName('script')
return scripts[scripts.length - 1]
})()
},
promiseAny: function(arrayOfPromises) {
if(!arrayOfPromises || !(arrayOfPromises instanceof Array)) {
throw new Error('Must pass Promise.any an array');
}
if(arrayOfPromises.length === 0) {
return Promise.resolve([]);
}
// For each promise that resolves or rejects,
// make them all resolve.
// Record which ones did resolve or reject
var resolvingPromises = arrayOfPromises.map(function(promise) {
return promise.then(function(result) {
return {
resolve: true,
result: result
};
}, function(error) {
return {
resolve: false,
result: error
};
});
});
return Promise.all(resolvingPromises).then(function(results) {
// Count how many passed/failed
var passed = [], failed = [], allFailed = true;
results.forEach(function(result) {
if(result.resolve) {
allFailed = false;
}
passed.push(result.resolve ? result.result : null);
failed.push(result.resolve ? null : result.result);
});
return passed;
});
}
}
| Add promiseAny until function to get Promise.any support without extending prototype | Add promiseAny until function to get Promise.any support without extending prototype | JavaScript | mit | opbeat/opbeat-angular,jahtalab/opbeat-js,opbeat/opbeat-js-core,opbeat/opbeat-angular,opbeat/opbeat-react,opbeat/opbeat-react,jahtalab/opbeat-js,opbeat/opbeat-react,jahtalab/opbeat-js,opbeat/opbeat-angular,opbeat/opbeat-js-core | ---
+++
@@ -36,6 +36,50 @@
var scripts = document.getElementsByTagName('script')
return scripts[scripts.length - 1]
})()
+ },
+
+ promiseAny: function(arrayOfPromises) {
+ if(!arrayOfPromises || !(arrayOfPromises instanceof Array)) {
+ throw new Error('Must pass Promise.any an array');
+ }
+
+ if(arrayOfPromises.length === 0) {
+ return Promise.resolve([]);
+ }
+
+
+ // For each promise that resolves or rejects,
+ // make them all resolve.
+ // Record which ones did resolve or reject
+ var resolvingPromises = arrayOfPromises.map(function(promise) {
+ return promise.then(function(result) {
+ return {
+ resolve: true,
+ result: result
+ };
+ }, function(error) {
+ return {
+ resolve: false,
+ result: error
+ };
+ });
+ });
+
+ return Promise.all(resolvingPromises).then(function(results) {
+ // Count how many passed/failed
+ var passed = [], failed = [], allFailed = true;
+ results.forEach(function(result) {
+ if(result.resolve) {
+ allFailed = false;
+ }
+ passed.push(result.resolve ? result.result : null);
+ failed.push(result.resolve ? null : result.result);
+ });
+
+ return passed;
+
+ });
+
}
} |
6ece176a96ddcc80e681ae668f5bdbf865fec567 | src/webpack/presets/eslint.js | src/webpack/presets/eslint.js | import path from 'path'
export default {
name: 'eslint',
configure ({ projectPath }) {
return {
eslint: {
configFile: path.join(projectPath, '.eslintrc')
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: 'eslint',
exclude: /node_modules/
}
]
}
}
}
}
| import path from 'path'
export default {
name: 'eslint',
configure ({ projectPath, enableCoverage }) {
if (!enableCoverage) {
return {}
}
return {
eslint: {
configFile: path.join(projectPath, '.eslintrc')
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: 'eslint',
exclude: /node_modules/
}
]
}
}
}
}
| Disable linting when generating coverage | feat(coverage): Disable linting when generating coverage
| JavaScript | mit | saguijs/sagui,saguijs/sagui | ---
+++
@@ -2,7 +2,11 @@
export default {
name: 'eslint',
- configure ({ projectPath }) {
+ configure ({ projectPath, enableCoverage }) {
+ if (!enableCoverage) {
+ return {}
+ }
+
return {
eslint: {
configFile: path.join(projectPath, '.eslintrc') |
29d78768f62444fbba32cab9e2ebf8aa3450991a | client/app/services/session.js | client/app/services/session.js | /* globals Stripe */
import Ember from 'ember';
var $ = Ember.$;
function registrationDataFromUrl(url) {
var matches = url.match(/\?code=(\d+)/);
if (matches && matches.length === 2) {
return {registration_code: matches[1]};
} else {
return {};
}
}
function initializeStripe(key) {
Stripe.setPublishableKey(key);
}
function setupCsrfHeaders(token) {
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
return jqXHR.setRequestHeader('X-CSRF-Token', token);
});
}
export default Ember.Service.extend({
setup: function(url) {
return $.get(
'/training/api/sessions',
registrationDataFromUrl(url)
).then(this.requestDidReturn);
},
requestDidReturn: function(response) {
setupCsrfHeaders(response.authenticity_token);
initializeStripe(response.stripe_public_key);
}
});
| /* globals Stripe */
import Ember from 'ember';
var $ = Ember.$;
function registrationDataFromUrl(url) {
var matches = url.match(/\?code=([a-z0-9]+)/);
if (matches && matches.length === 2) {
return {registration_code: matches[1]};
} else {
return {};
}
}
function initializeStripe(key) {
Stripe.setPublishableKey(key);
}
function setupCsrfHeaders(token) {
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
return jqXHR.setRequestHeader('X-CSRF-Token', token);
});
}
export default Ember.Service.extend({
setup: function(url) {
return $.get(
'/training/api/sessions',
registrationDataFromUrl(url)
).then(this.requestDidReturn);
},
requestDidReturn: function(response) {
setupCsrfHeaders(response.authenticity_token);
initializeStripe(response.stripe_public_key);
}
});
| Update regular expression for registration code | Update regular expression for registration code | JavaScript | mit | mitchlloyd/training,mitchlloyd/training,mitchlloyd/training | ---
+++
@@ -3,7 +3,7 @@
var $ = Ember.$;
function registrationDataFromUrl(url) {
- var matches = url.match(/\?code=(\d+)/);
+ var matches = url.match(/\?code=([a-z0-9]+)/);
if (matches && matches.length === 2) {
return {registration_code: matches[1]}; |
c3e1fa56c7b2690a59a2c6790eb83dd068746da0 | tests/canvas.js | tests/canvas.js | $(document).ready(function() {
module("Canvas presentations");
test("Check Canvas Presentations", function() {
expect(1);
ok(MITHGrid.Presentation.RaphSVG !== undefined, "RaphSVG Presentation exists");
//ok(MITHGrid.Presentation.SVGRect !== undefined, "SVGRect Presentation exists");
});
test("Check Canvas availability", function() {
expect(2);
var container = $("#test-158603");
var svg, presentation;
presentation = MITHGrid.Presentation.RaphSVG.initPresentation(container, {
dataView: MITHGrid.Data.initView({
dataStore: MITHGrid.Data.initStore({})
}),
cWidth: 1,
cHeight: 1,
lenses: {}
});
ok(presentation !== undefined, "Presentation object exists");
ok(presentation.canvas !== undefined && presentation.canvas.canvas !== undefined &&
presentation.canvas.canvas.localName === "svg", "presentation canvas svg element is good");
});
/*
module("Canvas");
test("Check namespace", function() {
expect(2);
ok(MITHGrid.Application.Canvas !== undefined, "MITHGrid.Application.Canvas exists");
ok($.isFunction(MITHGrid.Application.Canvas.namespace), "MITHGrid.Application.Canvas.namespace is a function");
});
module("Canvas.initApp");
test("Check initApp", function() {
expect(1);
ok(MITHGrid.Application.Canvas.initApp !== undefined, "Canvas.initApp defined and is a function");
});
*/
}); | $(document).ready(function() {
module("Canvas presentations");
test("Check Canvas Presentations", function() {
expect(1);
ok(MITHGrid.Presentation.RaphSVG !== undefined, "RaphSVG Presentation exists");
});
test("Check Canvas availability", function() {
var presentation;
expect(3);
try {
presentation = MITHGrid.Presentation.RaphSVG.initPresentation($('test-158603'), {
dataView: MITHGrid.Data.initView({
dataStore: MITHGrid.Data.initStore({})
}),
cWidth: 1,
cHeight: 1,
lenses: {}
});
ok(true, "Presentation object created");
}
catch(e) {
ok(false, "Presentation object not created: " + e);
}
ok(presentation !== undefined, "Presentation object exists");
ok(presentation.canvas !== undefined && presentation.canvas.canvas !== undefined &&
presentation.canvas.canvas.localName === "svg", "presentation canvas svg element is good");
});
}); | Fix test missing the container element | Fix test missing the container element
| JavaScript | apache-2.0 | umd-mith/OACVideoAnnotator,umd-mith/OACVideoAnnotator,umd-mith/OACVideoAnnotator | ---
+++
@@ -4,44 +4,31 @@
test("Check Canvas Presentations", function() {
expect(1);
- ok(MITHGrid.Presentation.RaphSVG !== undefined, "RaphSVG Presentation exists");
- //ok(MITHGrid.Presentation.SVGRect !== undefined, "SVGRect Presentation exists");
-
+ ok(MITHGrid.Presentation.RaphSVG !== undefined, "RaphSVG Presentation exists");
});
test("Check Canvas availability", function() {
- expect(2);
- var container = $("#test-158603");
+ var presentation;
+ expect(3);
- var svg, presentation;
- presentation = MITHGrid.Presentation.RaphSVG.initPresentation(container, {
- dataView: MITHGrid.Data.initView({
- dataStore: MITHGrid.Data.initStore({})
- }),
- cWidth: 1,
- cHeight: 1,
- lenses: {}
- });
+ try {
+ presentation = MITHGrid.Presentation.RaphSVG.initPresentation($('test-158603'), {
+ dataView: MITHGrid.Data.initView({
+ dataStore: MITHGrid.Data.initStore({})
+ }),
+ cWidth: 1,
+ cHeight: 1,
+ lenses: {}
+ });
+ ok(true, "Presentation object created");
+ }
+ catch(e) {
+ ok(false, "Presentation object not created: " + e);
+ }
+
ok(presentation !== undefined, "Presentation object exists");
ok(presentation.canvas !== undefined && presentation.canvas.canvas !== undefined &&
presentation.canvas.canvas.localName === "svg", "presentation canvas svg element is good");
});
-/*
- module("Canvas");
-
- test("Check namespace", function() {
- expect(2);
- ok(MITHGrid.Application.Canvas !== undefined, "MITHGrid.Application.Canvas exists");
- ok($.isFunction(MITHGrid.Application.Canvas.namespace), "MITHGrid.Application.Canvas.namespace is a function");
- });
-
- module("Canvas.initApp");
-
- test("Check initApp", function() {
- expect(1);
-
- ok(MITHGrid.Application.Canvas.initApp !== undefined, "Canvas.initApp defined and is a function");
- });
- */
}); |
a8bec029798389b68fe5081ff6736605cdc613a7 | tests/extend.js | tests/extend.js | var $ = require('../')
, assert = require('assert')
$.import('Foundation')
$.NSAutoreleasePool('alloc')('init')
// Subclass 'NSObject', creating a new class named 'NRTest'
var NRTest = $.NSObject.extend('NRTest')
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
return $.NSString('stringWithUTF8String', 'test')
})
// Finalize the class so the we can make instances of it
NRTest.register()
// Create an instance
var instance = NRTest('alloc')('init')
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
console.log(String(instance))
console.log(''+instance)
console.log(instance+'')
console.log(instance)
assert.equal(counter, 6)
| var $ = require('../')
, assert = require('assert')
$.import('Foundation')
$.NSAutoreleasePool('alloc')('init')
// Subclass 'NSObject', creating a new class named 'NRTest'
var NRTest = $.NSObject.extend('NRTest')
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
return $.NSString('stringWithUTF8String', 'test')
})
// Finalize the class so the we can make instances of it
NRTest.register()
// Create an instance
var instance = NRTest('alloc')('init')
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
//console.log(String(instance)) // now this one segfaults? WTF!?!?!
console.log(''+instance)
console.log(instance+'')
console.log(instance)
assert.equal(counter, 5)
| Remove this test case for now... still segfaulting for some crazy reason... | Remove this test case for now... still segfaulting for some crazy reason...
| JavaScript | mit | telerik/NodObjC,mralexgray/NodObjC,TooTallNate/NodObjC,TooTallNate/NodObjC,jerson/NodObjC,jerson/NodObjC,telerik/NodObjC,jerson/NodObjC,mralexgray/NodObjC | ---
+++
@@ -24,9 +24,9 @@
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
-console.log(String(instance))
+//console.log(String(instance)) // now this one segfaults? WTF!?!?!
console.log(''+instance)
console.log(instance+'')
console.log(instance)
-assert.equal(counter, 6)
+assert.equal(counter, 5) |
1e2f798a9a67e57350180e4ac847eac504f11d57 | ember-cli-build.js | ember-cli-build.js | /*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
// Add options here
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
| /*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
snippetSearchPaths: ['app', 'node_modules/ui-base-theme/addon']
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
| Fix code snippets in styleguide | Fix code snippets in styleguide
| JavaScript | mit | prototypal-io/ui-tomato-theme,prototypal-io/ui-tomato-theme | ---
+++
@@ -4,7 +4,7 @@
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
- // Add options here
+ snippetSearchPaths: ['app', 'node_modules/ui-base-theme/addon']
});
/* |
bfa5e93efef1b135edb4cf1807391b5bfc3646fe | src/redux/store.js | src/redux/store.js | // @flow
/* eslint-disable arrow-body-style */
import { applyMiddleware, createStore } from 'redux'
import { createEpicMiddleware } from 'redux-observable'
import thunk from 'redux-thunk'
import promiseMiddleware from 'redux-promise-middleware'
import { routerMiddleware } from 'react-router-redux'
import { composeWithDevTools } from 'redux-devtools-extension/logOnlyInProduction'
import rootEpic from './epics'
import rootReducer from './modules'
function configureStore (
preloadedState: Object, history: Object,
): Object {
const epicMiddleware = createEpicMiddleware(rootEpic)
const middleware = [
epicMiddleware,
thunk,
promiseMiddleware(),
routerMiddleware(history),
]
// only log redux actions in development
if (process.env.NODE_ENV === 'development') {
// logger needs to be last
// uncomment if needed
// middleware.push(require('redux-logger').createLogger())
}
// https://github.com/zalmoxisus/redux-devtools-extension
// https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f
const enhancer = composeWithDevTools(
applyMiddleware(...middleware)
)
const store = createStore(rootReducer, preloadedState, enhancer)
return store
}
export default configureStore
| // @flow
/* eslint-disable arrow-body-style */
import { applyMiddleware, createStore, compose } from 'redux'
import { createEpicMiddleware } from 'redux-observable'
import thunk from 'redux-thunk'
import promiseMiddleware from 'redux-promise-middleware'
import { routerMiddleware } from 'react-router-redux'
import { devToolsEnhancer } from 'redux-devtools-extension/logOnlyInProduction'
import rootEpic from './epics'
import rootReducer from './modules'
function configureStore (
preloadedState: Object, history: Object,
): Object {
const epicMiddleware = createEpicMiddleware(rootEpic)
const middleware = [
epicMiddleware,
thunk,
promiseMiddleware(),
routerMiddleware(history),
]
// only log redux actions in development
if (process.env.NODE_ENV === 'development') {
// logger needs to be last
// uncomment if needed
// middleware.push(require('redux-logger').createLogger())
}
// https://github.com/zalmoxisus/redux-devtools-extension
// https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f
const enhancer = compose(
applyMiddleware(...middleware),
devToolsEnhancer()
)
const store = createStore(rootReducer, preloadedState, enhancer)
return store
}
export default configureStore
| Use redux compose with devToolsEnhancer | Use redux compose with devToolsEnhancer
| JavaScript | apache-2.0 | tribou/react-template,tribou/react-template,tribou/react-template,tribou/react-template,tribou/react-template | ---
+++
@@ -1,11 +1,11 @@
// @flow
/* eslint-disable arrow-body-style */
-import { applyMiddleware, createStore } from 'redux'
+import { applyMiddleware, createStore, compose } from 'redux'
import { createEpicMiddleware } from 'redux-observable'
import thunk from 'redux-thunk'
import promiseMiddleware from 'redux-promise-middleware'
import { routerMiddleware } from 'react-router-redux'
-import { composeWithDevTools } from 'redux-devtools-extension/logOnlyInProduction'
+import { devToolsEnhancer } from 'redux-devtools-extension/logOnlyInProduction'
import rootEpic from './epics'
import rootReducer from './modules'
@@ -35,8 +35,9 @@
// https://github.com/zalmoxisus/redux-devtools-extension
// https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f
- const enhancer = composeWithDevTools(
- applyMiddleware(...middleware)
+ const enhancer = compose(
+ applyMiddleware(...middleware),
+ devToolsEnhancer()
)
const store = createStore(rootReducer, preloadedState, enhancer) |
316152ea0fed4dca0b38276bdbf94884a2363b5a | packages/articles/server/routes/articles.js | packages/articles/server/routes/articles.js | 'use strict';
var articles = require('../controllers/articles');
// Article authorization helpers
var hasAuthorization = function(req, res, next) {
if (req.article.user.id !== req.user.id) {
return res.send(401, 'User is not authorized');
}
next();
};
module.exports = function(Articles, app, auth) {
app.route('/articles')
.get(articles.all)
.post(auth.requiresLogin, articles.create);
app.route('/articles/:articleId')
.get(articles.show)
.put(auth.requiresLogin, hasAuthorization, articles.update)
.delete(auth.requiresLogin, hasAuthorization, articles.destroy);
// Finish with setting up the articleId param
app.param('articleId', articles.article);
};
| 'use strict';
var articles = require('../controllers/articles');
// Article authorization helpers
var hasAuthorization = function(req, res, next) {
if (res.adminEnabled() || (req.article.user && (req.article.user_id === req.user._id))) {
next();
}
else {
return res.send(401, 'User is not authorized');
}
};
module.exports = function(Articles, app, auth) {
app.route('/articles')
.get(articles.all)
.post(auth.requiresLogin, articles.create);
app.route('/articles/:articleId')
.get(articles.show)
.put(auth.requiresLogin, hasAuthorization, articles.update)
.delete(auth.requiresLogin, hasAuthorization, articles.destroy);
// Finish with setting up the articleId param
app.param('articleId', articles.article);
};
| Allow for Admin to Edit / Delete | Allow for Admin to Edit / Delete
Allow for Admin to Edit / Delete articles. Allow allow for edit / delete of articles if the user was deleted. | JavaScript | mit | rpalacios/preach-lander,paperdev7/web-project,suyesh/mean,Cneubauern/Test,Tukaiz/vmi,pavitlabs/mindappt,webapp-angularjs/football,MericGarcia/deployment-mean,reergymerej/counts,Edifice/OctoDo,dhivyaprp/Lets-Fix,szrobinli/mean,ngEdmundas/mean-user-management,cyberTrebuchet/this_is_forOM,Chien19861128/qa-app,kmdr/farmy,jasondecamp/mememe,stanosmith/mean-stack-reddit-hacker-news,OdenthalKay/abschluss,anthony-ism/funari,rncrtr/mean,lukert33/luke-will-build,webapp-angularjs/song-lyrics,achekh/civil_government,Damell/Creatures,otherwhitefrank/mean-frankdye-com,kouissar/dcFinderProject,codegaucho/mean-lessonplanner,lvarayut/mean,cedesantis/JamSesh,walton007/envomuse,DarkCascade/get2gether,overlox/OpenHangouts,webapp-angularjs/knowledge-for-sharing,KHam0425/mean,yesmagaly/tesis-review2,kevinzli/meanforms,andbet39/mongularpress,twistedgood/shioris-meanio,bradleytrager/vocab-activity-generator,Baconchin/MeanLearn,baskint/mean,asifalimd/mean-app,kalomj/Pollution,young-utf/meanstack-prac,lollek/MEAN-Social-Site,achekh/civil_government,smadjid/CoReaDa,ameerkawar/MahboussehGame,ThrowsException/crossfit-rivals,baskint/mean,suyesh/mean,alancnet/project,gauss1181/simple-group,baolocdo/python,jenavarro/AllRules,huynhlc100/mean-on-openshift,dandonmesvak/mean-on-openshift,JulienBreux/mean,alexballera/mean,guilhermeyo/mean-articles,pfryga/meanio-example,freddyrangel/tottus,mrClapham/mean_one,sidhart/mean,RStyrman/rstyrman_webdev,chohome2/gamelog,dherrera/revolutioncontribution,darrenmwong/PawPrintMEAN,mkelley33/mean,naveengogineni/navintestmeanapp,piolab/mean,manasmehrotra3/MEANTest,seanworkcode/clinker,pavitlabs/sportify,paulgalarza/empanadas,Sharmaz/mean,kartikmenon/Tinkering-with-MeanStack,ezekielriva/bus-locator,manasmehrotra3/MEANTest,evanjenkins/wtracker,jdelagal/mean,kmdr/farmy,tranphuoctien/mean-on-openshift,Baconchin/MEANTodo,yunx/meanPlay,virtualit786/showcasemean.io,JKTOpen/destiny,fkiller/mean,wagedomain/selfpub,magda/livinglab,johnnyli4a4c/pool-cards,ashblue/meanio-tutorial,darbio/Phoenix,jandeancatarata/Plan4Me,miguelmota/find-me-burritos,nscheu/mistufs,ericjsilva/mywinecellar,zesk8/Blog-Angular-MEAN,rutys/pictionary,dantepsychedelico/erp-tiny-system,mtrinitaria/addmore_app,jeffj/mean_example,OdenthalKay/editor,zulwasaya/meanCustomers,OrderMail/blacklabel,chenyaoli19/meanshop,linnovate/hellogitty,hectorgool/mean-santix,alannesta/mean-scaffold,tedtkang/meanTestApp,islanderz/trainingApp,Superjisan/NYCitizenry,ngEdmundas/mean-user-management,pratik60/mean-1,ShlomyShivek/SchoolMate,destromas1/hellogitty,ahfweb/ahfmpm,dantix/mean,slawomirkroczak/fmottracker,CodeCloudMe/meanExample,overlox/MeanUpload,darul75/nsjoy.github.io2,rconnelly/app,Quadramma/MeanApp.BasicERP,alvarocavalcanti/ring-the-bell,flomarin88/home-domotic,dandonmesvak/mean-on-openshift,taylorjames/noidea,arturomc/meanspace,bozzmob/mean,asicudl/mobile-backend,rahul-tiwari/MEANIO-Basics,vebin/mean,kumaria/mean,erfg/worldcup,marlonator/mean,zulwasaya/todolistsMean,dominicbosch/mean_app,dennisjoedavid123/Catalyst,EugeneZ/dungeonlords,pfryga/meanio-example,OdenthalKay/editor,pfryga/meanIO,kbeyer/K6BEventLoggerDashboard,lvarayut/mean,appirio-tech/lc1-project,andrewchen5678/testmeanio,Borys216307/booking_engine,stanosmith/mean-stack-reddit-hacker-news,alancnet/project,abegit/mean,msabdeljalil/meanApp,DiegoValdivia/mean_practice,brownman/mean_package_testing,dennisjoedavid123/ProjectX,appirio-tech/lc1-project,kaydeveloper/mean,dantepsychedelico/erp-tiny-system,webapp-angularjs/song-lyrics,chrismillsnbcu/mean-demo,blomm/meanio_template,scrock1987/Mean,moritzschaefer/werwolf,JeffCloverLeaf/nodeserver,mstackpo/MattsMeanApp,MericGarcia/deployment-mean,hassanabidpk/mean,09saurabh09/vocal,dherrera/revolutioncontribution,muthhus/mean,kira1009/mean,victorantos/mean,dianavermilya/rain,xxxbartasxxx/expenses,Chien19861128/catchie2,rbcorpgit/mean,ridan/Pakathon,columby/www.columby.com,Ideas2IT/mean-idea,kushaltirumala/mean,LukasK/mean,linnovate/icapi,oritpersik/admin-dashboard,yunx/meanPlay,pavitlabs/sportify,wagedomain/selfpub,mcottingham/FormulaBuilder,PankajMean/Dealdeck,steezeburger/jeannie,bmprovost/soundboard,chackerian/Trades,faisal00813/MEAN-Demo,devsaik/paropakar,thomas-p-wilson/performance-test,InonS/mean-inon,imsaar/zainab-school,commitdata/dasher,reergymerej/counts,standemchuk/if-051-ui,grantgeorge/meanApp,ascreven/mean.io,sontl/OAG-mean,intrepido/lildbiweb-mean,Andresvz/prueba-angular,kmdr/farmy,taylorjames/mpm,FLemon/balance_me,darecki/mean,filipemarruda/meanTest,garystafford/meanio-custom-search,prakma/wordheap,saurabhatjktech/destiny,CommandLineDesign/BeanJournal,msabdeljalil/meanApp,stevenaldous/mean,wagedomain/fitquest,sahibjaspal/wham,darul75/nsjoy.github.io2,albi34/mean,krahman/eparking,goblortikus/stroop,patrickkillalea/nodejs,mattkim/mean.io.tests,mkelley33/mean,erikLovesMetal/realtime_spotify,assafshp/meanBookLibrary,jithu21/acme,INFS3605MediPlus/INFS3605,udaykiranv/driver-tracker,misterdavemeister/meanio,zcalyz/mean,spiddy/wenode,thinkDevDM/mean,Ankushch/destiny,debona/Respirez,miguelmota/find-me-burritos,theoinglis/assessment,jbrunec/meantest,qtrandev/adopt_a_node,mykemp262/avalonStatTracker,siulikadrian/mapApp,VikramTiwari/mean,youhamid/aya,oritpersik/test,spiddy/wenode,xaotic/freewheelingdataapi,kouissar/dcFinderProject,firebull81/tasksapp,hayatnoor/haramain,despian/myFlix,blomm/meanio_template,bbaaxx/kaahal-timelines,jazzbassjohnson/thrive,ryantuck/public-xmas,idhere703/meanSample,spiddy/fvm.io,dpxxdp/webApp,jeffj/dasein,Anton5soft/mean,robort/mean,abhisekp/House-Rent-v2,wspurgin/BurgerBar,ascreven/mean.io,hassanabidpk/mean,ahfweb/ahfmpm,wolf-mtwo/attendance-origin-to-remove,tweiland/mean-on-openshift,sonnyfraikue/demo-meanio-app,wolf-mtwo/attendance,cronos2546/mean,szrobinli/mean,VeeteshJain/project_1000,toomu/mern,jeffj/mean_example,hsmyy/Register,Lywangwenbin/mean,LouizEchi/Scaffolds-Bar-And-Grill,walton007/miniERP,sunnypatneedi/nflmenu,whichoneapp/which-one,pratik60/mean-1,adecaneda/climan2,a5hik/payroll,ashblue/meanio-tutorial,colehudson/MEANstack,weed/ugo-butsu-p140912,loganetherton/ac,RStyrman/rstyrman_webdev,raymanxp/WhenWasTheLast,baolocdo/python,edivancamargo/mean,pavitlabs/mindappt,wearska/mean-mono,chrismillsnbcu/mean-demo,chohome2/gamelog,siulikadrian/mapApp,haddada/moneyAPP,harssh/meanio_app,wakandan/cah,padoo/contestAdmin,komarudin02/Public,dherrera/revolutioncontribution,yosifgenchev/iPlayIt,mikedorseyjr/roger_learns_mean,overlox/OpenHangouts,MaxwellPayne/summer-of-george,oliverk120/givetu2,ahanlon1987/solutionshud,bqevin/mean,KHam0425/mean,mcelreath/citibike-meanio,bozzmob/mean,guangyi/MeanStackPractice,jmadden85/ncms,bhanuprasad143/meanio-test,JulienBreux/mean,Prateek479/csv-parser,bhanuprasad143/meanio-test,OrderMail/blacklabel,Caes-project/ezTHEQUE,seanworkcode/BlogApp,haibo32012/webmchat,mottihoresh/nodarium-web,spiddy/fvm.io,behrooz46/mean-sample,nawasthi23/mean,haddada/moneyAPP,bbayo4/Businness-Application-using-MEAN.IO-Stack,mottihoresh/nodarium-web,codegaucho/mean-lessonplanner,joshharbaugh/wowpro,Shiftane/listedecourse2,rrudy90023/ocat,patrickkillalea/mean,assafshp/meanBookLibrary,anthony-ism/funari,islanderz/trainingApp,cloud26/meam-firstapp,nooysters/customprintapp,darrenmwong/PawPrintMEAN,asifalimd/mean-app,destromas1/hellogitty,yjkim1701/cmt-mgr,xz8888/NodeJS-kaoso,wakandan/cah,rahul-tiwari/MEANIO-Basics,yesmagaly/tesis-review2,rbecheras/mean-1,imsaar/zainab-school,winnie123/mean,evanjenkins/wtracker,maityneil001/mean,Gmora08/makeitcodejs,taylorjames/mpm,GrimDerp/mean,youhamid/aya,Cneubauern/Test,68a/meis,mickeyroy/SALES-DB,faisal00813/MEAN-Demo,psaradhi/mydrywall,jeffj/example-mean-app,virtualit786/showcasemean.io,ahanlon1987/solutionshud,evanjenkins/student-check-in,tradesmanhelix/myapp,vmee/ilinbei,ruarig/SCCUnite,siulikadrian/meaniotest,kumaria/mean,Biunovich/mean,taylorjames/wirestorm,Caes-project/ezTHEQUE,jandeancatarata/Plan4Me,mailjet/rupert,paulgalarza/empanadas,muthus2001/mail,siulikadrian/meaniotest,MohibWasay/marriaga,ezekielriva/bus-locator,jun-oka/bee-news-jp-client-1,CamonZ/greenmomit_st,joshsilverman/me,Atamos/testmean,firebull81/tasksapp,haibo32012/webmchat,kalomj/Pollution,Borys216307/booking_engine,alecashford/node_tut,PabloK/Hackaton-test,qtrandev/adopt_a_node,sontl/OAG-mean,lollek/TDP013-Webpages-and-Interactivity,hayatnoor/haramain,alexballera/mean,rbcorpgit/mean,psaradhi/mydrywall,liorclub/deals,despian/myFlix,jazzbassjohnson/thrive,quocnt/node-demo,piolab/mean,Muffasa/mean,Alexandre-Herve/fpmoney,andbet39/mongularpress,cronos2546/mean,thinkDevDM/mean,flomarin88/home-domotic,paramananda/mean,paperdev7/web-project,robort/mean,JKTOpen/destiny,cybercandyman/mean.io-app,zulwasaya/meanCustomers,whiteb0x/hasoffers-clientapp,tmrotz/brad,zcalyz/mean,zulwasaya/todolistsMean,CommandLineDesign/BeanJournal,OrderMail/blacklabel,vebin/mean,yjkim1701/cmt-mgr,dennisjoedavid123/ProjectX,inkless/cecelia,steezeburger/jeannie,codegaucho/mean-lessonplanner,taylorjames/wirestorm,webapp-angularjs/knowledge-for-sharing,tmfahey/Peppermint,Chien19861128/catchie,goblortikus/stroop,mummamw/mean,Damell/Creatures,kushaltirumala/mean,Muffasa/mean,jasondecamp/mememe,smadjid/CoReaDa,Prateek479/library,gscrazy1021/mean,vmee/bangmai,lakhvinderit/mean,HartleyShawn/resOP,CodeCloudMe/meanExample,oritpersik/admin-dashboard,fdecourcelle/meanfde,spacetag/TechEx_Josiah,arunsahni/dealdeck_app,kmdr/farmy,mstackpo/MattsMeanApp,huynhlc100/mean-on-openshift,JuanyiFeng/queueItUp,nscheu/bookshelf,hsmyy/meanwap,Janmichaelolsen/jamtoaster,gabrielzanoni/SGCAV,pathirana/mean,mikedorseyjr/roger_learns_mean,sguimont/sg-meanio-test,JeffPinkston/local-pub,prakma/wordheap,mceoin/meanApp,mceoin/meanApp,ericjsilva/mywinecellar,dherrera/revolutioncontribution,tloen/tutpass,cicadanator/BucketList,napalmdev/bemean01,dmauldin/setsumo,dflynn15/flomo,dbachko/mean,sguimont/sg-meanio-test,chackerian/Trades,kalomj/Pollution,zwhitchcox/mean,Prateek479/blog,row3/commune3,mychiara/stroke.crm,sandesh-jaikrishan/Lexstart,juanjmerono/basic,sjamartucheli/smartucheli,bradleytrager/vocab-activity-generator,OdenthalKay/abschluss,lukepearson/quiz,Shiftane/listedecourse,BenjaminHall/bugtracker,walton007/envomuse,lukepearson/quiz,columby/www.columby.com,qw3r/mean-io,magda/livinglab,liorclub/deals,cedesantis/Books,dpxxdp/stdapp,a5hik/payroll,sahibjaspal/wham,lukert33/luke-will-build,Tukaiz/vmi,abegit/mean,GeminiLegend/myRelephant265,cyberTrebuchet/this_is_forOM,TimWilkis/mean,termo/frits,Baconchin/MEANTodo,dpxxdp/webApp,yesmagaly/app-university,maityneil001/mean,miguelmota/find-me-burritos,parisminton/james.da.ydrea.ms,sonnyfraikue/demo-meanio-app,tweiland/mean-on-openshift,mrcarmody/zq-game-engine,FLemon/balance_me,DarkCascade/get2gether,rachelleannmorales/meanApp,C4AProjects/tracdr,elkingtonmcb/mean,karademada/mean,xiaoking/mean,onewaterdrop/reviewcenter,hbzhang/rsstack,seeyew/help140mean,joshua-oxley/Target,pratik60/mean,nawasthi23/mean,OdenthalKay/player,race604/Jlog,Chien19861128/qa-app,lukepearson/quiz,fkiller/mean,stujo/titan,evanjenkins/wtracker,Bunk/flippers-mean-io,FLemon/balance_me,miguelmota/find-me-burritos,dantepsychedelico/erp-tiny-system,andrescarceller/mean,seanworkcode/clinker,okuyan/my-mortgage,mtrinitaria/addmore_app,slawomirkroczak/fmottracker,tedtkang/meanTestApp,zwhitchcox/code,intrepido/lildbiweb-mean,victorantos/mean,HartleyShawn/resOP,dennisjoedavid123/ProjectX,muthhus/mean,andrescarceller/mean,swank-rats/game-logic,rekibnikufesin/demoApp,moritzschaefer/werwolf,FelikZ/meetings-demo,thefivetoes/votegoat,zulwasaya/zulsexcel,tradesmanhelix/myapp,ryanrankin/meanstack,jeffj/mean_example,gavgrego/trendyTodo,taylorjames/mpm,brownman/mean_package_testing,PabloK/Hackaton-test,stevenaldous/mean,freddyrangel/tottus,padoo/contestAdmin,adecaneda/climan2,mimiflynn/rideshare,DiegoValdivia/mean_practice,jshorwitz/mend,MattRamsayMSM/mingle-board,paulvi/meannewapp,vmee/1ju,phazebroek/voetbaltafel,kbeyer/K6BEventLoggerDashboard,youhamid/aya,minzen/u-qasar-mean,herveDarritchon/developHeureSiteJS,telekomatrix/mean,tloen/tutpass,LucasIsasmendi/ee-beta,mimiflynn/rideshare,walton007/miniERP,sjamartucheli/smartucheli,whtouche/davina_funder,lekkas/mean,NenadP/blocks,darecki/mean,walton007/miniERP,gscrazy1021/mean,herveDarritchon/developHeureSiteJS,VeeteshJain/project_1000,68a/meis,thefivetoes/votegoat,scrock1987/Mean,tannd155/TaiLieu,ulfmagnetics/fiftyfifty,Tukaiz/vmi,seanworkcode/BlogApp,mcelreath/citibike-meanio,rbecheras/mean-1,C4AProjects/tracdr,fvenegasp/rutadelvino_mean,Peretus/test-mean,johnnyli4a4c/pool-cards,overlox/MeanUpload,wombleton/hardholdr,rjVapes/mean,dgraham66/ECE-435,linnovate/mean-on-openshift,tanongkit/mean,linnovate/hellogitty,wombleton/hardholdr,mrClapham/mean_one,xnoguero/mobile-backend,erfg/worldcup,JPHUNTER/mean,pvhee/mean-test,tmrotz/brad,C4AProjects/Qatappult,09saurabh09/vocal,ddigioia/ToDoApp,commitdata/dasher,OrderMail/blacklabel,pratik60/mean,TimWilkis/mean,paulgalarza/empanadas,udaykiranv/driver-tracker,fkiller/harvard,zwhitchcox/lex,karademada/mean,whiteb0x/hasoffers-clientapp,phazebroek/voetbaltafel,yeapvin/juicebar,wolf-mtwo/attendance-old,xiaoking/mean,OdenthalKay/abschluss,jasondecamp/mememe,yesmagaly/app-university,kouissar/dcFinderProject,C4AProjects/Qatappult,pfryga/meanIO,Anton5soft/mean,haftapparat/mean,wspurgin/BurgerBar,pathirana/mean,alvarocavalcanti/ring-the-bell,nathanielltaylor/MEANkids,ameerkawar/MahboussehGame,jithu21/acme,MohibWasay/marriaga,lukert33/luke-will-build,linnovate/mean-on-openshift,FranGomez/porra,haftapparat/mean,ruarig/SCCUnite,garystafford/meanio-custom-search,evanjenkins/alTestPlan,dantix/mean,MHatmaker/maplinkr,alexmxu/mean,hsmyy/meanwap,yeapvin/juicebar,stujo/titan,zaczhou/cc,minzen/u-qasar-mean,mstone6769/stoneRecipes,spacetag/TechEx_Josiah,PankajMean/Note-Assignment,dominicbosch/mean_app,patrickkillalea/mean,hectorgool/mean-santix,Prateek479/library,sinmsinm/webconference,sjamartucheli/smartucheli,jun-oka/bee-news-jp-client-1,thewebtechguys/glowing-meme,albi34/mean,jgabriellima/zipress,msteward/meanTodo,ddigioia/ToDoApp,alexmxu/mean,twistedgood/shioris-meanio,walton007/envomuse,paulvi/meannewapp,ocorpening/charCounter,Peretus/test-mean,eddotman/attobyte,zwhitchcox/lex,hsmyy/Register,Ankushch/destiny,xz8888/NodeJS-kaoso,bentorfs/ddb,joshharbaugh/wowpro,dennisjoedavid123/ProjectX,kalomj/Pollution,zwhitchcox/code,NenadP/blocks,eddotman/attobyte,jgabriellima/zipress,MattRamsayMSM/mingle-board,taylorjames/mpm,youhamid/tb,krahman/eparking,bbayo4/Businness-Application-using-MEAN.IO-Stack,Gmora08/makeitcodejs,linnovate/icapi,kszpirak/yourNewApp,race604/Jlog,EugeneZ/dungeonlords,seigneur/kopispace,napalmdev/bemean01,mediavrog/worldcup-barometer,mauricionr/mean-on-openshift,tanongkit/mean,Prateek479/csv-parser,xxxbartasxxx/expenses,wolf-mtwo/attendance-old,thomas-p-wilson/performance-test,jeffj/dasein,taylorjames/noidea,mimiflynn/rideshare,mceoin/meanApp,ThrowsException/crossfit-rivals,toomu/mern,patrickkillalea/nodejs,xnoguero/mobile-backend,mykemp262/avalonStatTracker,achekh/civil_government,kalomj/Pollution,mandazi/haramain,mvcruzata/trends,misterdavemeister/meanio,miguelmota/find-me-burritos,fdecourcelle/meanfde,mailjet/rupert,asicudl/mobile-backend,cedesantis/JamSesh,zesk8/Blog-Angular-MEAN,oliverk120/givetu2,ryanlhunt/sim_ventory,bentorfs/ddb,udaykiranv/driver-tracker,OdenthalKay/abschluss,dbachko/mean,cicadanator/BucketList,ferrellms/mean,abhisekp/House-Rent-v2,fdecourcelle/meanfde,yinhe007/mean,onewaterdrop/reviewcenter,vildantursic/vildan-mean,inkless/cecelia,jshorwitz/mend,jbrunec/meantest,krahman/eparking,theoinglis/assessment,expsl/expsl,GeminiLegend/myRelephant265,qw3r/mean-io,ulfmagnetics/fiftyfifty,MHatmaker/maplinkr,idhere703/meanSample,tpsumeta/mean,islanderz/trainingApp,komarudin02/Public,yinhe007/mean,filipemarruda/meanTest,ahfweb/ahfmpm,wolf-mtwo/attendance,telekomatrix/mean,michelwatson/bmr,young-utf/meanstack-prac,ryantuck/public-xmas,projectsf/important-things,dhivyaprp/Lets-Fix,javi7/epl-98,zwhitchcox/lex,Paolocargnin/crossTables,wagedomain/fitquest,rutys/pictionary,vildantursic/vildan-mean,tpsumeta/mean,bforrest/gitapidemo,kaydeveloper/mean,JKTOpen/destiny,colehudson/MEANstack,naveengogineni/navintestmeanapp,vmee/bangmai,quocnt/node-demo,vmee/ilinbei,saurabhatjktech/destiny,cybercandyman/mean.io-app,gabrielzanoni/SGCAV,lollek/TDP013-Webpages-and-Interactivity,tmfahey/Peppermint,okuyan/my-mortgage,mulyoved/radio01,relizont/meanDemoApp,nathanielltaylor/MEANkids,Chien19861128/catchie2,rrudy90023/ocat,Lywangwenbin/mean,gcerrato/inverntory,vikram-bagga/zummy,cedesantis/Books,wolf-mtwo/attendance-old,jeffj/example-mean-app,Superjisan/NYCitizenry,AshevilleSkiClub/AvlSkiClub,Andresvz/prueba-angular,lakhvinderit/mean,dennisjoedavid123/Catalyst,DeveloperMeier/DvM,krahman/eClinic,garyxu1987/J.I.A,jackrosenhauer/nodebot-mean,darbio/Phoenix,lollek/TDP013-Webpages-and-Interactivity,jabiers/mean,weed/ugo-butsu-p140912,whichoneapp/which-one,mulyoved/radio01,ryanrankin/meanstack,dmauldin/setsumo,dianavermilya/rain,Baconchin/MeanLearn,mandazi/haramain,guilhermeyo/mean-articles,baolocdo/python,oliverk120/notesnack2,kartikmenon/Tinkering-with-MeanStack,InonS/mean-inon,thewebtechguys/glowing-meme,webapp-angularjs/football,jeffj/dasein,jenavarro/AllRules,bqevin/mean,PankajMean/Note-Assignment,Alexandre-Herve/fpmoney,DeveloperMeier/DvM,mickeyroy/SALES-DB,seigneur/kopispace,evanjenkins/student-check-in,Janmichaelolsen/jamtoaster,JeffCloverLeaf/nodeserver,ferrellms/mean,zulwasaya/zulsexcel,lollek/TDP013-Webpages-and-Interactivity,taylorjames/wirestorm,salivatears/mean,Atamos/testmean,GrimDerp/mean,dennisjoedavid123/ProjectX,rutys/pictionary,standemchuk/if-051-ui,mattkim/mean.io.tests,JeffPinkston/local-pub,wolf-mtwo/attendance,jmadden85/ncms,qtrandev/adopt_a_node,relizont/meanDemoApp,cloud26/meam-firstapp,zaczhou/cc,mstone6769/stoneRecipes,dustinmoorman/tau.pe,msteward/meanTodo,row3/commune3,lekkas/mean,Ideas2IT/mean-idea,PankajMean/Dealdeck,tannd155/TaiLieu,vmee/1ju,taylorjames/wirestorm,dgraham66/ECE-435,OrderMail/blacklabel,sinmsinm/webconference,dimitriwalters/diary,youhamid/tb,lollek/MEAN-Social-Site,jlin412/jason_demo,LucasIsasmendi/ee-beta,Quadramma/MeanApp.BasicERP,Biunovich/mean,projectsf/important-things,behrooz46/mean-sample,firebull81/tasksapp,rachelleannmorales/meanApp,hbzhang/rsstack,evanjenkins/wtracker,expsl/expsl,tranphuoctien/mean-on-openshift,arturomc/meanspace,elkingtonmcb/mean,Prateek479/blog,vanmartin/triVectorPoC,mimiflynn/rideshare,hsmyy/lab,smadjid/CoReaDa,FranGomez/porra,fvenegasp/rutadelvino_mean,rncrtr/mean,muthus2001/mail,dennisjoedavid123/ProjectX,misterdavemeister/meanio,AshevilleSkiClub/AvlSkiClub,evanjenkins/wtracker,spiddy/wenode,thisishuey/frogban,kevinzli/meanforms,OdenthalKay/player,nscheu/bookshelf,harssh/meanio_app,wolf-mtwo/attendance-origin-to-remove,juanjmerono/basic,gauss1181/simple-group,jdelagal/mean,mrcarmody/zq-game-engine,Paolocargnin/crossTables,thisishuey/frogban,dantepsychedelico/erp-tiny-system,youhamid/aya,paramananda/mean,lollek/MEAN-Social-Site,krahman/eClinic,xaotic/freewheelingdataapi,ryanlhunt/sim_ventory,mummamw/mean,vanmartin/triVectorPoC,joshua-oxley/Target,rconnelly/app,zilchrhythm/mean-myfeed,termo/frits,spiddy/fvm.io,bforrest/gitapidemo,LouizEchi/Scaffolds-Bar-And-Grill,dustinmoorman/tau.pe,loganetherton/ac,jithu21/acme,loganetherton/ac,dimitriwalters/diary,kasiwal/lets-fix,dpxxdp/stdapp,VikramTiwari/mean,overlox/OpenHangouts,whtouche/davina_funder,zilchrhythm/mean-myfeed,jeffj/example-mean-app,andrewchen5678/testmeanio,gcerrato/inverntory,FelikZ/meetings-demo,tmrotz/brad,nscheu/mistufs,C4AProjects/tracdr,overlox/OpenHangouts,gabrielzanoni/SGCAV,Prateek479/library,Shiftane/listedecourse,Edifice/OctoDo,CamonZ/greenmomit_st,fkiller/harvard,alannesta/mean-scaffold,mediavrog/worldcup-barometer,Bunk/flippers-mean-io,jlin412/jason_demo,bentorfs/ddb,LukasK/mean,otherwhitefrank/mean-frankdye-com,erikLovesMetal/realtime_spotify,youhamid/tb,LucasIsasmendi/ee-beta,dennisjoedavid123/Catalyst,mychiara/stroke.crm,hayatnoor/haramain,bbaaxx/kaahal-timelines,rekibnikufesin/demoApp,evanjenkins/alTestPlan,Janmichaelolsen/jamtoaster,javi7/epl-98,vikram-bagga/zummy,bmprovost/soundboard,joshsilverman/me,edivancamargo/mean,overlox/MeanUpload,mauricionr/mean-on-openshift,ShlomyShivek/SchoolMate,wearska/mean-mono,jackrosenhauer/nodebot-mean,JeffPinkston/local-pub,oritpersik/test,fdecourcelle/meanfde,kasiwal/lets-fix,LucasIsasmendi/ee-beta,ridan/Pakathon,sidhart/mean,pvhee/mean-test,rjVapes/mean,dflynn15/flomo,lollek/MEAN-Social-Site,guangyi/MeanStackPractice,jabiers/mean,sunnypatneedi/nflmenu,salivatears/mean,swank-rats/game-logic,zwhitchcox/mean,winnie123/mean,Caes-project/ezTHEQUE,Sharmaz/mean,dennisjoedavid123/ProjectX,mcottingham/FormulaBuilder,devsaik/paropakar,kszpirak/yourNewApp,chackerian/Trades,columby/www.columby.com,nooysters/customprintapp,jgabriellima/zipress,kalomj/Pollution,BenjaminHall/bugtracker,mvcruzata/trends,ThrowsException/crossfit-rivals,kira1009/mean,mtrinitaria/addmore_app,pvhee/mean-test,ahfweb/ahfmpm,michelwatson/bmr,rpalacios/preach-lander,yosifgenchev/iPlayIt,seeyew/help140mean,Shiftane/listedecourse2,andbet39/mongularpress,JuanyiFeng/queueItUp,lukepearson/quiz,ocorpening/charCounter,INFS3605MediPlus/INFS3605,chenyaoli19/meanshop,grantgeorge/meanApp,garyxu1987/J.I.A,alecashford/node_tut,gavgrego/trendyTodo,raymanxp/WhenWasTheLast,hsmyy/lab,marlonator/mean,arunsahni/dealdeck_app,oliverk120/notesnack2,debona/Respirez | ---
+++
@@ -4,10 +4,12 @@
// Article authorization helpers
var hasAuthorization = function(req, res, next) {
- if (req.article.user.id !== req.user.id) {
+ if (res.adminEnabled() || (req.article.user && (req.article.user_id === req.user._id))) {
+ next();
+ }
+ else {
return res.send(401, 'User is not authorized');
}
- next();
};
module.exports = function(Articles, app, auth) { |
f0144914bb08c8ffd3cd99a35fc9c4d4137b933c | Docs/static/custom/tooltips.js | Docs/static/custom/tooltips.js | var currentTip = null;
var currentTipElement = null;
function hideTip(evt, name, unique)
{
var el = document.getElementById(name);
el.style.display = "none";
currentTip = null;
}
function findPos(obj)
{
// no idea why, but it behaves differently in webbrowser component
if (window.location.search == "?inapp")
return [obj.offsetLeft + 10, obj.offsetTop + 30];
var curleft = 0;
var curtop = obj.offsetHeight;
while (obj)
{
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
obj = obj.offsetParent;
};
return [curleft, curtop];
}
function hideUsingEsc(e)
{
if (!e) { e = event; }
hideTip(e, currentTipElement, currentTip);
}
function showTip(evt, name, unique, owner)
{
document.onkeydown = hideUsingEsc;
if (currentTip == unique) return;
currentTip = unique;
currentTipElement = name;
var pos = findPos(owner ? owner : (evt.srcElement ? evt.srcElement : evt.target));
var posx = pos[0];
var posy = pos[1];
var el = document.getElementById(name);
var parent = (document.documentElement == null) ? document.body : document.documentElement;
el.style.position = "absolute";
el.style.left = posx + "px";
el.style.top = posy + "px";
el.style.display = "block";
} | var currentTip = null;
var currentTipElement = null;
function hideTip(evt, name, unique)
{
var el = document.getElementById(name);
el.style.display = "none";
currentTip = null;
}
function findPos(obj)
{
var curleft = 0;
var curtop = obj.offsetHeight;
while (obj)
{
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
obj = obj.offsetParent;
};
return [curleft, curtop];
}
function hideUsingEsc(e)
{
if (!e) { e = event; }
hideTip(e, currentTipElement, currentTip);
}
function showTip(evt, name, unique, owner)
{
document.onkeydown = hideUsingEsc;
if (currentTip == unique) return;
currentTip = unique;
currentTipElement = name;
var pos = findPos(owner ? owner : (evt.srcElement ? evt.srcElement : evt.target));
var posx = pos[0];
var posy = pos[1];
var el = document.getElementById(name);
var parent = (document.documentElement == null) ? document.body : document.documentElement;
parent.appendChild(el);
el.style.position = "absolute";
el.style.left = posx + "px";
el.style.top = posy + "px";
el.style.display = "block";
}
| Fix tooltip positions in tutorial pages | Fix tooltip positions in tutorial pages | JavaScript | apache-2.0 | NaseUkolyCZ/FunScript,NaseUkolyCZ/FunScript,mcgee/FunScript,ZachBray/FunScript,mcgee/FunScript,cloudRoutine/FunScript,tpetricek/FunScript,mcgee/FunScript,ovatsus/FunScript,nwolverson/FunScript,ZachBray/FunScript,ovatsus/FunScript,nwolverson/FunScript,ovatsus/FunScript,alfonsogarciacaro/FunScript,mcgee/FunScript,nwolverson/FunScript,alfonsogarciacaro/FunScript,ovatsus/FunScript,cloudRoutine/FunScript,tpetricek/FunScript | ---
+++
@@ -10,10 +10,6 @@
function findPos(obj)
{
- // no idea why, but it behaves differently in webbrowser component
- if (window.location.search == "?inapp")
- return [obj.offsetLeft + 10, obj.offsetTop + 30];
-
var curleft = 0;
var curtop = obj.offsetHeight;
while (obj)
@@ -44,6 +40,7 @@
var el = document.getElementById(name);
var parent = (document.documentElement == null) ? document.body : document.documentElement;
+ parent.appendChild(el);
el.style.position = "absolute";
el.style.left = posx + "px";
el.style.top = posy + "px"; |
3784330b114e5e5b03c7bf1ab854c6865c0079ef | addon/mixins/token-adapter.js | addon/mixins/token-adapter.js | import Mixin from '@ember/object/mixin';
import { inject } from '@ember/service';
import { get, computed } from '@ember/object';
import { isEmpty } from '@ember/utils';
import config from 'ember-get-config';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
/**
Adapter Mixin that works with token-based authentication like JWT.
@class TokenAdapter
@module ember-simple-auth-token/mixins/token-adapter
@extends Ember.Mixin
*/
export default Mixin.create(DataAdapterMixin, {
session: inject('session'),
/**
@method init
*/
init() {
this._super(...arguments);
const conf = config['ember-simple-auth-token'] || {};
this.tokenPropertyName = conf.tokenPropertyName || 'token';
this.authorizationHeaderName = conf.authorizationHeaderName || 'Authorization';
this.authorizationPrefix = conf.authorizationPrefix === '' ? '' : conf.authorizationPrefix || 'Bearer ';
},
/*
Adds the `token` property from the session to the `authorizationHeaderName`:
*/
headers: computed('session.isAuthenticated', function() {
const data = get(this, 'session.data.authenticated');
const token = get(data, this.get('tokenPropertyName'));
const prefix = this.get('authorizationPrefix');
const header = this.get('authorizationHeaderName');
if (this.get('session.isAuthenticated') && !isEmpty(token)) {
return {
[header]: `${prefix}${token}`
};
} else {
return {};
}
})
});
| import Mixin from '@ember/object/mixin';
import { inject } from '@ember/service';
import { get, computed } from '@ember/object';
import { isEmpty } from '@ember/utils';
import config from 'ember-get-config';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
/**
Adapter Mixin that works with token-based authentication like JWT.
@class TokenAdapter
@module ember-simple-auth-token/mixins/token-adapter
@extends Ember.Mixin
*/
export default Mixin.create(DataAdapterMixin, {
session: inject('session'),
/**
@method init
*/
init() {
this._super(...arguments);
const conf = config['ember-simple-auth-token'] || {};
this.tokenPropertyName = conf.tokenPropertyName || 'token';
this.authorizationHeaderName = conf.authorizationHeaderName || 'Authorization';
this.authorizationPrefix = conf.authorizationPrefix === '' ? '' : conf.authorizationPrefix || 'Bearer ';
},
/*
Adds the `token` property from the session to the `authorizationHeaderName`:
*/
headers: computed('session.data.authenticated', function() {
const data = this.get('session.data.authenticated');
const token = get(data, this.get('tokenPropertyName'));
const prefix = this.get('authorizationPrefix');
const header = this.get('authorizationHeaderName');
if (this.get('session.isAuthenticated') && !isEmpty(token)) {
return {
[header]: `${prefix}${token}`
};
} else {
return {};
}
})
});
| Fix computed header property issue | Fix computed header property issue
| JavaScript | mit | jpadilla/ember-simple-auth-token,jpadilla/ember-cli-simple-auth-token,jpadilla/ember-simple-auth-token,jpadilla/ember-cli-simple-auth-token | ---
+++
@@ -29,8 +29,8 @@
/*
Adds the `token` property from the session to the `authorizationHeaderName`:
*/
- headers: computed('session.isAuthenticated', function() {
- const data = get(this, 'session.data.authenticated');
+ headers: computed('session.data.authenticated', function() {
+ const data = this.get('session.data.authenticated');
const token = get(data, this.get('tokenPropertyName'));
const prefix = this.get('authorizationPrefix');
const header = this.get('authorizationHeaderName'); |
6d76e2009091d9997c0a692b4fc983112d889653 | src/util-lang.js | src/util-lang.js | /**
* util-lang.js - The minimal language enhancement
*/
function isType(type) {
return function(obj) {
return {}.toString.call(obj) == "[object " + type + "]"
}
}
var isObject = isType("Object")
var isString = isType("String")
var isArray = Array.isArray || isType("Array")
var isFunction = isType("Function")
var _cid = 0
function cid() {
return _cid++
}
| /**
* util-lang.js - The minimal language enhancement
*/
var _object = {}
function isType(type) {
return function(obj) {
return _object.toString.call(obj) == "[object " + type + "]"
}
}
var isObject = isType("Object")
var isString = isType("String")
var isArray = Array.isArray || isType("Array")
var isFunction = isType("Function")
var _cid = 0
function cid() {
return _cid++
}
| Update share one object for check type. | Update share one object for check type.
| JavaScript | mit | PUSEN/seajs,121595113/seajs,kuier/seajs,liupeng110112/seajs,evilemon/seajs,twoubt/seajs,treejames/seajs,seajs/seajs,mosoft521/seajs,Gatsbyy/seajs,lianggaolin/seajs,kaijiemo/seajs,coolyhx/seajs,imcys/seajs,sheldonzf/seajs,baiduoduo/seajs,liupeng110112/seajs,hbdrawn/seajs,judastree/seajs,yuhualingfeng/seajs,JeffLi1993/seajs,longze/seajs,chinakids/seajs,eleanors/SeaJS,evilemon/seajs,mosoft521/seajs,uestcNaldo/seajs,zwh6611/seajs,eleanors/SeaJS,LzhElite/seajs,AlvinWei1024/seajs,longze/seajs,PUSEN/seajs,FrankElean/SeaJS,moccen/seajs,FrankElean/SeaJS,eleanors/SeaJS,wenber/seajs,FrankElean/SeaJS,zwh6611/seajs,sheldonzf/seajs,tonny-zhang/seajs,yuhualingfeng/seajs,judastree/seajs,Lyfme/seajs,longze/seajs,treejames/seajs,lee-my/seajs,moccen/seajs,kaijiemo/seajs,lovelykobe/seajs,coolyhx/seajs,kaijiemo/seajs,tonny-zhang/seajs,coolyhx/seajs,imcys/seajs,zaoli/seajs,13693100472/seajs,sheldonzf/seajs,ysxlinux/seajs,Lyfme/seajs,zaoli/seajs,twoubt/seajs,Lyfme/seajs,jishichang/seajs,lianggaolin/seajs,wenber/seajs,LzhElite/seajs,evilemon/seajs,judastree/seajs,LzhElite/seajs,MrZhengliang/seajs,uestcNaldo/seajs,ysxlinux/seajs,moccen/seajs,AlvinWei1024/seajs,13693100472/seajs,kuier/seajs,twoubt/seajs,Gatsbyy/seajs,AlvinWei1024/seajs,hbdrawn/seajs,angelLYK/seajs,baiduoduo/seajs,seajs/seajs,JeffLi1993/seajs,yern/seajs,lee-my/seajs,mosoft521/seajs,jishichang/seajs,zaoli/seajs,MrZhengliang/seajs,kuier/seajs,yuhualingfeng/seajs,MrZhengliang/seajs,yern/seajs,baiduoduo/seajs,ysxlinux/seajs,imcys/seajs,JeffLi1993/seajs,Gatsbyy/seajs,jishichang/seajs,treejames/seajs,wenber/seajs,zwh6611/seajs,PUSEN/seajs,angelLYK/seajs,tonny-zhang/seajs,seajs/seajs,121595113/seajs,lovelykobe/seajs,lianggaolin/seajs,lee-my/seajs,liupeng110112/seajs,uestcNaldo/seajs,lovelykobe/seajs,angelLYK/seajs,chinakids/seajs,yern/seajs | ---
+++
@@ -2,9 +2,11 @@
* util-lang.js - The minimal language enhancement
*/
+var _object = {}
+
function isType(type) {
return function(obj) {
- return {}.toString.call(obj) == "[object " + type + "]"
+ return _object.toString.call(obj) == "[object " + type + "]"
}
}
@@ -17,4 +19,3 @@
function cid() {
return _cid++
}
- |
b8a59f454394bcc271966a5ffea5d086c4207ce7 | test/spec/controllers/formDropArea.js | test/spec/controllers/formDropArea.js | 'use strict';
describe('Controller: FormDropAreaCtrl', function () {
// load the controller's module
beforeEach(module('confRegistrationWebApp'));
var FormDropAreaCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
FormDropAreaCtrl = $controller('FormDropAreaCtrl', {
$scope: scope
});
}));
// it('should attach a list of awesomeThings to the scope', function () {
// expect(scope.awesomeThings.length).toBe(3);
// });
});
| 'use strict';
describe('Controller: FormDropAreaCtrl', function () {
// load the controller's module
beforeEach(module('confRegistrationWebApp'));
var FormDropAreaCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
scope.conference = {
registrationPages: [
{
id: 'page1',
blocks: [ { id: 'block1' } ]
},
{
id: 'page2',
blocks: [ { id: 'block2' } ]
}
]
};
FormDropAreaCtrl = $controller('FormDropAreaCtrl', {
$scope: scope
});
}));
it('should have a function to move a block', function () {
scope.moveBlock('block2', 'page1', 0);
expect(scope.conference.registrationPages[0].blocks.length).toBe(2);
expect(scope.conference.registrationPages[0].blocks[0].id).toBe('block2');
});
});
| Test the move block fn | Test the move block fn
| JavaScript | mit | CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web | ---
+++
@@ -11,12 +11,29 @@
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
+
+ scope.conference = {
+ registrationPages: [
+ {
+ id: 'page1',
+ blocks: [ { id: 'block1' } ]
+ },
+ {
+ id: 'page2',
+ blocks: [ { id: 'block2' } ]
+ }
+ ]
+ };
+
FormDropAreaCtrl = $controller('FormDropAreaCtrl', {
$scope: scope
});
}));
-// it('should attach a list of awesomeThings to the scope', function () {
-// expect(scope.awesomeThings.length).toBe(3);
-// });
+ it('should have a function to move a block', function () {
+ scope.moveBlock('block2', 'page1', 0);
+
+ expect(scope.conference.registrationPages[0].blocks.length).toBe(2);
+ expect(scope.conference.registrationPages[0].blocks[0].id).toBe('block2');
+ });
}); |
bac969961ad951c10d0cdfa1d8b622c0d121d26f | app/components/select-date.js | app/components/select-date.js | import Ember from 'ember';
export default Ember.Component.extend({
userSettings: Ember.inject.service(),
init () {
this._super();
this.get('userSettings').timePeriods().then(response => {
// Sort by latest on top
this.set('timePeriods', response.sortBy('begins').reverse());
// Create array of years
this.set('years', response.uniqBy('year'));
});
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
btnActive: false,
didReceiveAttrs () {
this.set('timePeriodChanged', this.get('currentDate'));
},
init () {
this._super();
this.get('userSettings').timePeriods().then(response => {
// Sort by latest on top
this.set('timePeriods', response.sortBy('begins').reverse());
// Create array of years
this.set('years', response.uniqBy('year'));
});
}
});
| Set variable for time period base on value passed to component | refactor: Set variable for time period base on value passed to component
| JavaScript | mit | pe1te3son/spendings-tracker,pe1te3son/spendings-tracker | ---
+++
@@ -1,7 +1,10 @@
import Ember from 'ember';
export default Ember.Component.extend({
- userSettings: Ember.inject.service(),
+ btnActive: false,
+ didReceiveAttrs () {
+ this.set('timePeriodChanged', this.get('currentDate'));
+ },
init () {
this._super(); |
a2361ee313e42f3b3446fa4baf3c0bbd4e072c48 | app/routes/index.js | app/routes/index.js | import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
var person_id = this.controllerFor('application').get('attrs.person.id');
return this.apijax.GET('/identifier.json', { 'person_id': person_id });
},
setupController: function(controller, model) {
this._super(controller, model);
var person = this.controllerFor('application').get('attrs.person');
person = model.objectAt(0);
this.controllerFor('application').set('attrs.person', person);
}
});
| import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
var person = this.controllerFor('application').get('attrs.person'),
person_id = person.id,
model;
if (!Ember.isEmpty(person.full_name)) {
// we have full passed in details for the person, no need for lookup
model = [person];
} else {
model = this.apijax.GET('/identifier.json', { 'person_id': person_id });
}
return model;
},
setupController: function(controller, model) {
this._super(controller, model);
var person = this.controllerFor('application').get('attrs.person');
person = model.objectAt(0);
this.controllerFor('application').set('attrs.person', person);
}
});
| Add ability to pass in full details for person | Add ability to pass in full details for person
* now no need for ajax call in this case
| JavaScript | mit | opengovernment/person-widget,opengovernment/person-widget | ---
+++
@@ -2,8 +2,18 @@
export default Ember.Route.extend({
model: function() {
- var person_id = this.controllerFor('application').get('attrs.person.id');
- return this.apijax.GET('/identifier.json', { 'person_id': person_id });
+ var person = this.controllerFor('application').get('attrs.person'),
+ person_id = person.id,
+ model;
+
+ if (!Ember.isEmpty(person.full_name)) {
+ // we have full passed in details for the person, no need for lookup
+ model = [person];
+ } else {
+ model = this.apijax.GET('/identifier.json', { 'person_id': person_id });
+ }
+
+ return model;
},
setupController: function(controller, model) {
this._super(controller, model); |
3480438a6698868c7cdcd743489d5e597e318cbe | app/main.js | app/main.js | // Install the configuration interface and set default values
require('configuration.js');
// Use DIM styling overrides and our own custom styling
require('beautification.js');
// Stores weapons pulled from our custom database
require('weaponDatabase.js');
// Pulls down weapon data and broadcasts updates
require('weaponDataRefresher.js');
// Removes DIM's native tagging elements
require('dimTagRemover.js');
// Store original details about the weapon in 'data-fate' attributes
require('weaponDecorator.js');
// Update weapon comments from our database
require('commentDecorator.js');
// Rejigger how weapons with legendary mods are displayed
require('modIndicator.js');
// Show higher/lower dupes
require('dupeIndicator.js');
/*
The nicest change-refresh flow means loading the development version of
the script from Tampermonkey while editing. This lets us skip kicking off
the app when running under Karma.
*/
if (!window.navigator.userAgent.includes('HeadlessChrome')) {
// const logger = require('logger');
// const postal = require('postal');
// logger.log('main.js: Initializing');
// postal.publish({topic:'fate.init'});
//
// setInterval(function() {
// postal.publish({topic:'fate.refresh'});
// }, 5000);
//
// setInterval(function() {
// postal.publish({topic:'fate.weaponDataStale'});
// }, 30000);
}
| // Install the configuration interface and set default values
require('configuration.js');
// Use DIM styling overrides and our own custom styling
require('beautification.js');
// Stores weapons pulled from our custom database
require('weaponDatabase.js');
// Pulls down weapon data and broadcasts updates
require('weaponDataRefresher.js');
// Removes DIM's native tagging elements
require('dimTagRemover.js');
// Store original details about the weapon in 'data-fate' attributes
require('weaponDecorator.js');
// Update weapon comments from our database
require('commentDecorator.js');
// Rejigger how weapons with legendary mods are displayed
require('modIndicator.js');
// Show higher/lower dupes
require('dupeIndicator.js');
/*
The nicest change-refresh flow means loading the development version of
the script from Tampermonkey while editing. This lets us skip kicking off
the app when running under Karma.
*/
if (!window.navigator.userAgent.includes('HeadlessChrome')) {
const logger = require('logger');
logger.log('main.js: Initializing');
fateBus.publish(module, 'fate.init');
setInterval(function() {
fateBus.publish(module, 'fate.refresh');
}, 5000);
setInterval(function() {
fateBus.publish(module, 'fate.weaponDataStale');
}, 30000);
}
| Swap over to using fateBus. | Swap over to using fateBus.
| JavaScript | mit | rslifka/fate_of_all_fools,rslifka/fate_of_all_fools | ---
+++
@@ -31,16 +31,15 @@
the app when running under Karma.
*/
if (!window.navigator.userAgent.includes('HeadlessChrome')) {
- // const logger = require('logger');
- // const postal = require('postal');
- // logger.log('main.js: Initializing');
- // postal.publish({topic:'fate.init'});
- //
- // setInterval(function() {
- // postal.publish({topic:'fate.refresh'});
- // }, 5000);
- //
- // setInterval(function() {
- // postal.publish({topic:'fate.weaponDataStale'});
- // }, 30000);
+ const logger = require('logger');
+ logger.log('main.js: Initializing');
+ fateBus.publish(module, 'fate.init');
+
+ setInterval(function() {
+ fateBus.publish(module, 'fate.refresh');
+ }, 5000);
+
+ setInterval(function() {
+ fateBus.publish(module, 'fate.weaponDataStale');
+ }, 30000);
} |
829354e73febe532252c48c171537db3b38eb749 | public/angular/directives/twitter-button.js | public/angular/directives/twitter-button.js | 'use strict';
(function(app) {
app.directive('twitterBtn', [function() {
var link = function() {
!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;
js.src=p+'://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js,fjs);
}
}(document, 'script', 'twitter-wjs');
};
return {
restrict: 'A',
link: link,
templateUrl: '/angular/views/twitter-button.html'
};
}]);
})(timer.app); | 'use strict';
(function(app) {
app.directive('twitterBtn', [function() {
var link = function() {
!function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js = d.createElement(s);
js.id = id;
js.src = p+'://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js,fjs);
}
}(document, 'script', 'twitter-wjs');
};
return {
restrict: 'A',
link: link,
templateUrl: '/angular/views/twitter-button.html'
};
}]);
})(timer.app); | Add more spaces to twitter js code. | Add more spaces to twitter js code. | JavaScript | mit | clamstew/timer | ---
+++
@@ -4,12 +4,12 @@
app.directive('twitterBtn', [function() {
var link = function() {
- !function(d,s,id){
- var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
+ !function(d, s, id){
+ var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
- js=d.createElement(s);
- js.id=id;
- js.src=p+'://platform.twitter.com/widgets.js';
+ js = d.createElement(s);
+ js.id = id;
+ js.src = p+'://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js,fjs);
}
}(document, 'script', 'twitter-wjs'); |
3c647e872aceea76b8bd4008032488909019a1f2 | .eslintrc.js | .eslintrc.js | module.exports = {
extends: [
'nextcloud'
],
/**
* Allow jest syntax in the src folder
*/
env: {
jest: true
},
/**
* Allow shallow import of @vue/test-utils in order to be able to use it in
* the src folder
*/
rules: {
"node/no-unpublished-import": ["error", {
"allowModules": ["@vue/test-utils"]
}]
}
}
| module.exports = {
extends: [
'nextcloud'
],
}
| Remove eslint rules added to the eslint-config module | Remove eslint rules added to the eslint-config module
Signed-off-by: Marco Ambrosini <3397c7e210a9d1588196cfebb12b2c6b133f6934@pm.me>
| JavaScript | agpl-3.0 | nextcloud/spreed,nextcloud/spreed,nextcloud/spreed | ---
+++
@@ -2,19 +2,4 @@
extends: [
'nextcloud'
],
- /**
- * Allow jest syntax in the src folder
- */
- env: {
- jest: true
- },
- /**
- * Allow shallow import of @vue/test-utils in order to be able to use it in
- * the src folder
- */
- rules: {
- "node/no-unpublished-import": ["error", {
- "allowModules": ["@vue/test-utils"]
- }]
- }
} |
0591ffecc36e9b5daebb284de7b74737749c3040 | app/components/sortable-items.js | app/components/sortable-items.js | import Ember from 'ember';
import SortableItems from 'sortable-items/components/sortable-items';
export default SortableItems;
| import Ember from 'ember';
import SortableItems from 'ember-cli-sortable/components/sortable-items';
export default SortableItems;
| Update import for the app with the correct ember-addon name | Update import for the app with the correct ember-addon name
| JavaScript | mit | Cryrivers/ember-cli-sortable,JennieJi/ember-cli-sortable,jqyu/ember-cli-sortable,JennieJi/ember-cli-sortable,laantorchaweb/ember-cli-sortable,laantorchaweb/ember-cli-sortable,MaazAli/ember-cli-sortable,Cryrivers/ember-cli-sortable,MaazAli/ember-cli-sortable,jqyu/ember-cli-sortable | ---
+++
@@ -1,4 +1,4 @@
import Ember from 'ember';
-import SortableItems from 'sortable-items/components/sortable-items';
+import SortableItems from 'ember-cli-sortable/components/sortable-items';
export default SortableItems; |
ce6666eace0a1b6f0d50db3f751fedf3bf1153a7 | utils/context.js | utils/context.js | 'use strict';
var _ = require('lodash');
var convert = require('./convert.js');
var context = {
getDefaults: getDefaults
};
function getDefaults(name, module) {
var folderName = convert.moduleToFolder(module);
return {
module: module,
camelName: _.camelCase(name),
controller: _.upperFirst(_.camelCase(name)) + 'Controller',
directive: _.camelCase(name),
directiveUrl: folderName + _.kebabCase(name) + '.directive.html',
kebabName: _.kebabCase(name),
route: _.camelCase(name) + 'Route',
service: _.camelCase(name) + 'Service',
state: module.replace('app.modules.', ''),
templateUrl: folderName + _.kebabCase(name) + '.html'
};
}
module.exports = context;
| 'use strict';
var _ = require('lodash');
var convert = require('./convert.js');
var context = {
getDefaults: getDefaults
};
function getDefaults(name, module) {
var folderName = convert.moduleToFolder(module);
return _.clone({
module: module,
camelName: _.camelCase(name),
controller: _.upperFirst(_.camelCase(name)) + 'Controller',
directive: _.camelCase(name),
directiveUrl: folderName + _.kebabCase(name) + '.directive.html',
kebabName: _.kebabCase(name),
route: _.camelCase(name) + 'Route',
service: _.camelCase(name) + 'Service',
state: module.replace('app.modules.', ''),
templateUrl: folderName + _.kebabCase(name) + '.html'
});
}
module.exports = context;
| Return new instance of object | Return new instance of object
| JavaScript | mit | sysgarage/generator-sys-angular,sysgarage/generator-sys-angular | ---
+++
@@ -8,7 +8,7 @@
function getDefaults(name, module) {
var folderName = convert.moduleToFolder(module);
- return {
+ return _.clone({
module: module,
camelName: _.camelCase(name),
controller: _.upperFirst(_.camelCase(name)) + 'Controller',
@@ -19,7 +19,7 @@
service: _.camelCase(name) + 'Service',
state: module.replace('app.modules.', ''),
templateUrl: folderName + _.kebabCase(name) + '.html'
- };
+ });
}
module.exports = context; |
fad9ff7971146796207687d03df30c8f41d77290 | rakuten_mail_unchecker.user.js | rakuten_mail_unchecker.user.js | // ==UserScript==
// @name Rakuten Mail Magazine Unchecker
// @namespace https://github.com/takamario/gm_script
// @description Rakuten Mail Magazine Unchecker
// @include https://order.step.rakuten.co.jp/rms/mall/basket/vc*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorder/*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorderquicknormalize/*
// @include https://books.step.rakuten.co.jp/rms/mall/book/bs*
// ==/UserScript==
(function() {
var i, ipt = document.getElementsByTagName('input');
for (i in ipt) {
if (ipt[i].type === 'checkbox') {
ipt[i].checked = '';
}
}
})();
| // ==UserScript==
// @name Rakuten Mail Magazine Unchecker
// @namespace https://github.com/takamario/gm_script
// @description Rakuten Mail Magazine Unchecker
// @include https://order.step.rakuten.co.jp/rms/mall/basket/vc*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorder/*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorderquicknormalize/*
// @include https://books.step.rakuten.co.jp/rms/mall/book/bs*
// @exclude https://books.step.rakuten.co.jp/rms/mall/book/bs/Cart*
// ==/UserScript==
(function() {
var i, ipt = document.getElementsByTagName('input');
for (i in ipt) {
if (ipt[i].type === 'checkbox') {
ipt[i].checked = '';
}
}
})();
| Add exclude books cart page | Add exclude books cart page
| JavaScript | mit | takamario/gm_script | ---
+++
@@ -6,6 +6,7 @@
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorder/*
// @include https://basket.step.rakuten.co.jp/rms/mall/bs/confirmorderquicknormalize/*
// @include https://books.step.rakuten.co.jp/rms/mall/book/bs*
+// @exclude https://books.step.rakuten.co.jp/rms/mall/book/bs/Cart*
// ==/UserScript==
(function() { |
fb0857c7e26ec7d3f9e1e3dca474769d52fc5cef | addon/mixins/export-to-svg.js | addon/mixins/export-to-svg.js | import Ember from "ember";
var container = '<g transform="scale(%s)">%h</g>';
export default Ember.Mixin.create({
exportToSvg: function(){
var svg = this.$("svg").clone(),
width = +svg.find("desc.width")[0].innerHTML,
div = document.createElement("div"),
svgContent,
promise;
// clean up a little
svg.find("image.base").remove();
svg.find("defs").remove();
svg.find("desc").remove();
div.appendChild(svg[0]);
svgContent = div.innerHTML;
svgContent = svgContent.replace(svgContent.match(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/)[0], "");
svgContent = svgContent.replace("</svg>", "");
promise = new Ember.RSVP.Promise(function(resolve, reject){
resolve(container.replace("%s", 1/width )
.replace("%h", svgContent) );
});
return promise;
}
});
| import Ember from "ember";
var container = '<g transform="scale(%s)">%h</g>';
export default Ember.Mixin.create({
exportToSvg: function(){
var svg = this.$("svg").clone(),
width = +svg.find("desc.width")[0].innerHTML,
div = document.createElement("div"),
svgContent,
promise;
// clean up a little
svg.find("image.base").remove();
svg.find("defs").remove();
svg.find("desc").remove();
svg.find("#base-svg").remove();
div.appendChild(svg[0]);
svgContent = div.innerHTML;
svgContent = svgContent.replace(svgContent.match(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/)[0], "");
svgContent = svgContent.replace("</svg>", "");
promise = new Ember.RSVP.Promise(function(resolve, reject){
resolve(container.replace("%s", 1/width )
.replace("%h", svgContent) );
});
return promise;
}
});
| Remove base svg from exported svg | Remove base svg from exported svg
| JavaScript | apache-2.0 | porkepic/squiggle,porkepic/squiggle | ---
+++
@@ -15,6 +15,7 @@
svg.find("image.base").remove();
svg.find("defs").remove();
svg.find("desc").remove();
+ svg.find("#base-svg").remove();
div.appendChild(svg[0]);
|
3690a15fc48242d95456fabd1f923f121dc0a2db | app/components/add-expense.js | app/components/add-expense.js | import Ember from 'ember';
// import $ from 'jquery';
export default Ember.Component.extend({
expense: {
sum: '',
category: '',
name: ''
},
currency: '£',
expenseCategories: [
'Charity',
'Clothing',
'Education',
'Events',
'Food',
'Gifts',
'Healthcare',
'Household',
'Leisure',
'Hobbies',
'Trasportation',
'Utilities',
'Vacation'
],
errorMessagesSum: {
emRequired: 'This field can\'t be blank',
emPattern: 'Must be a number!'
},
errorMessagesCategory: {
emRequired: 'Must select a category'
},
init () {
this._super();
Ember.TextSupport.reopen({
attributeBindings: ['em-required', 'em-min', 'em-max', 'em-pattern']
});
},
didInsertElement () {
componentHandler.upgradeAllRegistered();
},
actions: {
clearInputs () {
this.set('expense', {
sum: '',
category: '',
name: ''
});
this.$('.mdl-textfield').removeClass('is-dirty is-invalid is-touched');
},
addExpense () {
this.sendAction('action', this.get('expense'));
this.send('clearInputs');
}
}
});
| import Ember from 'ember';
// import $ from 'jquery';
export default Ember.Component.extend({
expense: {
sum: '',
category: '',
name: ''
},
currency: '£',
expenseCategories: [
'Charity',
'Clothing',
'Education',
'Events',
'Food',
'Gifts',
'Healthcare',
'Household',
'Leisure',
'Hobbies',
'Trasportation',
'Utilities',
'Vacation'
],
errorMessagesSum: {
emRequired: 'This field can\'t be blank',
emPattern: 'Must be a number!'
},
errorMessagesCategory: {
emRequired: 'Must select a category'
},
init () {
this._super();
Ember.TextSupport.reopen({
attributeBindings: ['em-required', 'em-min', 'em-max', 'em-pattern']
});
},
didInsertElement () {
componentHandler.upgradeAllRegistered();
},
actions: {
clearInputs () {
this.set('expense', {
sum: '',
category: '',
name: ''
});
this.$('.mdl-textfield').removeClass('is-dirty is-invalid is-touched');
},
addExpense () {
Ember.run.later(() => {
if (!this.$().find('.is-invalid').length) {
this.sendAction('action', this.get('expense'));
this.send('clearInputs');
}
}, 200);
}
}
});
| Check if form is valid and then send save action to parent | refactor: Check if form is valid and then send save action to parent
| JavaScript | mit | pe1te3son/spendings-tracker,pe1te3son/spendings-tracker | ---
+++
@@ -54,8 +54,12 @@
this.$('.mdl-textfield').removeClass('is-dirty is-invalid is-touched');
},
addExpense () {
- this.sendAction('action', this.get('expense'));
- this.send('clearInputs');
+ Ember.run.later(() => {
+ if (!this.$().find('.is-invalid').length) {
+ this.sendAction('action', this.get('expense'));
+ this.send('clearInputs');
+ }
+ }, 200);
}
}
}); |
dfbde5dcd59fce8101bdebf51d0b7489a07e209e | Gruntfile.js | Gruntfile.js | 'use strict';
module.exports = function(grunt) {
// Configuration.
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jshint: {
options: {
jshintrc: true
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jsonlint: {
jshint: ['.jshintrc'],
npm: ['package.json']
},
nodeunit: {
all: 'test/**/*.js'
}
});
// Load tasks.
grunt.loadTasks('./tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-jsonlint');
grunt.loadNpmTasks('grunt-release');
// Register tasks.
grunt.renameTask('release', 'bump');
grunt.registerTask('lint', ['jsonlint', 'jshint', 'jscs']);
grunt.registerTask('release', function() {
grunt.task.run('lint', Array.prototype.concat.apply('bump', arguments).join(':'));
});
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('travis', ['lint', 'validate']);
grunt.registerTask('validate', ['npm-validate']);
grunt.registerTask('default', ['lint', 'validate']);
};
| 'use strict';
module.exports = function(grunt) {
// Configuration.
grunt.initConfig({
jscs: {
options: {
config: '.jscsrc'
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jshint: {
options: {
jshintrc: true
},
grunt: 'Gruntfile.js',
tasks: 'tasks/**/*.js'
},
jsonlint: {
jshint: ['.jshintrc'],
npm: ['package.json']
},
nodeunit: {
all: 'test/**/*.js'
}
});
// Load tasks.
grunt.loadTasks('./tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-jsonlint');
grunt.loadNpmTasks('grunt-release');
// Register tasks.
grunt.renameTask('release', 'bump');
grunt.registerTask('lint', ['jsonlint', 'jshint', 'jscs']);
grunt.registerTask('release', function() {
grunt.task.run('lint', Array.prototype.concat.apply('bump', arguments).join(':'));
});
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('travis', ['lint', 'validate']);
grunt.registerTask('validate', ['npm-validate']);
grunt.registerTask('default', ['lint', 'test', 'validate']);
};
| Include testing workflow in default task. | Include testing workflow in default task.
| JavaScript | mit | joshuaspence/grunt-npm-validate | ---
+++
@@ -43,5 +43,5 @@
grunt.registerTask('test', ['nodeunit']);
grunt.registerTask('travis', ['lint', 'validate']);
grunt.registerTask('validate', ['npm-validate']);
- grunt.registerTask('default', ['lint', 'validate']);
+ grunt.registerTask('default', ['lint', 'test', 'validate']);
}; |
631aeb8a4b81645ad36852dc1076396a625208d1 | Gruntfile.js | Gruntfile.js | var path = require('path');
module.exports = function(grunt) {
grunt.initConfig({
'pkg': grunt.file.readJSON('package.json'),
'dtsGenerator': {
options: {
baseDir: './',
name: 'core-components',
out: './index.d.ts',
excludes: [
'typings/**',
'!typings/lib.ext.d.ts',
'bower_components/**'
]
},
default: {
src: [
'debug-configuration/debug-configuration.ts'
]
}
},
'tsc': {
options: {
tscPath: path.resolve('node_modules', 'typescript', 'bin', 'tsc')
},
default: {}
},
'tsd': {
lib: {
options: {
command: 'reinstall',
latest: true,
config: 'conf/tsd-lib.json',
opts: {
// props from tsd.Options
}
}
}
},
'vulcanize': {
default: {
options: {
csp: 'dependencies_bundle.js'
},
files: {
'dependencies_bundle.html': 'dependencies.html'
}
}
}
});
grunt.loadNpmTasks('grunt-tsc');
grunt.loadNpmTasks('grunt-tsd');
grunt.loadNpmTasks('dts-generator');
grunt.loadNpmTasks('grunt-vulcanize');
grunt.registerTask('default', ['vulcanize']);
};
| var path = require('path');
module.exports = function(grunt) {
grunt.initConfig({
'pkg': grunt.file.readJSON('package.json'),
'dtsGenerator': {
options: {
baseDir: './',
name: 'core-components',
out: './index.d.ts',
excludes: [
'typings/**',
'!typings/lib.ext.d.ts',
'bower_components/**'
]
},
default: {
src: [
'debug-configuration/debug-configuration.ts'
]
}
},
'tsc': {
options: {
tscPath: path.resolve('node_modules', 'typescript', 'bin', 'tsc')
},
default: {}
},
'tsd': {
lib: {
options: {
command: 'reinstall',
latest: true,
config: 'conf/tsd-lib.json',
opts: {
// props from tsd.Options
}
}
}
},
'vulcanize': {
default: {
options: {
// extract all inline JavaScript into a separate file to work around Atom's
// Content Security Policy
csp: 'dependencies_bundle.js'
},
files: {
// output: input
'dependencies_bundle.html': 'dependencies.html'
}
}
}
});
grunt.loadNpmTasks('grunt-tsc');
grunt.loadNpmTasks('grunt-tsd');
grunt.loadNpmTasks('dts-generator');
grunt.loadNpmTasks('grunt-vulcanize');
grunt.registerTask('default', ['vulcanize']);
};
| Add some comments for the vulcanize grunt task | Add some comments for the vulcanize grunt task
| JavaScript | mit | debugworkbench/core-components,debugworkbench/core-components,debugworkbench/core-components | ---
+++
@@ -41,9 +41,12 @@
'vulcanize': {
default: {
options: {
+ // extract all inline JavaScript into a separate file to work around Atom's
+ // Content Security Policy
csp: 'dependencies_bundle.js'
},
files: {
+ // output: input
'dependencies_bundle.html': 'dependencies.html'
}
} |
0bf04823deb5eb3c673ae8cd7663e5f8ff59de90 | Gruntfile.js | Gruntfile.js | 'use strict';
module.exports = function (grunt) {
require('time-grunt')(grunt);
grunt.initConfig({
eslint: {
all: {
src: [
'*.js',
'bin/grunth',
'lib/*.js',
],
},
},
jscs: {
all: {
src: '<%= eslint.all.src %>',
options: {
config: '.jscsrc',
},
},
},
});
// Load all grunt tasks matching the `grunt-*` pattern.
require('load-grunt-tasks')(grunt);
grunt.registerTask('asserts', function () {
try {
/* eslint-disable no-eval */
eval('function* f() {yield 2;} var g = f(); g.next();');
/* eslint-ensable no-eval */
} catch (e) {
throw new Error('Generators not recognized!');
}
try {
/* eslint-disable no-eval */
eval('function f() {"use strict"; const x = 2; return x;} f();');
/* eslint-ensable no-eval */
} catch (e) {
throw new Error('Generators not recognized!');
}
});
grunt.registerTask('lint', [
'eslint',
'jscs',
]);
grunt.registerTask('test', [
'lint',
'asserts',
]);
grunt.registerTask('default', ['test']);
};
| 'use strict';
module.exports = function (grunt) {
require('time-grunt')(grunt);
grunt.initConfig({
eslint: {
all: {
src: [
'*.js',
'bin/grunth',
'lib/*.js',
],
},
},
jscs: {
all: {
src: '<%= eslint.all.src %>',
options: {
config: '.jscsrc',
},
},
},
});
// Load all grunt tasks matching the `grunt-*` pattern.
require('load-grunt-tasks')(grunt);
grunt.registerTask('asserts', function () {
try {
/* eslint-disable no-eval */
eval('function* f() {yield 2;} var g = f(); g.next();');
/* eslint-ensable no-eval */
} catch (e) {
throw new Error('Generators not recognized!');
}
grunt.log.writeln('Generators recognized.');
try {
/* eslint-disable no-eval */
eval('function f() {"use strict"; const x = 2; let y = 3; return [x, y];} f();');
/* eslint-ensable no-eval */
} catch (e) {
throw new Error('Block scoping (const/let) not recognized!');
}
grunt.log.writeln('Block scoping (const/let) recognized.');
});
grunt.registerTask('lint', [
'eslint',
'jscs',
]);
grunt.registerTask('test', [
'lint',
'asserts',
]);
grunt.registerTask('default', ['test']);
};
| Correct messages printed during tests | Correct messages printed during tests
| JavaScript | mit | EE/grunth-cli | ---
+++
@@ -35,14 +35,16 @@
} catch (e) {
throw new Error('Generators not recognized!');
}
+ grunt.log.writeln('Generators recognized.');
try {
/* eslint-disable no-eval */
- eval('function f() {"use strict"; const x = 2; return x;} f();');
+ eval('function f() {"use strict"; const x = 2; let y = 3; return [x, y];} f();');
/* eslint-ensable no-eval */
} catch (e) {
- throw new Error('Generators not recognized!');
+ throw new Error('Block scoping (const/let) not recognized!');
}
+ grunt.log.writeln('Block scoping (const/let) recognized.');
});
grunt.registerTask('lint', [ |
04df28e0092f11aec568d26fea8cca5118756bce | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-git');
grunt.loadNpmTasks('grunt-shell');
grunt.initConfig( {
gitclone: {
mastercointools: {
options: {
repository: 'https://github.com/curtislacy/mastercoin-tools.git',
branch: 'Specify-Directory',
directory: 'node_modules/mastercoin-tools'
},
}
},
shell: {
html: {
command: "./gen_www.sh"
}
}
} );
grunt.registerTask( 'default', function( file ) {
if( !grunt.file.exists( 'node_modules/mastercoin-tools' ))
grunt.task.run( 'gitclone:mastercointools' );
grunt.task.run( 'shell:html' );
} );
grunt.registerTask( 'build', 'shell:html' );
};
| module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-git');
grunt.loadNpmTasks('grunt-shell');
grunt.initConfig( {
gitclone: {
mastercointools: {
options: {
repository: 'https://github.com/curtislacy/mastercoin-tools.git',
branch: 'master',
directory: 'node_modules/mastercoin-tools'
},
}
},
shell: {
html: {
command: "./gen_www.sh"
}
}
} );
grunt.registerTask( 'default', function( file ) {
if( !grunt.file.exists( 'node_modules/mastercoin-tools' ))
grunt.task.run( 'gitclone:mastercointools' );
grunt.task.run( 'shell:html' );
} );
grunt.registerTask( 'build', 'shell:html' );
};
| Switch to using the master branch of my mastercoin-tools fork. | Switch to using the master branch of my mastercoin-tools fork.
| JavaScript | agpl-3.0 | VukDukic/omniwallet,ripper234/omniwallet,arowser/omniwallet,Nevtep/omniwallet,FuzzyBearBTC/omniwallet,VukDukic/omniwallet,maran/omniwallet,arowser/omniwallet,achamely/omniwallet,OmniLayer/omniwallet,curtislacy/omniwallet,ripper234/omniwallet,habibmasuro/omniwallet,VukDukic/omniwallet,OmniLayer/omniwallet,habibmasuro/omniwallet,Nevtep/omniwallet,maran/omniwallet,maran/omniwallet,habibmasuro/omniwallet,OmniLayer/omniwallet,achamely/omniwallet,ripper234/omniwallet,curtislacy/omniwallet,dexX7/omniwallet,habibmasuro/omniwallet,FuzzyBearBTC/omniwallet,FuzzyBearBTC/omniwallet,achamely/omniwallet,OmniLayer/omniwallet,curtislacy/omniwallet,Nevtep/omniwallet,Nevtep/omniwallet,arowser/omniwallet,dexX7/omniwallet,achamely/omniwallet,dexX7/omniwallet | ---
+++
@@ -7,7 +7,7 @@
mastercointools: {
options: {
repository: 'https://github.com/curtislacy/mastercoin-tools.git',
- branch: 'Specify-Directory',
+ branch: 'master',
directory: 'node_modules/mastercoin-tools'
},
} |
196a15dca3290f4fed10470516840a29b1af3588 | Gruntfile.js | Gruntfile.js | 'use strict';
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['./*.js', 'routes/*.js', 'models/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'express:dev'],
options: {
spawn: false
}
},
},
express: {
dev: {
options: {
script: './bin/www'
}
},
prod: {
options: {
script: './bin/www',
node_env: 'production'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-express-server');
grunt.registerTask('default', ['jshint']);
grunt.registerTask('server', [ 'express:dev', 'watch' ]);
};
| 'use strict';
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['./*.js', 'routes/*.js', 'models/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: ['<%= jshint.lib.src %>', 'config.json'],
tasks: ['jshint:lib', 'express:dev'],
options: {
spawn: false
}
},
},
express: {
dev: {
options: {
script: './bin/www'
}
},
prod: {
options: {
script: './bin/www',
node_env: 'production'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-express-server');
grunt.registerTask('default', ['jshint']);
grunt.registerTask('server', [ 'express:dev', 'watch' ]);
};
| Include watching config.json for changes | Include watching config.json for changes
| JavaScript | mit | GuusK/disruptIT,GuusK/disruptIT,GuusK/disruptIT,GuusK/disruptIT | ---
+++
@@ -19,7 +19,7 @@
tasks: ['jshint:gruntfile']
},
lib: {
- files: '<%= jshint.lib.src %>',
+ files: ['<%= jshint.lib.src %>', 'config.json'],
tasks: ['jshint:lib', 'express:dev'],
options: {
spawn: false |
33d989b7a73129a9198da4c0147995cb19500364 | js/cookies-init.js | js/cookies-init.js | $(function handleSimpleIntegration() {
cookieChoices.showCookieBar({
linkHref: '#',
cookieText: 'spine.io uses cookies to help operate the site and gather analytics data. You can read more about it in our',
linkText: 'Privacy Statement',
dismissText: 'I agree',
dismissTextAlt: 'I agree',
styles: 'position: fixed;'
});
});
| $(function handleSimpleIntegration() {
cookieChoices.showCookieBar({
linkHref: '#',
cookieText: 'spine.io uses cookies to help operate the site and gather analytics data.',
// Unlink this 2 lines to add link to Privacy Statements
// cookieText: 'spine.io uses cookies to help operate the site and gather analytics data. You can read more about it in our',
// linkText: 'Privacy Statement',
dismissText: 'I agree',
dismissTextAlt: 'I agree',
styles: 'position: fixed;'
});
});
| Hide link to the Privacy Statement in the cookie notification | Hide link to the Privacy Statement in the cookie notification
| JavaScript | apache-2.0 | SpineEventEngine/SpineEventEngine.github.io,SpineEventEngine/SpineEventEngine.github.io,SpineEventEngine/SpineEventEngine.github.io,SpineEventEngine/SpineEventEngine.github.io,SpineEventEngine/SpineEventEngine.github.io,SpineEventEngine/SpineEventEngine.github.io | ---
+++
@@ -2,8 +2,10 @@
cookieChoices.showCookieBar({
linkHref: '#',
- cookieText: 'spine.io uses cookies to help operate the site and gather analytics data. You can read more about it in our',
- linkText: 'Privacy Statement',
+ cookieText: 'spine.io uses cookies to help operate the site and gather analytics data.',
+ // Unlink this 2 lines to add link to Privacy Statements
+ // cookieText: 'spine.io uses cookies to help operate the site and gather analytics data. You can read more about it in our',
+ // linkText: 'Privacy Statement',
dismissText: 'I agree',
dismissTextAlt: 'I agree',
styles: 'position: fixed;' |
1e6dd2f89b973d9fb1dc8e23d1cd77bb0dce24e4 | lib/auth/vault.js | lib/auth/vault.js | import crypto from 'crypto';
import { accountsKeyedbyAccessKey } from './vault.json';
export function hashSignature(stringToSign, secretKey, algorithm) {
const hmacObject = crypto.createHmac(algorithm, secretKey);
return hmacObject.update(stringToSign).digest('base64');
}
const vault = {
authenticateV2Request: (accessKey, signatureFromRequest,
stringToSign, callback) => {
const account = accountsKeyedbyAccessKey[accessKey];
if (!account) {
return callback('InvalidAccessKeyId');
}
const secretKey = account.secretKey;
const reconstructedSignature =
hashSignature(stringToSign, secretKey, 'sha1');
if (reconstructedSignature !== signatureFromRequest) {
return callback('SignatureDoesNotMatch');
}
const userInfoToSend = {
accountDisplayName: account.displayName,
canonicalID: account.canonicalID,
arn: account.arn,
IAMdisplayName: account.IAMdisplayName,
};
// For now, I am just sending back the canonicalID.
// TODO: Refactor so that the accessKey information
// passed to the API is the full accountInfo Object
// rather than just the canonicalID string.
// This is GH Issue#75
return callback(null, userInfoToSend.canonicalID);
}
};
export default vault;
| import crypto from 'crypto';
import { accountsKeyedbyAccessKey } from './vault.json';
export function hashSignature(stringToSign, secretKey, algorithm) {
const hmacObject = crypto.createHmac(algorithm, secretKey);
return hmacObject.update(stringToSign).digest('base64');
}
const vault = {
authenticateV2Request: (accessKey, signatureFromRequest,
stringToSign, callback) => {
const account = accountsKeyedbyAccessKey[accessKey];
if (!account) {
return callback('InvalidAccessKeyId');
}
const secretKey = account.secretKey;
// If the signature sent is 43 characters,
// this means that sha256 was used:
// 43 characters in base64
const algo = signatureFromRequest.length === 43 ?
'sha256' : 'sha1';
const reconstructedSig =
hashSignature(stringToSign, secretKey, algo);
if (signatureFromRequest !== reconstructedSig) {
return callback('SignatureDoesNotMatch');
}
const userInfoToSend = {
accountDisplayName: account.displayName,
canonicalID: account.canonicalID,
arn: account.arn,
IAMdisplayName: account.IAMdisplayName,
};
// For now, I am just sending back the canonicalID.
// TODO: Refactor so that the accessKey information
// passed to the API is the full accountInfo Object
// rather than just the canonicalID string.
// This is GH Issue#75
return callback(null, userInfoToSend.canonicalID);
}
};
export default vault;
| Add check for sha256 hashed signature | FT: Add check for sha256 hashed signature
| JavaScript | apache-2.0 | truststamp/S3,truststamp/S3,tomateos/S3,tomateos/S3,tomateos/S3,truststamp/S3,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,scality/S3,lucisilv/Silviu_S3-Antidote,tomateos/S3,tomateos/S3,truststamp/S3,scality/S3,scality/S3,truststamp/S3,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,lucisilv/Silviu_S3-Antidote,scality/S3,scality/S3,truststamp/S3,tomateos/S3,scality/S3,tomateos/S3,truststamp/S3,truststamp/S3,scality/S3,tomateos/S3,scality/S3 | ---
+++
@@ -15,9 +15,14 @@
return callback('InvalidAccessKeyId');
}
const secretKey = account.secretKey;
- const reconstructedSignature =
- hashSignature(stringToSign, secretKey, 'sha1');
- if (reconstructedSignature !== signatureFromRequest) {
+ // If the signature sent is 43 characters,
+ // this means that sha256 was used:
+ // 43 characters in base64
+ const algo = signatureFromRequest.length === 43 ?
+ 'sha256' : 'sha1';
+ const reconstructedSig =
+ hashSignature(stringToSign, secretKey, algo);
+ if (signatureFromRequest !== reconstructedSig) {
return callback('SignatureDoesNotMatch');
}
const userInfoToSend = { |
0b69c73dfa7f9873176aac684f8e5800ce48b308 | example-loop.js | example-loop.js | var TiVoRemote = require('./TiVoRemote');
var readline = require('readline');
var config = {
ip: '192.168.1.100',
port: 31339
}
var remote = new TiVoRemote(config);
var rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.setPrompt('');
remote.on('channel', function(channel) { console.log('Channel is now: ' + channel); });
remote.on('on', function(on) { console.log('On state is now: ' + on); });
remote.on('connecting', function() { console.log('Connecting'); });
remote.on('connect', function() { console.log('Connected'); rl.prompt(); });
remote.on('disconnect', function() { console.log('Disconnected'); });
rl.on('line', function(cmd) {
remote.sendCommand(cmd);
});
| var TiVoRemote = require('./TiVoRemote');
var readline = require('readline');
if (process.argv.length < 3) {
console.log('Usage: <script> <ip>');
process.exit(1);
}
var config = {
ip: process.argv[2],
port: 31339
}
var remote = new TiVoRemote(config);
var rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.setPrompt('');
remote.on('channel', function(channel) { console.log('Channel is now: ' + channel); });
remote.on('on', function(on) { console.log('On state is now: ' + on); });
remote.on('connecting', function() { console.log('Connecting'); });
remote.on('connect', function() { console.log('Connected'); rl.prompt(); });
remote.on('disconnect', function() { console.log('Disconnected'); });
rl.on('line', function(cmd) {
remote.sendCommand(cmd);
});
| Allow setting IP from command line argument | Allow setting IP from command line argument
| JavaScript | mit | mattjgalloway/homebridge-tivo | ---
+++
@@ -1,8 +1,13 @@
var TiVoRemote = require('./TiVoRemote');
var readline = require('readline');
+if (process.argv.length < 3) {
+ console.log('Usage: <script> <ip>');
+ process.exit(1);
+}
+
var config = {
- ip: '192.168.1.100',
+ ip: process.argv[2],
port: 31339
}
var remote = new TiVoRemote(config); |
4a67c4969fc66dd10d9fc6fb7c07be91c5ac2838 | src/welcome.js | src/welcome.js | import {ArrayExtensions} from './arrayextensions';
import {Letter} from './letter';
import {moveBefore, DIRECTION} from 'aurelia-dragula';
export class Welcome {
constructor() {
this.dragDirection = DIRECTION.HORIZONTAL;
this.reset();
}
get unjumbledName() {
return this.nameLetters.reduce((previous, current) => previous + current.char, '');
}
submit() {
this.nameLetters = [];
for(let i = 0; i < this.firstName.length; i++) {
this.nameLetters.push(new Letter(this.firstName.charAt(i)));
}
ArrayExtensions.shuffle(this.nameLetters);
//If, by chance, we shuffle it to the same as the original name, keep shuffling until it no longer is
while(this.unjumbledName === this.firstName)
ArrayExtensions.shuffle(this.nameLetters);
this.haveName = true;
}
drop(item, target, source, sibling) {
let itemId = item.dataset.id;
let siblingId = sibling ? sibling.dataset.id : null;
moveBefore(this.nameLetters, (letter) => letter.id === itemId, (letter) => letter.id === siblingId);
if (this.unjumbledName === this.firstName)
this.winner = true;
}
reset() {
this.firstName = '';
this.haveName = false;
this.winner = false;
}
}
| import {ArrayExtensions} from './arrayextensions';
import {Letter} from './letter';
import {moveBefore, DIRECTION} from 'aurelia-dragula';
export class Welcome {
constructor() {
this.dragDirection = DIRECTION.HORIZONTAL;
this.reset();
}
get unjumbledName() {
return this.nameLetters.reduce((previous, current) => previous + current.char, '');
}
submit() {
this.nameLetters = [];
for(let i = 0; i < this.firstName.length; i++) {
this.nameLetters.push(new Letter(this.firstName.charAt(i)));
}
do {
ArrayExtensions.shuffle(this.nameLetters);
}
//If, by chance, we shuffle it to the same as the original name, keep shuffling until it no longer is
while(this.unjumbledName === this.firstName)
this.haveName = true;
}
drop(item, target, source, sibling) {
let itemId = item.dataset.id;
let siblingId = sibling ? sibling.dataset.id : null;
moveBefore(this.nameLetters, (letter) => letter.id === itemId, (letter) => letter.id === siblingId);
if (this.unjumbledName === this.firstName)
this.winner = true;
}
reset() {
this.firstName = '';
this.haveName = false;
this.winner = false;
}
}
| Make the code slightly clearer | Make the code slightly clearer | JavaScript | apache-2.0 | michaelmalonenz/aurelia-dragula-example,michaelmalonenz/aurelia-dragula-example | ---
+++
@@ -19,11 +19,11 @@
this.nameLetters.push(new Letter(this.firstName.charAt(i)));
}
- ArrayExtensions.shuffle(this.nameLetters);
-
+ do {
+ ArrayExtensions.shuffle(this.nameLetters);
+ }
//If, by chance, we shuffle it to the same as the original name, keep shuffling until it no longer is
while(this.unjumbledName === this.firstName)
- ArrayExtensions.shuffle(this.nameLetters);
this.haveName = true;
} |
d7b23057f03f2af55e032999f8161b6458d8dd77 | spec/ui/control.js | spec/ui/control.js | define(['backbone', 'cilantro', 'text!/mock/fields.json'], function (Backbone, c, fieldsJSON) {
var fields = new Backbone.Collection(JSON.parse(fieldsJSON));
describe('FieldControl', function() {
var control;
describe('Base', function() {
beforeEach(function() {
control = new c.ui.FieldControl({
model: fields.models[0]
});
control.render();
});
it('should have an field by default', function() {
expect(control.get()).toEqual({field: 30});
});
it('should never clear the field attr', function() {
control.clear();
expect(control.get()).toEqual({field: 30});
});
});
describe('w/ Number', function() {
beforeEach(function() {
control = new c.ui.FieldControl({
model: fields.models[0]
});
control.render();
});
it('should coerce the value to a number', function() {
control.set('value', '30');
expect(control.get('value')).toEqual(30);
});
});
});
});
| define(['backbone', 'cilantro', 'text!/mock/fields.json'], function (Backbone, c, fieldsJSON) {
var fields = new Backbone.Collection(JSON.parse(fieldsJSON));
describe('FieldControl', function() {
var control;
describe('Base', function() {
beforeEach(function() {
control = new c.ui.FieldControl({
model: fields.models[0]
});
control.render();
});
it('should have an field by default', function() {
expect(control.get()).toEqual({
field: 30,
value: null,
operator: null
});
});
it('should never clear the field attr', function() {
control.clear();
expect(control.get()).toEqual({
field: 30,
value: null,
operator: null
});
});
});
describe('w/ Number', function() {
beforeEach(function() {
control = new c.ui.FieldControl({
model: fields.models[0]
});
control.render();
});
it('should coerce the value to a number', function() {
control.set('value', '30');
expect(control.get('value')).toEqual(30);
});
});
});
});
| Update spec to take in account null fields in context model | Update spec to take in account null fields in context model | JavaScript | bsd-2-clause | chop-dbhi/cilantro,chop-dbhi/cilantro,chop-dbhi/cilantro | ---
+++
@@ -13,12 +13,20 @@
});
it('should have an field by default', function() {
- expect(control.get()).toEqual({field: 30});
+ expect(control.get()).toEqual({
+ field: 30,
+ value: null,
+ operator: null
+ });
});
it('should never clear the field attr', function() {
control.clear();
- expect(control.get()).toEqual({field: 30});
+ expect(control.get()).toEqual({
+ field: 30,
+ value: null,
+ operator: null
+ });
});
});
|
ccac850fcd3878adbb54e9ae8f92e08f29c81d6f | test/helper.js | test/helper.js | 'use strict';
//supress log messages
process.env.LOG_LEVEL = 'fatal';
var chai = require('chai'),
cap = require('chai-as-promised');
global.sinon = require('sinon');
global.fs = require('fs');
global.utils = require('radiodan-client').utils;
global.EventEmitter = require('events').EventEmitter;
global.assert = chai.assert;
global.libDir = __dirname + '/../lib/';
chai.use(cap);
| 'use strict';
//supress log messages
process.env.LOG_LEVEL = 'fatal';
var chai = require('chai'),
cap = require('chai-as-promised');
global.sinon = require('sinon');
global.fs = require('fs');
global.utils = require('radiodan-client').utils;
global.EventEmitter = require('events').EventEmitter;
global.assert = chai.assert;
global.fakeRadiodan = fakeRadiodan;
global.libDir = __dirname + '/../lib/';
chai.use(cap);
function fakeRadiodan(objType) {
switch(objType) {
case 'player':
return fakeRadiodanPlayer();
case 'ui':
return fakeRadiodanUI();
default:
throw new Error('Unknown radiodan component ' + objType);
}
}
function fakeRadiodanPlayer() {
var actions = ['add', 'clear', 'next', 'pause', 'play', 'previous', 'random', 'remove', 'repeat', 'search', 'status', 'stop', 'updateDatabase', 'volume'],
players = ['main', 'announcer', 'avoider'],
output = {};
players.forEach(function(p) {
output[p] = stubbedPromisesForActions(actions);
});
return output;
}
function fakeRadiodanUI() {
var actions = ['emit'],
obj = { 'RGBLEDs': ['power'] },
colours = { 'green': 'green'},
output = { colours: colours };
Object.keys(obj).forEach(function(k) {
output[k] = {};
obj[k].forEach(function(p) {
output[k][p] = stubbedPromisesForActions(actions);
});
});
return output;
}
function stubbedPromisesForActions(actions) {
var instance = {};
actions.forEach(function(a) {
instance[a] = sinon.stub().returns(utils.promise.resolve());
});
return instance;
}
| Add fake Radiodan client objects | Add fake Radiodan client objects
| JavaScript | apache-2.0 | radiodan/magic-button,radiodan/magic-button | ---
+++
@@ -11,7 +11,57 @@
global.utils = require('radiodan-client').utils;
global.EventEmitter = require('events').EventEmitter;
global.assert = chai.assert;
+global.fakeRadiodan = fakeRadiodan;
global.libDir = __dirname + '/../lib/';
chai.use(cap);
+function fakeRadiodan(objType) {
+ switch(objType) {
+ case 'player':
+ return fakeRadiodanPlayer();
+ case 'ui':
+ return fakeRadiodanUI();
+ default:
+ throw new Error('Unknown radiodan component ' + objType);
+ }
+}
+
+function fakeRadiodanPlayer() {
+ var actions = ['add', 'clear', 'next', 'pause', 'play', 'previous', 'random', 'remove', 'repeat', 'search', 'status', 'stop', 'updateDatabase', 'volume'],
+ players = ['main', 'announcer', 'avoider'],
+ output = {};
+
+ players.forEach(function(p) {
+ output[p] = stubbedPromisesForActions(actions);
+ });
+
+ return output;
+}
+
+function fakeRadiodanUI() {
+ var actions = ['emit'],
+ obj = { 'RGBLEDs': ['power'] },
+ colours = { 'green': 'green'},
+ output = { colours: colours };
+
+ Object.keys(obj).forEach(function(k) {
+ output[k] = {};
+
+ obj[k].forEach(function(p) {
+ output[k][p] = stubbedPromisesForActions(actions);
+ });
+ });
+
+ return output;
+}
+
+function stubbedPromisesForActions(actions) {
+ var instance = {};
+
+ actions.forEach(function(a) {
+ instance[a] = sinon.stub().returns(utils.promise.resolve());
+ });
+
+ return instance;
+} |
083c74399f6c260d1738272c60b282d83b2a0b44 | document/documentConversion.js | document/documentConversion.js | import DocumentConfigurator from './DocumentConfigurator'
import DocumentModel from './DocumentModel'
import DocumentJSONConverter from './DocumentJSONConverter'
import DocumentHTMLImporter from './DocumentHTMLImporter'
import DocumentHTMLExporter from './DocumentHTMLExporter'
function importJSON (content) {
let doc = new DocumentModel()
let jsonConverter = new DocumentJSONConverter()
jsonConverter.importDocument(doc, content)
return doc
}
function exportJSON (doc) {
let jsonConverter = new DocumentJSONConverter()
return jsonConverter.exportDocument(doc)
}
function importHTML (content) {
let htmlImporter = new DocumentHTMLImporter({
configurator: new DocumentConfigurator()
})
return htmlImporter.importDocument(content)
}
function exportHTML (doc) {
let htmlExporter = new DocumentHTMLExporter({
configurator: new DocumentConfigurator()
})
return htmlExporter.exportDocument(doc)
}
export {
importJSON,
exportJSON,
importHTML,
exportHTML
}
| import DocumentConfigurator from './DocumentConfigurator'
import DocumentModel from './DocumentModel'
import DocumentJSONConverter from './DocumentJSONConverter'
import DocumentHTMLImporter from './DocumentHTMLImporter'
import DocumentHTMLExporter from './DocumentHTMLExporter'
function importJSON (content) {
let doc = new DocumentModel()
let jsonConverter = new DocumentJSONConverter()
jsonConverter.importDocument(doc, content)
return doc
}
function exportJSON (doc) {
let jsonConverter = new DocumentJSONConverter()
return jsonConverter.exportDocument(doc)
}
function importHTML (content) {
let htmlImporter = new DocumentHTMLImporter({
configurator: new DocumentConfigurator()
})
return htmlImporter.importDocument(content)
}
function exportHTML (doc) {
let htmlExporter = new DocumentHTMLExporter({
configurator: new DocumentConfigurator()
})
let html = htmlExporter.exportDocument(doc)
html = html.replace(/ data-id=".+?"/g, '')
return html
}
export {
importJSON,
exportJSON,
importHTML,
exportHTML
}
| Remove the data-id attribute on HTML export | Remove the data-id attribute on HTML export
| JavaScript | apache-2.0 | stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila | ---
+++
@@ -27,7 +27,9 @@
let htmlExporter = new DocumentHTMLExporter({
configurator: new DocumentConfigurator()
})
- return htmlExporter.exportDocument(doc)
+ let html = htmlExporter.exportDocument(doc)
+ html = html.replace(/ data-id=".+?"/g, '')
+ return html
}
export { |
22b7b0759a48eadbb3268f30d34926e43ee7d2ca | src/database/DataTypes/InsuranceProvider.js | src/database/DataTypes/InsuranceProvider.js | import Realm from 'realm';
export class InsuranceProvider extends Realm.Object {}
InsuranceProvider.schema = {
name: 'InsuranceProvider',
primaryKey: 'id',
properties: {
id: 'string',
name: 'string',
comment: 'string?',
validityDays: 'int',
isActive: 'bool',
policies: {
type: 'linkingObjects',
objectType: 'InsurancePolicy',
property: 'insuranceProvider',
},
},
};
export default InsuranceProvider;
| import Realm from 'realm';
export class InsuranceProvider extends Realm.Object {}
InsuranceProvider.schema = {
name: 'InsuranceProvider',
primaryKey: 'id',
properties: {
id: 'string',
name: { type: 'string', optional: true },
comment: { type: 'string', optional: true },
validityDays: { type: 'int', optional: true },
isActive: { type: 'bool', optional: true },
policies: {
type: 'linkingObjects',
objectType: 'InsurancePolicy',
property: 'insuranceProvider',
},
},
};
export default InsuranceProvider;
| Add update to provider properties | Add update to provider properties
| JavaScript | mit | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile | ---
+++
@@ -7,10 +7,10 @@
primaryKey: 'id',
properties: {
id: 'string',
- name: 'string',
- comment: 'string?',
- validityDays: 'int',
- isActive: 'bool',
+ name: { type: 'string', optional: true },
+ comment: { type: 'string', optional: true },
+ validityDays: { type: 'int', optional: true },
+ isActive: { type: 'bool', optional: true },
policies: {
type: 'linkingObjects',
objectType: 'InsurancePolicy', |
92538b650ec1da071fe6be0697234c6236b118a1 | build-dev-bundle.js | build-dev-bundle.js | var path = require("path");
var stealTools = require("steal-tools");
var promise = stealTools.bundle({
config: path.join(__dirname, "package.json!npm")
}, {
filter: [ "**/*", "package.json" ],
minify: true
});
| var path = require("path");
var stealTools = require("steal-tools");
stealTools.bundle({
config: path.join(__dirname, "package.json!npm")
}, {
filter: [ "**/*", "package.json" ],
minify: true
}).catch(function(error) {
console.error(error);
process.exit(1);
});
| Exit with an error when the deps-bundle script fails | Exit with an error when the deps-bundle script fails
Previously, if you ran the deps-bundle script and steal-tools reported an error, the script would still exit successfully and the next script would run (e.g. when building the site/docs). This would leave you with an out-of-date (or non-existent) dev-bundle.
This fixes the issue by catching any errors reported by steal-tools and exiting the script in a way that will make Node report the error and stop.
| JavaScript | mit | bitovi/canjs,bitovi/canjs,bitovi/canjs,bitovi/canjs | ---
+++
@@ -1,9 +1,12 @@
var path = require("path");
var stealTools = require("steal-tools");
-var promise = stealTools.bundle({
+stealTools.bundle({
config: path.join(__dirname, "package.json!npm")
}, {
filter: [ "**/*", "package.json" ],
minify: true
+}).catch(function(error) {
+ console.error(error);
+ process.exit(1);
}); |
6552de30288ec17a669a949f1808bd6bb817a1ae | js/change_logos.js | js/change_logos.js | window.addEventListener("load", function() {
const EXTRA_IMAGES = document.getElementsByClassName("alt-logo-img");
EXTRA_IMAGES[0].classList.toggle("active");
EXTRA_IMAGES[EXTRA_IMAGES.length - 1].classList.toggle("active");
var just_switched = false;
Array.from(EXTRA_IMAGES).forEach(function(img, idx) {
var next_idx = idx + 1;
if(next_idx == EXTRA_IMAGES.length)
next_idx = 0;
// Only triggered on active alt images
img.addEventListener("mouseover", function() {
if(!just_switched) {
img.classList.toggle("active");
EXTRA_IMAGES[next_idx].classList.toggle("active");
just_switched = true;
} else
just_switched = false;
});
});
});
| window.addEventListener("load", function() {
const EXTRA_IMAGES = document.getElementsByClassName("alt-logo-img");
EXTRA_IMAGES[0].classList.toggle("active");
EXTRA_IMAGES[EXTRA_IMAGES.length - 1].classList.toggle("active");
var just_switched = false;
Array.from(EXTRA_IMAGES).forEach(function(img, idx) {
var next_idx = (idx + 1) % EXTRA_IMAGES.length;
// Only triggered on active alt images
img.addEventListener("mouseover", function() {
if(!just_switched) {
img.classList.toggle("active");
EXTRA_IMAGES[next_idx].classList.toggle("active");
just_switched = true;
} else
just_switched = false;
});
});
});
| Reduce if to a modulo for changing logos | Reduce if to a modulo for changing logos
Thanks to @karolsw2 for pointing this out
Ref: #1
| JavaScript | mit | nabijaczleweli/nabijaczleweli.github.io,nabijaczleweli/nabijaczleweli.github.io | ---
+++
@@ -5,9 +5,7 @@
var just_switched = false;
Array.from(EXTRA_IMAGES).forEach(function(img, idx) {
- var next_idx = idx + 1;
- if(next_idx == EXTRA_IMAGES.length)
- next_idx = 0;
+ var next_idx = (idx + 1) % EXTRA_IMAGES.length;
// Only triggered on active alt images
img.addEventListener("mouseover", function() { |
299868764c1340bc5cec893ea1081b8947d14838 | scripts/createsearchindex.js | scripts/createsearchindex.js | console.log("=================================");
console.log("Creating search index...");
console.log("=================================");
// Scan through all content/ directories
// For each markdown file
// CreateIndex(title,content,path)
var lunr = require('lunr');
var idx = lunr(function () {
this.field('title')
this.field('body')
this.add({
"title": "Twelfth-Night",
"body": "If music be the food of love, play on: Give me excess of it…",
"author": "William Shakespeare",
"id": "/william/shakespeare/"
})
this.add({
"title": "Batman",
"body": "Batman loves throwing batarangs.",
"author": "DC Comics",
"id": "/dc/batman/"
})
})
console.log(idx.search("love"));
console.log("=================================");
console.log(JSON.stringify(idx));
| console.log("=================================");
console.log("Creating search index...");
console.log("=================================");
// Scan through all content/ directories
// For each markdown file
// CreateIndex(title,content,path)
var lunr = require('lunr');
var idx = lunr(function () {
this.field('title')
this.field('body')
this.field('author')
this.ref('id')
this.add({
"title": "Wolverine",
"body": "A animal-human hybrid with a indestructible metal skeleton",
"author": "Marvel Comics",
"id": "/xmen/wolverine/"
})
this.add({
"title": "Batman",
"body": "A cloaked hero with ninja like skills and dark personality",
"author": "DC Comics",
"id": "/justiceleague/batman/"
})
this.add({
"title": "Superman",
"body": "A humanoid alien that grew up on earth with super-human powers",
"author": "DC Comics",
"id": "/justiceleague/superman/"
})
})
const searchTerm = "metal";
console.log(JSON.stringify(idx.search(searchTerm),null,2));
console.log("=================================");
// Build the search index
//console.log(JSON.stringify(idx));
| Add super hero search data. Format the search output. | Add super hero search data. Format the search output.
| JavaScript | mit | govau/service-manual | ---
+++
@@ -11,21 +11,33 @@
var idx = lunr(function () {
this.field('title')
this.field('body')
+ this.field('author')
+ this.ref('id')
this.add({
- "title": "Twelfth-Night",
- "body": "If music be the food of love, play on: Give me excess of it…",
- "author": "William Shakespeare",
- "id": "/william/shakespeare/"
+ "title": "Wolverine",
+ "body": "A animal-human hybrid with a indestructible metal skeleton",
+ "author": "Marvel Comics",
+ "id": "/xmen/wolverine/"
})
this.add({
"title": "Batman",
- "body": "Batman loves throwing batarangs.",
+ "body": "A cloaked hero with ninja like skills and dark personality",
"author": "DC Comics",
- "id": "/dc/batman/"
+ "id": "/justiceleague/batman/"
+ })
+ this.add({
+ "title": "Superman",
+ "body": "A humanoid alien that grew up on earth with super-human powers",
+ "author": "DC Comics",
+ "id": "/justiceleague/superman/"
})
})
-console.log(idx.search("love"));
+const searchTerm = "metal";
+
+console.log(JSON.stringify(idx.search(searchTerm),null,2));
console.log("=================================");
-console.log(JSON.stringify(idx));
+
+// Build the search index
+//console.log(JSON.stringify(idx)); |
30273baa75c1319034d46f254176b5701125a3b5 | server/api/breweries/breweryRoutes.js | server/api/breweries/breweryRoutes.js | 'use strict';
const router = require('express').Router();
const brewery = require('./breweryController');
router.route('/')
.get(brewery.get)
.post(brewery.post);
module.exports = router;
| 'use strict';
const router = require('express').Router();
const brewery = require('./breweryController');
router.route('/:location')
.get(brewery.get)
.post(brewery.post);
module.exports = router;
| Add route param for location | Add route param for location
| JavaScript | mit | ntoung/beer.ly,ntoung/beer.ly | ---
+++
@@ -3,7 +3,7 @@
const router = require('express').Router();
const brewery = require('./breweryController');
-router.route('/')
+router.route('/:location')
.get(brewery.get)
.post(brewery.post);
|
b2f9d7066c4bf6dff22a448e2d34e3a00f7e1431 | lib/catch-links.js | lib/catch-links.js |
module.exports = function (root, cb) {
root.addEventListener('click', (ev) => {
if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) {
return true
}
var anchor = null
for (var n = ev.target; n.parentNode; n = n.parentNode) {
if (n.nodeName === 'A') {
anchor = n
break
}
}
if (!anchor) return true
var href = anchor.getAttribute('href')
if (href) {
var isUrl
try {
var url = new URL(href)
isUrl = true
} catch (e) {
isUrl = false
}
if (isUrl && url.host || isUrl && url.protocol === 'magnet:') {
cb(href, true)
} else if (href !== '#') {
cb(href, false, anchor.anchor)
}
}
ev.preventDefault()
ev.stopPropagation()
})
}
|
module.exports = function (root, cb) {
root.addEventListener('click', (ev) => {
if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) {
return true
}
var anchor = null
for (var n = ev.target; n.parentNode; n = n.parentNode) {
if (n.nodeName === 'A') {
anchor = n
break
}
}
if (!anchor) return true
var href = anchor.getAttribute('href')
if (href) {
var isUrl
try {
var url = new URL(href)
isUrl = true
} catch (e) {
isUrl = false
}
if (isUrl && (url.host || url.protocol === 'magnet:')) {
cb(href, true)
} else if (href !== '#') {
cb(href, false, anchor.anchor)
}
}
ev.preventDefault()
ev.stopPropagation()
})
}
| Refactor magnet URI link catch logic | Refactor magnet URI link catch logic
| JavaScript | agpl-3.0 | ssbc/patchwork,ssbc/patchwork | ---
+++
@@ -27,7 +27,7 @@
isUrl = false
}
- if (isUrl && url.host || isUrl && url.protocol === 'magnet:') {
+ if (isUrl && (url.host || url.protocol === 'magnet:')) {
cb(href, true)
} else if (href !== '#') {
cb(href, false, anchor.anchor) |
8de8572bcb78739bc25f471dfbfec3ab7e75964c | lib/bot/queries.js | lib/bot/queries.js | var r = require('rethinkdb');
// Number of seconds after which Reddit will archive an article
// (180 days): https://github.com/reddit/reddit/commit/b7b24d2e9fa06ba37ea78e0275dce86d95158e64
var archiveLimit = 180 * 24 * 60 * 60;
exports.mostUrgentSubject = r.table('subjects')
.between(r.now().sub(archiveLimit),r.now(),{index:'article_created'})
.orderBy(r.desc(function(subject){
var staleness = subject('last_checked').sub(r.now());
var age = subject('article_created').sub(r.now());
return staleness.div(age);
})).limit(1).merge(function(subject){ return {
forfeits: r.table('forfeits').getAll(
subject('name'),{index: 'subject'})
.filter(function(forfeit){
return r.not(forfeit('withdrawn').default(false))})
.merge(function(forfeit){ return {
reply_klaxons: r.table('klaxons').getAll(
forfeit('id'),{index:'forfeits'})
.map(function(klaxon){return klaxon('parent')('id')})
.coerceTo('array')
};
}).coerceTo('array')
};
})(0).default(null);
| var r = require('rethinkdb');
// Number of seconds after which Reddit will archive an article
// (180 days): https://github.com/reddit/reddit/commit/b7b24d2e9fa06ba37ea78e0275dce86d95158e64
var archiveLimit = 180 * 24 * 60 * 60;
exports.mostUrgentSubject = r.table('subjects')
.between(r.now().sub(archiveLimit),r.now(),{index:'article_created'})
.orderBy(r.desc(function(subject){
var staleness = subject('last_checked').sub(r.now());
var age = subject('article_created').sub(r.now());
return staleness.div(age);
}))
.limit(1)(0)
.merge(function(subject){ return {
forfeits: r.table('forfeits').getAll(
subject('name'),{index: 'subject'})
.filter(function(forfeit){
return r.not(forfeit('withdrawn').default(false))})
.merge(function(forfeit){ return {
reply_klaxons: r.table('klaxons').getAll(
forfeit('id'),{index:'forfeits'})
.map(function(klaxon){return klaxon('parent')('id')})
.coerceTo('array')
};
}).coerceTo('array')
};
})
.default(null);
| Put sub-index immediately after limit on query | Put sub-index immediately after limit on query
| JavaScript | mit | stuartpb/QIKlaxonBot,stuartpb/QIKlaxonBot | ---
+++
@@ -10,7 +10,9 @@
var staleness = subject('last_checked').sub(r.now());
var age = subject('article_created').sub(r.now());
return staleness.div(age);
- })).limit(1).merge(function(subject){ return {
+ }))
+ .limit(1)(0)
+ .merge(function(subject){ return {
forfeits: r.table('forfeits').getAll(
subject('name'),{index: 'subject'})
.filter(function(forfeit){
@@ -23,4 +25,5 @@
};
}).coerceTo('array')
};
- })(0).default(null);
+ })
+ .default(null); |
c4c365e613a68109aa33d7a14fc0041b3cf5c148 | lib/less/render.js | lib/less/render.js | var PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise;
module.exports = function(environment, ParseTree, ImportManager) {
var render = function (input, options, callback) {
var parse = require('./parse')(environment, ParseTree, ImportManager);
if (typeof(options) === 'function') {
callback = options;
options = {};
}
if (!callback) {
var self = this;
return new PromiseConstructor(function (resolve, reject) {
render.call(self, input, options, function(err, output) {
if (err) {
reject(err);
} else {
resolve(output);
}
});
});
} else {
parse(input, options, function(err, root, imports, options) {
if (err) { return callback(err); }
var result;
try {
var parseTree = new ParseTree(root, imports);
result = parseTree.toCSS(options);
}
catch (err) { return callback(err); }
callback(null, result);
});
}
};
return render;
};
| var PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise;
module.exports = function(environment, ParseTree, ImportManager) {
var render = function (input, options, callback) {
if (typeof(options) === 'function') {
callback = options;
options = {};
}
if (!callback) {
var self = this;
return new PromiseConstructor(function (resolve, reject) {
render.call(self, input, options, function(err, output) {
if (err) {
reject(err);
} else {
resolve(output);
}
});
});
} else {
this.parse(input, options, function(err, root, imports, options) {
if (err) { return callback(err); }
var result;
try {
var parseTree = new ParseTree(root, imports);
result = parseTree.toCSS(options);
}
catch (err) { return callback(err); }
callback(null, result);
});
}
};
return render;
};
| Fix parse refactor - this passed to the plugin manager must be less | Fix parse refactor - this passed to the plugin manager must be less
| JavaScript | apache-2.0 | foresthz/less.js,chenxiaoxing1992/less.js,wjb12/less.js,NaSymbol/less.js,evocateur/less.js,less/less.js,seven-phases-max/less.js,MrChen2015/less.js,SkReD/less.js,deciament/less.js,christer155/less.js,yuhualingfeng/less.js,xiaoyanit/less.js,NirViaje/less.js,royriojas/less.js,royriojas/less.js,less/less.js,bendroid/less.js,foresthz/less.js,angeliaz/less.js,miguel-serrano/less.js,PUSEN/less.js,chenxiaoxing1992/less.js,cgvarela/less.js,bendroid/less.js,yuhualingfeng/less.js,PUSEN/less.js,nolanlawson/less.js,aichangzhi123/less.js,miguel-serrano/less.js,cypher0x9/less.js,christer155/less.js,cypher0x9/less.js,huzion/less.js,ahutchings/less.js,sqliang/less.js,wyfyyy818818/less.js,SkReD/less.js,sqliang/less.js,dyx/less.js,arusanov/less.js,angeliaz/less.js,thinkDevDM/less.js,xiaoyanit/less.js,featurist/less-vars,ahstro/less.js,paladox/less.js,ahutchings/less.js,pkdevbox/less.js,wyfyyy818818/less.js,SomMeri/less-rhino.js,idreamingreen/less.js,bammoo/less.js,mishal/less.js,gencer/less.js,AlexMeliq/less.js,mcanthony/less.js,jdan/less.js,bhavyaNaveen/project1,Synchro/less.js,arusanov/less.js,deciament/less.js,dyx/less.js,bammoo/less.js,paladox/less.js,jjj117/less.js,lincome/less.js,Nastarani1368/less.js,cgvarela/less.js,Nastarani1368/less.js,SomMeri/less-rhino.js,jdan/less.js,demohi/less.js,lvpeng/less.js,lincome/less.js,lvpeng/less.js,thinkDevDM/less.js,mcanthony/less.js,ridixcr/less.js,wjb12/less.js,NirViaje/less.js,ridixcr/less.js,MrChen2015/less.js,AlexMeliq/less.js,gencer/less.js,NaSymbol/less.js,pkdevbox/less.js,jjj117/less.js,demohi/less.js,egg-/less.js,nolanlawson/less.js,Synchro/less.js,waiter/less.js,aichangzhi123/less.js,featurist/less-vars,less/less.js,seven-phases-max/less.js,mishal/less.js,waiter/less.js,idreamingreen/less.js,ahstro/less.js,evocateur/less.js,huzion/less.js,bhavyaNaveen/project1,egg-/less.js | ---
+++
@@ -2,8 +2,6 @@
module.exports = function(environment, ParseTree, ImportManager) {
var render = function (input, options, callback) {
- var parse = require('./parse')(environment, ParseTree, ImportManager);
-
if (typeof(options) === 'function') {
callback = options;
options = {};
@@ -21,7 +19,7 @@
});
});
} else {
- parse(input, options, function(err, root, imports, options) {
+ this.parse(input, options, function(err, root, imports, options) {
if (err) { return callback(err); }
var result; |
f7032ee4eb1b17cdab455259ea46e4bba055b5da | lib/parsers/sax.js | lib/parsers/sax.js | var util = require('util');
var sax = require('sax');
var TreeBuilder = require('./../treebuilder').TreeBuilder;
function XMLParser(target) {
var self = this;
this.parser = sax.parser(true);
this.target = (target) ? target : new TreeBuilder();
/* TODO: would be nice to move these out */
this.parser.onopentag = function(tag) {
self.target.start(tag.name, tag.attributes);
};
this.parser.ontext = function(text) {
self.target.data(text);
};
this.parser.oncdata = function(text) {
self.target.data(text);
};
this.parser.ondoctype = function(text) {
};
this.parser.oncomment = function(comment) {
/* TODO: parse comment? */
};
this.parser.onclosetag = function(tag) {
self.target.end(tag);
};
this.parser.onerror = function(error) {
throw error;
};
}
XMLParser.prototype.feed = function(chunk) {
this.parser.write(chunk);
};
XMLParser.prototype.close = function() {
this.parser.close();
return this.target.close();
};
exports.XMLParser = XMLParser;
| var util = require('util');
var sax = require('sax');
var TreeBuilder = require('./../treebuilder').TreeBuilder;
function XMLParser(target) {
this.parser = sax.parser(true);
this.target = (target) ? target : new TreeBuilder();
this.parser.onopentag = this._handleOpenTag.bind(this);
this.parser.ontext = this._handleText.bind(this);
this.parser.oncdata = this._handleCdata.bind(this);
this.parser.ondoctype = this._handleDoctype.bind(this);
this.parser.oncomment = this._handleComment.bind(this);
this.parser.onclosetag = this._handleCloseTag.bind(this);
this.parser.onerror = this._handleError.bind(this);
}
XMLParser.prototype._handleOpenTag = function(tag) {
this.target.start(tag.name, tag.attributes);
};
XMLParser.prototype._handleText = function(text) {
this.target.data(text);
};
XMLParser.prototype._handleCdata = function(text) {
this.target.data(text);
};
XMLParser.prototype._handleDoctype = function(text) {
};
XMLParser.prototype._handleComment = function(comment) {
};
XMLParser.prototype._handleCloseTag = function(tag) {
this.target.end(tag);
};
XMLParser.prototype._handleError = function(err) {
throw err;
};
XMLParser.prototype.feed = function(chunk) {
this.parser.write(chunk);
};
XMLParser.prototype.close = function() {
this.parser.close();
return this.target.close();
};
exports.XMLParser = XMLParser;
| Move methods out of the constructor. | Move methods out of the constructor.
| JavaScript | apache-2.0 | racker/node-elementtree | ---
+++
@@ -5,40 +5,44 @@
var TreeBuilder = require('./../treebuilder').TreeBuilder;
function XMLParser(target) {
- var self = this;
this.parser = sax.parser(true);
this.target = (target) ? target : new TreeBuilder();
- /* TODO: would be nice to move these out */
- this.parser.onopentag = function(tag) {
- self.target.start(tag.name, tag.attributes);
- };
+ this.parser.onopentag = this._handleOpenTag.bind(this);
+ this.parser.ontext = this._handleText.bind(this);
+ this.parser.oncdata = this._handleCdata.bind(this);
+ this.parser.ondoctype = this._handleDoctype.bind(this);
+ this.parser.oncomment = this._handleComment.bind(this);
+ this.parser.onclosetag = this._handleCloseTag.bind(this);
+ this.parser.onerror = this._handleError.bind(this);
+}
- this.parser.ontext = function(text) {
- self.target.data(text);
- };
+XMLParser.prototype._handleOpenTag = function(tag) {
+ this.target.start(tag.name, tag.attributes);
+};
- this.parser.oncdata = function(text) {
- self.target.data(text);
- };
+XMLParser.prototype._handleText = function(text) {
+ this.target.data(text);
+};
- this.parser.ondoctype = function(text) {
+XMLParser.prototype._handleCdata = function(text) {
+ this.target.data(text);
+};
- };
+XMLParser.prototype._handleDoctype = function(text) {
+};
- this.parser.oncomment = function(comment) {
- /* TODO: parse comment? */
- };
+XMLParser.prototype._handleComment = function(comment) {
+};
- this.parser.onclosetag = function(tag) {
- self.target.end(tag);
- };
+XMLParser.prototype._handleCloseTag = function(tag) {
+ this.target.end(tag);
+};
- this.parser.onerror = function(error) {
- throw error;
- };
-}
+XMLParser.prototype._handleError = function(err) {
+ throw err;
+};
XMLParser.prototype.feed = function(chunk) {
this.parser.write(chunk); |
73d49ad830e028c64d5a68754757dcfc38d34792 | source/test/authenticate-flow-test.js | source/test/authenticate-flow-test.js | import { describe } from 'riteway';
import dsm from '../dsm';
const SIGNED_OUT = 'signed_out';
const AUTHENTICATING = 'authenticating';
const actionStates = [
['initialize', SIGNED_OUT,
['sign in', AUTHENTICATING
// ['report error', 'error',
// ['handle error', 'signed out']
// ],
// ['sign-in success', 'signed in']
]
]
];
const { reducer, actionCreators: { initialize, signIn } } = dsm({
component: 'user-authentication',
description: 'authenticate user',
actionStates
});
const createState = ({
status = SIGNED_OUT,
payload = { type: 'empty' }
} = {}) => ({ status, payload });
describe('userAuthenticationReducer', async should => {
{
const {assert} = should('use "signed out" as initialized state');
assert({
given: '["initialize", "signed out", /*...*/',
actual: reducer(),
expected: createState()
});
}
{
const {assert} = should('transition into authenticating state');
const initialState = reducer(undefined, initialize());
assert({
given: 'signed out initial state & signIn action',
actual: reducer(initialState, signIn()),
expected: createState({ status: 'authenticating' })
});
}
});
| import { describe } from 'riteway';
import dsm from '../dsm';
const SIGNED_OUT = 'signed_out';
const AUTHENTICATING = 'authenticating';
const actionStates = [
['initialize', SIGNED_OUT,
['sign in', AUTHENTICATING
// ['report error', 'error',
// ['handle error', 'signed out']
// ],
// ['sign-in success', 'signed in']
]
]
];
const { reducer, actionCreators: { initialize, signIn } } = dsm({
component: 'user-authentication',
description: 'authenticate user',
actionStates
});
describe('userAuthenticationReducer', async should => {
{
const {assert} = should('use "signed out" as initialized state');
assert({
given: '["initialize", "signed out", /*...*/',
actual: reducer().status,
expected: SIGNED_OUT
});
}
{
const {assert} = should('transition into authenticating state');
const initialState = reducer(undefined, initialize());
assert({
given: 'signed out initial state & signIn action',
actual: reducer(initialState, signIn()).status,
expected: AUTHENTICATING
});
}
});
| Fix test to use main unit test files standards | Fix test to use main unit test files standards
The main unit test file tested action creators against `reducer().status` instead of the full state. There seems to be inconsistencies in the payload for action creators which caused these tests to fail. I have updated the tests to only check the status instead of the entire state.
| JavaScript | mit | ericelliott/redux-dsm | ---
+++
@@ -23,19 +23,14 @@
});
-const createState = ({
- status = SIGNED_OUT,
- payload = { type: 'empty' }
-} = {}) => ({ status, payload });
-
describe('userAuthenticationReducer', async should => {
{
const {assert} = should('use "signed out" as initialized state');
assert({
given: '["initialize", "signed out", /*...*/',
- actual: reducer(),
- expected: createState()
+ actual: reducer().status,
+ expected: SIGNED_OUT
});
}
@@ -45,8 +40,8 @@
assert({
given: 'signed out initial state & signIn action',
- actual: reducer(initialState, signIn()),
- expected: createState({ status: 'authenticating' })
+ actual: reducer(initialState, signIn()).status,
+ expected: AUTHENTICATING
});
}
}); |
12f75878ccc243dbd40a8f755133fb19a97f9954 | htmlbars-loader.js | htmlbars-loader.js | var path = require('path')
var loaderUtils = require('loader-utils')
var HtmlbarsCompiler = require('ember-cli-htmlbars')
var DEFAULT_TEMPLATE_COMPILER = 'components-ember/ember-template-compiler.js'
var templateTree
var appPath
/*
* options:
* - appPath: default assuming webpack.config.js in root folder + ./app
* - templateCompiler: default 'components-ember/ember-template-compiler.js'
*/
module.exports = function(source) {
this.cacheable && this.cacheable()
var options = loaderUtils.getOptions(this);
var appPath = (options.appPath || 'app').replace(/\/$/, '')
var templatesFolder = path.join(appPath, 'templates')
templateTree = templateTree || new HtmlbarsCompiler(templatesFolder, {
isHTMLBars: true,
templateCompiler: require(options.templateCompiler || DEFAULT_TEMPLATE_COMPILER)
});
var resourcePathMatcher = new RegExp(templatesFolder + '/(.*)\.hbs$')
var templateMatch = this.resourcePath.match(resourcePathMatcher)
var templatePath = templateMatch.pop()
var fullTemplate = templateTree.processString(source, templatePath)
var templateString = fullTemplate.replace(/^export default Ember\./, 'Ember.')
return 'Ember.TEMPLATES["' + templatePath + '"] = ' + templateString
}
| var path = require('path')
var loaderUtils = require('loader-utils')
var HtmlbarsCompiler = require('ember-cli-htmlbars')
var DEFAULT_TEMPLATE_COMPILER = 'components-ember/ember-template-compiler.js'
var templateTree
var appPath
/*
* options:
* - appPath: default assuming webpack.config.js in root folder + ./app
* - templateCompiler: default 'components-ember/ember-template-compiler.js'
*/
module.exports = function(source) {
this.cacheable && this.cacheable()
var options = loaderUtils.getOptions(this);
var appPath = (options.appPath || 'app').replace(/\/$/, '')
var templatesFolder = path.join(appPath, 'templates')
templateTree = templateTree || new HtmlbarsCompiler(templatesFolder, {
isHTMLBars: true,
templateCompiler: require(options.templateCompiler || DEFAULT_TEMPLATE_COMPILER)
});
var resourcePathMatcher = new RegExp(templatesFolder + '/(.*)\.hbs$')
var templateMatch = this.resourcePath.match(resourcePathMatcher)
var templatePath = templateMatch.pop()
var fullTemplate = templateTree.processString(source, templatePath)
var templateString = fullTemplate.replace(/^export default Ember\./, 'Ember.')
return 'Ember.TEMPLATES["' + templatePath + '"] = ' + templateString
}
| Add indentation fix on htmlbar loader. | Add indentation fix on htmlbar loader.
| JavaScript | mit | tulios/ember-webpack-loaders | ---
+++
@@ -12,8 +12,8 @@
* - templateCompiler: default 'components-ember/ember-template-compiler.js'
*/
module.exports = function(source) {
- this.cacheable && this.cacheable()
- var options = loaderUtils.getOptions(this);
+ this.cacheable && this.cacheable()
+ var options = loaderUtils.getOptions(this);
var appPath = (options.appPath || 'app').replace(/\/$/, '')
var templatesFolder = path.join(appPath, 'templates')
|
de51636cdf89ae16ab0f9070127acffad5c3b277 | js/ClientApp.js | js/ClientApp.js | var div = React.DOM.div;
var h1 = React.DOM.h1;
var MyTitle = React.createClass({
render: function() {
return (
div(null, h1(null, this.props.title))
)
}
})
var MyTitleFactory = React.createFactory(MyTitle)
var MyFirstComponent = React.createClass({
render: function() {
return (
div(null, [
MyTitleFactory({ title: 'props are the best' }),
MyTitleFactory({ title: 'jk' }),
MyTitleFactory({ title: 'whatever'}),
MyTitleFactory({ title: 'best workshop' })
]
)
)
}
})
ReactDOM.render(React.createElement(MyFirstComponent), document.getElementById('app')) | var div = React.DOM.div;
var h1 = React.DOM.h1;
var MyTitle = React.createClass({
render: function() {
return (
div(null, h1({ style: {color: this.props.color} }, this.props.title))
)
}
})
var MyTitleFactory = React.createFactory(MyTitle)
var MyFirstComponent = React.createClass({
render: function() {
return (
div(null, [
MyTitleFactory({title: 'Props are great!', color: 'rebeccapurple'}),
MyTitleFactory({title: 'Props are great!', color: 'dodgerblue'}),
MyTitleFactory({title: 'Use props everywhere!', color: 'mediumaquamarine'}),
MyTitleFactory({title: 'Props are the best!', color: 'peru'})
]
)
)
}
})
ReactDOM.render(React.createElement(MyFirstComponent), document.getElementById('app')) | Add props to the components | Add props to the components
| JavaScript | mit | jbarbettini/intro-to-react-workshop,jbarbettini/intro-to-react-workshop | ---
+++
@@ -4,7 +4,7 @@
var MyTitle = React.createClass({
render: function() {
return (
- div(null, h1(null, this.props.title))
+ div(null, h1({ style: {color: this.props.color} }, this.props.title))
)
}
})
@@ -15,10 +15,10 @@
render: function() {
return (
div(null, [
- MyTitleFactory({ title: 'props are the best' }),
- MyTitleFactory({ title: 'jk' }),
- MyTitleFactory({ title: 'whatever'}),
- MyTitleFactory({ title: 'best workshop' })
+ MyTitleFactory({title: 'Props are great!', color: 'rebeccapurple'}),
+ MyTitleFactory({title: 'Props are great!', color: 'dodgerblue'}),
+ MyTitleFactory({title: 'Use props everywhere!', color: 'mediumaquamarine'}),
+ MyTitleFactory({title: 'Props are the best!', color: 'peru'})
]
)
) |
197029775986b12767f07084b269f6174e85b988 | middleware/intl.js | middleware/intl.js | 'use strict';
var path = require('path');
var config = require('../config');
module.exports = function (req, res, next) {
var app = req.app,
locales = app.get('locales'),
locale = req.acceptsLanguage(locales) || app.get('default locale'),
messages = require(path.join(config.dirs.i18n, locale));
req.locale = locale;
res.locals.intl || (res.locals.intl = {});
res.locals.intl.locale = locale;
res.locals.intl.messages = messages;
// TODO: Handle/merge and Expose the common formats.
res.expose(res.locals.intl, 'APP.intl')
next();
};
| 'use strict';
var path = require('path');
var config = require('../config');
module.exports = function (req, res, next) {
var app = req.app,
locales = app.get('locales'),
locale = req.acceptsLanguage(locales) || app.get('default locale'),
messages = require(path.join(config.dirs.i18n, locale));
req.locale = locale;
res.locals.intl || (res.locals.intl = {});
res.locals.intl.locale = locale;
res.locals.intl.messages = messages;
// TODO: Handle/merge and Expose the common formats.
res.expose(res.locals.intl, 'intl')
next();
};
| Remove APP prefix from middleware | Remove APP prefix from middleware
| JavaScript | bsd-3-clause | ericf/formatjs-site,okuryu/formatjs-site,ericf/formatjs-site | ---
+++
@@ -17,7 +17,7 @@
res.locals.intl.messages = messages;
// TODO: Handle/merge and Expose the common formats.
- res.expose(res.locals.intl, 'APP.intl')
+ res.expose(res.locals.intl, 'intl')
next();
}; |
8fc701cdda3fe6bb65d17b854787be36d5236d92 | models/analysis.js | models/analysis.js | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var analysisSchema = new Schema({
user_id: {type: Schema.Types.ObjectId, ref: 'User', required: true},
analysis_name: {type: String, required: true},
analysis: {type: String, required: true},
corpora_ids: [{type: String, required: true}],
result: Schema.Types.Mixed
});
module.exports = mongoose.model('Analysis', analysisSchema);
| var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var analysisSchema = new Schema({
user_id: {type: Schema.Types.ObjectId, ref: 'User', required: true},
analysis_name: {type: String, required: true},
eta: {type: Number, required: true},
time_created: {type: Date, required: true},
analysis: {type: String, required: true},
corpora_ids: [{type: String, required: true}],
result: Schema.Types.Mixed
});
module.exports = mongoose.model('Analysis', analysisSchema);
| Add eta and time created to db schema | Add eta and time created to db schema
| JavaScript | mit | rigatoni/linguine-node,rigatoni/linguine-node,Pastafarians/linguine-node,Pastafarians/linguine-node | ---
+++
@@ -4,6 +4,8 @@
var analysisSchema = new Schema({
user_id: {type: Schema.Types.ObjectId, ref: 'User', required: true},
analysis_name: {type: String, required: true},
+ eta: {type: Number, required: true},
+ time_created: {type: Date, required: true},
analysis: {type: String, required: true},
corpora_ids: [{type: String, required: true}],
result: Schema.Types.Mixed |
eb95bb8ff136c601257b3143f9f2c9ecee7b8fc1 | dom-text.js | dom-text.js | module.exports = DOMText
function DOMText(value, owner) {
if (!(this instanceof DOMText)) {
return new DOMText(value)
}
this.data = value || ""
this.length = this.data.length
this.ownerDocument = owner || null
}
DOMText.prototype.type = "DOMTextNode"
DOMText.prototype.nodeType = 3
DOMText.prototype.toString = function _Text_toString() {
return this.data
}
DOMText.prototype.replaceData = function replaceData(index, length, value) {
var current = this.data
var left = current.substring(0, index)
var right = current.substring(index + length, current.length)
this.data = left + value + right
this.length = this.data.length
}
| module.exports = DOMText
function DOMText(value, owner) {
if (!(this instanceof DOMText)) {
return new DOMText(value)
}
this.data = value || ""
this.length = this.data.length
this.ownerDocument = owner || null
}
DOMText.prototype.type = "DOMTextNode"
DOMText.prototype.nodeType = 3
DOMText.prototype.nodeName = "#text"
DOMText.prototype.toString = function _Text_toString() {
return this.data
}
DOMText.prototype.replaceData = function replaceData(index, length, value) {
var current = this.data
var left = current.substring(0, index)
var right = current.substring(index + length, current.length)
this.data = left + value + right
this.length = this.data.length
}
| Add nodeName property to text nodes | Add nodeName property to text nodes
| JavaScript | mit | Raynos/min-document,Raynos/min-document | ---
+++
@@ -12,6 +12,7 @@
DOMText.prototype.type = "DOMTextNode"
DOMText.prototype.nodeType = 3
+DOMText.prototype.nodeName = "#text"
DOMText.prototype.toString = function _Text_toString() {
return this.data |
3a352b8f2d9795eebf2d106dada7cca026c42035 | bin/index.js | bin/index.js | #! /usr/bin/env node
'use strict';
var yarnOrNpm = require('../index');
// Execute the command
try {
const { status } = yarnOrNpm.spawn.sync(
process.argv.slice(2), { stdio: 'inherit' }
);
process.exit(status);
} catch (err) {
console.log(err);
process.exit(1);
}
| #! /usr/bin/env node
'use strict';
const yarnOrNpm = require('../index');
// Execute the command
try {
const status = yarnOrNpm.spawn.sync(
process.argv.slice(2),
{ stdio: 'inherit' }
).status
process.exit(status);
} catch (err) {
console.log(err);
process.exit(1);
}
| Replace destructuring with regular property access | Replace destructuring with regular property access
| JavaScript | mit | camacho/yarn-or-npm | ---
+++
@@ -1,13 +1,13 @@
#! /usr/bin/env node
'use strict';
-var yarnOrNpm = require('../index');
-
+const yarnOrNpm = require('../index');
// Execute the command
try {
- const { status } = yarnOrNpm.spawn.sync(
- process.argv.slice(2), { stdio: 'inherit' }
- );
+ const status = yarnOrNpm.spawn.sync(
+ process.argv.slice(2),
+ { stdio: 'inherit' }
+ ).status
process.exit(status);
} catch (err) {
console.log(err); |
64bb2784ffa12a6ae67596dcc98c129bca81f1f6 | src/formatter.js | src/formatter.js | class JsonFormatter {
static stringify(object, options) {
options = {
space: options.prettify ? ' ' : null
}
return JSON.stringify(object, null, options.space)
}
static parse(string) {
return JSON.parse(string)
}
}
export default {
json: JsonFormatter
}
| class JsonFormatter {
static stringify(object, options) {
options = {
space: (options && options.prettify) ? ' ' : null
}
return JSON.stringify(object, null, options.space)
}
static parse(string) {
return JSON.parse(string)
}
}
export default {
json: JsonFormatter
}
| Make stringify's options parameter optional | Make stringify's options parameter optional
| JavaScript | mit | lujjjh/ea-utils | ---
+++
@@ -1,7 +1,7 @@
class JsonFormatter {
static stringify(object, options) {
options = {
- space: options.prettify ? ' ' : null
+ space: (options && options.prettify) ? ' ' : null
}
return JSON.stringify(object, null, options.space)
} |
6be75b7f6ce6ee69251ee59f8295e2f1e6bd0356 | public/js/oauthLogin.js | public/js/oauthLogin.js | var parts = window.location.hash.slice(1).split('&');
parts.forEach(function (value) {
if (value.substr(0, 12) === "access_token") {
var token = value.substr(13);
$.ajax({
type: 'get',
url: 'https://api.andbang.com/me',
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + token
},
success: function (user) {
localStorage.config = JSON.stringify({
jid: user.username.toLowerCase() + "@otalk.im",
server: "otalk.im",
wsURL: "wss://otalk.im:5281/xmpp-websocket",
credentials: {
username: user.username.toLowerCase(),
password: token
}
});
window.location = '/';
},
error: function () {
window.location = '/logout';
}
});
}
});
| var parts = window.location.hash.slice(1).split('&');
parts.forEach(function (value) {
if (value.substr(0, 12) === "access_token") {
var token = value.substr(13);
$.ajax({
type: 'get',
url: 'https://api.andbang.com/me',
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + token
},
success: function (user) {
localStorage.config = JSON.stringify({
jid: user.username.toLowerCase() + "@otalk.im",
server: "otalk.im",
wsURL: "wss://otalk.im/xmpp-websocket",
credentials: {
username: user.username.toLowerCase(),
password: token
}
});
window.location = '/';
},
error: function () {
window.location = '/logout';
}
});
}
});
| Use non-port url for otalk.im ws url | Use non-port url for otalk.im ws url
| JavaScript | mit | heyLu/kaiwa,unam3/kaiwa,birkb/kaiwa,warcode/kaiwa,unam3/kaiwa,digicoop/kaiwa,rogervaas/otalk-im-client,birkb/kaiwa,weiss/kaiwa,nsg/kaiwa,lasombra/kaiwa,nsg/kaiwa,syci/kaiwa,digicoop/kaiwa,heyLu/kaiwa,otalk/otalk-im-client,otalk/otalk-im-client,weiss/kaiwa,birkb/kaiwa,nsg/kaiwa,rogervaas/otalk-im-client,warcode/kaiwa,di-stars/kaiwa,digicoop/kaiwa,lasombra/kaiwa,syci/kaiwa,ForNeVeR/kaiwa,ForNeVeR/kaiwa,ForNeVeR/kaiwa,di-stars/kaiwa,lasombra/kaiwa,di-stars/kaiwa,ForNeVeR/kaiwa,syci/kaiwa,warcode/kaiwa,heyLu/kaiwa,weiss/kaiwa | ---
+++
@@ -14,7 +14,7 @@
localStorage.config = JSON.stringify({
jid: user.username.toLowerCase() + "@otalk.im",
server: "otalk.im",
- wsURL: "wss://otalk.im:5281/xmpp-websocket",
+ wsURL: "wss://otalk.im/xmpp-websocket",
credentials: {
username: user.username.toLowerCase(),
password: token |
30895bdd709819dbc7c8f2ec0d4398fb377f00f6 | node/#/_exclude.js | node/#/_exclude.js | 'use strict';
var d = require('d/d')
, defineProperty = Object.defineProperty;
module.exports = function () {
var text;
if (!this.parentNode) return;
if (!this._domExtLocation) {
defineProperty(this, '_domExtLocation', d(this.parentNode.insertBefore(
text = this.ownerDocument.createTextNode(''),
this.nextSibling
)));
text._isDomExtLocation_ = true;
}
this.parentNode.removeChild(this);
};
| 'use strict';
var d = require('d')
, defineProperty = Object.defineProperty;
module.exports = function () {
var text;
if (!this.parentNode) return;
if (!this._domExtLocation) {
defineProperty(this, '_domExtLocation', d(this.parentNode.insertBefore(
text = this.ownerDocument.createTextNode(''),
this.nextSibling
)));
text._isDomExtLocation_ = true;
}
this.parentNode.removeChild(this);
};
| Update up to changes in d package | Update up to changes in d package
| JavaScript | mit | medikoo/dom-ext | ---
+++
@@ -1,6 +1,6 @@
'use strict';
-var d = require('d/d')
+var d = require('d')
, defineProperty = Object.defineProperty;
|
11ad49c32359d07e95487e27651968cd9300e822 | src/models/Post.js | src/models/Post.js | import cuid from 'cuid';
import {database, auth} from '@/config/firebase';
export default function (post = {}) {
// Properties
this.id = post.id || cuid();
this.title = post.title || '';
this.created = post.created || Date.now();
this.lastEdited = post.lastEdited || null;
this.lastSaved = post.lastSaved || null;
this.lastPublished = post.lastPublished || null;
this.author = post.author || auth.currentUser.uid;
this.published = post.published || false;
this.markdown = post.markdown || '';
this.images = post.images || [];
const ref = database.ref(`/posts/${this.id}`);
// Methods
this.set = () => {
this.lastSaved = Date.now();
return ref.set(JSON.parse(JSON.stringify(this))).then(snapshot => {
return snapshot;
});
};
} | import cuid from 'cuid';
import {database, auth} from '@/config/firebase';
export default function (post = {}) {
// Properties
this.id = post.id || cuid();
this.created = post.created || Date.now();
this.lastEdited = post.lastEdited || null;
this.lastSaved = post.lastSaved || null;
this.lastPublished = post.lastPublished || null;
this.author = post.author || auth.currentUser.uid;
this.published = post.published || false;
this.markdown = post.markdown || '';
this.images = post.images || [];
// Constants
const ref = database.ref(`/posts/${this.id}`);
/**
* Save the post to firebase
*/
this.set = () => {
this.lastSaved = Date.now();
return ref.set(JSON.parse(JSON.stringify(this))).then(snapshot => {
return snapshot;
});
};
/**
* Get the post title, first line starting with a single #
*/
Object.defineProperty(this, 'title', {
get() {
const title = this.markdown.match(/^# .+/gm);
return title ? title[0].replace('# ', '') : '';
},
});
} | Refactor the title into a getter method | Refactor the title into a getter method
| JavaScript | mit | tuelsch/bolg,tuelsch/bolg | ---
+++
@@ -5,7 +5,6 @@
// Properties
this.id = post.id || cuid();
- this.title = post.title || '';
this.created = post.created || Date.now();
this.lastEdited = post.lastEdited || null;
this.lastSaved = post.lastSaved || null;
@@ -15,13 +14,26 @@
this.markdown = post.markdown || '';
this.images = post.images || [];
+ // Constants
const ref = database.ref(`/posts/${this.id}`);
- // Methods
+ /**
+ * Save the post to firebase
+ */
this.set = () => {
this.lastSaved = Date.now();
return ref.set(JSON.parse(JSON.stringify(this))).then(snapshot => {
return snapshot;
});
};
+
+ /**
+ * Get the post title, first line starting with a single #
+ */
+ Object.defineProperty(this, 'title', {
+ get() {
+ const title = this.markdown.match(/^# .+/gm);
+ return title ? title[0].replace('# ', '') : '';
+ },
+ });
} |
996ed3e9977489df473230cadc3973ba24d0ea6d | tests/controllers/reverseControllerTests.js | tests/controllers/reverseControllerTests.js | describe("ReverseController", function () {
var fakeReverseFilter;
// See: https://docs.angularjs.org/api/ng/provider/$filterProvider
beforeEach(module("app.controllers", function ($filterProvider) {
console.log($filterProvider);
fakeReverseFilter = jasmine.createSpy("fakeReverseFilter");
$filterProvider.register("reverse", function () {
return fakeReverseFilter;
});
}));
beforeEach(inject(function ($controller) {
reverseController = $controller("ReverseController");
}));
describe("reverse() method", function () {
it("delegates to the reverse filter", function () {
var value = "reverse";
var expectedValue = "esrever";
fakeReverseFilter.and.returnValue(expectedValue);
var actualValue = reverseController.reverse(value);
expect(fakeReverseFilter).toHaveBeenCalledWith(value);
expect(actualValue).toBe(expectedValue);
});
});
}); | describe("ReverseController", function () {
var fakeReverseFilter;
// See: https://docs.angularjs.org/api/ng/provider/$filterProvider
beforeEach(module("app.controllers", function ($filterProvider) {
fakeReverseFilter = jasmine.createSpy("fakeReverseFilter");
$filterProvider.register("reverse", function () {
return fakeReverseFilter;
});
}));
beforeEach(inject(function ($controller) {
reverseController = $controller("ReverseController");
}));
describe("reverse() method", function () {
it("delegates to the reverse filter", function () {
var value = "reverse";
var expectedValue = "esrever";
fakeReverseFilter.and.returnValue(expectedValue);
var actualValue = reverseController.reverse(value);
expect(fakeReverseFilter).toHaveBeenCalledWith(value);
expect(actualValue).toBe(expectedValue);
});
});
}); | Add example of faking a filter | Add example of faking a filter
| JavaScript | mit | mariojvargas/angularjs-stringcalc,mariojvargas/angularjs-stringcalc | ---
+++
@@ -3,7 +3,6 @@
// See: https://docs.angularjs.org/api/ng/provider/$filterProvider
beforeEach(module("app.controllers", function ($filterProvider) {
- console.log($filterProvider);
fakeReverseFilter = jasmine.createSpy("fakeReverseFilter");
$filterProvider.register("reverse", function () { |
8e0a36fc602135fd1ec6318c8cc7ee0f7576499d | client/js/google_analytics.js | client/js/google_analytics.js | (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;// noinspection CommaExpressionJS
i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();// noinspection CommaExpressionJS
a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-82069835-1', 'auto');
ga('send', 'pageview'); | (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;// noinspection CommaExpressionJS
i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();// noinspection CommaExpressionJS
a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-82069835-1', 'auto');
ga('send', 'pageview');
ga('send', 'event', 'host', window.location.host);
| Add event to track host usage | Add event to track host usage | JavaScript | mit | samg2014/VirtualHand,samg2014/VirtualHand | ---
+++
@@ -6,3 +6,4 @@
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-82069835-1', 'auto');
ga('send', 'pageview');
+ ga('send', 'event', 'host', window.location.host); |
cb35b30799405a9b43f1736758efd463652a0206 | lib/provider.js | lib/provider.js | module.exports = {
selector: ['.source.python'],
id: 'aligner-python',
config: {
':-alignment': {
title: 'Padding for :',
description: 'Pad left or right of the character',
type: 'string',
"enum": ['left', 'right'],
"default": 'right'
},
':-leftSpace': {
title: 'Left space for :',
description: 'Add 1 whitespace to the left',
type: 'boolean',
"default": false
},
':-rightSpace': {
title: 'Right space for :',
description: 'Add 1 whitespace to the right',
type: 'boolean',
"default": true
},
'=-alignment': {
title: 'Padding for =',
description: 'Pad left or right of the character',
type: 'string',
"enum": ['left', 'right'],
"default": 'left'
},
'=-leftSpace': {
title: 'Left space for =',
description: 'Add 1 whitespace to the left',
type: 'boolean',
"default": true
},
'=-rightSpace': {
title: 'Right space for =',
description: 'Add 1 whitespace to the right',
type: 'boolean',
"default": true
}
},
privateConfig: {
':-scope': 'valuepair',
'=-scope': 'assignment'
}
};
| module.exports = {
selector: [
'.source.python',
'.source.embedded.python',
],
id: 'aligner-python',
config: {
':-alignment': {
title: 'Padding for :',
description: 'Pad left or right of the character',
type: 'string',
"enum": ['left', 'right'],
"default": 'right'
},
':-leftSpace': {
title: 'Left space for :',
description: 'Add 1 whitespace to the left',
type: 'boolean',
"default": false
},
':-rightSpace': {
title: 'Right space for :',
description: 'Add 1 whitespace to the right',
type: 'boolean',
"default": true
},
'=-alignment': {
title: 'Padding for =',
description: 'Pad left or right of the character',
type: 'string',
"enum": ['left', 'right'],
"default": 'left'
},
'=-leftSpace': {
title: 'Left space for =',
description: 'Add 1 whitespace to the left',
type: 'boolean',
"default": true
},
'=-rightSpace': {
title: 'Right space for =',
description: 'Add 1 whitespace to the right',
type: 'boolean',
"default": true
}
},
privateConfig: {
':-scope': 'valuepair',
'=-scope': 'assignment'
}
};
| Add support for embedded python | Add support for embedded python
| JavaScript | mit | adrianlee44/atom-aligner-python | ---
+++
@@ -1,5 +1,8 @@
module.exports = {
- selector: ['.source.python'],
+ selector: [
+ '.source.python',
+ '.source.embedded.python',
+ ],
id: 'aligner-python',
config: {
':-alignment': { |
c8af2b414debcbafc0f87012da0ee3a23f44a107 | lib/rx-fetch.js | lib/rx-fetch.js | 'use strict';
const Rx = require('rx');
require('isomorphic-fetch');
const rxResponse = function (promiseResponse) {
this._promiseResponse = promiseResponse;
this.status = promiseResponse.status;
this.ok = promiseResponse.ok;
this.statusText = promiseResponse.statusText;
this.headers = promiseResponse.headers;
this.url = promiseResponse.url;
return this;
};
/* Disabled for now as I'm not sure what the use case is.
Send me a PR with test coverage if you need these. :-)
rxResponse.prototype.blob = function () {
return Rx.Observable.fromPromise(this._promiseResponse.blob());
};
rxResponse.prototype.arrayBuffer = function () {
return Rx.Observable.fromPromise(this._promiseResponse.arrayBuffer());
};
rxResponse.prototype.formData = function () {
return Rx.Observable.fromPromise(this._promiseResponse.formData());
};
*/
rxResponse.prototype.text = function () {
return Rx.Observable.fromPromise(this._promiseResponse.text());
};
rxResponse.prototype.json = function () {
return Rx.Observable.fromPromise(this._promiseResponse.json());
};
module.exports = function (url, options) {
return Rx.Observable.fromPromise(fetch(url, options))
.map((promiseResponse) => new rxResponse(promiseResponse));
};
| 'use strict';
const Rx = require('rx');
require('isomorphic-fetch');
//------------------------------------------------------------------------------
const rxResponse = function (promiseResponse) {
this._promiseResponse = promiseResponse;
this.status = promiseResponse.status;
this.ok = promiseResponse.ok;
this.statusText = promiseResponse.statusText;
this.headers = promiseResponse.headers;
this.url = promiseResponse.url;
return this;
};
//------------------------------------------------------------------------------
/* Disabled for now as I'm not sure what the use case is.
Send me a PR with test coverage if you need these. :-)
rxResponse.prototype.blob = function () {
return Rx.Observable.fromPromise(this._promiseResponse.blob());
};
rxResponse.prototype.arrayBuffer = function () {
return Rx.Observable.fromPromise(this._promiseResponse.arrayBuffer());
};
rxResponse.prototype.formData = function () {
return Rx.Observable.fromPromise(this._promiseResponse.formData());
};
*/
//------------------------------------------------------------------------------
rxResponse.prototype.text = function () {
return Rx.Observable.fromPromise(this._promiseResponse.text());
};
//------------------------------------------------------------------------------
rxResponse.prototype.json = function () {
return Rx.Observable.fromPromise(this._promiseResponse.json());
};
//------------------------------------------------------------------------------
module.exports = function (url, options) {
return Rx.Observable.fromPromise(fetch(url, options))
.map((promiseResponse) => new rxResponse(promiseResponse));
};
| Add divider lines between functions. | Add divider lines between functions.
| JavaScript | mit | tangledfruit/rxjs-fetch,tangledfruit/rx-fetch | ---
+++
@@ -2,6 +2,8 @@
const Rx = require('rx');
require('isomorphic-fetch');
+
+//------------------------------------------------------------------------------
const rxResponse = function (promiseResponse) {
this._promiseResponse = promiseResponse;
@@ -12,6 +14,8 @@
this.url = promiseResponse.url;
return this;
};
+
+//------------------------------------------------------------------------------
/* Disabled for now as I'm not sure what the use case is.
Send me a PR with test coverage if you need these. :-)
@@ -28,13 +32,19 @@
};
*/
+//------------------------------------------------------------------------------
+
rxResponse.prototype.text = function () {
return Rx.Observable.fromPromise(this._promiseResponse.text());
};
+//------------------------------------------------------------------------------
+
rxResponse.prototype.json = function () {
return Rx.Observable.fromPromise(this._promiseResponse.json());
};
+
+//------------------------------------------------------------------------------
module.exports = function (url, options) {
|
7018847ded01cd7c338b23eafc72935d60938264 | connectors/byte.fm.js | connectors/byte.fm.js | 'use strict';
/* global Connector, Util */
Connector.playerSelector = '#player';
Connector.artistTrackSelector = '.player-current-title';
Connector.getArtistTrack = function() {
var text = $(Connector.artistTrackSelector).text();
var m = text.match(/ - /g);
if (m && (m.length === 2)) {
var arr = text.split(' - ');
return {artist: arr[1], track: arr[2]};
}
return Util.splitArtistTrack(text);
};
Connector.isPlaying = function () {
return $('.player-pause').is(':visible');
};
| 'use strict';
/* global Connector, Util */
Connector.playerSelector = '#player';
Connector.artistTrackSelector = '.player-current-title';
Connector.getArtistTrack = function() {
var text = $(Connector.artistTrackSelector).text();
var m = text.match(/ - /g);
if (m && (m.length === 2)) {
var arr = text.split(' - ');
return {artist: arr[1], track: arr[2]};
}
return Util.splitArtistTrack(text);
};
Connector.isPlaying = function () {
return $('.player-pause').is(':visible');
};
Connector.onReady = Connector.onStateChanged;
| Use 'Connector.onReady' function to emulate DOM update | Use 'Connector.onReady' function to emulate DOM update
| JavaScript | mit | usdivad/web-scrobbler,david-sabata/web-scrobbler,Paszt/web-scrobbler,galeksandrp/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,inverse/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,david-sabata/web-scrobbler,carpet-berlin/web-scrobbler,alexesprit/web-scrobbler,alexesprit/web-scrobbler,inverse/web-scrobbler,carpet-berlin/web-scrobbler,Paszt/web-scrobbler,usdivad/web-scrobbler,galeksandrp/web-scrobbler | ---
+++
@@ -19,3 +19,5 @@
Connector.isPlaying = function () {
return $('.player-pause').is(':visible');
};
+
+Connector.onReady = Connector.onStateChanged; |
730bd53bf36ce19ab57d70aef3992a69bc77636d | modules/database/controller.js | modules/database/controller.js | var Promise = require('bluebird'),
dbUtils = require('utils/database'),
socketUtils = require('utils/socket');
module.exports = {
all : All,
add : Add,
rename : Rename,
delete : Delete
};
function All(request,reply) {
dbUtils.list()
.then(function(data){
reply.data = data;
reply.next();
socketUtils.allDbInfo();
})
.catch(function(err){
reply.next(err);
})
}
function Add(request,reply) {
reply('Successfully started db creation');
dbUtils.connect(request.payload.database)
.then(function(){
return dbUtils.initDB(request.payload.database);
})
.then(function(){
socketUtils.broadCast('db-create',{db_name : request.payload.database, stats : {}});
return dbUtils.dbInfo(request.payload.database);
})
.then(function(data){
data.verified = true;
data.name = request.payload.database;
socketUtils.broadCast('db-info',data);
});
}
function Rename(request,reply) {
}
function Delete(request,reply) {
var db = dbUtils.getDb();
db[request.query.database].dropDatabase();
db[request.query.database] = null;
setTimeout(function(){
socketUtils.broadcast('db-delete',request.query.database);
},5000);
reply.next();
} | var Promise = require('bluebird'),
dbUtils = require('utils/database'),
socketUtils = require('utils/socket');
module.exports = {
all : All,
add : Add,
rename : Rename,
delete : Delete
};
function All(request,reply) {
dbUtils.list()
.then(function(data){
reply.data = data;
reply.next();
socketUtils.allDbInfo();
})
.catch(function(err){
reply.next(err);
})
}
function Add(request,reply) {
reply('Successfully started db creation');
dbUtils.connect(request.payload.database)
.then(function(){
return dbUtils.initDB(request.payload.database);
})
.then(function(){
socketUtils.broadCast('db-create',{db_name : request.payload.database, stats : {}});
return dbUtils.dbInfo(request.payload.database);
})
.then(function(data){
data.verified = true;
data.name = request.payload.database;
socketUtils.broadCast('db-info',data);
});
}
function Rename(request,reply) {
}
function Delete(request,reply) {
var db = dbUtils.getDb();
db[request.query.database].dropDatabase();
db[request.query.database] = null;
setTimeout(function(){
socketUtils.broadCast('db-delete',request.query.database);
},5000);
reply.next();
} | Use correct method for broadCast | Use correct method for broadCast
| JavaScript | mit | code-pool/Easy-Mongo-Server | ---
+++
@@ -48,7 +48,7 @@
db[request.query.database].dropDatabase();
db[request.query.database] = null;
setTimeout(function(){
- socketUtils.broadcast('db-delete',request.query.database);
+ socketUtils.broadCast('db-delete',request.query.database);
},5000);
reply.next();
} |
fe3639819bbc7bb2c6143c670157912b10ad9330 | test/count-test.js | test/count-test.js | var mongoose = require('mongoose'),
async = require('async'),
config = require('./config'),
Schema = mongoose.Schema,
mongoosastic = require('../lib/mongoosastic');
var CommentSchema = new Schema({
user: String,
post_date: {type:Date, es_type:'date'},
message: {type:String},
title: {type:String, es_boost:2.0}
});
CommentSchema.plugin(mongoosastic, {
bulk: {
size: 2,
delay: 100
}
});
var Comment = mongoose.model('Comment', CommentSchema);
describe.only('Count', function() {
before(function(done) {
mongoose.connect(config.mongoUrl, function() {
Comment.remove(function() {
config.deleteIndexIfExists(['comments'], function() {
var comments = [
new Comment({
user: 'terry',
title: 'Ilikecars'
}),
new Comment({
user: 'fred',
title: 'Ihatefish'
})
];
async.forEach(comments, function(item, cb) {
item.save(cb);
}, function() {
setTimeout(done, config.indexingTimeout);
});
});
});
});
});
after(function() {
mongoose.disconnect();
Comment.esClient.close();
});
it('should count a type', function(done) {
Comment.esCount({
term: {
user: 'terry'
}
}, function(err, results) {
results.count.should.eql(1);
done(err);
});
});
});
| var mongoose = require('mongoose'),
async = require('async'),
config = require('./config'),
Schema = mongoose.Schema,
mongoosastic = require('../lib/mongoosastic');
var CommentSchema = new Schema({
user: String,
post_date: {type:Date, es_type:'date'},
message: {type:String},
title: {type:String, es_boost:2.0}
});
CommentSchema.plugin(mongoosastic, {
bulk: {
size: 2,
delay: 100
}
});
var Comment = mongoose.model('Comment', CommentSchema);
describe.only('Count', function() {
before(function(done) {
mongoose.connect(config.mongoUrl, function() {
Comment.remove(function() {
config.deleteIndexIfExists(['comments'], function() {
var comments = [
new Comment({
user: 'terry',
title: 'Ilikecars'
}),
new Comment({
user: 'fred',
title: 'Ihatefish'
})
];
async.forEach(comments, function(item, cb) {
item.save(cb);
}, function() {
setTimeout(done, 2000);
});
});
});
});
});
after(function() {
mongoose.disconnect();
Comment.esClient.close();
});
it('should count a type', function(done) {
Comment.esCount({
term: {
user: 'terry'
}
}, function(err, results) {
results.count.should.eql(1);
done(err);
});
});
});
| Set manual timeout for count test | Set manual timeout for count test
| JavaScript | mit | francesconero/mongoosastic,guumaster/mongoosastic,mongoosastic/mongoosastic,hdngr/mongoosastic,teambition/mongoosastic,hdngr/mongoosastic,francesconero/mongoosastic,avastms/mongoosastic,guumaster/mongoosastic,ennosol/mongoosastic,mongoosastic/mongoosastic,mallzee/mongoosastic,mallzee/mongoosastic,mallzee/mongoosastic,mongoosastic/mongoosastic,teambition/mongoosastic,ennosol/mongoosastic,avastms/mongoosastic,hdngr/mongoosastic,guumaster/mongoosastic | ---
+++
@@ -38,7 +38,7 @@
async.forEach(comments, function(item, cb) {
item.save(cb);
}, function() {
- setTimeout(done, config.indexingTimeout);
+ setTimeout(done, 2000);
});
});
}); |
4532ca7d069d433b2494945e4ed42cf1759541c5 | test/unit/users.js | test/unit/users.js | describe('Users', function() {
describe('Creation', function () {
context('When creating a new user', function() {
it('Should have an id', function() {
var some_guy = jsf(mocks.user);
// ADD SHOULD.JS
some_guy.should.have.property('id');
some_guy.id.should.be.ok();
some_guy.id.should.be.String();
});
});
});
});
| describe('Users', function() {
describe('Creation', function () {
context('When creating a new user', function() {
var some_guy = jsf(mocks.user);
it('Should have an id', function() {
some_guy.should.have.property('userId');
some_guy.userId.should.be.ok();
some_guy.userId.should.be.String();
});
});
});
});
});
| Set user schema global to the test context | Set user schema global to the test context
| JavaScript | mit | facundovictor/mocha-testing | ---
+++
@@ -3,12 +3,12 @@
describe('Creation', function () {
context('When creating a new user', function() {
+ var some_guy = jsf(mocks.user);
it('Should have an id', function() {
- var some_guy = jsf(mocks.user);
- // ADD SHOULD.JS
- some_guy.should.have.property('id');
- some_guy.id.should.be.ok();
- some_guy.id.should.be.String();
+ some_guy.should.have.property('userId');
+ some_guy.userId.should.be.ok();
+ some_guy.userId.should.be.String();
+ });
});
});
}); |
5ed29e091ef3f24b2f5c9720da5b38ec67e5548c | src/detectors/threads/index.js | src/detectors/threads/index.js | /**
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* 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.
*/
// Name: Threads
// Proposal: https://github.com/webassembly/threads
import inlineModule from "wat2wasm:--enable-threads:./module.wat";
import { testCompile } from "../../helpers.js";
export default async function() {
try {
// Test for availability of shared Wasm memory
new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
// Test for transferability of SABs (needed for Firefox)
await new Promise(resolve => {
const sab = new SharedArrayBuffer(1);
const { port1, port2 } = new MessageChannel();
port2.onmessage = resolve;
port1.postMessage(sab);
});
// Test for atomics
await testCompile(inlineModule);
return true;
} catch (e) {
return false;
}
}
| /**
* Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* 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.
*/
// Name: Threads
// Proposal: https://github.com/webassembly/threads
import inlineModule from "wat2wasm:--enable-threads:./module.wat";
import { testCompile } from "../../helpers.js";
export default async function() {
try {
// Test for availability of shared Wasm memory
new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
// Test for transferability of SABs (needed for Firefox)
// https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ
await new Promise(resolve => {
const sab = new SharedArrayBuffer(1);
const { port1, port2 } = new MessageChannel();
port2.onmessage = resolve;
port1.postMessage(sab);
});
// Test for atomics
await testCompile(inlineModule);
return true;
} catch (e) {
return false;
}
}
| Add link to Firefox’s I2P | Add link to Firefox’s I2P
| JavaScript | apache-2.0 | GoogleChromeLabs/wasm-feature-detect | ---
+++
@@ -23,6 +23,7 @@
// Test for availability of shared Wasm memory
new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
// Test for transferability of SABs (needed for Firefox)
+ // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ
await new Promise(resolve => {
const sab = new SharedArrayBuffer(1);
const { port1, port2 } = new MessageChannel(); |
20bfcc8c2dba1ccc5d848bbd321f47067e036418 | src/modules/schedule/CommandEvents.js | src/modules/schedule/CommandEvents.js | 'use strict';
const Promise = require('bluebird');
const i18next = Promise.promisifyAll(require('i18next'));
const MentionableCommandMiddleware = require('../../middleware/MentionableCommandMiddleware');
const RestrictChannelsMiddleware = require('../../middleware/RestrictChannelsMiddleware');
const CommandDatabaseSchedule = require('./CommandDatabaseSchedule');
class CommandEvents extends CommandDatabaseSchedule {
constructor(module) {
super(module, 'list', {
defaultTrigger: 'events'
});
i18next.loadNamespacesAsync('schedule').then(() => {
this.helpText = i18next.t('schedule:events.help');
this.shortHelpText = i18next.t('schedule:events.short-help');
});
this.middleware = [
new RestrictChannelsMiddleware({ types: 'text' }),
new MentionableCommandMiddleware()
];
}
formatResult(response, result) {
const list = [];
if (list.length === 0) {
return i18next.t('schedule:events.response-empty');
}
for (let event of result) {
const id = event.id;
const title = event.title || i18next.t('schedule:events.missing-title');
const start = event.start;
if (start) {
list.push(i18next.t('schedule:events.response-item', { id, title, start }));
}
}
return i18next.t('schedule:events.response-list', { events: list.join('\n') });
}
}
module.exports = CommandEvents;
| 'use strict';
const Promise = require('bluebird');
const i18next = Promise.promisifyAll(require('i18next'));
const MentionableCommandMiddleware = require('../../middleware/MentionableCommandMiddleware');
const RestrictChannelsMiddleware = require('../../middleware/RestrictChannelsMiddleware');
const CommandDatabaseSchedule = require('./CommandDatabaseSchedule');
class CommandEvents extends CommandDatabaseSchedule {
constructor(module) {
super(module, 'list', {
defaultTrigger: 'events'
});
i18next.loadNamespacesAsync('schedule').then(() => {
this.helpText = i18next.t('schedule:events.help');
this.shortHelpText = i18next.t('schedule:events.short-help');
});
this.middleware = [
new RestrictChannelsMiddleware({ types: 'text' }),
new MentionableCommandMiddleware()
];
}
formatResult(response, result) {
const list = [];
if (result.length === 0) {
return i18next.t('schedule:events.response-empty');
}
for (let event of result) {
const id = event.id;
const title = event.title || i18next.t('schedule:events.missing-title');
const start = event.start;
if (start) {
list.push(i18next.t('schedule:events.response-item', { id, title, start }));
}
}
return i18next.t('schedule:events.response-list', { events: list.join('\n') });
}
}
module.exports = CommandEvents;
| Fix !events always returning no events | Fix !events always returning no events
| JavaScript | mit | Archomeda/kormir-discord-bot,Archomeda/kormir-discord-bot | ---
+++
@@ -27,7 +27,7 @@
formatResult(response, result) {
const list = [];
- if (list.length === 0) {
+ if (result.length === 0) {
return i18next.t('schedule:events.response-empty');
}
|
5d881c58a1c425d70d9e38bb8a07f3ebf17c2a2a | components/gh-upload-modal.js | components/gh-upload-modal.js | import ModalDialog from 'ghost/components/gh-modal-dialog';
import upload from 'ghost/assets/lib/uploader';
var UploadModal = ModalDialog.extend({
layoutName: 'components/gh-modal-dialog',
didInsertElement: function () {
this._super();
upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')});
},
confirm: {
reject: {
func: function () { // The function called on rejection
return true;
},
buttonClass: true,
text: 'Cancel' // The reject button text
},
accept: {
buttonClass: 'btn btn-blue right',
text: 'Save', // The accept button texttext: 'Save'
func: function () {
var imageType = 'model.' + this.get('imageType');
if (this.$('.js-upload-url').val()) {
this.set(imageType, this.$('.js-upload-url').val());
} else {
this.set(imageType, this.$('.js-upload-target').attr('src'));
}
return true;
}
}
},
actions: {
closeModal: function () {
this.sendAction();
},
confirm: function (type) {
var func = this.get('confirm.' + type + '.func');
if (typeof func === 'function') {
func.apply(this);
}
this.sendAction();
this.sendAction('confirm' + type);
}
}
});
export default UploadModal;
| import ModalDialog from 'ghost/components/gh-modal-dialog';
import upload from 'ghost/assets/lib/uploader';
var UploadModal = ModalDialog.extend({
layoutName: 'components/gh-modal-dialog',
didInsertElement: function () {
this._super();
upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')});
},
confirm: {
reject: {
func: function () { // The function called on rejection
return true;
},
buttonClass: 'btn btn-default',
text: 'Cancel' // The reject button text
},
accept: {
buttonClass: 'btn btn-blue right',
text: 'Save', // The accept button texttext: 'Save'
func: function () {
var imageType = 'model.' + this.get('imageType');
if (this.$('.js-upload-url').val()) {
this.set(imageType, this.$('.js-upload-url').val());
} else {
this.set(imageType, this.$('.js-upload-target').attr('src'));
}
return true;
}
}
},
actions: {
closeModal: function () {
this.sendAction();
},
confirm: function (type) {
var func = this.get('confirm.' + type + '.func');
if (typeof func === 'function') {
func.apply(this);
}
this.sendAction();
this.sendAction('confirm' + type);
}
}
});
export default UploadModal;
| Fix button class on upload modal | Fix button class on upload modal
no issue
- this makes sure that the cancel button on the upload modal gets the
correct class
| JavaScript | mit | JohnONolan/Ghost-Admin,airycanon/Ghost-Admin,TryGhost/Ghost-Admin,acburdine/Ghost-Admin,JohnONolan/Ghost-Admin,kevinansfield/Ghost-Admin,dbalders/Ghost-Admin,kevinansfield/Ghost-Admin,acburdine/Ghost-Admin,airycanon/Ghost-Admin,dbalders/Ghost-Admin,TryGhost/Ghost-Admin | ---
+++
@@ -13,7 +13,7 @@
func: function () { // The function called on rejection
return true;
},
- buttonClass: true,
+ buttonClass: 'btn btn-default',
text: 'Cancel' // The reject button text
},
accept: { |
00a3cfa32ebd0e7c2a2940fa7b881c7c30b03990 | assets/index.js | assets/index.js | // To use https://github.com/KyleAMathews/typefaces
// import "typeface-nunito";
import "./js/polyfills.js"; //MUST GO AT TOP
import "./js/lazysizes.js";
import "./js/quicklink.js";
import "./js/nojs.js";
import Vue from "vue";
import App from "./js/app/filters.vue";
// FILTERS APP
if (document.getElementById("app")) {
new Vue({
el: "#app",
components: { App }
});
}
console.log("NODE_ENV=", process.env.NODE_ENV);
// TODO: Add back --experimental-scope-hoisting to parcel command after upgrade to 1.13 (if path issue is fixed)
| // To use https://github.com/KyleAMathews/typefaces
// import "typeface-nunito";
import "./js/polyfills.js"; //MUST GO AT TOP
import "./js/lazysizes.js";
import "./js/quicklink.js";
import "./js/nojs.js";
// import Vue from "vue";
// import App from "./js/app/filters.vue";
// // FILTERS APP
// if (document.getElementById("app")) {
// new Vue({
// el: "#app",
// components: { App }
// });
// }
console.log("NODE_ENVg=", process.env.NODE_ENV);
// TODO: Add back --experimental-scope-hoisting to parcel command after upgrade to 1.13 (if path issue is fixed)
| Hide db scripts for now | Hide db scripts for now
| JavaScript | mit | budparr/thenewdynamic,budparr/thenewdynamic,budparr/thenewdynamic | ---
+++
@@ -7,17 +7,17 @@
import "./js/quicklink.js";
import "./js/nojs.js";
-import Vue from "vue";
-import App from "./js/app/filters.vue";
+// import Vue from "vue";
+// import App from "./js/app/filters.vue";
-// FILTERS APP
-if (document.getElementById("app")) {
+// // FILTERS APP
+// if (document.getElementById("app")) {
- new Vue({
- el: "#app",
- components: { App }
- });
-}
-console.log("NODE_ENV=", process.env.NODE_ENV);
+// new Vue({
+// el: "#app",
+// components: { App }
+// });
+// }
+console.log("NODE_ENVg=", process.env.NODE_ENV);
// TODO: Add back --experimental-scope-hoisting to parcel command after upgrade to 1.13 (if path issue is fixed) |
cf80e4f2dac2617236eead8bc94fb0d4c2b81eb5 | lib/cli.js | lib/cli.js | var program = require('commander');
var hap = require("hap-nodejs");
var version = require('./version');
var Server = require('./server').Server;
var Plugin = require('./plugin').Plugin;
var User = require('./user').User;
var log = require("./logger")._system;
'use strict';
module.exports = function() {
var insecureAccess = false;
program
.version(version)
.option('-P, --plugin-path [path]', 'look for plugins installed at [path] as well as the default locations ([path] can also point to a single plugin)', function(p) { Plugin.addPluginPath(p); })
.option('-U, --user-storage-path [path]', 'look for homebridge user files at [path] instead of the default location (~/.homebridge)', function(p) { User.setStoragePath(p); })
.option('-D, --debug', 'turn on debug level logging', function() { require('./logger').setDebugEnabled(true) })
.option('-I, --insecure', 'allow unauthenticated requests (for easier hacking)', function() { insecureAccess = true })
.parse(process.argv);
// Initialize HAP-NodeJS with a custom persist directory
hap.init(User.persistPath());
new Server(insecureAccess).run();
}
| var program = require('commander');
var hap = require("hap-nodejs");
var version = require('./version');
var Server = require('./server').Server;
var Plugin = require('./plugin').Plugin;
var User = require('./user').User;
var log = require("./logger")._system;
'use strict';
module.exports = function() {
var insecureAccess = false;
program
.version(version)
.option('-P, --plugin-path [path]', 'look for plugins installed at [path] as well as the default locations ([path] can also point to a single plugin)', function(p) { Plugin.addPluginPath(p); })
.option('-U, --user-storage-path [path]', 'look for homebridge user files at [path] instead of the default location (~/.homebridge)', function(p) { User.setStoragePath(p); })
.option('-D, --debug', 'turn on debug level logging', function() { require('./logger').setDebugEnabled(true) })
.option('-I, --insecure', 'allow unauthenticated requests (for easier hacking)', function() { insecureAccess = true })
.parse(process.argv);
// Initialize HAP-NodeJS with a custom persist directory
hap.init(User.persistPath());
var server = new Server(insecureAccess);
var signals = { 'SIGINT': 2, 'SIGTERM': 15 };
Object.keys(signals).forEach(function (signal) {
process.on(signal, function () {
log.info("Got %s, shutting down Homebridge...", signal);
// FIXME: Shut down server cleanly
process.exit(128 + signals[signal]);
});
});
server.run();
}
| Handle SIGINT and SIGTERM to enable clean shutdown of Homebridge | Handle SIGINT and SIGTERM to enable clean shutdown of Homebridge
For now we terminate the process, but in the future we may tell the
server to stop, which may possibly include some teardown logic.
Handling these signals also make it easier to put Homebridge inside
a docker container, as docker uses SIGTERM to tell a container process
to stop, and passes SIGINT when attached to the container and receiving
a Ctrl+C.
| JavaScript | apache-2.0 | nfarina/homebridge,felixekman/homebridge,inonprince/homebridge,nfarina/homebridge,chrisi21/homebridge,snowdd1/homebridge | ---
+++
@@ -23,5 +23,17 @@
// Initialize HAP-NodeJS with a custom persist directory
hap.init(User.persistPath());
- new Server(insecureAccess).run();
+ var server = new Server(insecureAccess);
+
+ var signals = { 'SIGINT': 2, 'SIGTERM': 15 };
+ Object.keys(signals).forEach(function (signal) {
+ process.on(signal, function () {
+ log.info("Got %s, shutting down Homebridge...", signal);
+
+ // FIXME: Shut down server cleanly
+ process.exit(128 + signals[signal]);
+ });
+ });
+
+ server.run();
} |
05acc2bfdd8ed19b586ebeaf830c03a8b8456722 | package.js | package.js | var where = 'client';
Package.describe({
name: 'lookback:dropdowns',
summary: 'Reactive dropdowns for Meteor.',
version: '1.1.0',
git: 'http://github.com/lookback/meteor-dropdowns'
});
Package.onUse(function(api) {
api.versionsFrom('1.0.2');
api.use('percolate:momentum@0.7.2', where);
api.use([
'underscore',
'tracker',
'coffeescript',
'jquery',
'reactive-dict',
'templating',
'check'
], where);
api.add_files([
'transitions/default.coffee',
'dropdown.html',
'dropdown.coffee'
], 'client');
api.export('Dropdowns', where);
});
Package.onTest(function(api) {
api.use([
'coffeescript',
'check',
'tracker',
'lookback:dropdowns',
'practicalmeteor:munit'
], where);
api.addFiles('tests/DropdownTest.coffee', where);
});
| var where = 'client';
Package.describe({
name: 'lookback:dropdowns',
summary: 'Reactive dropdowns for Meteor.',
version: '1.1.0',
git: 'http://github.com/lookback/meteor-dropdowns'
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@0.9.2');
api.use('percolate:momentum@0.7.2', where);
api.use([
'underscore',
'tracker',
'coffeescript',
'jquery',
'reactive-dict',
'templating',
'check'
], where);
api.add_files([
'transitions/default.coffee',
'dropdown.html',
'dropdown.coffee'
], 'client');
api.export('Dropdowns', where);
});
Package.onTest(function(api) {
api.use([
'coffeescript',
'check',
'tracker',
'lookback:dropdowns',
'practicalmeteor:munit'
], where);
api.addFiles('tests/DropdownTest.coffee', where);
});
| Downgrade Meteor dep to 0.9.2 | Downgrade Meteor dep to 0.9.2
| JavaScript | mit | lookback/meteor-dropdowns,lookback/meteor-dropdowns | ---
+++
@@ -8,7 +8,7 @@
});
Package.onUse(function(api) {
- api.versionsFrom('1.0.2');
+ api.versionsFrom('METEOR@0.9.2');
api.use('percolate:momentum@0.7.2', where);
api.use([
'underscore', |
e33da7f293c1dc45e2121b5dd881773c8716c76a | tests/dummy/app/routes/application.js | tests/dummy/app/routes/application.js | import Ember from 'ember';
export default Ember.Route.extend({
title: function(tokens) {
var base = 'My Blog';
var hasTokens = tokens && tokens.length;
return hasTokens ? tokens.reverse().join(' - ') + ' - ' + base : base;
}
});
| import Ember from 'ember';
export default Ember.Route.extend({
title: function(tokens) {
tokens = Ember.makeArray(tokens);
tokens.unshift('My Blog');
return tokens.reverse().join(' - ');
}
});
| Update test code to match README example | Update test code to match README example
| JavaScript | mit | ronco/ember-cli-document-title,kimroen/ember-cli-document-title,kimroen/ember-cli-document-title,ronco/ember-cli-document-title | ---
+++
@@ -2,9 +2,8 @@
export default Ember.Route.extend({
title: function(tokens) {
- var base = 'My Blog';
- var hasTokens = tokens && tokens.length;
-
- return hasTokens ? tokens.reverse().join(' - ') + ' - ' + base : base;
+ tokens = Ember.makeArray(tokens);
+ tokens.unshift('My Blog');
+ return tokens.reverse().join(' - ');
}
}); |
50c48e8d59b08c01a58f7b5918a6d99dd1ae5755 | addons/storysource/src/events.js | addons/storysource/src/events.js | export const ADDON_ID = 'storybook/storysource';
export const PANEL_ID = `${ADDON_ID}/panel`;
export const EVENT_ID = `${ADDON_ID}/story-event`;
| export const ADDON_ID = 'storybook/storysource';
export const PANEL_ID = `${ADDON_ID}/panel`;
export const EVENT_ID = `${ADDON_ID}/set`;
| CHANGE the `set` event of storysource addon, to prevent confusion | CHANGE the `set` event of storysource addon, to prevent confusion
`story-event` is very unclear IMHO
| JavaScript | mit | storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -1,3 +1,3 @@
export const ADDON_ID = 'storybook/storysource';
export const PANEL_ID = `${ADDON_ID}/panel`;
-export const EVENT_ID = `${ADDON_ID}/story-event`;
+export const EVENT_ID = `${ADDON_ID}/set`; |
8d197c49b89665981b90fa7b43b73516ed6a67bc | app/modules/demo/demo.routes.js | app/modules/demo/demo.routes.js | 'use strict';
require('./demo.module.js')
.config(Routes);
/**
* @ngInject
*/
function Routes($stateProvider, $locationProvider, $urlRouterProvider) {
$locationProvider.html5Mode(true);
$stateProvider
.state('Home', {
url: '/',
controller: 'ExampleCtrl as home',
templateUrl: 'demo/home.html',
title: 'Home'
});
$urlRouterProvider.otherwise('/');
}
| 'use strict';
require('./demo.module.js')
.config(Routes);
/**
* @ngInject
*/
function Routes($stateProvider, $locationProvider, $urlRouterProvider) {
$stateProvider
.state('Home', {
url: '/',
controller: 'ExampleCtrl as home',
templateUrl: 'demo/home.html',
title: 'Home'
});
$urlRouterProvider.otherwise('/');
}
| Remove html5 config option from demo module | Remove html5 config option from demo module
| JavaScript | mit | rogerhutchings/ng-davai,rogerhutchings/ng-davai | ---
+++
@@ -7,8 +7,6 @@
* @ngInject
*/
function Routes($stateProvider, $locationProvider, $urlRouterProvider) {
-
- $locationProvider.html5Mode(true);
$stateProvider
.state('Home', { |
8dc0cfa1768a7dcee8dbfacc27e617dbd74ae966 | src/test/tests/example_test.js | src/test/tests/example_test.js | module.exports = (() => {
'use strict';
const Nodal = require('nodal');
class ExampleTest extends Nodal.Test {
test(expect) {
it('Should compare 1 and 1', () => {
expect(1).to.equal(1);
});
it('Should add 1 and 1, asynchronously', done => {
setTimeout(() => {
expect(1 + 1).to.equal(2);
done();
});
});
}
}
return ExampleTest;
})();
| module.exports = (() => {
'use strict';
const Nodal = require('nodal');
class ExampleTest extends Nodal.Test {
test(expect) {
it('Should compare 1 and 1', () => {
expect(1).to.equal(1);
});
it('Should add 1 and 1, asynchronously', done => {
setTimeout(() => {
expect(1 + 1).to.equal(2);
done();
}, 10);
});
}
}
return ExampleTest;
})();
| Set Timeout with 10ms delay in example test | Set Timeout with 10ms delay in example test
| JavaScript | mit | rlugojr/nodal,keithwhor/nodal,IrregularShed/nodal,abossard/nodal,nsipplswezey/nodal,nsipplswezey/nodal,abossard/nodal,nsipplswezey/nodal,IrregularShed/nodal | ---
+++
@@ -21,7 +21,7 @@
expect(1 + 1).to.equal(2);
done();
- });
+ }, 10);
});
|
e8d18d8b96361c0ba06f3e540fdf7717e8b1025c | src/google/fontapiurlbuilder.js | src/google/fontapiurlbuilder.js | /**
* @constructor
*/
webfont.FontApiUrlBuilder = function(apiUrl) {
if (apiUrl) {
this.apiUrl_ = apiUrl;
} else {
var protocol = 'https:' == window.location.protocol ? 'https:' : 'http:';
this.apiUrl_ = protocol + webfont.FontApiUrlBuilder.DEFAULT_API_URL;
}
this.fontFamilies_ = null;
};
webfont.FontApiUrlBuilder.DEFAULT_API_URL = '//fonts.googleapis.com/css';
webfont.FontApiUrlBuilder.prototype.setFontFamilies = function(fontFamilies) {
// maybe clone?
this.fontFamilies_ = fontFamilies;
};
webfont.FontApiUrlBuilder.prototype.webSafe = function(string) {
return string.replace(/ /g, '+');
};
webfont.FontApiUrlBuilder.prototype.build = function() {
if (!this.fontFamilies_) {
throw new Error('No fonts to load !');
}
var length = this.fontFamilies_.length;
var sb = [];
for (var i = 0; i < length; i++) {
sb.push(this.webSafe(this.fontFamilies_[i]));
}
var url = this.apiUrl_ + '?family=' + sb.join('%7C'); // '|' escaped.
return url;
};
| /**
* @constructor
*/
webfont.FontApiUrlBuilder = function(apiUrl) {
if (apiUrl) {
this.apiUrl_ = apiUrl;
} else {
var protocol = 'https:' == window.location.protocol ? 'https:' : 'http:';
this.apiUrl_ = protocol + webfont.FontApiUrlBuilder.DEFAULT_API_URL;
}
this.fontFamilies_ = null;
};
webfont.FontApiUrlBuilder.DEFAULT_API_URL = '//fonts.googleapis.com/css';
webfont.FontApiUrlBuilder.prototype.setFontFamilies = function(fontFamilies) {
// maybe clone?
this.fontFamilies_ = fontFamilies;
};
webfont.FontApiUrlBuilder.prototype.webSafe = function(string) {
return string.replace(/ /g, '+');
};
webfont.FontApiUrlBuilder.prototype.build = function() {
if (!this.fontFamilies_) {
throw new Error('No fonts to load !');
}
if (this.apiUrl_.indexOf("kit=") != -1) {
return this.apiUrl_;
}
var length = this.fontFamilies_.length;
var sb = [];
for (var i = 0; i < length; i++) {
sb.push(this.webSafe(this.fontFamilies_[i]));
}
var url = this.apiUrl_ + '?family=' + sb.join('%7C'); // '|' escaped.
return url;
};
| Change the url builder to handle integrations. | Change the url builder to handle integrations.
| JavaScript | apache-2.0 | typekit/webfontloader,zeixcom/webfontloader,kevinrodbe/webfontloader,mettjus/webfontloader,sapics/webfontloader,Monotype/webfontloader,typekit/webfontloader,omo/webfontloader,sapics/webfontloader,digideskio/webfontloader,armandocanals/webfontloader,omo/webfontloader,ahmadruhaifi/webfontloader,JBusch/webfontloader,joelrich/webfontloader,sapics/webfontloader,mettjus/webfontloader,Monotype/webfontloader,typekit/webfontloader,zeixcom/webfontloader,JBusch/webfontloader,ahmadruhaifi/webfontloader,exsodus3249/webfontloader,ramghaju/webfontloader,armandocanals/webfontloader,digideskio/webfontloader,zeixcom/webfontloader,armandocanals/webfontloader,joelrich/webfontloader,mettjus/webfontloader,ramghaju/webfontloader,joelrich/webfontloader,Monotype/webfontloader,kevinrodbe/webfontloader,ahmadruhaifi/webfontloader,JBusch/webfontloader,exsodus3249/webfontloader,digideskio/webfontloader,omo/webfontloader,exsodus3249/webfontloader,ramghaju/webfontloader,kevinrodbe/webfontloader | ---
+++
@@ -27,6 +27,9 @@
if (!this.fontFamilies_) {
throw new Error('No fonts to load !');
}
+ if (this.apiUrl_.indexOf("kit=") != -1) {
+ return this.apiUrl_;
+ }
var length = this.fontFamilies_.length;
var sb = [];
|
d1ccfc9a672c42c9fe3967f657ad1213d7288abd | gulpfile.js | gulpfile.js | const babel = require('gulp-babel');
const gulp = require('gulp');
const print = require('gulp-print');
gulp.task('js', () => {
return gulp.src('src/*.js')
.pipe(print())
.pipe( babel({ presets: ['es2015'] }))
.pipe(gulp.dest('dist'));
}); | const babel = require('gulp-babel');
const gulp = require('gulp');
const print = require('gulp-print');
gulp.task('build', () => {
return gulp.src('src/*.js')
.pipe(print())
.pipe( babel({ presets: ['es2015'] }))
.pipe(gulp.dest('dist'));
});
gulp.task('watch', () => {
gulp.watch('src/*.js', ['build']);
}); | Change task name from 'js' to 'build' | Change task name from 'js' to 'build'
Add 'watch' task to gulp to build compiled JS files on ES6 file change
| JavaScript | mit | keenanamigos/es6-js-helper-functions | ---
+++
@@ -3,9 +3,13 @@
const print = require('gulp-print');
-gulp.task('js', () => {
+gulp.task('build', () => {
return gulp.src('src/*.js')
.pipe(print())
.pipe( babel({ presets: ['es2015'] }))
.pipe(gulp.dest('dist'));
});
+
+gulp.task('watch', () => {
+ gulp.watch('src/*.js', ['build']);
+}); |
f733cbcb5881b7d137931d8c9c16e5e8f1386c82 | gulpfile.js | gulpfile.js | //
// Adapted from:
// http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle
//
var gulp = require('gulp');
var browserify = require('browserify');
//var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
var packageJson = require('./package.json');
var dependencies = Object.keys(packageJson && packageJson.dependencies || {});
function handleErrors(error) {
console.error(error.stack);
this.emit('end');
}
gulp.task('libs', function () {
return browserify()
.require(dependencies)
.bundle()
.on('error', handleErrors)
.pipe(source('libs.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('scripts', function () {
return browserify('./src/index.js')
.external(dependencies)
.bundle()
.on('error', handleErrors)
.on('end', ()=>{console.log("ended")})
.pipe(source('bundle.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function(){
gulp.watch('package.json', ['libs']);
gulp.watch('src/**', ['scripts']);
});
gulp.task('default', ['libs', 'scripts', 'watch']);
| //
// Adapted from:
// http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle
//
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var packageJson = require('./package.json');
var dependencies = Object.keys(packageJson && packageJson.dependencies || {});
function handleErrors(error) {
console.error(error.stack);
// Emit 'end' as the stream wouldn't do it itself.
// Without this, the gulp task won't end and the watch stops working.
this.emit('end');
}
gulp.task('libs', function () {
return browserify({debug: true})
.require(dependencies)
.bundle()
.on('error', handleErrors)
.pipe(source('libs.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('scripts', function () {
return browserify('./src/index.js', {debug: true})
.external(dependencies)
.bundle()
.on('error', handleErrors)
.on('end', ()=>{console.log("ended")})
.pipe(source('bundle.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('watch', function(){
gulp.watch('package.json', ['libs']);
gulp.watch('src/**', ['scripts']);
});
gulp.task('default', ['libs', 'scripts', 'watch']);
| Build process now has source maps enabled. | Build process now has source maps enabled.
| JavaScript | mit | pafalium/gd-web-env,pafalium/gd-web-env | ---
+++
@@ -5,7 +5,6 @@
var gulp = require('gulp');
var browserify = require('browserify');
-//var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
var packageJson = require('./package.json');
@@ -13,11 +12,13 @@
function handleErrors(error) {
console.error(error.stack);
+ // Emit 'end' as the stream wouldn't do it itself.
+ // Without this, the gulp task won't end and the watch stops working.
this.emit('end');
}
gulp.task('libs', function () {
- return browserify()
+ return browserify({debug: true})
.require(dependencies)
.bundle()
.on('error', handleErrors)
@@ -26,7 +27,7 @@
});
gulp.task('scripts', function () {
- return browserify('./src/index.js')
+ return browserify('./src/index.js', {debug: true})
.external(dependencies)
.bundle()
.on('error', handleErrors) |
ce720652f2be50886165eb07b856bf85fb22bd67 | src/renderer/store/configure.js | src/renderer/store/configure.js | import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers';
import { createLogger } from '../../browser/remote';
const middlewares = [thunkMiddleware];
/* eslint global-require:0 */
if (global.SQLECTRON_CONFIG.log.console) {
const loggerConfig = {
level: global.SQLECTRON_CONFIG.log.level,
collapsed: true,
};
if (global.SQLECTRON_CONFIG.log.file) {
const logger = createLogger('renderer:redux');
logger.log = logger.debug.bind(logger);
loggerConfig.logger = logger;
// log only the error messages
// otherwise is too much private information
// the user would need to remove to issue a bug
loggerConfig.stateTransformer = () => null;
loggerConfig.actionTransformer = (data) => {
const error = data && data.error;
return { error };
};
}
middlewares.push(require('redux-logger')(loggerConfig));
}
const createStoreWithMiddleware = applyMiddleware(
...middlewares
)(createStore);
export default function configureStore(initialState) {
const store = createStoreWithMiddleware(rootReducer, initialState);
if (module.hot) {
module.hot.accept('../reducers', () =>
store.replaceReducer(require('../reducers').default)
);
}
return store;
}
| import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers';
import { createLogger } from '../../browser/remote';
const middlewares = [thunkMiddleware];
/* eslint global-require:0 */
if (global.SQLECTRON_CONFIG.log.console) {
const loggerConfig = {
level: global.SQLECTRON_CONFIG.log.level,
collapsed: true,
};
if (global.SQLECTRON_CONFIG.log.file) {
const logger = createLogger('renderer:redux');
logger.log = logger.debug.bind(logger);
loggerConfig.logger = logger;
loggerConfig.colors = {}; // disable formatting
// log only the error messages
// otherwise is too much private information
// the user would need to remove to issue a bug
loggerConfig.stateTransformer = () => null;
loggerConfig.actionTransformer = (data) => {
const error = data && data.error;
return { error };
};
}
middlewares.push(require('redux-logger')(loggerConfig));
}
const createStoreWithMiddleware = applyMiddleware(
...middlewares
)(createStore);
export default function configureStore(initialState) {
const store = createStoreWithMiddleware(rootReducer, initialState);
if (module.hot) {
module.hot.accept('../reducers', () =>
store.replaceReducer(require('../reducers').default)
);
}
return store;
}
| Disable formatting for renderer logs to file | Disable formatting for renderer logs to file
| JavaScript | mit | sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui | ---
+++
@@ -17,6 +17,7 @@
const logger = createLogger('renderer:redux');
logger.log = logger.debug.bind(logger);
loggerConfig.logger = logger;
+ loggerConfig.colors = {}; // disable formatting
// log only the error messages
// otherwise is too much private information |
4ff3cccc2379de1df8dda1723a34789c507a6ad1 | source/AppMenu.js | source/AppMenu.js | enyo.kind({
name: "enyo.AppMenu",
kind: onyx.Menu,
classes: "enyo-appmenu",
defaultKind: "enyo.AppMenuItem",
published: {
maxHeight: 400
},
components: [
{
kind: enyo.Signals,
onmenubutton: "toggle"
}
],
//* @public
toggle: function() {
// if we're visible, hide it; else, show it
if (this.showing)
this.hide();
else
this.show();
},
//* @public
show: function() {
var height = 30 * this.controls.length - 1; /* take the scroller out of the equation */
if (height > this.maxHeight) {
height = this.maxHeight;
}
this.setBounds({
height: height
});
this.inherited(arguments);
},
//* @private
maxHeightChanged: function() {
// if this is currently visible, go ahead and call show() to update the height if necessary
if (this.showing) {
this.show();
}
}
});
enyo.kind({
name: "enyo.AppMenuItem",
kind: onyx.MenuItem,
classes: "enyo-item"
}); | enyo.kind({
name: "enyo.AppMenu",
kind: onyx.Menu,
classes: "enyo-appmenu",
defaultKind: "enyo.AppMenuItem",
published: {
maxHeight: 400
},
components: [
{
kind: enyo.Signals,
onmenubutton: "toggle"
}
],
//* @public
toggle: function() {
// if we're visible, hide it; else, show it
if (this.showing)
this.hide();
else
this.show();
},
//* @public
show: function() {
var height = 40 * this.controls.length - 1; /* take the scroller out of the equation */
if (height > this.maxHeight) {
height = this.maxHeight;
}
this.setBounds({
height: height + 20
});
this.inherited(arguments);
},
//* @private
maxHeightChanged: function() {
// if this is currently visible, go ahead and call show() to update the height if necessary
if (this.showing) {
this.show();
}
}
});
enyo.kind({
name: "enyo.AppMenuItem",
kind: onyx.MenuItem,
classes: "enyo-item"
}); | Fix it so it is not running out side of the appMenu control | Fix it so it is not running out side of the appMenu control
Open-WebOS-DCO-1.0-Signed-Off-By: john mcconnell johnmcconnell@yahoo.com
| JavaScript | apache-2.0 | JayCanuck/enyo-luneos | ---
+++
@@ -22,14 +22,14 @@
},
//* @public
show: function() {
- var height = 30 * this.controls.length - 1; /* take the scroller out of the equation */
+ var height = 40 * this.controls.length - 1; /* take the scroller out of the equation */
if (height > this.maxHeight) {
height = this.maxHeight;
}
this.setBounds({
- height: height
+ height: height + 20
});
this.inherited(arguments);
}, |
f4ad01bf552e757b0afe515b4d5f0603403f7922 | app/assets/javascripts/comfortable_mexican_sofa/admin/modules/LinkManager.js | app/assets/javascripts/comfortable_mexican_sofa/admin/modules/LinkManager.js | define([
'jquery',
'DoughBaseComponent',
'InsertManager',
'eventsWithPromises'
], function (
$,
DoughBaseComponent,
InsertManager,
eventsWithPromises
) {
'use strict';
var LinkManagerProto,
defaultConfig = {
selectors: {
}
};
function LinkManager($el, config, customConfig) {
LinkManager.baseConstructor.call(this, $el, config, customConfig || defaultConfig);
this.open = false;
this.itemValues = {
'page': null,
'file': null,
'external': null
};
}
DoughBaseComponent.extend(LinkManager, InsertManager);
LinkManagerProto = LinkManager.prototype;
LinkManagerProto.init = function(initialised) {
LinkManager.superclass.init.call(this);
this._initialisedSuccess(initialised);
};
LinkManagerProto._setupAppEvents = function() {
eventsWithPromises.subscribe('cmseditor:insert-published', $.proxy(this._handleShown, this));
LinkManager.superclass._setupAppEvents.call(this);
}
return LinkManager;
});
| define([
'jquery',
'DoughBaseComponent',
'InsertManager',
'eventsWithPromises',
'filter-event'
], function (
$,
DoughBaseComponent,
InsertManager,
eventsWithPromises,
filterEvent
) {
'use strict';
var LinkManagerProto,
defaultConfig = {
selectors: {
}
};
function LinkManager($el, config, customConfig) {
LinkManager.baseConstructor.call(this, $el, config, customConfig || defaultConfig);
this.open = false;
this.itemValues = {
'page': null,
'file': null,
'external': null
};
}
DoughBaseComponent.extend(LinkManager, InsertManager);
LinkManagerProto = LinkManager.prototype;
LinkManagerProto.init = function(initialised) {
LinkManager.superclass.init.call(this);
this._initialisedSuccess(initialised);
};
LinkManagerProto._setupAppEvents = function() {
eventsWithPromises.subscribe('cmseditor:insert-published', filterEvent($.proxy(this._handleShown, this), this.context));
LinkManager.superclass._setupAppEvents.call(this);
};
return LinkManager;
});
| Use filterEvent for filtering events | Use filterEvent for filtering events
| JavaScript | mit | moneyadviceservice/cms,moneyadviceservice/cms,moneyadviceservice/cms,moneyadviceservice/cms | ---
+++
@@ -2,12 +2,14 @@
'jquery',
'DoughBaseComponent',
'InsertManager',
- 'eventsWithPromises'
+ 'eventsWithPromises',
+ 'filter-event'
], function (
$,
DoughBaseComponent,
InsertManager,
- eventsWithPromises
+ eventsWithPromises,
+ filterEvent
) {
'use strict';
@@ -37,9 +39,9 @@
};
LinkManagerProto._setupAppEvents = function() {
- eventsWithPromises.subscribe('cmseditor:insert-published', $.proxy(this._handleShown, this));
+ eventsWithPromises.subscribe('cmseditor:insert-published', filterEvent($.proxy(this._handleShown, this), this.context));
LinkManager.superclass._setupAppEvents.call(this);
- }
+ };
return LinkManager;
}); |
01b0c0c8a2d5c78d81cd0532fe837c14550fdf50 | hello.js | hello.js | // Hello page
//
exports.View =
{
title: "Hello World",
elements:
[
{ control: "stackpanel", orientation: "Horizontal", contents: [
{ control: "text", value: "First name:", fontsize: 12, width: 200, textAlignment: "Right", margin: { top: 10, right: 10 } },
{ control: "edit", fontsize: 12, width: 200, binding: "firstName" },
] },
{ control: "stackpanel", orientation: "Horizontal", contents: [
{ control: "text", value: "Last name:", fontsize: 12, width: 200, textAlignment: "Right", margin: { top: 10, right: 10 } },
{ control: "edit", fontsize: 12, width: 200, binding: "lastName" },
] },
{ control: "text", value: "Hello {firstName} {lastName}", fontsize: 12 },
]
}
exports.InitializeViewModel = function(context, session)
{
var viewModel =
{
firstName: "Planet",
lastName: "Earth",
}
return viewModel;
}
| // Hello page
//
exports.View =
{
title: "Hello World",
elements:
[
{ control: "text", value: "Enter your name:", font: { size: 12, bold: true } },
{ control: "stackpanel", orientation: "Horizontal", contents: [
{ control: "text", value: "First name:", fontsize: 12, width: 200, verticalAlignment: "Center", textAlignment: "Right" },
{ control: "edit", fontsize: 12, width: 200, verticalAlignment: "Center", binding: "firstName" },
] },
{ control: "stackpanel", orientation: "Horizontal", contents: [
{ control: "text", value: "Last name:", fontsize: 12, width: 200, verticalAlignment: "Center", textAlignment: "Right" },
{ control: "edit", fontsize: 12, width: 200, verticalAlignment: "Center", binding: "lastName" },
] },
{ control: "text", value: "Hello {firstName} {lastName}", fontsize: 12 },
]
}
exports.InitializeViewModel = function(context, session)
{
var viewModel =
{
firstName: "Planet",
lastName: "Earth",
}
return viewModel;
}
| Update control alignment (was relying in platform-specific margins) | Update control alignment (was relying in platform-specific margins)
| JavaScript | mit | SynchroLabs/SynchroSamples | ---
+++
@@ -5,13 +5,15 @@
title: "Hello World",
elements:
[
+ { control: "text", value: "Enter your name:", font: { size: 12, bold: true } },
+
{ control: "stackpanel", orientation: "Horizontal", contents: [
- { control: "text", value: "First name:", fontsize: 12, width: 200, textAlignment: "Right", margin: { top: 10, right: 10 } },
- { control: "edit", fontsize: 12, width: 200, binding: "firstName" },
+ { control: "text", value: "First name:", fontsize: 12, width: 200, verticalAlignment: "Center", textAlignment: "Right" },
+ { control: "edit", fontsize: 12, width: 200, verticalAlignment: "Center", binding: "firstName" },
] },
{ control: "stackpanel", orientation: "Horizontal", contents: [
- { control: "text", value: "Last name:", fontsize: 12, width: 200, textAlignment: "Right", margin: { top: 10, right: 10 } },
- { control: "edit", fontsize: 12, width: 200, binding: "lastName" },
+ { control: "text", value: "Last name:", fontsize: 12, width: 200, verticalAlignment: "Center", textAlignment: "Right" },
+ { control: "edit", fontsize: 12, width: 200, verticalAlignment: "Center", binding: "lastName" },
] },
{ control: "text", value: "Hello {firstName} {lastName}", fontsize: 12 }, |
159ad3bafaa5ed4aa892267e887a24622bee385b | app/javascript/app/components/footer/site-map-footer/site-map-footer-data.js | app/javascript/app/components/footer/site-map-footer/site-map-footer-data.js | export const siteMapData = [
{
title: 'Tools',
links: [
{ title: 'Country Profiles', href: '/countries' },
{ title: 'NDCs', href: '/ndcs-content' },
{ title: 'NDC-SDG Linkages', href: '/ndcs-sdg' },
{ title: 'Historical GHG Emissions', href: '/ghg-emissions' },
{ title: 'Pathways', href: '/pathways' }
]
},
{
title: 'Data',
links: [{ title: 'Explore Datasets', href: '/data-explorer' }]
},
{
title: 'Country Platforms',
links: [
// { title: 'India', href: '/' },
// { title: 'Indonesia', href: '/' },
{ title: 'South Africa', href: '/http://southafricaclimateexplorer.org/' }
]
},
{
title: 'About',
links: [
{ title: 'About Climate Watch', href: '/about' },
{ title: 'Climate Watch Partners', href: '/about/partners' },
{ title: 'Contact Us & Feedback', href: '/about/contact' },
{ title: 'Permissions & Licensing', href: '/about/permissions' }
]
}
];
| export const siteMapData = [
{
title: 'Tools',
links: [
{ title: 'Country Profiles', href: '/countries' },
{ title: 'NDCs', href: '/ndcs-content' },
{ title: 'NDC-SDG Linkages', href: '/ndcs-sdg' },
{ title: 'Historical GHG Emissions', href: '/ghg-emissions' },
{ title: 'Pathways', href: '/pathways' }
]
},
{
title: 'Data',
links: [{ title: 'Explore Datasets', href: '/data-explorer' }]
},
{
title: 'Country Platforms',
links: [
// { title: 'India', href: '/' },
// { title: 'Indonesia', href: '/' },
{ title: 'South Africa', href: 'http://southafricaclimateexplorer.org/' }
]
},
{
title: 'About',
links: [
{ title: 'About Climate Watch', href: '/about' },
{ title: 'Climate Watch Partners', href: '/about/partners' },
{ title: 'Contact Us & Feedback', href: '/about/contact' },
{ title: 'Permissions & Licensing', href: '/about/permissions' }
]
}
];
| Fix south africa url typo | Fix south africa url typo
| JavaScript | mit | Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch | ---
+++
@@ -18,7 +18,7 @@
links: [
// { title: 'India', href: '/' },
// { title: 'Indonesia', href: '/' },
- { title: 'South Africa', href: '/http://southafricaclimateexplorer.org/' }
+ { title: 'South Africa', href: 'http://southafricaclimateexplorer.org/' }
]
},
{ |
386fc28565d8e7fb325eec7a45d8fbbc232c2b33 | public/javascripts/labelingGuidePanelResize.js | public/javascripts/labelingGuidePanelResize.js | function checkWindowSize(){
var w = document.documentElement.clientWidth;
var panel = document.getElementById("help-panel");
if (w < 978) {
panel.style.position = "static";
panel.style.width = "auto";
} else if (w >= 978 && w < 1184) {
panel.style.position = "fixed";
panel.style.width = "250px";
unfix();
} else {
panel.style.position = "fixed";
panel.style.width = "275px";
unfix();
}
}
function unfix() {
if (document.readyState === "complete") {
var panel = document.getElementById("help-panel");
if (panel.style.position !== "static") {
var panelRect = panel.getBoundingClientRect();
var yOffset = document.body.clientHeight - 600 - panelRect.height - 95;
if (window.pageYOffset > yOffset) {
panel.style.top = "" + yOffset + "px";
panel.style.position = "absolute";
} else if (window.pageYOffset < yOffset) {
panel.style.top = "95px";
panel.style.position = "fixed";
}
}
}
}
window.addEventListener("resize", checkWindowSize);
window.addEventListener("scroll", unfix);
$(document).ready(function() {
checkWindowSize();
}); | function checkWindowSize(){
var w = document.documentElement.clientWidth;
var panel = document.getElementById("help-panel");
if (w < 978) {
panel.style.position = "static";
panel.style.width = "auto";
} else if (w >= 978 && w < 1184) {
panel.style.position = "fixed";
panel.style.width = "250px";
unfix();
} else {
panel.style.position = "fixed";
panel.style.width = "275px";
unfix();
}
}
function unfix() {
if (document.readyState === "complete") {
var panel = document.getElementById("help-panel");
if (panel.style.position !== "static") {
var panelRect = panel.getBoundingClientRect();
var yOffset = document.body.clientHeight - 600 - panelRect.height - 95;
if (window.pageYOffset > yOffset) {
panel.style.top = "" + yOffset + "px";
panel.style.position = "absolute";
} else if (window.pageYOffset < yOffset) {
panel.style.top = "95px";
panel.style.position = "fixed";
}
}
}
}
window.addEventListener("resize", checkWindowSize);
window.addEventListener("scroll", unfix);
$(document).ready(function() {
checkWindowSize();
});
| Add newline to end of file | Add newline to end of file
| JavaScript | mit | ProjectSidewalk/SidewalkWebpage,ProjectSidewalk/SidewalkWebpage,ProjectSidewalk/SidewalkWebpage,ProjectSidewalk/SidewalkWebpage,ProjectSidewalk/SidewalkWebpage,ProjectSidewalk/SidewalkWebpage | |
5111ce507cea494abc1a7f896af15d81349473cf | app/components/validated-form.js | app/components/validated-form.js | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'form',
classNameBindings: [ 'isValid:valid:invalid' ],
cancel: 'cancel',
isValid: Ember.computed.alias('formModel.isValid'),
notify: 'notify',
save: 'save',
showButtons: true,
transitionTo: 'transitionTo',
actions: {
cancel: function () {
this.sendAction('cancel');
},
submit: function () {
this.set('formModel.showInputErrors', true);
if (!this.get('isValid')) {
// console.log('[ValidatedFormComponent] Not submitting invalid formModel.');
return false;
}
var self = this;
var deferred = Ember.RSVP.defer();
this.set('errors', false);
this.sendAction('save', deferred);
deferred.promise.catch(function (result) {
// console.log('[ValidatedFormComponent]', result);
if (result.unauthorized) self.sendAction('transitionTo', 'login.screen');
self.set('errors', result.errors || [ 'Oops! There was a problem.' ]);
});
},
notify: function (opts) {
this.sendAction('notify', opts);
}
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'form',
classNameBindings: [ 'isValid:valid:invalid' ],
cancel: 'cancel',
isValid: Ember.computed.alias('formModel.isValid'),
notify: 'notify',
save: 'save',
showButtons: true,
transitionTo: 'transitionTo',
actions: {
cancel: function () {
this.sendAction('cancel');
},
submit: function () {
this.set('formModel.showInputErrors', true);
if (!this.get('isValid')) {
// console.log('[ValidatedFormComponent] Not submitting invalid formModel.');
return false;
}
var self = this;
var deferred = Ember.RSVP.defer();
this.set('errors', false);
this.sendAction('save', deferred);
deferred.promise.fail(function (result) {
// console.log('[ValidatedFormComponent]', result);
if (result.unauthorized) self.sendAction('transitionTo', 'login.screen');
self.set('errors', result.errors || [ 'Oops! There was a problem.' ]);
});
},
notify: function (opts) {
this.sendAction('notify', opts);
}
}
});
| Use FAIL functions, not CATCH | Use FAIL functions, not CATCH
| JavaScript | mit | dollarshaveclub/ember-uni-form,dollarshaveclub/ember-uni-form | ---
+++
@@ -33,7 +33,7 @@
this.set('errors', false);
this.sendAction('save', deferred);
- deferred.promise.catch(function (result) {
+ deferred.promise.fail(function (result) {
// console.log('[ValidatedFormComponent]', result);
if (result.unauthorized) self.sendAction('transitionTo', 'login.screen');
self.set('errors', result.errors || [ 'Oops! There was a problem.' ]); |
f9a5b3dcdef34dcca69c5f152db43626cf683945 | controller/templates/_spec.js | controller/templates/_spec.js | define([
'config',
'angular',
'controller/<%= _.slugify(name) %>-controller'
], function(cfg, A) {
return describe('<%= _.humanize(name) %> controller', function() {
var $scope,
createController;
beforeEach(module(cfg.ngApp));
beforeEach(inject(function($injector) {
var $controller = $injector.get('$controller'),
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
createController = function() {
$controller('<%= _.classify(name) %>Controller', {
$scope: $scope
});
};
}));
it('should load', function() {
var controller = createController();
});
});
}); | define([
'config',
'angular',
'controller/<%= _.slugify(name) %>-controller'
], function(cfg, A) {
return describe('<%= _.humanize(name) %> controller', function() {
var $scope,
createController;
beforeEach(module(cfg.ngApp));
beforeEach(inject(function($injector) {
var $controller = $injector.get('$controller'),
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
createController = function() {
return $controller('<%= _.classify(name) %>Controller', {
$scope: $scope
});
};
}));
it('should load', function() {
var controller = createController();
});
});
});
| Return instance of controller in createController | Return instance of controller in createController | JavaScript | mit | ahmednuaman/generator-radian | ---
+++
@@ -15,7 +15,7 @@
$scope = $rootScope.$new();
createController = function() {
- $controller('<%= _.classify(name) %>Controller', {
+ return $controller('<%= _.classify(name) %>Controller', {
$scope: $scope
});
}; |
c517504edce5d6767a353abc088e5084ad1a7e2a | spec/main-spec.js | spec/main-spec.js | 'use babel'
import {fork} from 'child_process'
import * as Communication from '../src/main'
const WORKER_PATH = __dirname + '/fixtures/worker.js'
describe('Process-Communication', function() {
describe('createFromProcess', function() {
it('works as expected', function() {
const child = fork(WORKER_PATH)
const communication = Communication.createFromProcess(child)
waitsForPromise(function() {
return communication.request('ping', 'ping').then(function(response) {
expect(response).toBe('pong')
return communication.request('ping', 'ping')
}).then(function(response) {
expect(response).toBe('pong')
communication.kill()
})
})
})
})
describe('forkFile', function() {
it('works as expected', function() {
const communication = Communication.forkFile(WORKER_PATH)
waitsForPromise(function(){
return communication.request('error', {error: true}).then(function() {
expect(false).toBe(true)
}, function(error) {
expect(error.message).toBe('Yes! It works too!')
communication.kill()
})
})
})
})
})
| 'use babel'
import {fork} from 'child_process'
import * as Communication from '../src/main'
const WORKER_PATH = __dirname + '/fixtures/worker.js'
describe('Process-Communication', function() {
describe('createFromProcess', function() {
it('works as expected', function() {
const child = fork(WORKER_PATH)
const communication = Communication.createFromProcess(child)
let exitTriggered = 0
waitsForPromise(function() {
communication.onDidExit(function() {
++exitTriggered
})
return communication.request('ping', 'ping').then(function(response) {
expect(response).toBe('pong')
return communication.request('ping', 'ping')
}).then(function(response) {
expect(response).toBe('pong')
communication.kill()
}).then(function() {
expect(exitTriggered).toBe(1)
})
})
})
})
describe('forkFile', function() {
it('works as expected', function() {
const communication = Communication.forkFile(WORKER_PATH)
waitsForPromise(function(){
return communication.request('error', {error: true}).then(function() {
expect(false).toBe(true)
}, function(error) {
expect(error.message).toBe('Yes! It works too!')
communication.kill()
})
})
})
})
})
| Add specs for latest exit event | :new: Add specs for latest exit event
| JavaScript | mit | steelbrain/process-communication | ---
+++
@@ -11,14 +11,20 @@
it('works as expected', function() {
const child = fork(WORKER_PATH)
const communication = Communication.createFromProcess(child)
+ let exitTriggered = 0
waitsForPromise(function() {
+ communication.onDidExit(function() {
+ ++exitTriggered
+ })
return communication.request('ping', 'ping').then(function(response) {
expect(response).toBe('pong')
return communication.request('ping', 'ping')
}).then(function(response) {
expect(response).toBe('pong')
communication.kill()
+ }).then(function() {
+ expect(exitTriggered).toBe(1)
})
})
}) |
03e248c9803b16c6c1cd8bad5524b668f3ac987e | modules/help.js | modules/help.js | 'use strict';
const builder = require('botbuilder');
module.exports = exports = [(session) => {
const card = new builder.HeroCard(session)
.title('JIRA Journal Bot')
.text('Your bullet journal - whatever you want to log.')
.images([
builder.CardImage.create(session, 'http://docs.botframework.com/images/demo_bot_image.png')
]);
const reply = new builder.Message(session)
.attachmentLayout(builder.AttachmentLayout.list)
.attachments([card]);
session.send(reply);
session.endDialog('Hi... I\'m the JIRA Journal Bot for time reporting. Thanks for adding me. Say \'help\' to see what I can do');
}]; | 'use strict';
const builder = require('botbuilder');
module.exports = exports = [(session) => {
const card = new builder.HeroCard(session)
.title('JIRA Journal Bot')
.text('Your bullet journal - whatever you want to log.')
.images([
builder.CardImage.create(session, 'https://bot-framework.azureedge.net/bot-icons-v1/jira-journal_1kD9TrAk04dW4K92uPBis7Bk2wP1rT3VI6NMBk95Lo7TC3BU.png')
]);
const reply = new builder.Message(session)
.attachmentLayout(builder.AttachmentLayout.list)
.attachments([card]);
session.send(reply);
session.endDialog('Hi... I\'m the JIRA Journal Bot for time reporting. Thanks for adding me. Say \'help\' to see what I can do!');
}]; | Include a temp logo for bot. | Include a temp logo for bot.
| JavaScript | mit | 99xt/jira-journal,99xt/jira-journal | ---
+++
@@ -8,12 +8,12 @@
.title('JIRA Journal Bot')
.text('Your bullet journal - whatever you want to log.')
.images([
- builder.CardImage.create(session, 'http://docs.botframework.com/images/demo_bot_image.png')
+ builder.CardImage.create(session, 'https://bot-framework.azureedge.net/bot-icons-v1/jira-journal_1kD9TrAk04dW4K92uPBis7Bk2wP1rT3VI6NMBk95Lo7TC3BU.png')
]);
const reply = new builder.Message(session)
.attachmentLayout(builder.AttachmentLayout.list)
.attachments([card]);
session.send(reply);
- session.endDialog('Hi... I\'m the JIRA Journal Bot for time reporting. Thanks for adding me. Say \'help\' to see what I can do');
+ session.endDialog('Hi... I\'m the JIRA Journal Bot for time reporting. Thanks for adding me. Say \'help\' to see what I can do!');
}]; |
764df7490dd131106a62bea47469aa171f283cdb | client/templates/app/nav/nav.js | client/templates/app/nav/nav.js | Template.nav.onRendered(function() {
this.$('.button-collapse').sideNav({
closeOnClick: true
});
});
Template.nav.events({
'click .logout': function(e){
e.preventDefault();
Meteor.logout(function(){
sAlert.info('Logged out succesfully');
});
}
})
Template.userDropdown.onRendered(function() {
this.$('.dropdown-button').dropdown({
beloworigin: true
});
});
Template.userDropdown.helpers({
avatar: function(){
return Meteor.user().profile.avatarImg;
}
});
Template.sidenav.onRendered(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
this.$('.open-notifications').leanModal();
});
Template.sidenav.events({
'click .open-notifications': function(){
}
}); | Template.nav.onRendered(function() {
this.$('.button-collapse').sideNav({
closeOnClick: true
});
});
Template.nav.events({
'click .logout': function(e){
e.preventDefault();
Meteor.logout(function(){
sAlert.info('Logged out succesfully');
});
}
})
Template.userDropdown.onRendered(function() {
this.$('.dropdown-button').dropdown({
beloworigin: true
});
});
Template.userDropdown.helpers({
avatar: function(){
return Meteor.user().profile.avatarImg;
}
});
Template.sidenav.onRendered(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
this.$('.open-notifications').leanModal();
});
Template.sidenav.events({
'click .open-notifications': function(){
$('#notifications_modal').openModal();
}
}); | Fix pesky modal duplication issue... | Fix pesky modal duplication issue...
| JavaScript | mit | mtr-cherish/cherish,mtr-cherish/cherish | ---
+++
@@ -33,6 +33,6 @@
Template.sidenav.events({
'click .open-notifications': function(){
-
+ $('#notifications_modal').openModal();
}
}); |
49af20920479ecd2772c929e301dbe48623f4a07 | src/Characters.js | src/Characters.js | "use strict"
const Characters = {
WIDE_BAR: "W",
NARROW_BAR: "N",
WIDE_SPACE: "w",
NARROW_SPACE: "n",
}
module.exports = Characters
| export const WIDE_BAR = "W"
export const NARROW_BAR = "N"
export const WIDE_SPACE = "w"
export const NARROW_SPACE = "n"
| Use es6 imports / exports | Use es6 imports / exports
| JavaScript | mit | mormahr/barcode.js,mormahr/barcode.js | ---
+++
@@ -1,10 +1,4 @@
-"use strict"
-
-const Characters = {
- WIDE_BAR: "W",
- NARROW_BAR: "N",
- WIDE_SPACE: "w",
- NARROW_SPACE: "n",
-}
-
-module.exports = Characters
+export const WIDE_BAR = "W"
+export const NARROW_BAR = "N"
+export const WIDE_SPACE = "w"
+export const NARROW_SPACE = "n" |
20c23bb1482b7bf2498baa46db2b97fba6ff701d | src/state/FormBuilderState.js | src/state/FormBuilderState.js | import DefaultContainer from './DefaultContainer'
import {getFieldType} from '../utils/getFieldType'
const noop = () => {}
export function createFieldValue(value, context) {
const {schema, field, resolveContainer} = context
if (!field) {
throw new Error(`Missing field for value ${value}`)
}
const fieldType = getFieldType(schema, field)
const ResolvedContainer = resolveContainer(field, fieldType) || DefaultContainer
return ResolvedContainer.deserialize(value, context)
}
export function createFormBuilderState(value, {type, schema, resolveContainer}) {
const context = {
schema: schema,
field: {type: type.name},
resolveContainer: resolveContainer || noop
}
return createFieldValue(value, context)
}
| import DefaultContainer from './DefaultContainer'
import {getFieldType} from '../utils/getFieldType'
const noop = () => {}
export function createFieldValue(value, context) {
const {schema, field, resolveContainer} = context
if (!field) {
throw new Error(`Missing field for value ${value}`)
}
const fieldType = getFieldType(schema, field)
let ResolvedContainer
try {
ResolvedContainer = resolveContainer(field, fieldType) || DefaultContainer
} catch (error) {
error.message = `Got error while resolving value container for field "${field.name}" of type ${fieldType.name}: ${error.message}.`
throw error
}
return ResolvedContainer.deserialize(value, context)
}
export function createFormBuilderState(value, {type, schema, resolveContainer}) {
const context = {
schema: schema,
field: {type: type.name},
resolveContainer: resolveContainer || noop
}
return createFieldValue(value, context)
}
| Improve error message if resolveContainer throws | Improve error message if resolveContainer throws
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -12,7 +12,13 @@
const fieldType = getFieldType(schema, field)
- const ResolvedContainer = resolveContainer(field, fieldType) || DefaultContainer
+ let ResolvedContainer
+ try {
+ ResolvedContainer = resolveContainer(field, fieldType) || DefaultContainer
+ } catch (error) {
+ error.message = `Got error while resolving value container for field "${field.name}" of type ${fieldType.name}: ${error.message}.`
+ throw error
+ }
return ResolvedContainer.deserialize(value, context)
} |
782f9a4018618fc0615b7857848a0f7d918a77bf | public/js/controllers/index.js | public/js/controllers/index.js | angular.module('mean.system').controller('IndexController', ['$scope', 'Global', 'socket', function ($scope, Global, socket) {
$scope.global = Global;
socket.on('test', function() {
console.log('test!');
});
}]); | angular.module('mean.system').controller('IndexController', ['$scope', 'Global', 'socket', function ($scope, Global, socket) {
$scope.global = Global;
socket.on('test', function() {
console.log('test!');
});
}]).controller('CardController', ['$scope', 'ApiService', function($scope, ApiService) {
ApiService.getCards()
.then(function(data) {
angular.forEach(data, function(data, key){
if (data.numAnswers) {
answers(data);
} else if (!data.numAnswers) {
questions(data);
}
});
});
var answers = function(answerCards) {
};
var questions = function(questionCards) {
};
}]);
/**
data.id -> card number
data.text -> card text
data.expansion -> if it's from the base card set or an expansion pack
--> types available -
---- Base, CAHe1, CAHe2, CAHgrognards, CAHweeaboo, CAHxmas, NEIndy,
---- NSFH, CAHe3, Image1, GOT, PAXP13
data.numAnswers --> identifies if it's a question card and how many
answers it accepts
**/ | Split up question/answer cards to be handled by different functions | Split up question/answer cards to be handled by different functions
| JavaScript | mit | andela/kissa-cfh-project,andela/kiba-cfh,andela/temari-cfh,andela/kissa-cfh-project,cardsforhumanity/cardsforhumanity,andela/kiba-cfh,cardsforhumanity/cardsforhumanity,andela/temari-cfh | ---
+++
@@ -3,4 +3,34 @@
socket.on('test', function() {
console.log('test!');
});
+}]).controller('CardController', ['$scope', 'ApiService', function($scope, ApiService) {
+ ApiService.getCards()
+ .then(function(data) {
+ angular.forEach(data, function(data, key){
+ if (data.numAnswers) {
+ answers(data);
+ } else if (!data.numAnswers) {
+ questions(data);
+ }
+ });
+ });
+
+ var answers = function(answerCards) {
+
+ };
+
+ var questions = function(questionCards) {
+
+ };
}]);
+
+/**
+data.id -> card number
+data.text -> card text
+data.expansion -> if it's from the base card set or an expansion pack
+--> types available -
+---- Base, CAHe1, CAHe2, CAHgrognards, CAHweeaboo, CAHxmas, NEIndy,
+---- NSFH, CAHe3, Image1, GOT, PAXP13
+data.numAnswers --> identifies if it's a question card and how many
+answers it accepts
+**/ |
1264e8cea2ee7a0289344b516f064ac0f5329fdb | tasks/scripts.js | tasks/scripts.js | 'use strict';
var gulp = require('gulp');
var paths = require('./_paths');
var concat = require('gulp-concat');
gulp.task('scripts', ['clean-js', 'lint'], function() {
var scripts = paths.vendor_scripts.concat(paths.scripts);
return gulp
.src(scripts)
.pipe(concat('cla.js'))
.pipe(gulp.dest(paths.dest + 'javascripts'));
});
| 'use strict';
var gulp = require('gulp');
var paths = require('./_paths');
var concat = require('gulp-concat');
gulp.task('scripts', ['clean-js'], function() {
var prod = [paths.scripts];
prod.push('!' + paths.scripts + '*debug*');
gulp.src(prod)
.pipe(concat('cla.js'))
.pipe(gulp.dest(paths.dest + 'javascripts'));
return gulp.src(paths.scripts + '*debug*')
.pipe(concat('cla-debug.js'))
.pipe(gulp.dest(paths.dest + 'javascripts'));
});
| Add additional debug JS file that is generated by Gulp | Add additional debug JS file that is generated by Gulp
| JavaScript | mit | ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public | ---
+++
@@ -4,11 +4,15 @@
var paths = require('./_paths');
var concat = require('gulp-concat');
-gulp.task('scripts', ['clean-js', 'lint'], function() {
- var scripts = paths.vendor_scripts.concat(paths.scripts);
+gulp.task('scripts', ['clean-js'], function() {
+ var prod = [paths.scripts];
+ prod.push('!' + paths.scripts + '*debug*');
- return gulp
- .src(scripts)
+ gulp.src(prod)
.pipe(concat('cla.js'))
.pipe(gulp.dest(paths.dest + 'javascripts'));
+
+ return gulp.src(paths.scripts + '*debug*')
+ .pipe(concat('cla-debug.js'))
+ .pipe(gulp.dest(paths.dest + 'javascripts'));
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.