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 |
|---|---|---|---|---|---|---|---|---|---|---|
b9ba28cc9b550c56c95fddcb18076eac1d26f75e | app/www/js/local-storage/local-storage.js | app/www/js/local-storage/local-storage.js | (function()
{
angular
.module('ionic.utils', [])
.factory('localStorage', localStorage);
localStorage.$inject = ['$window'];
function localStorage($window)
{
return {
set : function (key, value)
{
$window.localStorage[key] = value;
},
get : function (key, defaultValue)
{
return $window.localStorage[key] || defaultValue;
},
setObject : function (key, value)
{
$window.localStorage[key] = JSON.stringify(value);
},
getObject : function (key, defaultValue)
{
return $window.localStorage[key] === "undefined" ? {} : JSON.parse($window.localStorage[key] || (defaultValue ? defaultValue : '{}'));
},
setArray : function (key, value)
{
this.setObject(key, value);
},
getArray : function (key)
{
return JSON.parse($window.localStorage[key] || '[]');
}
};
}
})(); | (function()
{
angular
.module('ionic.utils', [])
.factory('localStorage', localStorage);
localStorage.$inject = ['$window'];
function localStorage($window)
{
return {
set : function (key, value)
{
$window.localStorage[key] = value;
},
get : function (key, defaultValue)
{
return $window.localStorage[key] || defaultValue;
},
setObject : function (key, value)
{
$window.localStorage[key] = JSON.stringify(value);
},
getObject : function (key, defaultValue)
{
return $window.localStorage[key] === "undefined" ? {} : JSON.parse($window.localStorage[key] || (_.isUndefined(defaultValue) ? '{}' : defaultValue));
},
setArray : function (key, value)
{
this.setObject(key, value);
},
getArray : function (key)
{
return JSON.parse($window.localStorage[key] || '[]');
}
};
}
})(); | Fix settings with false defaults | Fix settings with false defaults
| JavaScript | mit | dank-meme-dealership/foosey,dank-meme-dealership/foosey,brikr/foosey,dank-meme-dealership/foosey,brikr/foosey,dank-meme-dealership/foosey,dank-meme-dealership/foosey | ---
+++
@@ -23,7 +23,7 @@
},
getObject : function (key, defaultValue)
{
- return $window.localStorage[key] === "undefined" ? {} : JSON.parse($window.localStorage[key] || (defaultValue ? defaultValue : '{}'));
+ return $window.localStorage[key] === "undefined" ? {} : JSON.parse($window.localStorage[key] || (_.isUndefined(defaultValue) ? '{}' : defaultValue));
},
setArray : function (key, value)
{ |
a3f71bfa790f4f0e8d767f0f5a7f8997b3e26c14 | javascript/QueuedJobsAdmin.js | javascript/QueuedJobsAdmin.js | Behaviour.register({
'#Form_EditForm' : {
getPageFromServer : function(id) {
statusMessage("loading...");
var requestURL = 'admin/_queued-jobs/showqueue/' + id;
this.loadURLFromServer(requestURL);
$('sitetree').setCurrentByIdx(id);
}
},
}); | Behaviour.register({
'#Form_EditForm' : {
getPageFromServer : function(id) {
statusMessage("loading...");
var requestURL = 'admin/queuedjobs/showqueue/' + id;
this.loadURLFromServer(requestURL);
$('sitetree').setCurrentByIdx(id);
}
},
});
| Fix JS not matching the updated controller path | BUGFIX: Fix JS not matching the updated controller path
| JavaScript | bsd-3-clause | andrewandante/silverstripe-queuedjobs,open-sausages/silverstripe-queuedjobs,nyeholt/silverstripe-queuedjobs,open-sausages/silverstripe-queuedjobs,souldigital/silverstripe-queuedjobs,souldigital/silverstripe-queuedjobs,silverstripe-australia/silverstripe-queuedjobs,andrewandante/silverstripe-queuedjobs,nyeholt/silverstripe-queuedjobs,silverstripe-australia/silverstripe-queuedjobs,mattclegg/silverstripe-queuedjobs,mattclegg/silverstripe-queuedjobs | ---
+++
@@ -2,7 +2,7 @@
'#Form_EditForm' : {
getPageFromServer : function(id) {
statusMessage("loading...");
- var requestURL = 'admin/_queued-jobs/showqueue/' + id;
+ var requestURL = 'admin/queuedjobs/showqueue/' + id;
this.loadURLFromServer(requestURL);
$('sitetree').setCurrentByIdx(id);
} |
5ab43ba75dd491770855cac859be106c8d409eb7 | client/karma.conf.js | client/karma.conf.js | process.env.NODE_ENV = 'test';
const path = require('path');
var webpackConfig = require(path.join(__dirname, './node_modules/react-scripts/config/webpack.config.dev.js'));
webpackConfig.devtool = 'inline-source-map';
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['src/**/**.test.js'],
exclude: [],
preprocessors: { 'src/**/**.test.js': ['webpack', 'sourcemap'] },
webpack: webpackConfig,
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome', 'Firefox'],
singleRun: true,
concurrency: 1,
})
}
| process.env.NODE_ENV = 'test';
const path = require('path');
var webpackConfig = require(path.join(__dirname, './node_modules/react-scripts/config/webpack.config.dev.js'));
webpackConfig.devtool = 'inline-source-map';
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['src/**/**.test.js'],
exclude: [],
preprocessors: { 'src/**/**.test.js': ['webpack', 'sourcemap'] },
webpack: webpackConfig,
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome', 'Firefox'],
singleRun: true,
concurrency: 1,
customLaunchers: {
ex_Chrome: {
base: 'Chrome',
flags: ['--load-extension=../extension']
}
}
})
}
| Add Chrome browser definition with the extension loaded | Add Chrome browser definition with the extension loaded
| JavaScript | mit | apiaryio/console-proxy,apiaryio/apiary-console-seed,apiaryio/console-proxy,apiaryio/apiary-console-seed | ---
+++
@@ -3,6 +3,7 @@
var webpackConfig = require(path.join(__dirname, './node_modules/react-scripts/config/webpack.config.dev.js'));
webpackConfig.devtool = 'inline-source-map';
+
module.exports = function (config) {
config.set({
@@ -20,5 +21,11 @@
browsers: ['Chrome', 'Firefox'],
singleRun: true,
concurrency: 1,
+ customLaunchers: {
+ ex_Chrome: {
+ base: 'Chrome',
+ flags: ['--load-extension=../extension']
+ }
+ }
})
} |
a0117e82557b4d8a49c20f7e7900f5aa373ba8b5 | ui/src/utils/ajax.js | ui/src/utils/ajax.js | import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logout: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logout: links.logout} // eslint-disable-line no-throw-literal
}
}
| import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logoutLink: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logout: links.logout} // eslint-disable-line no-throw-literal
}
}
| Fix missing renaming of logout => logoutLink | Fix missing renaming of logout => logoutLink
During development, this was previously named `logout`. This cleans up a
remaining instance of `logout`, renaming it to the preferred
`logoutLink` to remain consistent with the rest of the codebase.
| JavaScript | agpl-3.0 | brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf | ---
+++
@@ -44,7 +44,7 @@
return {
...response,
auth: {links: auth},
- logout: links.logout,
+ logoutLink: links.logout,
}
} catch (error) {
const {response} = error |
2b6c2e33ac40e6096b4317f4f910065ee5d796ad | index.js | index.js | const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.set('view engine', 'ejs');
app.set('views', './')
app.post('/api/users/:user', (req, res) => {
return res.json(Object.assign({
id: req.params.id,
name: 'Vincenzo',
surname: 'Chianese',
age: 27 // Ahi Ahi, getting older
}, req.body));
});
app.get('/serve-seed.html', (req, res) => {
res.render('./serve-seed.ejs', {
url: process.env.APIARY_SEED_URL || 'http://localhost:3000'
});
});
app.listen(process.env.PORT || 3001);
| const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.set('view engine', 'ejs');
app.set('views', './')
app.get('/serve-seed.html', (req, res) => {
res.render('./serve-seed.ejs', {
url: process.env.APIARY_SEED_URL || 'http://localhost:3000'
});
});
app.use(bodyParser.json());
app.use(cors());
app.post('/api/users/:user', (req, res) => {
return res.json(Object.assign({
id: req.params.id,
name: 'Vincenzo',
surname: 'Chianese',
age: 27 // Ahi Ahi, getting older
}, req.body));
});
app.listen(process.env.PORT || 3001);
| Change routes and middlewares order | Change routes and middlewares order
| JavaScript | mit | apiaryio/apiary-console-seed,apiaryio/apiary-console-seed,apiaryio/console-proxy,apiaryio/console-proxy | ---
+++
@@ -4,10 +4,17 @@
const app = express();
+app.set('view engine', 'ejs');
+app.set('views', './')
+
+app.get('/serve-seed.html', (req, res) => {
+ res.render('./serve-seed.ejs', {
+ url: process.env.APIARY_SEED_URL || 'http://localhost:3000'
+ });
+});
+
app.use(bodyParser.json());
app.use(cors());
-app.set('view engine', 'ejs');
-app.set('views', './')
app.post('/api/users/:user', (req, res) => {
return res.json(Object.assign({
@@ -18,10 +25,5 @@
}, req.body));
});
-app.get('/serve-seed.html', (req, res) => {
- res.render('./serve-seed.ejs', {
- url: process.env.APIARY_SEED_URL || 'http://localhost:3000'
- });
-});
app.listen(process.env.PORT || 3001); |
60830702cfad70c1417d6c5708b8de36f19e2226 | index.js | index.js | var sudo = require('sudo-prompt');
var cmdFnPath = require.resolve('cmd-fn');
var setName = sudo.setName;
var call = function(options, cb) {
var cmd = process.execPath + ' ' + cmdFnPath;
if (process.execPath.indexOf("/Contents/MacOS/Electron") >= 0) {
// If we're running in Electron then make sure that the process is being
// run in node mode not as the GUI app.
cmd = 'ATOM_SHELL_INTERNAL_RUN_AS_NODE=1 ' + cmd;
}
if (options.module) {
cmd = cmd + ' --module ' + options.module;
} else {
return cb(new Error('module option is required'));
}
if (options.function) {
cmd = cmd + ' --function ' + options.function;
}
if (options.params) {
cmd = cmd + ' --params \'' + JSON.stringify(options.params) + '\'';
}
if (options.cwd) {
cmd = cmd + ' --cwd \'' + options.cwd + '\'';
}
if (options.type) {
cmd = cmd + ' --' + options.type;
}
return sudo.exec(cmd, function(err, val) {
try {
val = JSON.parse(val);
} catch (e) {
// Do Nothing
}
cb(err,val);
});
};
module.exports = {
call: call,
setName: setName
};
| var sudo = require('sudo-prompt');
var cmdFnPath = require.resolve('cmd-fn');
var setName = sudo.setName;
var call = function(options, cb) {
// Put paths inside quotes so spaces don't need to be escaped
var cmd = '"' + process.execPath +'" "' + cmdFnPath + '"';
if (process.execPath.indexOf("/Contents/MacOS/Electron") >= 0) {
// If we're running in Electron then make sure that the process is being
// run in node mode not as the GUI app.
cmd = 'ATOM_SHELL_INTERNAL_RUN_AS_NODE=1 ' + cmd;
}
if (options.module) {
cmd = cmd + ' --module ' + options.module;
} else {
return cb(new Error('module option is required'));
}
if (options.function) {
cmd = cmd + ' --function ' + options.function;
}
if (options.params) {
cmd = cmd + ' --params \'' + JSON.stringify(options.params) + '\'';
}
if (options.cwd) {
cmd = cmd + ' --cwd \'' + options.cwd + '\'';
}
if (options.type) {
cmd = cmd + ' --' + options.type;
}
return sudo.exec(cmd, function(err, val) {
try {
val = JSON.parse(val);
} catch (e) {
// Do Nothing
}
cb(err,val);
});
};
module.exports = {
call: call,
setName: setName
};
| Put paths inside quotes so spaces don't need to be escaped | Put paths inside quotes so spaces don't need to be escaped
| JavaScript | mit | davej/sudo-fn | ---
+++
@@ -4,7 +4,8 @@
var setName = sudo.setName;
var call = function(options, cb) {
- var cmd = process.execPath + ' ' + cmdFnPath;
+ // Put paths inside quotes so spaces don't need to be escaped
+ var cmd = '"' + process.execPath +'" "' + cmdFnPath + '"';
if (process.execPath.indexOf("/Contents/MacOS/Electron") >= 0) {
// If we're running in Electron then make sure that the process is being |
d0c08ec3d1bd509086c322d0b53847e637074fdc | katas/es6/language/destructuring/object.js | katas/es6/language/destructuring/object.js | // 12: destructuring - object
// To do: make all tests pass, leave the assert lines unchanged!
describe('destructuring objects', () => {
it('is simple', () => {
const {x} = {x: 1};
assert.equal(x, 1);
});
describe('nested', () => {
it('multiple objects', () => {
const magic = {first: 23, second: 42};
const {magic: {second}} = {magic};
assert.equal(second, 42);
});
it('object and array', () => {
const {z:[,x]} = {z: [23, 42]};
assert.equal(x, 42);
});
it('array and object', () => {
const [,[{lang}]] = [null, [{env: 'browser', lang: 'ES6'}]];
assert.equal(lang, 'ES6');
});
});
it('missing => undefined', () => {
const {z} = {x: 1};
assert.equal(z, void 0);
});
it('destructure from builtins (string)', () => {
const {substr} = '';
assert.equal(substr, String.prototype.substr);
});
});
| // 12: destructuring - object
// To do: make all tests pass, leave the assert lines unchanged!
describe('destructuring objects', () => {
it('is simple', () => {
const x = {x: 1};
assert.equal(x, 1);
});
describe('nested', () => {
it('multiple objects', () => {
const magic = {first: 23, second: 42};
const {magic: [second]} = {magic};
assert.equal(second, 42);
});
it('object and array', () => {
const {z:[x]} = {z: [23, 42]};
assert.equal(x, 42);
});
it('array and object', () => {
const [,{lang}] = [null, [{env: 'browser', lang: 'ES6'}]];
assert.equal(lang, 'ES6');
});
});
describe('interesting', () => {
it('missing refs become undefined', () => {
const {z} = {x: 1, z: 2};
assert.equal(z, void 0);
});
it('destructure from builtins (string)', () => {
const {substr} = 1;
assert.equal(substr, String.prototype.substr);
});
});
});
| Make them fail, so it is a real kata now :). | Make them fail, so it is a real kata now :). | JavaScript | mit | ehpc/katas,ehpc/katas,ehpc/katas,Semigradsky/katas,JonathanPrince/katas,JonathanPrince/katas,tddbin/katas,JonathanPrince/katas,cmisenas/katas,Semigradsky/katas,Semigradsky/katas,cmisenas/katas,rafaelrocha/katas,rafaelrocha/katas,rafaelrocha/katas,tddbin/katas,tddbin/katas,cmisenas/katas | ---
+++
@@ -4,34 +4,36 @@
describe('destructuring objects', () => {
it('is simple', () => {
- const {x} = {x: 1};
+ const x = {x: 1};
assert.equal(x, 1);
});
describe('nested', () => {
it('multiple objects', () => {
const magic = {first: 23, second: 42};
- const {magic: {second}} = {magic};
+ const {magic: [second]} = {magic};
assert.equal(second, 42);
});
it('object and array', () => {
- const {z:[,x]} = {z: [23, 42]};
+ const {z:[x]} = {z: [23, 42]};
assert.equal(x, 42);
});
it('array and object', () => {
- const [,[{lang}]] = [null, [{env: 'browser', lang: 'ES6'}]];
+ const [,{lang}] = [null, [{env: 'browser', lang: 'ES6'}]];
assert.equal(lang, 'ES6');
});
});
- it('missing => undefined', () => {
- const {z} = {x: 1};
- assert.equal(z, void 0);
- });
-
- it('destructure from builtins (string)', () => {
- const {substr} = '';
- assert.equal(substr, String.prototype.substr);
+ describe('interesting', () => {
+ it('missing refs become undefined', () => {
+ const {z} = {x: 1, z: 2};
+ assert.equal(z, void 0);
+ });
+
+ it('destructure from builtins (string)', () => {
+ const {substr} = 1;
+ assert.equal(substr, String.prototype.substr);
+ });
});
}); |
63b7714347e0e7793c19ccae2e7d96cd834bd7bd | LayoutTests/crypto/resources/worker-infinite-loop-generateKey.js | LayoutTests/crypto/resources/worker-infinite-loop-generateKey.js | importScripts('common.js');
function continuouslyGenerateRsaKey()
{
var extractable = false;
var usages = ['encrypt', 'decrypt'];
// Note that the modulus length is small.
var algorithm = {name: "RSAES-PKCS1-v1_5", modulusLength: 512, publicExponent: hexStringToUint8Array("010001")};
return crypto.subtle.generateKey(algorithm, extractable, usages).then(function(result) {
// Infinite recursion intentional!
return continuouslyGenerateRsaKey();
});
}
// Starts a Promise which continually generates new RSA keys.
var unusedPromise = continuouslyGenerateRsaKey();
// Inform the outer script that the worker started.
postMessage("Worker started");
| importScripts('common.js');
function continuouslyGenerateRsaKey()
{
var extractable = false;
var usages = ['sign', 'verify'];
// Note that the modulus length is small.
var algorithm = {name: "RSASSA-PKCS1-v1_5", modulusLength: 512, publicExponent: hexStringToUint8Array("010001"), hash: {name: 'sha-1'}};
return crypto.subtle.generateKey(algorithm, extractable, usages).then(function(result) {
// Infinite recursion intentional!
return continuouslyGenerateRsaKey();
});
}
// Starts a Promise which continually generates new RSA keys.
var unusedPromise = continuouslyGenerateRsaKey();
// Inform the outer script that the worker started.
postMessage("Worker started");
| Remove a lingering usage of RSA-ES. | [webcrypto] Remove a lingering usage of RSA-ES.
TBR=jww
BUG=372920,245025
Review URL: https://codereview.chromium.org/344503003
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@176389 bbb929c8-8fbe-4397-9dbb-9b2b20218538
| JavaScript | bsd-3-clause | jtg-gg/blink,modulexcite/blink,modulexcite/blink,nwjs/blink,PeterWangIntel/blink-crosswalk,hgl888/blink-crosswalk-efl,smishenk/blink-crosswalk,modulexcite/blink,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,nwjs/blink,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,ondra-novak/blink,hgl888/blink-crosswalk-efl,ondra-novak/blink,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,XiaosongWei/blink-crosswalk,Pluto-tv/blink-crosswalk,nwjs/blink,smishenk/blink-crosswalk,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,Bysmyyr/blink-crosswalk,jtg-gg/blink,XiaosongWei/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,smishenk/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,modulexcite/blink,modulexcite/blink,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,nwjs/blink,nwjs/blink,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,hgl888/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,Pluto-tv/blink-crosswalk,Pluto-tv/blink-crosswalk,modulexcite/blink,ondra-novak/blink,PeterWangIntel/blink-crosswalk,jtg-gg/blink,kurli/blink-crosswalk,jtg-gg/blink,nwjs/blink,XiaosongWei/blink-crosswalk,jtg-gg/blink,Pluto-tv/blink-crosswalk,Pluto-tv/blink-crosswalk,ondra-novak/blink,hgl888/blink-crosswalk-efl,PeterWangIntel/blink-crosswalk,modulexcite/blink,ondra-novak/blink,smishenk/blink-crosswalk,XiaosongWei/blink-crosswalk,jtg-gg/blink,Bysmyyr/blink-crosswalk,ondra-novak/blink,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,smishenk/blink-crosswalk,XiaosongWei/blink-crosswalk,jtg-gg/blink,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,smishenk/blink-crosswalk,modulexcite/blink,nwjs/blink,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,nwjs/blink,Pluto-tv/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,smishenk/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,modulexcite/blink,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,modulexcite/blink,jtg-gg/blink,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,jtg-gg/blink,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,ondra-novak/blink,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,ondra-novak/blink,ondra-novak/blink | ---
+++
@@ -3,9 +3,9 @@
function continuouslyGenerateRsaKey()
{
var extractable = false;
- var usages = ['encrypt', 'decrypt'];
+ var usages = ['sign', 'verify'];
// Note that the modulus length is small.
- var algorithm = {name: "RSAES-PKCS1-v1_5", modulusLength: 512, publicExponent: hexStringToUint8Array("010001")};
+ var algorithm = {name: "RSASSA-PKCS1-v1_5", modulusLength: 512, publicExponent: hexStringToUint8Array("010001"), hash: {name: 'sha-1'}};
return crypto.subtle.generateKey(algorithm, extractable, usages).then(function(result) {
// Infinite recursion intentional! |
ce9ce6ecf7a6dde9b21b29b7b39c85b9986dd143 | app/assets/javascripts/globals.js | app/assets/javascripts/globals.js | function only_on_page(name, fn) {
if ($('body').data('page') === name) {
fn();
}
}
function init_on_page(name, fn) {
$(document).on('turbolinks:load', function () {
only_on_page(name, function() {
fn();
});
});
}
function applyManyBindings(o) {
_.each(o, function (vm, el) {
ko.applyBindings(vm, document.getElementById(el));
});
}
| function only_on_page(name, fn) {
if ($('body').data('page') === name) {
fn();
}
}
function init_on_page(name, fn) {
$(document).on('turbolinks:load', function () {
only_on_page(name, function() {
fn();
});
});
}
function applyManyBindings(o) {
_.each(o, function (vm, id) {
var el = document.getElementById(id);
ko.cleanNode(el);
ko.applyBindings(vm, el);
});
}
| Clean nodes before binding so we can have inner bindings | Clean nodes before binding so we can have inner bindings
| JavaScript | apache-2.0 | Xalgorithms/xa-elegans,Xalgorithms/xa-elegans,Xalgorithms/xa-elegans | ---
+++
@@ -13,7 +13,9 @@
}
function applyManyBindings(o) {
- _.each(o, function (vm, el) {
- ko.applyBindings(vm, document.getElementById(el));
+ _.each(o, function (vm, id) {
+ var el = document.getElementById(id);
+ ko.cleanNode(el);
+ ko.applyBindings(vm, el);
});
} |
de0ca8f858b5b3f0692a55f9a0b7835bbc432903 | js/state/main.js | js/state/main.js | define(['phaser'], function(Phaser) {
var state = new Phaser.State();
var paddle;
state.create = function() {
paddle = state.add.sprite(400, 500, 'atlas', 'paddle');
paddle.anchor.set(0.5);
state.physics.enable(paddle, Phaser.Physics.ARCADE);
};
state.update = function() {
// Phaser doesn't allow maxvelocity of 0, see physics/arcade/World.js ln 292
state.physics.arcade.accelerateToPointer(paddle, state.input.activePointer, 1000, 300, 1);
};
return state;
}); | define(['phaser', 'objects/ball'], function(Phaser, Ball) {
var state = new Phaser.State();
var paddle;
var balls = [];
state.create = function() {
paddle = state.add.sprite(400, 500, 'atlas', 'paddle');
paddle.anchor.set(0.5);
state.physics.enable(paddle, Phaser.Physics.ARCADE);
state.physics.arcade.setBoundsToWorld();
paddle.body.immovable = true;
balls.push(new Ball(state, 400, 450));
balls[0].body.velocity.set(200,500);
paddle.inputEnabled = true;
paddle.input.enableDrag();
paddle.input.allowVerticalDrag = false;
};
state.update = function() {
state.physics.arcade.collide(balls,paddle);
};
return state;
}); | Add ball and paddle/world collision. | Add ball and paddle/world collision.
| JavaScript | mit | zekoff/1gam-breakout,zekoff/1gam-breakout | ---
+++
@@ -1,14 +1,21 @@
-define(['phaser'], function(Phaser) {
+define(['phaser', 'objects/ball'], function(Phaser, Ball) {
var state = new Phaser.State();
var paddle;
+ var balls = [];
state.create = function() {
paddle = state.add.sprite(400, 500, 'atlas', 'paddle');
paddle.anchor.set(0.5);
state.physics.enable(paddle, Phaser.Physics.ARCADE);
+ state.physics.arcade.setBoundsToWorld();
+ paddle.body.immovable = true;
+ balls.push(new Ball(state, 400, 450));
+ balls[0].body.velocity.set(200,500);
+ paddle.inputEnabled = true;
+ paddle.input.enableDrag();
+ paddle.input.allowVerticalDrag = false;
};
state.update = function() {
- // Phaser doesn't allow maxvelocity of 0, see physics/arcade/World.js ln 292
- state.physics.arcade.accelerateToPointer(paddle, state.input.activePointer, 1000, 300, 1);
+ state.physics.arcade.collide(balls,paddle);
};
return state;
}); |
a62bf8509e69239f898b595958c9bc4c71cad4ea | app/containers/EditRequestPage.js | app/containers/EditRequestPage.js | import React, { Component } from 'react';
import RequestEditor from '../components/RequestEditor';
import ResponseViewer from '../components/ResponseViewer';
import * as actionCreators from '../actions/project';
import { connect } from 'react-redux';
class EditRequestPage extends Component {
constructor(props) {
super(props);
this.state = {};
}
findRequest() {
const project = this.props.projects.filter(p => p.id == this.props.params.projectId).get(0);
if (!project)
return null;
return project.requests.filter(r => r.id == this.props.params.id).get(0);
}
onExecuteRequest(request) {
this.props.executeRequest(request.method, request.url, request.headers.toJS(), request.body);
}
render() {
const request = this.findRequest();
if (request == null)
return (<div/>);
return (
<div className="edit-request-page">
<RequestEditor request={ request }
onRequestChange={this.props.updateRequest}
onRequestDelete={this.props.deleteRequest}
onRequestExecute={this.onExecuteRequest.bind(this)}/>
<ResponseViewer response={ this.props.response }/>
</div>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects,
response: state.response
}
}
export default connect(mapStateToProps, actionCreators)(EditRequestPage);
| import React, { Component } from 'react';
import RequestEditor from '../components/RequestEditor';
import ResponseViewer from '../components/ResponseViewer';
import * as actionCreators from '../actions/project';
import { connect } from 'react-redux';
class EditRequestPage extends Component {
constructor(props) {
super(props);
this.state = {};
}
onExecuteRequest(request) {
this.props.executeRequest(request.method, request.url, request.headers.toJS(), request.body);
}
render() {
if (!this.props.request)
return null;
return (
<div className="edit-request-page">
<RequestEditor request={ this.props.request }
onRequestChange={this.props.updateRequest}
onRequestDelete={this.props.deleteRequest}
onRequestExecute={this.onExecuteRequest.bind(this)}/>
<ResponseViewer response={ this.props.response }/>
</div>
);
}
}
function mapStateToProps(state, ownProps) {
const project = state.projects.filter(p => p.id == ownProps.params.projectId).get(0);
const request = project && project.requests.filter(r => r.id == ownProps.params.id).get(0);
return {
request: request,
response: state.response
}
}
export default connect(mapStateToProps, actionCreators)(EditRequestPage);
| Select specific request from redux state directly in connect | Select specific request from redux state directly in connect
This prevents unneeded re-renders, because before it would rerender when
anything in a project would change.
| JavaScript | mpl-2.0 | pascalw/gettable,pascalw/gettable | ---
+++
@@ -10,26 +10,17 @@
this.state = {};
}
- findRequest() {
- const project = this.props.projects.filter(p => p.id == this.props.params.projectId).get(0);
- if (!project)
- return null;
-
- return project.requests.filter(r => r.id == this.props.params.id).get(0);
- }
-
onExecuteRequest(request) {
this.props.executeRequest(request.method, request.url, request.headers.toJS(), request.body);
}
render() {
- const request = this.findRequest();
- if (request == null)
- return (<div/>);
+ if (!this.props.request)
+ return null;
return (
<div className="edit-request-page">
- <RequestEditor request={ request }
+ <RequestEditor request={ this.props.request }
onRequestChange={this.props.updateRequest}
onRequestDelete={this.props.deleteRequest}
onRequestExecute={this.onExecuteRequest.bind(this)}/>
@@ -40,9 +31,12 @@
}
}
-function mapStateToProps(state) {
+function mapStateToProps(state, ownProps) {
+ const project = state.projects.filter(p => p.id == ownProps.params.projectId).get(0);
+ const request = project && project.requests.filter(r => r.id == ownProps.params.id).get(0);
+
return {
- projects: state.projects,
+ request: request,
response: state.response
}
} |
1276870295d9239124bac74e6f6762ab58f26817 | packages/react-widgets/src/util/Props.js | packages/react-widgets/src/util/Props.js |
const whitelist = [
'style',
'className',
'role',
'id',
'autocomplete',
'size',
];
const whitelistRegex = [/^aria-/, /^data-/, /^on[A-Z]\w+/]
export function pick(props, componentClass) {
let keys = Object.keys(componentClass.propTypes);
let result = {};
Object.keys(props).forEach(key => {
if (keys.indexOf(key) === -1) return
result[key] = props[key];
})
return result
}
export function pickElementProps(component) {
const props = omitOwn(component);
const result = {};
Object.keys(props).forEach(key => {
if (
whitelist.indexOf(key) !== -1 ||
whitelistRegex.some(r => !!key.match(r))
)
result[key] = props[key];
})
return result;
}
export function omitOwn(component, ...others) {
let initial = Object.keys(component.constructor.propTypes);
let keys = others.reduce((arr, compClass) => [
...arr,
...Object.keys(compClass.propTypes)], initial
);
let result = {};
Object.keys(component.props).forEach(key => {
if (keys.indexOf(key) !== -1) return
result[key] = component.props[key];
})
return result
}
|
const whitelist = [
'style',
'className',
'role',
'id',
'autocomplete',
'size',
'tabIndex',
'maxLength',
'name'
];
const whitelistRegex = [/^aria-/, /^data-/, /^on[A-Z]\w+/]
export function pick(props, componentClass) {
let keys = Object.keys(componentClass.propTypes);
let result = {};
Object.keys(props).forEach(key => {
if (keys.indexOf(key) === -1) return
result[key] = props[key];
})
return result
}
export function pickElementProps(component) {
const props = omitOwn(component);
const result = {};
Object.keys(props).forEach(key => {
if (
whitelist.indexOf(key) !== -1 ||
whitelistRegex.some(r => !!key.match(r))
)
result[key] = props[key];
})
return result;
}
export function omitOwn(component, ...others) {
let initial = Object.keys(component.constructor.propTypes);
let keys = others.reduce((arr, compClass) => [
...arr,
...Object.keys(compClass.propTypes)], initial
);
let result = {};
Object.keys(component.props).forEach(key => {
if (keys.indexOf(key) !== -1) return
result[key] = component.props[key];
})
return result
}
| Add some more props to whitelist | Add some more props to whitelist | JavaScript | mit | jquense/react-widgets,jquense/react-widgets,jquense/react-widgets,haneev/react-widgets,haneev/react-widgets | ---
+++
@@ -6,6 +6,9 @@
'id',
'autocomplete',
'size',
+ 'tabIndex',
+ 'maxLength',
+ 'name'
];
const whitelistRegex = [/^aria-/, /^data-/, /^on[A-Z]\w+/] |
f6590f8c05acf2ed3d59a09e719986a5966c5b0a | src/methods/users.js | src/methods/users.js | /* @flow */
export default function users(): Object {
return {
profile: (username: string) => {
const url = `/users/${username}`;
return this.request({
url,
method: "GET"
});
},
photos: (username: string) => {
const url = `/users/${username}/photos`;
return this.request({
url,
method: "GET"
});
},
likes: (username: string, page: number, perPage: number) => {
const url = `/users/${username}/likes`;
let query = {
page,
per_page: perPage
};
return this.request({
url,
method: "GET",
query
});
}
};
}
| /* @flow */
export default function users(): Object {
return {
profile: (username: string) => {
const url = `/users/${username}`;
return this.request({
url,
method: "GET"
});
},
photos: (username: string) => {
const url = `/users/${username}/photos`;
return this.request({
url,
method: "GET"
});
},
likes: (username: string, page: number = 1, perPage: number = 10) => {
const url = `/users/${username}/likes`;
let query = {
page,
per_page: perPage
};
return this.request({
url,
method: "GET",
query
});
}
};
}
| Add default page and perPage values to user likes | Add default page and perPage values to user likes
| JavaScript | mit | unsplash/unsplash-js,unsplash/unsplash-js,naoufal/unsplash-js | ---
+++
@@ -20,7 +20,7 @@
});
},
- likes: (username: string, page: number, perPage: number) => {
+ likes: (username: string, page: number = 1, perPage: number = 10) => {
const url = `/users/${username}/likes`;
let query = { |
85aa7eebfc4857a12c1c49048ea8cf6c8696b6d3 | fixtures/src/components/fixtures/index.js | fixtures/src/components/fixtures/index.js | const React = window.React;
import RangeInputFixtures from './range-inputs';
import TextInputFixtures from './text-inputs';
import SelectFixtures from './selects';
import TextAreaFixtures from './textareas/';
/**
* A simple routing component that renders the appropriate
* fixture based on the location pathname.
*/
const FixturesPage = React.createClass({
render() {
switch (window.location.pathname) {
case '/text-inputs':
return <TextInputFixtures />;
case '/range-inputs':
return <RangeInputFixtures />;
case '/selects':
return <SelectFixtures />;
case '/textareas':
return <TextAreaFixtures />;
default:
return <span />;
}
},
});
module.exports = FixturesPage;
| const React = window.React;
import RangeInputFixtures from './range-inputs';
import TextInputFixtures from './text-inputs';
import SelectFixtures from './selects';
import TextAreaFixtures from './textareas/';
/**
* A simple routing component that renders the appropriate
* fixture based on the location pathname.
*/
const FixturesPage = React.createClass({
render() {
switch (window.location.pathname) {
case '/text-inputs':
return <TextInputFixtures />;
case '/range-inputs':
return <RangeInputFixtures />;
case '/selects':
return <SelectFixtures />;
case '/textareas':
return <TextAreaFixtures />;
default:
return <p>Please select a text fixture.</p>
}
},
});
module.exports = FixturesPage;
| Add test prompt message when no fixture is selected | Add test prompt message when no fixture is selected
| JavaScript | mit | AlmeroSteyn/react,Simek/react,kaushik94/react,joecritch/react,yungsters/react,flarnie/react,roth1002/react,acdlite/react,silvestrijonathan/react,nhunzaker/react,jameszhan/react,joecritch/react,TheBlasfem/react,jordanpapaleo/react,nhunzaker/react,TheBlasfem/react,jdlehman/react,mosoft521/react,aickin/react,mjackson/react,jzmq/react,trueadm/react,Simek/react,glenjamin/react,dilidili/react,terminatorheart/react,bspaulding/react,STRML/react,niubaba63/react,yiminghe/react,yungsters/react,mosoft521/react,mjackson/react,prometheansacrifice/react,Simek/react,Simek/react,brigand/react,jquense/react,aickin/react,shergin/react,pyitphyoaung/react,jzmq/react,prometheansacrifice/react,jzmq/react,richiethomas/react,cpojer/react,nhunzaker/react,yungsters/react,ericyang321/react,acdlite/react,camsong/react,krasimir/react,kaushik94/react,leexiaosi/react,tomocchino/react,ericyang321/react,maxschmeling/react,dilidili/react,cpojer/react,yangshun/react,wmydz1/react,edvinerikson/react,claudiopro/react,aickin/react,AlmeroSteyn/react,richiethomas/react,maxschmeling/react,mosoft521/react,empyrical/react,sekiyaeiji/react,andrerpena/react,jquense/react,brigand/react,prometheansacrifice/react,richiethomas/react,claudiopro/react,sekiyaeiji/react,silvestrijonathan/react,glenjamin/react,flarnie/react,VioletLife/react,trueadm/react,jameszhan/react,rickbeerendonk/react,apaatsio/react,maxschmeling/react,yangshun/react,yangshun/react,joecritch/react,chenglou/react,ericyang321/react,pyitphyoaung/react,syranide/react,leexiaosi/react,ericyang321/react,shergin/react,prometheansacrifice/react,glenjamin/react,Simek/react,brigand/react,mhhegazy/react,pyitphyoaung/react,rickbeerendonk/react,jordanpapaleo/react,mjackson/react,yiminghe/react,rricard/react,apaatsio/react,edvinerikson/react,krasimir/react,nhunzaker/react,terminatorheart/react,glenjamin/react,bspaulding/react,niubaba63/react,jquense/react,flipactual/react,kaushik94/react,jorrit/react,jquense/react,ArunTesco/react,aickin/react,jordanpapaleo/react,tomocchino/react,mosoft521/react,sekiyaeiji/react,flarnie/react,trueadm/react,wmydz1/react,niubaba63/react,edvinerikson/react,rlugojr/react,brigand/react,andrerpena/react,flarnie/react,roth1002/react,kaushik94/react,jdlehman/react,rickbeerendonk/react,ArunTesco/react,terminatorheart/react,krasimir/react,cpojer/react,rricard/react,ericyang321/react,camsong/react,silvestrijonathan/react,roth1002/react,TheBlasfem/react,andrerpena/react,yangshun/react,acdlite/react,tomocchino/react,yiminghe/react,niubaba63/react,acdlite/react,pyitphyoaung/react,mosoft521/react,flarnie/react,roth1002/react,jordanpapaleo/react,quip/react,apaatsio/react,chicoxyzzy/react,syranide/react,acdlite/react,rohannair/react,mhhegazy/react,jdlehman/react,silvestrijonathan/react,wmydz1/react,rickbeerendonk/react,rohannair/react,silvestrijonathan/react,jdlehman/react,brigand/react,empyrical/react,glenjamin/react,tomocchino/react,claudiopro/react,trueadm/react,trueadm/react,claudiopro/react,wmydz1/react,Simek/react,shergin/react,AlmeroSteyn/react,jordanpapaleo/react,roth1002/react,quip/react,nhunzaker/react,nhunzaker/react,chenglou/react,jdlehman/react,aickin/react,rohannair/react,bspaulding/react,TheBlasfem/react,jorrit/react,wmydz1/react,terminatorheart/react,rricard/react,mhhegazy/react,leexiaosi/react,glenjamin/react,cpojer/react,yungsters/react,tomocchino/react,rohannair/react,rickbeerendonk/react,ericyang321/react,AlmeroSteyn/react,apaatsio/react,krasimir/react,dilidili/react,syranide/react,mhhegazy/react,aickin/react,dilidili/react,billfeller/react,jdlehman/react,camsong/react,silvestrijonathan/react,quip/react,rlugojr/react,anushreesubramani/react,claudiopro/react,VioletLife/react,flarnie/react,camsong/react,yangshun/react,chicoxyzzy/react,STRML/react,mhhegazy/react,chicoxyzzy/react,acdlite/react,jorrit/react,richiethomas/react,rricard/react,andrerpena/react,jorrit/react,bspaulding/react,AlmeroSteyn/react,yungsters/react,facebook/react,flarnie/react,jzmq/react,maxschmeling/react,yangshun/react,ArunTesco/react,claudiopro/react,trueadm/react,rohannair/react,jameszhan/react,TheBlasfem/react,glenjamin/react,VioletLife/react,billfeller/react,STRML/react,yiminghe/react,facebook/react,edvinerikson/react,wmydz1/react,rricard/react,aickin/react,rlugojr/react,rickbeerendonk/react,pyitphyoaung/react,roth1002/react,bspaulding/react,mosoft521/react,VioletLife/react,maxschmeling/react,niubaba63/react,krasimir/react,STRML/react,mhhegazy/react,anushreesubramani/react,prometheansacrifice/react,jameszhan/react,rlugojr/react,shergin/react,chicoxyzzy/react,yangshun/react,cpojer/react,joecritch/react,richiethomas/react,rricard/react,shergin/react,empyrical/react,pyitphyoaung/react,jorrit/react,yiminghe/react,camsong/react,apaatsio/react,chicoxyzzy/react,tomocchino/react,richiethomas/react,andrerpena/react,TheBlasfem/react,nhunzaker/react,STRML/react,billfeller/react,rickbeerendonk/react,chenglou/react,niubaba63/react,anushreesubramani/react,niubaba63/react,wmydz1/react,cpojer/react,camsong/react,prometheansacrifice/react,pyitphyoaung/react,jquense/react,jameszhan/react,terminatorheart/react,joecritch/react,jorrit/react,jordanpapaleo/react,chenglou/react,maxschmeling/react,anushreesubramani/react,edvinerikson/react,ericyang321/react,chenglou/react,dilidili/react,shergin/react,empyrical/react,tomocchino/react,facebook/react,prometheansacrifice/react,jzmq/react,trueadm/react,krasimir/react,billfeller/react,terminatorheart/react,AlmeroSteyn/react,kaushik94/react,VioletLife/react,mjackson/react,jorrit/react,chicoxyzzy/react,joecritch/react,rlugojr/react,andrerpena/react,joecritch/react,AlmeroSteyn/react,quip/react,kaushik94/react,yiminghe/react,STRML/react,roth1002/react,chenglou/react,empyrical/react,jzmq/react,chenglou/react,facebook/react,anushreesubramani/react,mjackson/react,anushreesubramani/react,shergin/react,facebook/react,yungsters/react,cpojer/react,Simek/react,richiethomas/react,jquense/react,bspaulding/react,quip/react,rohannair/react,apaatsio/react,facebook/react,rohannair/react,facebook/react,mosoft521/react,rlugojr/react,jameszhan/react,jdlehman/react,maxschmeling/react,dilidili/react,bspaulding/react,empyrical/react,edvinerikson/react,dilidili/react,kaushik94/react,krasimir/react,claudiopro/react,empyrical/react,brigand/react,anushreesubramani/react,VioletLife/react,mhhegazy/react,jquense/react,jzmq/react,edvinerikson/react,acdlite/react,billfeller/react,billfeller/react,mjackson/react,camsong/react,quip/react,apaatsio/react,syranide/react,yungsters/react,flipactual/react,jameszhan/react,rlugojr/react,VioletLife/react,billfeller/react,yiminghe/react,chicoxyzzy/react,flipactual/react,brigand/react,mjackson/react,quip/react,STRML/react,silvestrijonathan/react,jordanpapaleo/react | ---
+++
@@ -20,7 +20,7 @@
case '/textareas':
return <TextAreaFixtures />;
default:
- return <span />;
+ return <p>Please select a text fixture.</p>
}
},
}); |
b69d1bb34980f58b29ee4d5cc068151492733f79 | frontend/detail_pane/DetailPaneSection.js | frontend/detail_pane/DetailPaneSection.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
var React = require('react');
class DetailPaneSection extends React.Component {
render(): React.Element {
var {
children,
hint,
} = this.props;
return (
<div style={styles.section}>
<strong style={styles.title}>{this.props.title}</strong>
{hint ? ' ' + hint : null}
{children}
</div>
);
}
}
var styles = {
section: {
marginBottom: 10,
flexShrink: 0,
},
title: {
marginRight: 5,
},
};
module.exports = DetailPaneSection;
| /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
var React = require('react');
class DetailPaneSection extends React.Component {
render(): React.Element {
var {
children,
hint,
} = this.props;
return (
<div style={styles.section}>
<strong style={styles.title}>{this.props.title}</strong>
{hint}
{children}
</div>
);
}
}
var styles = {
section: {
marginBottom: 10,
flexShrink: 0,
},
title: {
marginRight: 7,
},
};
module.exports = DetailPaneSection;
| Increase margin and remove the padded space | Increase margin and remove the padded space
| JavaScript | bsd-3-clause | aarondancer/react-devtools,aolesky/react-devtools,keyanzhang/react-devtools,aolesky/react-devtools,aolesky/react-devtools,jhen0409/react-devtools,jhen0409/react-devtools,aarondancer/react-devtools,keyanzhang/react-devtools,aarondancer/react-devtools,jhen0409/react-devtools | ---
+++
@@ -21,7 +21,7 @@
return (
<div style={styles.section}>
<strong style={styles.title}>{this.props.title}</strong>
- {hint ? ' ' + hint : null}
+ {hint}
{children}
</div>
);
@@ -34,7 +34,7 @@
flexShrink: 0,
},
title: {
- marginRight: 5,
+ marginRight: 7,
},
};
|
3c31f728b9736ffbc41e9766eddff19f803a84cc | index.js | index.js | 'use strict';
/* Expose. */
module.exports = visit;
visit.CONTINUE = true;
visit.SKIP = 'skip';
visit.EXIT = false;
var is = require('unist-util-is');
/* Visit. */
function visit(tree, test, visitor, reverse) {
if (typeof test === 'function' && typeof visitor !== 'function') {
reverse = visitor;
visitor = test;
test = null;
}
one(tree);
/* Visit a single node. */
function one(node, index, parent) {
var result;
index = index || (parent ? 0 : null);
if (!test || node.type === test || is(test, node, index, parent || null)) {
result = visitor(node, index, parent || null);
}
if (result === visit.EXIT) {
return result;
}
if (node.children && result !== visit.SKIP) {
return all(node.children, node);
}
return visit.CONTINUE;
}
/* Visit children in `parent`. */
function all(children, parent) {
var step = reverse ? -1 : 1;
var max = children.length;
var min = -1;
var index = (reverse ? max : min) + step;
var child;
var result;
while (index > min && index < max) {
child = children[index];
result = child && one(child, index, parent);
if (result === visit.EXIT) {
return result;
}
index += step;
}
return visit.CONTINUE;
}
}
| 'use strict';
module.exports = visit;
var is = require('unist-util-is');
var CONTINUE = true;
var SKIP = 'skip';
var EXIT = false;
visit.CONTINUE = CONTINUE;
visit.SKIP = SKIP;
visit.EXIT = EXIT;
function visit(tree, test, visitor, reverse) {
if (typeof test === 'function' && typeof visitor !== 'function') {
reverse = visitor;
visitor = test;
test = null;
}
one(tree);
/* Visit a single node. */
function one(node, index, parent) {
var result;
index = index || (parent ? 0 : null);
if (!test || node.type === test || is(test, node, index, parent || null)) {
result = visitor(node, index, parent || null);
}
if (result === EXIT) {
return result;
}
if (node.children && result !== SKIP) {
return all(node.children, node);
}
return CONTINUE;
}
/* Visit children in `parent`. */
function all(children, parent) {
var step = reverse ? -1 : 1;
var max = children.length;
var min = -1;
var index = (reverse ? max : min) + step;
var child;
var result;
while (index > min && index < max) {
child = children[index];
result = child && one(child, index, parent);
if (result === EXIT) {
return result;
}
index += step;
}
return CONTINUE;
}
}
| Refactor internal use of constants | Refactor internal use of constants
| JavaScript | mit | wooorm/mdast-util-visit,wooorm/unist-util-visit | ---
+++
@@ -1,15 +1,17 @@
'use strict';
-/* Expose. */
module.exports = visit;
-
-visit.CONTINUE = true;
-visit.SKIP = 'skip';
-visit.EXIT = false;
var is = require('unist-util-is');
-/* Visit. */
+var CONTINUE = true;
+var SKIP = 'skip';
+var EXIT = false;
+
+visit.CONTINUE = CONTINUE;
+visit.SKIP = SKIP;
+visit.EXIT = EXIT;
+
function visit(tree, test, visitor, reverse) {
if (typeof test === 'function' && typeof visitor !== 'function') {
reverse = visitor;
@@ -29,15 +31,15 @@
result = visitor(node, index, parent || null);
}
- if (result === visit.EXIT) {
+ if (result === EXIT) {
return result;
}
- if (node.children && result !== visit.SKIP) {
+ if (node.children && result !== SKIP) {
return all(node.children, node);
}
- return visit.CONTINUE;
+ return CONTINUE;
}
/* Visit children in `parent`. */
@@ -53,13 +55,13 @@
child = children[index];
result = child && one(child, index, parent);
- if (result === visit.EXIT) {
+ if (result === EXIT) {
return result;
}
index += step;
}
- return visit.CONTINUE;
+ return CONTINUE;
}
} |
34f823129e9d42246b6d66e753517c02a0dba3cc | index.js | index.js | #!/usr/bin/env node
"use strict";
const meow = require("meow");
const Promise = require("pinkie-promise");
const Xray = require("x-ray"), xray = Xray();
const periods = ['day', 'week', 'month'];
const cli = meow(`
Usage
$ pkgstats -u <user> -n <package name> -p <day|week|month>
Options
-u, --user npm user
-n, --name pkg name
-p, --period time period
`);
| #!/usr/bin/env node
'use strict';
const Promise = require('pinkie-promise');
const Xray = require('x-ray'), xray = Xray();
const cli = require('./cli');
const getUsrPkgs = function(username) {
return new Promise(function(resolve, reject) {
var url = 'https://www.npmjs.com/~' + username + '/';
xray(url, '.collaborated-packages', ['li'], 'a')(function(err, pkgs) {
if (err) reject(err);
// resolve(data);
var usrPkgs = [];
pkgs.forEach(function(pkg) {
usrPkgs.push(pkg.trim().split('- ')[0].trim());
});
resolve(usrPkgs);
});
});
}
getUsrPkgs(cli.flags['u']).then(function(pkgs) {
return pkgs;
});
| Add scraper for user packages | Add scraper for user packages
| JavaScript | mit | kshvmdn/pkg-stats | ---
+++
@@ -1,17 +1,24 @@
#!/usr/bin/env node
-"use strict";
-const meow = require("meow");
-const Promise = require("pinkie-promise");
-const Xray = require("x-ray"), xray = Xray();
+'use strict';
+const Promise = require('pinkie-promise');
+const Xray = require('x-ray'), xray = Xray();
+const cli = require('./cli');
-const periods = ['day', 'week', 'month'];
+const getUsrPkgs = function(username) {
+ return new Promise(function(resolve, reject) {
+ var url = 'https://www.npmjs.com/~' + username + '/';
+ xray(url, '.collaborated-packages', ['li'], 'a')(function(err, pkgs) {
+ if (err) reject(err);
+ // resolve(data);
+ var usrPkgs = [];
+ pkgs.forEach(function(pkg) {
+ usrPkgs.push(pkg.trim().split('- ')[0].trim());
+ });
+ resolve(usrPkgs);
+ });
+ });
+}
-const cli = meow(`
- Usage
- $ pkgstats -u <user> -n <package name> -p <day|week|month>
-
- Options
- -u, --user npm user
- -n, --name pkg name
- -p, --period time period
-`);
+getUsrPkgs(cli.flags['u']).then(function(pkgs) {
+ return pkgs;
+}); |
40825ff0a2c4d0292943bd5d6c095920a6306c37 | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-medium-editor',
included: function(app) {
this._super.included(app);
var options = app.options.mediumEditorOptions || {};
this.app.import(app.bowerDirectory + '/medium-editor/dist/js/medium-editor.js');
if (options.theme && options.excludeBaseStyles !== false) {
this.app.import(app.bowerDirectory + '/medium-editor/dist/css/medium-editor.css');
}
if (options.theme && options.theme !== false) {
this.app.import(app.bowerDirectory + '/medium-editor/dist/css/themes/' + options.theme + '.css');
}
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-medium-editor',
included: function(app) {
this._super.included(app);
var options = app.options.mediumEditorOptions || {};
this.app.import(app.bowerDirectory + '/medium-editor/dist/js/medium-editor.js');
if (!options.excludeBaseStyles) {
this.app.import(app.bowerDirectory + '/medium-editor/dist/css/medium-editor.css');
}
if (options.theme) {
this.app.import(app.bowerDirectory + '/medium-editor/dist/css/themes/' + options.theme + '.css');
} else if (options.theme !== false) {
this.app.import(app.bowerDirectory + '/medium-editor/dist/css/themes/default.css');
}
}
};
| Fix logic for style overrides. | Fix logic for style overrides.
| JavaScript | isc | lukebrenton/ember-cli-medium-editor | ---
+++
@@ -10,12 +10,14 @@
this.app.import(app.bowerDirectory + '/medium-editor/dist/js/medium-editor.js');
- if (options.theme && options.excludeBaseStyles !== false) {
+ if (!options.excludeBaseStyles) {
this.app.import(app.bowerDirectory + '/medium-editor/dist/css/medium-editor.css');
}
- if (options.theme && options.theme !== false) {
+ if (options.theme) {
this.app.import(app.bowerDirectory + '/medium-editor/dist/css/themes/' + options.theme + '.css');
+ } else if (options.theme !== false) {
+ this.app.import(app.bowerDirectory + '/medium-editor/dist/css/themes/default.css');
}
}
}; |
5d950f48b7a24143aba6f073d54c5c3b7da1975b | index.js | index.js | 'use strict';
var stemmer;
/**
* Module dependencies.
*/
stemmer = require('lancaster-stemmer');
/**
* `changetextinside` handler;
*
* @this Node
*/
function onchangetextinside() {
var value;
value = this.toString();
this.data.stem = value ? stemmer(value) : null;
}
/**
* Define `lancasterStemmer`.
*
* @param {Retext} retext - Instance of Retext.
*/
function lancasterStemmer(retext) {
var WordNode;
WordNode = retext.parser.TextOM.WordNode;
WordNode.on('changetextinside', onchangetextinside);
WordNode.on('removeinside', onchangetextinside);
WordNode.on('insertinside', onchangetextinside);
}
/**
* Expose `lancasterStemmer`.
*/
module.exports = lancasterStemmer;
| 'use strict';
var stemmer;
/**
* Module dependencies.
*/
stemmer = require('lancaster-stemmer');
/**
* `changetextinside` handler;
*
* @this Node
*/
function onchangeinside() {
var value;
value = this.toString();
this.data.stem = value ? stemmer(value) : null;
}
/**
* Define `lancasterStemmer`.
*
* @param {Retext} retext - Instance of Retext.
*/
function lancasterStemmer(retext) {
retext.TextOM.WordNode.on('changeinside', onchangeinside);
}
/**
* Expose `lancasterStemmer`.
*/
module.exports = lancasterStemmer;
| Refactor to use generic `changeinside` in new retext | Refactor to use generic `changeinside` in new retext
| JavaScript | mit | wooorm/retext-lancaster-stemmer | ---
+++
@@ -14,7 +14,7 @@
* @this Node
*/
-function onchangetextinside() {
+function onchangeinside() {
var value;
value = this.toString();
@@ -29,13 +29,7 @@
*/
function lancasterStemmer(retext) {
- var WordNode;
-
- WordNode = retext.parser.TextOM.WordNode;
-
- WordNode.on('changetextinside', onchangetextinside);
- WordNode.on('removeinside', onchangetextinside);
- WordNode.on('insertinside', onchangetextinside);
+ retext.TextOM.WordNode.on('changeinside', onchangeinside);
}
/** |
2dc611a249044ba57290c387f2a5665cc7d123b5 | index.js | index.js | const config = require('./config');
const express = require('express');
const cors = require('cors');
const importer = require('./middleware/importer');
const mongoose = require('mongoose');
const dbHelper = require('./lib/db');
// import routers
const bitcoinRouter = require('./router/bitcoin');
const defaultRouter = require('./router/default');
// activate configured cron jobs
const updateDataCronJobs = require('./cronjobs/updateData');
const deleteOldDataCronJobs = require('./cronjobs/deleteOldData');
// create Express server
var server = express();
// add CORS middleware
server.use(cors());
// connect to MongoDB
var mongoDbUri = dbHelper.getMongoDbUri(config.dbParams);
var mongoDbOptions = {
useMongoClient: true
};
mongoose.connect(mongoDbUri, mongoDbOptions);
// Check if there is a need for data import/sync initiation
// (initiated if number of months is more than the monthly averages in the DB)
importer.checkDBcompleteness();
// apply /bitcoin routes
server.use(config.urlPrefix + '/bitcoin', bitcoinRouter);
// apply default router to catch ANY other requested route
server.use(config.urlPrefix + '/', defaultRouter);
// start the server
server.listen(config.serverPort, function () {
console.log('Server is running on port: ' + config.serverPort);
});
| const config = require('./config');
const express = require('express');
const cors = require('cors');
const importer = require('./middleware/importer');
const mongoose = require('mongoose');
const dbHelper = require('./lib/db');
const tools = require('./lib/tools');
// import routers
const bitcoinRouter = require('./router/bitcoin');
const defaultRouter = require('./router/default');
// activate configured cron jobs
const updateDataCronJobs = require('./cronjobs/updateData');
const deleteOldDataCronJobs = require('./cronjobs/deleteOldData');
// create Express server
var server = express();
// add CORS middleware
server.use(cors());
// connect to MongoDB
var mongoDbUri = dbHelper.getMongoDbUri(config.dbParams);
var mongoDbOptions = {
useMongoClient: true
};
mongoose.connect(mongoDbUri, mongoDbOptions);
// Check if there is a need for data import/sync initiation
// (initiated if number of months is more than the monthly averages in the DB)
importer.checkDBcompleteness();
// log time and ip address of request
server.use(function(req, res, next) {
console.log(tools.getCurrentDatetimeString(), req.ip);
next();
});
// apply /bitcoin routes
server.use(config.urlPrefix + '/bitcoin', bitcoinRouter);
// apply default router to catch ANY other requested route
server.use(config.urlPrefix + '/', defaultRouter);
// start the server
server.listen(config.serverPort, function () {
console.log('Server is running on port: ' + config.serverPort);
});
| Add logging info for request | Add logging info for request
| JavaScript | mit | cmihaylov/bitcoin-price-api,cmihaylov/bitcoin-price-api | ---
+++
@@ -4,6 +4,7 @@
const importer = require('./middleware/importer');
const mongoose = require('mongoose');
const dbHelper = require('./lib/db');
+const tools = require('./lib/tools');
// import routers
const bitcoinRouter = require('./router/bitcoin');
@@ -30,6 +31,12 @@
// (initiated if number of months is more than the monthly averages in the DB)
importer.checkDBcompleteness();
+// log time and ip address of request
+server.use(function(req, res, next) {
+ console.log(tools.getCurrentDatetimeString(), req.ip);
+ next();
+});
+
// apply /bitcoin routes
server.use(config.urlPrefix + '/bitcoin', bitcoinRouter);
|
585ce986ea286dc488fd34582cb075eac93e12e2 | index.js | index.js | 'use strict'
module.exports = visit
var visitParents = require('unist-util-visit-parents')
var CONTINUE = visitParents.CONTINUE
var SKIP = visitParents.SKIP
var EXIT = visitParents.EXIT
visit.CONTINUE = CONTINUE
visit.SKIP = SKIP
visit.EXIT = EXIT
function visit(tree, test, visitor, reverse) {
if (typeof test === 'function' && typeof visitor !== 'function') {
reverse = visitor
visitor = test
test = null
}
visitParents(tree, test, overload, reverse)
function overload(node, parents) {
var parent = parents[parents.length - 1]
var index = parent ? parent.children.indexOf(node) : null
return visitor(node, index, parent)
}
}
| 'use strict'
module.exports = visit
var visitParents = require('unist-util-visit-parents')
visit.CONTINUE = visitParents.CONTINUE
visit.SKIP = visitParents.SKIP
visit.EXIT = visitParents.EXIT
function visit(tree, test, visitor, reverse) {
if (typeof test === 'function' && typeof visitor !== 'function') {
reverse = visitor
visitor = test
test = null
}
visitParents(tree, test, overload, reverse)
function overload(node, parents) {
var parent = parents[parents.length - 1]
var index = parent ? parent.children.indexOf(node) : null
return visitor(node, index, parent)
}
}
| Refactor to improve bundle size | Refactor to improve bundle size
| JavaScript | mit | wooorm/mdast-util-visit,wooorm/unist-util-visit | ---
+++
@@ -4,13 +4,9 @@
var visitParents = require('unist-util-visit-parents')
-var CONTINUE = visitParents.CONTINUE
-var SKIP = visitParents.SKIP
-var EXIT = visitParents.EXIT
-
-visit.CONTINUE = CONTINUE
-visit.SKIP = SKIP
-visit.EXIT = EXIT
+visit.CONTINUE = visitParents.CONTINUE
+visit.SKIP = visitParents.SKIP
+visit.EXIT = visitParents.EXIT
function visit(tree, test, visitor, reverse) {
if (typeof test === 'function' && typeof visitor !== 'function') { |
347f3dd6b971f9c89f82759c78028504adde54ec | index.js | index.js | var explode = require('turf-explode');
var point = require('turf-point');
/**
* Calculates the centroid of a polygon Feature or
* FeatureCollection using the geometric mean of all vertices.
* This lessens the effect of small islands and artifacts when calculating
* the centroid of a set of polygons.
*
* @module turf/centroid
* @param {FeatureCollection} fc a {@link Feature} or FeatureCollection of any type
* @return {Point} a Point showing the centroid of the input feature(s)
* @example
* var poly = turf.polygon([[[0,0], [0,10], [10,10] , [10,0]]])
* var centroidPt = turf.centroid(poly)
*/
module.exports = function(features){
var vertices = explode(features).features,
xSum = 0,
ySum = 0,
len = vertices.length;
for (var i = 0; i < len; i++) {
xSum += vertices[i].geometry.coordinates[0];
ySum += vertices[i].geometry.coordinates[1];
}
return point(xSum / len, ySum / len);
};
| var explode = require('turf-explode');
var point = require('turf-point');
/**
* Calculates the centroid of a polygon Feature or
* FeatureCollection using the geometric mean of all vertices.
* This lessens the effect of small islands and artifacts when calculating
* the centroid of a set of polygons.
*
* @module turf/centroid
* @param {FeatureCollection} fc a {@link Feature} or FeatureCollection of any type
* @return {Point} a Point showing the centroid of the input feature(s)
* @example
* var poly = turf.polygon([[[0,0], [0,10], [10,10] , [10,0], [0, 0]]]);
* var centroidPt = turf.centroid(poly);
*
* var result = turf.featurecollection([poly, centroidPt]);
*
* //=result
*/
module.exports = function(features){
var vertices = explode(features).features,
xSum = 0,
ySum = 0,
len = vertices.length;
for (var i = 0; i < len; i++) {
xSum += vertices[i].geometry.coordinates[0];
ySum += vertices[i].geometry.coordinates[1];
}
return point(xSum / len, ySum / len);
};
| Fix polygon, add semicolons, rpl-ize | Fix polygon, add semicolons, rpl-ize
| JavaScript | mit | Turfjs/turf-centroid | ---
+++
@@ -11,8 +11,12 @@
* @param {FeatureCollection} fc a {@link Feature} or FeatureCollection of any type
* @return {Point} a Point showing the centroid of the input feature(s)
* @example
- * var poly = turf.polygon([[[0,0], [0,10], [10,10] , [10,0]]])
- * var centroidPt = turf.centroid(poly)
+ * var poly = turf.polygon([[[0,0], [0,10], [10,10] , [10,0], [0, 0]]]);
+ * var centroidPt = turf.centroid(poly);
+ *
+ * var result = turf.featurecollection([poly, centroidPt]);
+ *
+ * //=result
*/
module.exports = function(features){
var vertices = explode(features).features, |
3dd5774a998c26740e319d0b31c2364e1e75a49b | index.js | index.js | module.exports = function (App) {
if (typeof (App) == 'undefined') {
console.error('ERROR: Seminarjs not detected');
process.exit(-1);
}
try {
App.express.use('/plugins/chat/', function (req, res, next) {
if (req.method !== 'GET') {
next();
return;
}
res.sendFile(__dirname + "/public/" + req.path);
});
var Chat = require('./src/chat-server.js');
Chat(App.io);
} catch (e) {
console.error(e.getMessage());
}
}; | module.exports = function (seminarjs) {
if (typeof (seminarjs) == 'undefined') {
console.error('[ERROR] Seminarjs not detected');
process.exit(-1);
}
try {
seminarjs.app.use('/plugins/chat/', function (req, res, next) {
if (req.method !== 'GET') {
next();
return;
}
res.sendFile(__dirname + "/public/" + req.path);
});
var Chat = require('./src/chat-server.js');
Chat(seminarjs.io);
} catch (e) {
console.error(e.getMessage());
}
}; | Upgrade to new Seminarjs plugin system | Upgrade to new Seminarjs plugin system
| JavaScript | mit | Nichejs/Seminarjs-Chat | ---
+++
@@ -1,12 +1,12 @@
-module.exports = function (App) {
- if (typeof (App) == 'undefined') {
- console.error('ERROR: Seminarjs not detected');
+module.exports = function (seminarjs) {
+ if (typeof (seminarjs) == 'undefined') {
+ console.error('[ERROR] Seminarjs not detected');
process.exit(-1);
}
try {
- App.express.use('/plugins/chat/', function (req, res, next) {
+ seminarjs.app.use('/plugins/chat/', function (req, res, next) {
if (req.method !== 'GET') {
next();
return;
@@ -15,7 +15,7 @@
});
var Chat = require('./src/chat-server.js');
- Chat(App.io);
+ Chat(seminarjs.io);
} catch (e) {
console.error(e.getMessage()); |
b02d185b8fb7d4ff2d4c3be40f97fe87542db8d8 | index.js | index.js | 'use strict';
module.exports = isJsObject;
function isJsObject(obj) {
return /^\[object (?:object|global)\]$/i
.test(Object.prototype.toString.call(obj));
}
| 'use strict';
module.exports = isJsObject;
function isJsObject(obj) {
return /^\[object (?:object|global|window)\]$/i
.test(Object.prototype.toString.call(obj));
}
| Make it work in Firefox | Make it work in Firefox
Firefox returns `[object Window]` if object is window | JavaScript | isc | joaquimserafim/is-js-object | ---
+++
@@ -3,6 +3,6 @@
module.exports = isJsObject;
function isJsObject(obj) {
- return /^\[object (?:object|global)\]$/i
+ return /^\[object (?:object|global|window)\]$/i
.test(Object.prototype.toString.call(obj));
} |
6917cbf558cbe2a2ab2d602154c588c44290abb2 | index.js | index.js | var PATH_SEPARATOR = require('path').sep;
var requirejs = exports.requirejs = require('requirejs');
var getStackTrace = require('./stack-trace');
requirejs.config({baseUrl: process.cwd()});
var loadedModules = Object.create(null);
var toModuleId = PATH_SEPARATOR === '/' ?
function(fileName) { return fileName; } :
function(fileName) { return fileName.split(PATH_SEPARATOR).join('/'); };
function define() {
var fileName = getStackTrace(1, define)[0].getFileName();
if (!(loadedModules[fileName])) {
require.cache[fileName].exports = requirejs(toModuleId(fileName));
}
}
global.define = define;
| var PATH_SEPARATOR = require('path').sep;
var requirejs = exports.requirejs = require('requirejs');
var getStackTrace = require('./stack-trace');
var config = {baseUrl: process.cwd()};
var loadedModules = Object.create(null);
var toModuleId = PATH_SEPARATOR === '/' ?
function(fileName) { return fileName; } :
function(fileName) { return fileName.split(PATH_SEPARATOR).join('/'); };
function define() {
var fileName = getStackTrace(1, define)[0].getFileName();
if (!(loadedModules[fileName])) {
var module = require.cache[fileName];
config.nodeRequire = module.require.bind(module);
module.exports = requirejs.config(config)(toModuleId(fileName));
}
}
global.define = define;
| Reconfigure RequireJS with the module-local `require` for each call | Reconfigure RequireJS with the module-local `require` for each call | JavaScript | mit | davidaurelio/node-define | ---
+++
@@ -2,8 +2,7 @@
var requirejs = exports.requirejs = require('requirejs');
var getStackTrace = require('./stack-trace');
-requirejs.config({baseUrl: process.cwd()});
-
+var config = {baseUrl: process.cwd()};
var loadedModules = Object.create(null);
var toModuleId = PATH_SEPARATOR === '/' ?
@@ -13,7 +12,9 @@
function define() {
var fileName = getStackTrace(1, define)[0].getFileName();
if (!(loadedModules[fileName])) {
- require.cache[fileName].exports = requirejs(toModuleId(fileName));
+ var module = require.cache[fileName];
+ config.nodeRequire = module.require.bind(module);
+ module.exports = requirejs.config(config)(toModuleId(fileName));
}
}
|
5574187f570acc10ccc14078788b853cfadf0499 | index.js | index.js |
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
module.exports = function(fn) {
inherits(fn, EventEmitter);
var self = new fn();
self.addEventListener = function(ev, cb) {
self.on(ev,cb);
};
global.postMessage = // unfortunately global for worker (no namespaces?)
self.postMessage = function(msg) {
self.emit('message', {data:msg});
};
return self;
};
|
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
module.exports = function(fn) {
inherits(fn, EventEmitter);
fn.prototype.addEventListener = function(ev, cb) {
this.on(ev,cb);
};
var self = new fn();
global.postMessage = // unfortunately global for worker (no namespaces?)
self.postMessage = function(msg) {
self.emit('message', {data:msg});
};
return self;
};
| Move addEventListener back to prototype so webworkers can call it on themselves in constructor | Move addEventListener back to prototype so webworkers can call it on themselves in constructor
| JavaScript | mit | deathcap/unworkify | ---
+++
@@ -6,11 +6,11 @@
inherits(fn, EventEmitter);
+ fn.prototype.addEventListener = function(ev, cb) {
+ this.on(ev,cb);
+ };
+
var self = new fn();
-
- self.addEventListener = function(ev, cb) {
- self.on(ev,cb);
- };
global.postMessage = // unfortunately global for worker (no namespaces?)
self.postMessage = function(msg) { |
45a9cc5a2d330c8c89a947627566fa0cda0a6be2 | test/markup/index.js | test/markup/index.js | 'use strict';
var bluebird = require('bluebird');
var fs = bluebird.promisifyAll(require('fs'));
var glob = require('glob');
var hljs = require('../../build');
var path = require('path');
var utility = require('../utility');
function testLanguage(language) {
describe(language, function() {
var filePath = utility.buildPath('markup', language, '*.expect.txt'),
filenames = glob.sync(filePath);
filenames.forEach(function(filename) {
var testName = path.basename(filename, '.expect.txt'),
sourceName = filename.replace(/\.expect/, '');
it('should markup ' + testName, function(done) {
var sourceFile = fs.readFileAsync(sourceName, 'utf-8'),
expectedFile = fs.readFileAsync(filename, 'utf-8');
bluebird.join(sourceFile, expectedFile, function(source, expected) {
var actual = hljs.highlight(language, source).value;
actual.should.equal(expected);
done();
});
});
});
});
}
describe('markup generation test', function() {
var languages = fs.readdirSync(utility.buildPath('markup'));
languages.forEach(testLanguage);
});
| 'use strict';
var _ = require('lodash');
var bluebird = require('bluebird');
var fs = bluebird.promisifyAll(require('fs'));
var glob = require('glob');
var hljs = require('../../build');
var path = require('path');
var utility = require('../utility');
function testLanguage(language) {
describe(language, function() {
var filePath = utility.buildPath('markup', language, '*.expect.txt'),
filenames = glob.sync(filePath);
_.each(filenames, function(filename) {
var testName = path.basename(filename, '.expect.txt'),
sourceName = filename.replace(/\.expect/, '');
it('should markup ' + testName, function(done) {
var sourceFile = fs.readFileAsync(sourceName, 'utf-8'),
expectedFile = fs.readFileAsync(filename, 'utf-8');
bluebird.join(sourceFile, expectedFile, function(source, expected) {
var actual = hljs.highlight(language, source).value;
actual.should.equal(expected);
done();
});
});
});
});
}
describe('markup generation test', function() {
var languages = fs.readdirSync(utility.buildPath('markup'));
_.each(languages, testLanguage, this);
});
| Change forEach to lodash each functions | Change forEach to lodash each functions
| JavaScript | bsd-3-clause | abhishekgahlot/highlight.js,aristidesstaffieri/highlight.js,Delermando/highlight.js,yxxme/highlight.js,MakeNowJust/highlight.js,Sannis/highlight.js,STRML/highlight.js,Delermando/highlight.js,bluepichu/highlight.js,carlokok/highlight.js,liang42hao/highlight.js,teambition/highlight.js,J2TeaM/highlight.js,kayyyy/highlight.js,zachaysan/highlight.js,zachaysan/highlight.js,christoffer/highlight.js,J2TeaM/highlight.js,highlightjs/highlight.js,xing-zhi/highlight.js,adjohnson916/highlight.js,aurusov/highlight.js,lead-auth/highlight.js,robconery/highlight.js,VoldemarLeGrand/highlight.js,Ajunboys/highlight.js,CausalityLtd/highlight.js,weiyibin/highlight.js,Sannis/highlight.js,aristidesstaffieri/highlight.js,dbkaplun/highlight.js,dx285/highlight.js,lizhil/highlight.js,jean/highlight.js,isagalaev/highlight.js,christoffer/highlight.js,devmario/highlight.js,alex-zhang/highlight.js,dYale/highlight.js,VoldemarLeGrand/highlight.js,J2TeaM/highlight.js,krig/highlight.js,kba/highlight.js,tenbits/highlight.js,martijnrusschen/highlight.js,liang42hao/highlight.js,ehornbostel/highlight.js,aurusov/highlight.js,kba/highlight.js,tenbits/highlight.js,christoffer/highlight.js,krig/highlight.js,robconery/highlight.js,delebash/highlight.js,yxxme/highlight.js,SibuStephen/highlight.js,carlokok/highlight.js,snegovick/highlight.js,Sannis/highlight.js,tenbits/highlight.js,0x7fffffff/highlight.js,kba/highlight.js,devmario/highlight.js,xing-zhi/highlight.js,StanislawSwierc/highlight.js,0x7fffffff/highlight.js,ponylang/highlight.js,jean/highlight.js,bluepichu/highlight.js,daimor/highlight.js,isagalaev/highlight.js,axter/highlight.js,kevinrodbe/highlight.js,jean/highlight.js,bluepichu/highlight.js,dbkaplun/highlight.js,martijnrusschen/highlight.js,aurusov/highlight.js,carlokok/highlight.js,ilovezy/highlight.js,ehornbostel/highlight.js,snegovick/highlight.js,adam-lynch/highlight.js,SibuStephen/highlight.js,adam-lynch/highlight.js,weiyibin/highlight.js,palmin/highlight.js,dbkaplun/highlight.js,Amrit01/highlight.js,cicorias/highlight.js,STRML/highlight.js,Ankirama/highlight.js,dublebuble/highlight.js,devmario/highlight.js,dx285/highlight.js,krig/highlight.js,Ankirama/highlight.js,martijnrusschen/highlight.js,ilovezy/highlight.js,xing-zhi/highlight.js,alex-zhang/highlight.js,Amrit01/highlight.js,sourrust/highlight.js,axter/highlight.js,zachaysan/highlight.js,lizhil/highlight.js,Ankirama/highlight.js,ponylang/highlight.js,liang42hao/highlight.js,sourrust/highlight.js,1st1/highlight.js,dublebuble/highlight.js,teambition/highlight.js,0x7fffffff/highlight.js,Ajunboys/highlight.js,ponylang/highlight.js,sourrust/highlight.js,1st1/highlight.js,lizhil/highlight.js,taoger/highlight.js,robconery/highlight.js,cicorias/highlight.js,CausalityLtd/highlight.js,dYale/highlight.js,aristidesstaffieri/highlight.js,abhishekgahlot/highlight.js,abhishekgahlot/highlight.js,dublebuble/highlight.js,daimor/highlight.js,MakeNowJust/highlight.js,1st1/highlight.js,taoger/highlight.js,carlokok/highlight.js,dYale/highlight.js,alex-zhang/highlight.js,delebash/highlight.js,ilovezy/highlight.js,kevinrodbe/highlight.js,teambition/highlight.js,Delermando/highlight.js,MakeNowJust/highlight.js,VoldemarLeGrand/highlight.js,brennced/highlight.js,kayyyy/highlight.js,yxxme/highlight.js,kevinrodbe/highlight.js,kayyyy/highlight.js,ysbaddaden/highlight.js,dx285/highlight.js,daimor/highlight.js,highlightjs/highlight.js,axter/highlight.js,StanislawSwierc/highlight.js,brennced/highlight.js,adjohnson916/highlight.js,palmin/highlight.js,ehornbostel/highlight.js,highlightjs/highlight.js,taoger/highlight.js,ysbaddaden/highlight.js,palmin/highlight.js,adjohnson916/highlight.js,snegovick/highlight.js,CausalityLtd/highlight.js,weiyibin/highlight.js,highlightjs/highlight.js,ysbaddaden/highlight.js,brennced/highlight.js,STRML/highlight.js,delebash/highlight.js,cicorias/highlight.js,Amrit01/highlight.js,SibuStephen/highlight.js,adam-lynch/highlight.js,Ajunboys/highlight.js | ---
+++
@@ -1,5 +1,6 @@
'use strict';
+var _ = require('lodash');
var bluebird = require('bluebird');
var fs = bluebird.promisifyAll(require('fs'));
var glob = require('glob');
@@ -12,7 +13,7 @@
var filePath = utility.buildPath('markup', language, '*.expect.txt'),
filenames = glob.sync(filePath);
- filenames.forEach(function(filename) {
+ _.each(filenames, function(filename) {
var testName = path.basename(filename, '.expect.txt'),
sourceName = filename.replace(/\.expect/, '');
@@ -34,5 +35,5 @@
describe('markup generation test', function() {
var languages = fs.readdirSync(utility.buildPath('markup'));
- languages.forEach(testLanguage);
+ _.each(languages, testLanguage, this);
}); |
0ed90fd2f19781a5f6ea0c6fa192bf1f8ee11d61 | packages/strapi-generate-new/lib/resources/files/config/server.js | packages/strapi-generate-new/lib/resources/files/config/server.js | module.exports = ({ env }) => ({
host: env('HOST'),
port: env.int('PORT'),
});
| module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
});
| Use default host and port | Use default host and port
Signed-off-by: Alexandre Bodin <70f0c7aa1e44ecfca5832512bee3743e3471816f@gmail.com>
| JavaScript | mit | wistityhq/strapi,wistityhq/strapi | ---
+++
@@ -1,4 +1,4 @@
module.exports = ({ env }) => ({
- host: env('HOST'),
- port: env.int('PORT'),
+ host: env('HOST', '0.0.0.0'),
+ port: env.int('PORT', 1337),
}); |
196e973b703b9f1c86efd7594fab5c0cd3c6bbdd | src/assets/scripts/modern/slideout.init.js | src/assets/scripts/modern/slideout.init.js | // JavaScript Document
// Scripts written by __gulp_init__author_name @ __gulp_init__author_company
import Slideout from "slideout";
// get the elements
const PANEL = document.getElementById("page-container");
const MENU = document.getElementById("mobile-menu");
const TOGGLE = document.querySelector("[data-toggle=mobile-menu]");
// verify that the elements exist
if (PANEL !== null && MENU !== null && TOGGLE !== null) {
// initialize the menu
const MOBILE_MENU = new Slideout({
duration: 250,
menu: MENU,
panel: PANEL,
});
// toggle the menu when clicking on the toggle
TOGGLE.addEventListener("click", (e) => {
e.preventDefault();
MOBILE_MENU.toggle();
});
// close the menu when it's open and the content is clicked
PANEL.addEventListener("click", (e) => {
if (e.target !== TOGGLE && MOBILE_MENU.isOpen()) {
e.preventDefault();
MOBILE_MENU.close();
}
});
}
| // JavaScript Document
// Scripts written by __gulp_init__author_name @ __gulp_init__author_company
import Slideout from "slideout";
// get the elements
const PANEL = document.getElementById("page-container");
const MENU = document.getElementById("mobile-menu");
const TOGGLE = document.querySelector("[data-toggle=mobile-menu]");
const MOBILE_WIDTH = 768;
// verify that the elements exist
if (PANEL !== null && MENU !== null && TOGGLE !== null) {
// initialize the menu
let mobile_menu = null;
// toggle the menu when clicking on the toggle
TOGGLE.addEventListener("click", (e) => {
e.preventDefault();
if (mobile_menu !== null) {
mobile_menu.toggle();
}
});
// close the menu when it's open and the content is clicked
PANEL.addEventListener("click", (e) => {
if (mobile_menu !== null && e.target !== TOGGLE && mobile_menu.isOpen()) {
e.preventDefault();
mobile_menu.close();
}
});
const CONSTRUCT_MENU = () => {
return new Slideout({
duration: 250,
menu: MENU,
panel: PANEL,
});
};
// destroy the menu on desktop
window.addEventListener("load", () => {
if (mobile_menu === null && document.documentElement.clientWidth < MOBILE_WIDTH) {
mobile_menu = CONSTRUCT_MENU();
}
});
// destroy the menu on desktop
window.addEventListener("resize", () => {
const CLIENT_WIDTH = document.documentElement.clientWidth;
if (mobile_menu !== null && CLIENT_WIDTH >= MOBILE_WIDTH) {
mobile_menu.destroy();
mobile_menu = null;
} else if (mobile_menu === null && CLIENT_WIDTH < MOBILE_WIDTH) {
mobile_menu = CONSTRUCT_MENU();
}
});
}
| Disable the mobile menu on desktop | Disable the mobile menu on desktop
| JavaScript | mit | JacobDB/new-site,JacobDB/new-site,revxx14/new-site,JacobDB/new-site,revxx14/new-site | ---
+++
@@ -5,30 +5,57 @@
import Slideout from "slideout";
// get the elements
-const PANEL = document.getElementById("page-container");
-const MENU = document.getElementById("mobile-menu");
-const TOGGLE = document.querySelector("[data-toggle=mobile-menu]");
+const PANEL = document.getElementById("page-container");
+const MENU = document.getElementById("mobile-menu");
+const TOGGLE = document.querySelector("[data-toggle=mobile-menu]");
+const MOBILE_WIDTH = 768;
// verify that the elements exist
if (PANEL !== null && MENU !== null && TOGGLE !== null) {
// initialize the menu
- const MOBILE_MENU = new Slideout({
- duration: 250,
- menu: MENU,
- panel: PANEL,
- });
+ let mobile_menu = null;
// toggle the menu when clicking on the toggle
TOGGLE.addEventListener("click", (e) => {
e.preventDefault();
- MOBILE_MENU.toggle();
+
+ if (mobile_menu !== null) {
+ mobile_menu.toggle();
+ }
});
// close the menu when it's open and the content is clicked
PANEL.addEventListener("click", (e) => {
- if (e.target !== TOGGLE && MOBILE_MENU.isOpen()) {
+ if (mobile_menu !== null && e.target !== TOGGLE && mobile_menu.isOpen()) {
e.preventDefault();
- MOBILE_MENU.close();
+ mobile_menu.close();
+ }
+ });
+
+ const CONSTRUCT_MENU = () => {
+ return new Slideout({
+ duration: 250,
+ menu: MENU,
+ panel: PANEL,
+ });
+ };
+
+ // destroy the menu on desktop
+ window.addEventListener("load", () => {
+ if (mobile_menu === null && document.documentElement.clientWidth < MOBILE_WIDTH) {
+ mobile_menu = CONSTRUCT_MENU();
+ }
+ });
+
+ // destroy the menu on desktop
+ window.addEventListener("resize", () => {
+ const CLIENT_WIDTH = document.documentElement.clientWidth;
+
+ if (mobile_menu !== null && CLIENT_WIDTH >= MOBILE_WIDTH) {
+ mobile_menu.destroy();
+ mobile_menu = null;
+ } else if (mobile_menu === null && CLIENT_WIDTH < MOBILE_WIDTH) {
+ mobile_menu = CONSTRUCT_MENU();
}
});
} |
1ac3f864b65d93c153ec1ef112cd83f01c437845 | tests/parse-error.js | tests/parse-error.js | var test = require('tape')
var parse = require('../parser')
test('partial input', function (t) {
// These should all produce syntax errors at the end of the input
var examples = [
{ input: "echo ( this will fail", position: 5 }
]
examples.forEach(function (example) {
try {
parse(example.input)
} catch (err) {
t.equal(err.constructor, parse.SyntaxError, 'got a SyntaxError');
t.equal(example.position, err.offset);
}
})
t.end()
})
| var test = require('tape')
var parse = require('../parser')
test('partial input', function (t) {
// These should all produce syntax errors at the given position
var examples = [
{ input: "echo ( this will fail", position: 5 }
]
examples.forEach(function (example) {
t.test('SyntaxError test "' + example.input + '"', function (t) {
try {
parse(example.input)
t.fail("did not throw expected SyntaxError")
} catch (err) {
t.equal(err.constructor, parse.SyntaxError, 'threw expected SyntaxError')
t.equal(example.position, err.offset, 'SyntaxError has expected offset')
try {
parse(example.input.substr(err.offset), 'continuationStart')
t.fail('was successfully parsed as a continuationStart')
} catch (e) {
t.pass('could not parse continuationStart')
}
}
})
})
t.end()
})
| Test parse errors aren't treated as partial input | Test parse errors aren't treated as partial input | JavaScript | mit | grncdr/js-shell-parse | ---
+++
@@ -2,18 +2,28 @@
var parse = require('../parser')
test('partial input', function (t) {
- // These should all produce syntax errors at the end of the input
+ // These should all produce syntax errors at the given position
var examples = [
{ input: "echo ( this will fail", position: 5 }
]
examples.forEach(function (example) {
- try {
- parse(example.input)
- } catch (err) {
- t.equal(err.constructor, parse.SyntaxError, 'got a SyntaxError');
- t.equal(example.position, err.offset);
- }
+ t.test('SyntaxError test "' + example.input + '"', function (t) {
+ try {
+ parse(example.input)
+ t.fail("did not throw expected SyntaxError")
+ } catch (err) {
+
+ t.equal(err.constructor, parse.SyntaxError, 'threw expected SyntaxError')
+ t.equal(example.position, err.offset, 'SyntaxError has expected offset')
+ try {
+ parse(example.input.substr(err.offset), 'continuationStart')
+ t.fail('was successfully parsed as a continuationStart')
+ } catch (e) {
+ t.pass('could not parse continuationStart')
+ }
+ }
+ })
})
t.end() |
03badb0a4760b8ee40e31373c56e50777349a815 | src/workers/egress/text_message/index.js | src/workers/egress/text_message/index.js | import BaseWorker from '../../base'
import twilio from 'twilio'
import path from 'path'
const client = new twilio.RestClient(
process.env.TWILIO_SID,
process.env.TWILIO_TOKEN
)
export class TextMessage extends BaseWorker {
constructor (rsmq) {
super('text_message', rsmq)
}
body (message) {
return this.render(
path.join(__dirname, '../templates', 'plain_text.ejs'),
message
)
}
async process (message, next) {
try {
await client.sendMessage({
body: this.body(message),
to: process.env.TWILIO_TO_NUMBER,
from: process.env.TWILIO_FROM_NUMBER
})
next()
} catch (err) {
next(err)
}
}
}
export default TextMessage
| import BaseWorker from '../../base'
import twilio from 'twilio'
import path from 'path'
export class TextMessage extends BaseWorker {
constructor (rsmq) {
super('text_message', rsmq)
this.client = new twilio.RestClient(
process.env.TWILIO_SID,
process.env.TWILIO_TOKEN
)
}
body (message) {
return this.render(
path.join(__dirname, '../templates', 'plain_text.ejs'),
message
)
}
async process (message, next) {
try {
await this.client.sendMessage({
body: this.body(message),
to: process.env.TWILIO_TO_NUMBER,
from: process.env.TWILIO_FROM_NUMBER
})
next(null)
} catch (err) {
next(err)
}
}
}
export default TextMessage
| Change the way text message egress initializes | Change the way text message egress initializes
| JavaScript | mit | craftship/phonebox,craftship/phonebox,craftship/phonebox | ---
+++
@@ -2,14 +2,14 @@
import twilio from 'twilio'
import path from 'path'
-const client = new twilio.RestClient(
- process.env.TWILIO_SID,
- process.env.TWILIO_TOKEN
-)
-
export class TextMessage extends BaseWorker {
constructor (rsmq) {
super('text_message', rsmq)
+
+ this.client = new twilio.RestClient(
+ process.env.TWILIO_SID,
+ process.env.TWILIO_TOKEN
+ )
}
body (message) {
@@ -21,12 +21,12 @@
async process (message, next) {
try {
- await client.sendMessage({
+ await this.client.sendMessage({
body: this.body(message),
to: process.env.TWILIO_TO_NUMBER,
from: process.env.TWILIO_FROM_NUMBER
})
- next()
+ next(null)
} catch (err) {
next(err)
} |
e51b4152b15a75ca9b18cb6afd435926ac0b5086 | src/components/FileDetails/FileDetails.js | src/components/FileDetails/FileDetails.js | import React from 'react'
import styled from 'styled-components'
const Wrapper = styled.div`
margin-top: 2rem;
`
const Key = styled.label`
font-weight: 700;
`
const Value = styled.label`
word-break: break-all;
`
export const FileDetails = ({ file }) => {
const { name, size } = file
return (
<Wrapper>
<div>
<Key>Name: </Key>
<Value>{name}</Value>
</div>
<div>
<Key>Size: </Key>
<Value>{size} bytes</Value>
</div>
</Wrapper>
)
}
| import React from 'react'
import styled from 'styled-components'
const Wrapper = styled.dl`
margin-top: 2rem;
`
const Key = styled.dt`
font-weight: 700;
`
const Value = styled.dd`
word-break: break-all;
margin-bottom: 0.5rem;
`
export const FileDetails = ({ file }) => {
const { name, size } = file
return (
<Wrapper>
<Key>Name</Key>
<Value>{name}</Value>
<Key>Size</Key>
<Value>{size} bytes</Value>
</Wrapper>
)
}
| Use dt and dd elements for displaying file metadata | Use dt and dd elements for displaying file metadata
| JavaScript | mit | joelgeorgev/file-hash-verifier,joelgeorgev/file-hash-verifier | ---
+++
@@ -1,16 +1,17 @@
import React from 'react'
import styled from 'styled-components'
-const Wrapper = styled.div`
+const Wrapper = styled.dl`
margin-top: 2rem;
`
-const Key = styled.label`
+const Key = styled.dt`
font-weight: 700;
`
-const Value = styled.label`
+const Value = styled.dd`
word-break: break-all;
+ margin-bottom: 0.5rem;
`
export const FileDetails = ({ file }) => {
@@ -18,14 +19,10 @@
return (
<Wrapper>
- <div>
- <Key>Name: </Key>
- <Value>{name}</Value>
- </div>
- <div>
- <Key>Size: </Key>
- <Value>{size} bytes</Value>
- </div>
+ <Key>Name</Key>
+ <Value>{name}</Value>
+ <Key>Size</Key>
+ <Value>{size} bytes</Value>
</Wrapper>
)
} |
22edd37a0f8bf93f0bf1e3e86ffc8bcae9eda116 | src/js/components/TabPanel/Measurement.js | src/js/components/TabPanel/Measurement.js | import Measurement from 'esri/dijit/Measurement';
import React, {
Component,
PropTypes
} from 'react';
export default class InfoWindow extends Component {
static contextTypes = {
map: PropTypes.object.isRequired
}
initialized = false
componentWillUpdate(prevProps) {
if (
this.context.map.loaded
// the Measurement tool depends on navigationManager so we
// need to explicitly check for that before starting the widget
&& this.context.map.navigationManager
&& !this.initialized
) {
this.initialized = true;
const measurementDiv = document.createElement('DIV');
this.measurementContainer.appendChild(measurementDiv);
this.measurement = new Measurement({
map: this.context.map
}, measurementDiv);
this.measurement.startup();
this.measurement.on('measure-end', (event) => {
// deactivate the tool after drawing
const toolName = event.toolName;
this.measurement.setTool(toolName, false);
});
}
if (prevProps.activeWebmap !== undefined && prevProps.activeWebmap !== this.props.activeWebmap) {
if (this.context.map.destroy && this.initialized) {
this.measurement.destroy();
this.initialized = false;
}
}
}
componentWillUnmount() {
this.measurement.destroy();
}
render () {
return <div
ref={(div) => { this.measurementContainer = div; }}
className='measurement-container'
/>;
}
}
| import Measurement from 'esri/dijit/Measurement';
import React, {
Component,
PropTypes
} from 'react';
export default class InfoWindow extends Component {
static contextTypes = {
map: PropTypes.object.isRequired
}
initialized = false
componentWillUpdate(prevProps) {
if (
this.context.map.loaded
// the Measurement tool depends on navigationManager so we
// need to explicitly check for that before starting the widget
&& this.context.map.navigationManager
&& !this.initialized
) {
this.initialized = true;
const measurementDiv = document.createElement('DIV');
this.measurementContainer.appendChild(measurementDiv);
this.measurement = new Measurement({
map: this.context.map
}, measurementDiv);
this.measurement.startup();
this.measurement.on('measure-end', (event) => {
// deactivate the tool after drawing
const toolName = event.toolName;
this.measurement.setTool(toolName, false);
});
}
if (prevProps.activeWebmap !== undefined && prevProps.activeWebmap !== this.props.activeWebmap) {
if (this.context.map.destroy && this.initialized) {
this.measurement.clearResult();
this.initialized = false;
}
}
}
componentWillUnmount() {
this.measurement.destroy();
}
render () {
return <div
ref={(div) => { this.measurementContainer = div; }}
className='measurement-container'
/>;
}
}
| Use clearResult instead of destroy on measurement so that user's selection will clear when switching tools or when the user clicks same tool again | Use clearResult instead of destroy on measurement so that user's selection will clear when switching tools or when the user clicks same tool again
| JavaScript | mit | wri/gfw-mapbuilder,wri/gfw-mapbuilder,wri/gfw-mapbuilder | ---
+++
@@ -37,7 +37,7 @@
if (prevProps.activeWebmap !== undefined && prevProps.activeWebmap !== this.props.activeWebmap) {
if (this.context.map.destroy && this.initialized) {
- this.measurement.destroy();
+ this.measurement.clearResult();
this.initialized = false;
}
} |
f795c21c0ea556f0c050fc15b1b68520799944c1 | test/types-ext/string/string-line/enum.js | test/types-ext/string/string-line/enum.js | 'use strict';
var isError = require('es5-ext/lib/Error/is-error');
module.exports = function (t, a) {
var week = t.create('Enumweektest', {
options: ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']
});
a(week('MO'), 'MO', "Valid");
a.throws(function () { week('FOO'); }, "Invalid");
return {
"Is": function (a) {
a(week.is({ toString: function () { return 'MO'; } }), false,
"Not string");
a(week.is('TU'), true, "Option");
a(week.is('FOO'), false, "Other string");
},
"Normalize": function () {
a(week.normalize('MO'), 'MO', "Valid");
a(week.normalize('FOO'), null, "Invalid");
a(week.normalize({ toString: function () { return 'MO'; } }), 'MO',
"Coercible");
a(week.normalize({}), null, "Invalid #2");
},
"Validate": function () {
a(week.validate('MO'), null, "Valid");
a(isError(week.validate('FOO')), true, "Invalid");
a(week.validate({ toString: function () { return 'MO'; } }), null,
"Coercible");
a(isError(week.validate({})), true, "Invalid #2");
}
};
};
| 'use strict';
var isError = require('es5-ext/lib/Error/is-error');
module.exports = function (t, a) {
var week = t.create('Enumweektest',
['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']);
a(week('MO'), 'MO', "Valid");
a.throws(function () { week('FOO'); }, "Invalid");
return {
"Is": function (a) {
a(week.is({ toString: function () { return 'MO'; } }), false,
"Not string");
a(week.is('TU'), true, "Option");
a(week.is('FOO'), false, "Other string");
},
"Normalize": function () {
a(week.normalize('MO'), 'MO', "Valid");
a(week.normalize('FOO'), null, "Invalid");
a(week.normalize({ toString: function () { return 'MO'; } }), 'MO',
"Coercible");
a(week.normalize({}), null, "Invalid #2");
},
"Validate": function () {
a(week.validate('MO'), null, "Valid");
a(isError(week.validate('FOO')), true, "Invalid");
a(week.validate({ toString: function () { return 'MO'; } }), null,
"Coercible");
a(isError(week.validate({})), true, "Invalid #2");
}
};
};
| Fix tests up to recent Enum change | Fix tests up to recent Enum change
| JavaScript | mit | medikoo/dbjs | ---
+++
@@ -3,9 +3,8 @@
var isError = require('es5-ext/lib/Error/is-error');
module.exports = function (t, a) {
- var week = t.create('Enumweektest', {
- options: ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']
- });
+ var week = t.create('Enumweektest',
+ ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']);
a(week('MO'), 'MO', "Valid");
a.throws(function () { week('FOO'); }, "Invalid"); |
0543f03b58d980e06dc377ab7a6352806a680cdc | erpnext/hr/doctype/employee_separation/employee_separation_list.js | erpnext/hr/doctype/employee_separation/employee_separation_list.js | frappe.listview_settings['Employee Separation'] = {
add_fields: ["boarding_status", "employee_name", "date_of_joining", "department"],
filters:[["boarding_status","=", "Pending"]],
get_indicator: function(doc) {
return [__(doc.boarding_status), frappe.utils.guess_colour(doc.boarding_status), "status,=," + doc.boarding_status];
}
};
| frappe.listview_settings['Employee Separation'] = {
add_fields: ["boarding_status", "employee_name", "department"],
filters:[["boarding_status","=", "Pending"]],
get_indicator: function(doc) {
return [__(doc.boarding_status), frappe.utils.guess_colour(doc.boarding_status), "status,=," + doc.boarding_status];
}
};
| Remove date_of_joining from field list | fix: Remove date_of_joining from field list
| JavaScript | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext | ---
+++
@@ -1,5 +1,5 @@
frappe.listview_settings['Employee Separation'] = {
- add_fields: ["boarding_status", "employee_name", "date_of_joining", "department"],
+ add_fields: ["boarding_status", "employee_name", "department"],
filters:[["boarding_status","=", "Pending"]],
get_indicator: function(doc) {
return [__(doc.boarding_status), frappe.utils.guess_colour(doc.boarding_status), "status,=," + doc.boarding_status]; |
5b6b999e55ed669070ccb7127ebbc1560828414d | server/categories.js | server/categories.js | Meteor.publish('categories', function (name) {
return Categories.find({
name: { $regex: name }
});
});
Categories.allow({
insert: function(userId, doc){
return true;
},
update: function(userId, doc, fieldNames, modifier){
return false;
},
remove: function(userId, doc){
return true;
}
}); | Meteor.publish('categories', function (text) {
return Categories.find({
$or: [
{name: { $regex: text }},
{description: { $regex: text }}
]
});
});
Categories.allow({
insert: function(userId, doc){
return true;
},
update: function(userId, doc, fieldNames, modifier){
return false;
},
remove: function(userId, doc){
return true;
}
}); | Add description to category search | Add description to category search
| JavaScript | mit | be-ndee/notes-app,be-ndee/notes-app | ---
+++
@@ -1,6 +1,9 @@
-Meteor.publish('categories', function (name) {
+Meteor.publish('categories', function (text) {
return Categories.find({
- name: { $regex: name }
+ $or: [
+ {name: { $regex: text }},
+ {description: { $regex: text }}
+ ]
});
});
|
14373be962e1f21d5bbff2b13b0462bdb834d401 | server/routes/api.js | server/routes/api.js | import express from 'express';
import Firebase from 'firebase';
const router = express.Router();
router.post('/dump', (req, res) => {
const distance = req.body.distance;
const remoteAddress = req.body.remoteAddress;
console.log(distance, remoteAddress);
const firebase = new Firebase('https://parkviz.firebaseio.com/');
firebase.set({
remoteAddress: {
distance: distance
}
});
});
export default router;
| import express from 'express';
import Firebase from 'firebase';
const router = express.Router();
router.post('/dump', (req, res) => {
const distance = req.body.distance;
const remoteAddress = req.body.remoteAddress;
console.log(distance, remoteAddress);
const firebase = new Firebase('https://parkviz.firebaseio.com/');
let data = {};
data[remoteAddress] = { distance: distance };
firebase.set(data);
});
export default router;
| Fix node name when saving to Firebase | Fix node name when saving to Firebase
| JavaScript | mit | sbekti/parkviz,sbekti/parkviz | ---
+++
@@ -11,11 +11,10 @@
const firebase = new Firebase('https://parkviz.firebaseio.com/');
- firebase.set({
- remoteAddress: {
- distance: distance
- }
- });
+ let data = {};
+ data[remoteAddress] = { distance: distance };
+
+ firebase.set(data);
});
export default router; |
94fbca15db45fc41377c8bb31e81af75779a39c1 | src/components/mock/PartyMatchViz.js | src/components/mock/PartyMatchViz.js | import React from 'react';
export default function PartyMatchViz({partyAbbr, partyFit, partyLogo}) {
const indicatorStyle = {
backgroundImage: `url(${partyLogo})`,
};
return (<div className="dib mb3">
<a className="link dim white dib mh2 pv3 w2 h2 tc lh-copy cover bg-center" href="#" title="{partyAbbr}" style={indicatorStyle}>
</a>
<div className="tc b gray">{partyFit}</div>
</div>);
}
| import React from 'react';
export default function PartyMatchViz({partyAbbr, partyFit, partyLogo}) {
const indicatorStyle = {
backgroundImage: `url(${partyLogo})`,
};
return (<div className="dib mb3">
<a className="link dim white dib mh2 pv3 w2 h2 tc lh-copy cover bg-center" href="#" title={partyAbbr} style={indicatorStyle}>
</a>
<div className="tc b gray">{partyFit}</div>
</div>);
}
| Fix party logo mouseover text | Fix party logo mouseover text
| JavaScript | agpl-3.0 | tituomin/council-compass,tituomin/council-compass,tituomin/council-compass | ---
+++
@@ -6,7 +6,7 @@
backgroundImage: `url(${partyLogo})`,
};
return (<div className="dib mb3">
- <a className="link dim white dib mh2 pv3 w2 h2 tc lh-copy cover bg-center" href="#" title="{partyAbbr}" style={indicatorStyle}>
+ <a className="link dim white dib mh2 pv3 w2 h2 tc lh-copy cover bg-center" href="#" title={partyAbbr} style={indicatorStyle}>
</a>
<div className="tc b gray">{partyFit}</div>
</div>); |
e1115c1af7393ec5e284680c828a91d11f65bf21 | src/core/utils.js | src/core/utils.js | import _merge from 'lodash/merge'
import _template from 'lodash/template'
/**
* Send a request using axios. Designed to be used by Model and their instance
*
* @param {Object} caller Object that call this function
* @param {Object} config Axios config
* @param {Object} [options]
* @param {string} [options.on] Which route ('collection' or 'member')
* @return {Promise} Axios promise
*/
export function request (caller, config, options = {}) {
const interpolate = caller.getOption('urlParamPattern')
const params = caller.toParam()
const route = caller.getRoute(options.on)
// set variables pre request
caller._pending = true
caller._routeParams = {}
// merge default config (api) with config
config = _merge({}, caller.axios(), config)
// prepend route to url and replace variables
config.url = _template([route, config.url].join(''), { interpolate })(params)
// send request and handle responses
return caller.getGlobal('axios')(config)
.then((response) => {
caller._pending = false
return response
})
.catch((error) => {
caller._pending = false
throw error
})
}
| import _merge from 'lodash/merge'
import _template from 'lodash/template'
/**
* Send a request using axios. Designed to be used by Model and their instance
*
* @param {Object} caller Object that call this function
* @param {Object} config Axios config
* @param {Object} [options]
* @param {string} [options.on] Which route ('collection' or 'member')
* @return {Promise} Axios promise
*/
export function request (caller, config, options = {}) {
const interpolate = caller.getOption('urlParamPattern')
const params = caller.toParam()
const route = caller.getRoute(options.on)
// set variables pre request
caller._pending = true
caller._routeParams = {}
// merge default config (api) with config
config = _merge({}, caller.axios(), config)
// prepend route to url and interpolate url and baseURL
config.url = _template([route, config.url].join(''), { interpolate })(params)
config.baseURL = _template(config.baseURL, { interpolate })(params)
// send request and handle responses
return caller.getGlobal('axios')(config)
.then((response) => {
caller._pending = false
return response
})
.catch((error) => {
caller._pending = false
throw error
})
}
| Interpolate parameters in baseURL as well | Interpolate parameters in baseURL as well
| JavaScript | mit | alexandremagro/modele | ---
+++
@@ -22,8 +22,9 @@
// merge default config (api) with config
config = _merge({}, caller.axios(), config)
- // prepend route to url and replace variables
+ // prepend route to url and interpolate url and baseURL
config.url = _template([route, config.url].join(''), { interpolate })(params)
+ config.baseURL = _template(config.baseURL, { interpolate })(params)
// send request and handle responses
return caller.getGlobal('axios')(config) |
e1e1bbc6b366d441d4ef1a4cf4d6ca9996223097 | src/lib/render.js | src/lib/render.js | /**
* @copyright © 2015, Rick Wong. All rights reserved.
*/
"use strict";
var React = require("./react");
var assign = React.__spread;
/**
* @function render
*/
module.exports = function (Component, props, targetDOMNode, callback) {
var myProps = assign({}, props, window.__reactTransmitPacket || {});
React.render(React.createElement(Component, myProps), targetDOMNode, callback);
};
| /**
* @copyright © 2015, Rick Wong. All rights reserved.
*/
"use strict";
var React = require("./react");
var assign = React.__spread;
/**
* @function render
*/
module.exports = function (Component, props, targetDOMNode, callback) {
var myProps = assign({}, props, window.__reactTransmitPacket || {});
if (window.__reactTransmitPacket) {
delete window.__reactTransmitPacket;
}
React.render(React.createElement(Component, myProps), targetDOMNode, callback);
};
| Delete `window.__reactTransmitPacket` after first use. | Delete `window.__reactTransmitPacket` after first use.
| JavaScript | bsd-3-clause | brysgo/react-transmit,leonid-shevtsov/react-transmit,RickWong/react-transmit,alexeyraspopov/react-transmit,leonid-shevtsov/react-transmit,alexeyraspopov/react-transmit,RickWong/react-transmit,brysgo/react-transmit | ---
+++
@@ -12,5 +12,9 @@
module.exports = function (Component, props, targetDOMNode, callback) {
var myProps = assign({}, props, window.__reactTransmitPacket || {});
+ if (window.__reactTransmitPacket) {
+ delete window.__reactTransmitPacket;
+ }
+
React.render(React.createElement(Component, myProps), targetDOMNode, callback);
}; |
960c0f871e387c9d623606314c663b2e66259830 | test/rules/fields_have_descriptions.js | test/rules/fields_have_descriptions.js | import assert from 'assert';
import { parse } from 'graphql';
import { validate } from 'graphql/validation';
import { buildASTSchema } from 'graphql/utilities/buildASTSchema';
import { FieldsHaveDescriptions } from '../../src/rules/fields_have_descriptions';
describe('FieldsHaveDescriptions rule', () => {
it('catches fields that have no description', () => {
const ast = parse(`
type QueryRoot {
withoutDescription: String
withoutDescriptionAgain: String!
# Description
withDescription: String
}
schema {
query: QueryRoot
}
`);
const schema = buildASTSchema(ast);
const errors = validate(schema, ast, [FieldsHaveDescriptions]);
assert.equal(errors.length, 2);
assert.equal(errors[0].ruleName, 'fields-have-descriptions');
assert.equal(
errors[0].message,
'The field `QueryRoot.withoutDescription` is missing a description.'
);
assert.deepEqual(errors[0].locations, [{ line: 3, column: 9 }]);
assert.equal(errors[1].ruleName, 'fields-have-descriptions');
assert.equal(
errors[1].message,
'The field `QueryRoot.withoutDescriptionAgain` is missing a description.'
);
assert.deepEqual(errors[1].locations, [{ line: 4, column: 9 }]);
});
});
| import { FieldsHaveDescriptions } from '../../src/rules/fields_have_descriptions';
import { expectFailsRule } from '../assertions';
describe('FieldsHaveDescriptions rule', () => {
it('catches fields that have no description', () => {
expectFailsRule(
FieldsHaveDescriptions,
`
type QueryRoot {
withoutDescription: String
withoutDescriptionAgain: String!
# Description
withDescription: String
}
schema {
query: QueryRoot
}
`,
[
{
message:
'The field `QueryRoot.withoutDescription` is missing a description.',
locations: [{ line: 3, column: 9 }],
},
{
message:
'The field `QueryRoot.withoutDescriptionAgain` is missing a description.',
locations: [{ line: 4, column: 9 }],
},
]
);
});
});
| Use test helpers in FieldsHaveDescriptions tests | Use test helpers in FieldsHaveDescriptions tests
| JavaScript | mit | cjoudrey/graphql-schema-linter | ---
+++
@@ -1,13 +1,11 @@
-import assert from 'assert';
-import { parse } from 'graphql';
-import { validate } from 'graphql/validation';
-import { buildASTSchema } from 'graphql/utilities/buildASTSchema';
-
import { FieldsHaveDescriptions } from '../../src/rules/fields_have_descriptions';
+import { expectFailsRule } from '../assertions';
describe('FieldsHaveDescriptions rule', () => {
it('catches fields that have no description', () => {
- const ast = parse(`
+ expectFailsRule(
+ FieldsHaveDescriptions,
+ `
type QueryRoot {
withoutDescription: String
withoutDescriptionAgain: String!
@@ -19,25 +17,19 @@
schema {
query: QueryRoot
}
- `);
-
- const schema = buildASTSchema(ast);
- const errors = validate(schema, ast, [FieldsHaveDescriptions]);
-
- assert.equal(errors.length, 2);
-
- assert.equal(errors[0].ruleName, 'fields-have-descriptions');
- assert.equal(
- errors[0].message,
- 'The field `QueryRoot.withoutDescription` is missing a description.'
+ `,
+ [
+ {
+ message:
+ 'The field `QueryRoot.withoutDescription` is missing a description.',
+ locations: [{ line: 3, column: 9 }],
+ },
+ {
+ message:
+ 'The field `QueryRoot.withoutDescriptionAgain` is missing a description.',
+ locations: [{ line: 4, column: 9 }],
+ },
+ ]
);
- assert.deepEqual(errors[0].locations, [{ line: 3, column: 9 }]);
-
- assert.equal(errors[1].ruleName, 'fields-have-descriptions');
- assert.equal(
- errors[1].message,
- 'The field `QueryRoot.withoutDescriptionAgain` is missing a description.'
- );
- assert.deepEqual(errors[1].locations, [{ line: 4, column: 9 }]);
});
}); |
6ec64f59cfd817ab1e8724c9e4b9a1498963e27d | rollup.config.js | rollup.config.js | import buble from 'rollup-plugin-buble';
export default {
input: "src/codemirror.js",
output: {
banner: `// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// This is CodeMirror (https://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
`,
format: "umd",
file: "lib/codemirror.js",
name: "CodeMirror"
},
plugins: [ buble({namedFunctionExpressions: false}) ]
};
| import buble from 'rollup-plugin-buble';
export default {
input: "src/codemirror.js",
output: {
banner: `// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// This is CodeMirror (https://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
`,
format: "umd",
file: "lib/codemirror.js",
name: "CodeMirror"
},
plugins: [ buble({namedFunctionExpressions: false}) ]
};
| Fix trailing whitespace in build output | Fix trailing whitespace in build output
| JavaScript | mit | mtaran-google/CodeMirror,pabloferz/CodeMirror,hackmdio/CodeMirror,pabloferz/CodeMirror,dperetti/CodeMirror,pabloferz/CodeMirror,hackmdio/CodeMirror,codio/CodeMirror,namin/CodeMirror,nightwing/CodeMirror,thomasjm/CodeMirror,nightwing/CodeMirror,dperetti/CodeMirror,namin/CodeMirror,mtaran-google/CodeMirror,notepadqq/CodeMirror,wingify/CodeMirror,codio/CodeMirror,notepadqq/CodeMirror,codio/CodeMirror,nightwing/CodeMirror,notepadqq/CodeMirror,jkaplon/CodeMirror,hackmdio/CodeMirror,mtaran-google/CodeMirror,SidPresse/CodeMirror,wingify/CodeMirror,namin/CodeMirror,thomasjm/CodeMirror,thomasjm/CodeMirror,SidPresse/CodeMirror,jkaplon/CodeMirror,jkaplon/CodeMirror,SidPresse/CodeMirror,dperetti/CodeMirror,wingify/CodeMirror | ---
+++
@@ -11,7 +11,7 @@
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
- `,
+`,
format: "umd",
file: "lib/codemirror.js",
name: "CodeMirror" |
ca4c1ed33e6169a6f5462fe781e76bf58203d327 | scripts/build.js | scripts/build.js | const glob = require(`glob`);
const buildArticleHtml = require(`./build/article-html.js`);
const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const extractArticleData = require(`./lib/extract-article-data.js`);
const articleFiles = glob.sync(`resources/articles/*.md`).reverse();
const defaultData = {
css: `<link rel="stylesheet" href="/base/css/global.css">`,
articles: [],
};
articleFiles.forEach((fileName) => {
const data = JSON.parse(JSON.stringify(defaultData));
Object.assign(data, extractArticleData(fileName));
defaultData.articles.push(data);
buildArticleHtml(fileName, data);
});
buildBaseHtml(defaultData);
buildBaseCss();
| const glob = require(`glob`);
const buildArticleHtml = require(`./build/article-html.js`);
const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const extractArticleData = require(`./lib/extract-article-data.js`);
const articleFiles = glob.sync(`resources/articles/*.md`).reverse();
const defaultData = {
css: `<link rel="stylesheet" href="/base/css/global.css">`,
articles: [],
};
articleFiles.forEach((fileName) => {
const articleData = Object.assign({}, defaultData, extractArticleData(fileName));
defaultData.articles.push(articleData);
buildArticleHtml(fileName, articleData);
});
buildBaseHtml(defaultData);
buildBaseCss();
| Use Object.assign to dereference object. | Use Object.assign to dereference object.
| JavaScript | mit | maoberlehner/markus-oberlehner-net,maoberlehner/markus-oberlehner-net | ---
+++
@@ -13,11 +13,10 @@
};
articleFiles.forEach((fileName) => {
- const data = JSON.parse(JSON.stringify(defaultData));
- Object.assign(data, extractArticleData(fileName));
- defaultData.articles.push(data);
+ const articleData = Object.assign({}, defaultData, extractArticleData(fileName));
+ defaultData.articles.push(articleData);
- buildArticleHtml(fileName, data);
+ buildArticleHtml(fileName, articleData);
});
buildBaseHtml(defaultData); |
bbb7afd4468b72088eccdb0f085f010734f34c90 | scripts/build.js | scripts/build.js | const FS = require('fs');
const Child = require('child_process').execSync;
// Copy local package files
Child('npm run clean');
Child('npm run compile');
Child('npm run compile:module');
Child('npm run compile:rollup');
Child('npm run compile:rollup-browser');
Child('mkdir -p dist/npm');
Child('cp -r dist/cjs/* dist/npm/');
Child('cp dist/es/index.module.js dist/npm/module.js');
Child('cp dist/es/index-browser.module.js dist/npm/browser-module.js');
Child(`cp ${__dirname}/../*.md dist/npm`);
Child('npm run compile:webpack');
// Create package.json file
const Pkg = JSON.parse(FS.readFileSync('package.json'));
FS.writeFileSync(
'dist/npm/package.json',
JSON.stringify(
{
...Pkg,
browser: {
...Pkg.browser,
'./module.js': './browser-module.js'
},
devDependencies: undefined,
'jsnext:main': './module.js',
main: './index.js',
module: './module.js',
private: false,
scripts: undefined,
sideEffects: false,
typings: './index'
},
null,
2
)
);
// Create package bundle
Child('cd dist/npm && npm pack');
Child(`mv dist/npm/*.tgz ${__dirname}/../dist/${Pkg.name}.tgz`);
| const FS = require('fs');
const Child = require('child_process').execSync;
// Copy local package files
Child('npm run clean');
Child('npm run compile');
Child('npm run compile:module');
Child('npm run compile:rollup');
Child('npm run compile:rollup-browser');
Child('mkdir dist/npm');
Child('cp -r dist/cjs/* dist/npm/');
Child('cp dist/es/index.module.js dist/npm/module.js');
Child('cp dist/es/index-browser.module.js dist/npm/browser-module.js');
Child(`cp ${__dirname}/../*.md dist/npm`);
Child('npm run compile:webpack');
// Create package.json file
const Pkg = JSON.parse(FS.readFileSync('package.json'));
FS.writeFileSync(
'dist/npm/package.json',
JSON.stringify(
{
...Pkg,
browser: {
...Pkg.browser,
'./module.js': './browser-module.js'
},
devDependencies: undefined,
'jsnext:main': './module.js',
main: './index.js',
module: './module.js',
private: false,
scripts: undefined,
sideEffects: false,
typings: './index'
},
null,
2
)
);
// Create package bundle
Child('cd dist/npm && npm pack');
Child(`mv dist/npm/*.tgz ${__dirname}/../dist/${Pkg.name}.tgz`);
| Remove unneeded -p from mkdir call | Remove unneeded -p from mkdir call
| JavaScript | mit | otalk/stanza.io,legastero/stanza.io,otalk/stanza.io,legastero/stanza.io | ---
+++
@@ -7,7 +7,7 @@
Child('npm run compile:module');
Child('npm run compile:rollup');
Child('npm run compile:rollup-browser');
-Child('mkdir -p dist/npm');
+Child('mkdir dist/npm');
Child('cp -r dist/cjs/* dist/npm/');
Child('cp dist/es/index.module.js dist/npm/module.js');
Child('cp dist/es/index-browser.module.js dist/npm/browser-module.js'); |
acc391181995a16dcac3d5df0a0579b220726ab6 | src/modes/command/client/commands/misc.js | src/modes/command/client/commands/misc.js | export function toggleHelpMenu () {
// TODO
}
export function toggleSaka () {
try {
browser.runtime.sendMessage(
'nbdfpcokndmapcollfpjdpjlabnibjdi',
'toggleSaka'
)
} catch (e) {
console.error(
'Install Saka at https://chrome.google.com/webstore/detail/saka/nbdfpcokndmapcollfpjdpjlabnibjdi'
)
}
}
export function passOneKey (event) {
// preventDefault() to suppress keypress event
// no way to suppress keyup event, so Pass mode must ignore
// first keyup event
event.preventDefault()
event.passKeyType = 'one'
return 'Pass'
}
export function passAllKeys (event) {
event.preventDefault()
event.passKeyType = 'all'
return 'Pass'
}
| export function toggleHelpMenu () {
// TODO
}
export function toggleSaka () {
try {
const extensionId =
SAKA_PLATFORM === 'chrome'
? 'nbdfpcokndmapcollfpjdpjlabnibjdi'
: '{7d7cad35-2182-4457-972d-5a41a2051240}'
console.log('ID: ', extensionId)
browser.runtime.sendMessage(extensionId, 'toggleSaka')
} catch (e) {
console.error(
'Install Saka at https://chrome.google.com/webstore/detail/saka/nbdfpcokndmapcollfpjdpjlabnibjdi'
)
}
}
export function passOneKey (event) {
// preventDefault() to suppress keypress event
// no way to suppress keyup event, so Pass mode must ignore
// first keyup event
event.preventDefault()
event.passKeyType = 'one'
return 'Pass'
}
export function passAllKeys (event) {
event.preventDefault()
event.passKeyType = 'all'
return 'Pass'
}
| Fix for opening Saka in chrome and firefox | Fix for opening Saka in chrome and firefox
| JavaScript | mit | lusakasa/saka-key,lusakasa/saka-key | ---
+++
@@ -4,10 +4,12 @@
export function toggleSaka () {
try {
- browser.runtime.sendMessage(
- 'nbdfpcokndmapcollfpjdpjlabnibjdi',
- 'toggleSaka'
- )
+ const extensionId =
+ SAKA_PLATFORM === 'chrome'
+ ? 'nbdfpcokndmapcollfpjdpjlabnibjdi'
+ : '{7d7cad35-2182-4457-972d-5a41a2051240}'
+ console.log('ID: ', extensionId)
+ browser.runtime.sendMessage(extensionId, 'toggleSaka')
} catch (e) {
console.error(
'Install Saka at https://chrome.google.com/webstore/detail/saka/nbdfpcokndmapcollfpjdpjlabnibjdi' |
41f89690312be521a90db8fd092eb619b883bf9c | sections/faqs/when-to-use-attrs.js | sections/faqs/when-to-use-attrs.js | import md from 'components/md'
const WhenToUseAttrs = () => md`
## When to use attrs?
You can pass in attributes to styled components using [attrs](/docs/basics#attaching-additional-props), but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled
component to have that prop, and pass props directly when every instance needs a
different one:
\`\`\`js
const PasswordInput = styled.input.attrs({
// Every <PasswordInput /> should be type="password"
type: 'password'
})\`\`
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
`
export default WhenToUseAttrs
| import md from 'components/md'
const WhenToUseAttrs = () => md`
## When to use attrs?
You can pass in attributes to styled components using [attrs](/docs/basics#attaching-additional-props), but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled
component to have that prop, and pass props directly when every instance needs a
different one:
\`\`\`js
const PasswordInput = styled.input.attrs({
// Every <PasswordInput /> should be type="password"
type: 'password'
})\`\`
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
The same goes for props that can be inferred based on the "mode" of another prop.
In this case you can set a property on \`attrs\` to a function that computes
that prop based on other props.
`
export default WhenToUseAttrs
| Add a paragraph on computed props | Add a paragraph on computed props
| JavaScript | mit | styled-components/styled-components-website,styled-components/styled-components-website | ---
+++
@@ -19,6 +19,10 @@
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
+
+ The same goes for props that can be inferred based on the "mode" of another prop.
+ In this case you can set a property on \`attrs\` to a function that computes
+ that prop based on other props.
`
export default WhenToUseAttrs |
d4d728b18295cc91e1059681b5791fb2fcebcd8f | src/notebook/api/messaging/kernel-info.js | src/notebook/api/messaging/kernel-info.js | import {
createMessage,
} from '../api/messaging';
// Usage, assuming using Fluorine
// dispatch(executeCell(id,source)(channels))
export default function kernelInfo(channels) {
if (!channels || !channels.shell) {
throw new Error('shell channel not available for sending kernel info request');
}
const { shell } = channels;
const message = createMessage('kernel_info_request');
return shell
.childOf(message)
.map(msg => msg.content)
.first()
.toPromse();
}
| import {
createMessage,
} from '../api/messaging';
export default function kernelInfo(channels) {
if (!channels || !channels.shell) {
throw new Error('shell channel not available for sending kernel info request');
}
const { shell } = channels;
const message = createMessage('kernel_info_request');
return shell
.childOf(message)
.map(msg => msg.content)
.first()
.toPromse();
}
| Move copy pasta'ed comment out. | Move copy pasta'ed comment out.
| JavaScript | bsd-3-clause | nteract/nteract,jdetle/nteract,jdetle/nteract,temogen/nteract,rgbkrk/nteract,0u812/nteract,jdfreder/nteract,jdfreder/nteract,0u812/nteract,nteract/composition,captainsafia/nteract,rgbkrk/nteract,rgbkrk/nteract,temogen/nteract,jdetle/nteract,nteract/nteract,captainsafia/nteract,nteract/nteract,0u812/nteract,jdfreder/nteract,captainsafia/nteract,jdetle/nteract,jdfreder/nteract,nteract/composition,0u812/nteract,nteract/nteract,captainsafia/nteract,temogen/nteract,nteract/nteract,rgbkrk/nteract,nteract/composition,rgbkrk/nteract | ---
+++
@@ -1,9 +1,6 @@
import {
createMessage,
} from '../api/messaging';
-
-// Usage, assuming using Fluorine
-// dispatch(executeCell(id,source)(channels))
export default function kernelInfo(channels) {
if (!channels || !channels.shell) { |
37e8345dc86778b29c75352ad68e4e4fa6902d66 | doc/source/_static/docversions.js | doc/source/_static/docversions.js | function insert_version_links() {
var labels = ['dev', '0.7', '0.6', '0.5', '0.4', '0.3'];
for (i = 0; i < labels.length; i++){
open_list = '<li>'
if (typeof(DOCUMENTATION_OPTIONS) !== 'undefined') {
if ((DOCUMENTATION_OPTIONS['VERSION'] == labels[i]) ||
(DOCUMENTATION_OPTIONS['VERSION'].match(/dev$/) && (i == 0))) {
open_list = '<li id="current">'
}
}
document.write(open_list);
document.write('<a href="URL">skimage VERSION</a> </li>\n'
.replace('VERSION', labels[i])
.replace('URL', 'http://skimage.org/docs/' + labels[i]));
}
}
| function insert_version_links() {
var labels = ['dev', '0.7.0', '0.6', '0.5', '0.4', '0.3'];
for (i = 0; i < labels.length; i++){
open_list = '<li>'
if (typeof(DOCUMENTATION_OPTIONS) !== 'undefined') {
if ((DOCUMENTATION_OPTIONS['VERSION'] == labels[i]) ||
(DOCUMENTATION_OPTIONS['VERSION'].match(/dev$/) && (i == 0))) {
open_list = '<li id="current">'
}
}
document.write(open_list);
document.write('<a href="URL">skimage VERSION</a> </li>\n'
.replace('VERSION', labels[i])
.replace('URL', 'http://skimage.org/docs/' + labels[i]));
}
}
| Fix doc version 0.7 link | Fix doc version 0.7 link
| JavaScript | bsd-3-clause | vighneshbirodkar/scikit-image,bsipocz/scikit-image,almarklein/scikit-image,Midafi/scikit-image,GaZ3ll3/scikit-image,WarrenWeckesser/scikits-image,dpshelio/scikit-image,jwiggins/scikit-image,rjeli/scikit-image,dpshelio/scikit-image,juliusbierk/scikit-image,newville/scikit-image,chriscrosscutler/scikit-image,jwiggins/scikit-image,emon10005/scikit-image,SamHames/scikit-image,bsipocz/scikit-image,oew1v07/scikit-image,robintw/scikit-image,keflavich/scikit-image,chintak/scikit-image,pratapvardhan/scikit-image,SamHames/scikit-image,bennlich/scikit-image,robintw/scikit-image,juliusbierk/scikit-image,ofgulban/scikit-image,michaelpacer/scikit-image,youprofit/scikit-image,ofgulban/scikit-image,chintak/scikit-image,warmspringwinds/scikit-image,Hiyorimi/scikit-image,chriscrosscutler/scikit-image,michaelaye/scikit-image,paalge/scikit-image,bennlich/scikit-image,michaelaye/scikit-image,Hiyorimi/scikit-image,almarklein/scikit-image,SamHames/scikit-image,blink1073/scikit-image,paalge/scikit-image,chintak/scikit-image,almarklein/scikit-image,ajaybhat/scikit-image,newville/scikit-image,rjeli/scikit-image,ajaybhat/scikit-image,Britefury/scikit-image,SamHames/scikit-image,chintak/scikit-image,pratapvardhan/scikit-image,rjeli/scikit-image,youprofit/scikit-image,GaZ3ll3/scikit-image,Britefury/scikit-image,michaelpacer/scikit-image,vighneshbirodkar/scikit-image,almarklein/scikit-image,blink1073/scikit-image,vighneshbirodkar/scikit-image,warmspringwinds/scikit-image,ClinicalGraphics/scikit-image,ClinicalGraphics/scikit-image,oew1v07/scikit-image,paalge/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,keflavich/scikit-image,Midafi/scikit-image,emon10005/scikit-image | ---
+++
@@ -1,5 +1,5 @@
function insert_version_links() {
- var labels = ['dev', '0.7', '0.6', '0.5', '0.4', '0.3'];
+ var labels = ['dev', '0.7.0', '0.6', '0.5', '0.4', '0.3'];
for (i = 0; i < labels.length; i++){
open_list = '<li>' |
f95e961379088dcb5883bb29ff879bce50f6ed3f | src/targets/chrome/get-browser-globals.js | src/targets/chrome/get-browser-globals.js | const { JSDOM } = require('jsdom');
function getBrowserGlobals(html) {
const dom = new JSDOM(html);
const { window } = dom;
const noop = function noop() {};
const EventSource = noop;
const navigator = {
userAgent: 'loki',
};
let localStorageData = {};
const localStorage = {
setItem(id, val) {
localStorageData[id] = String(val);
},
getItem(id) {
return localStorageData[id] ? localStorageData[id] : undefined;
},
removeItem(id) {
delete localStorageData[id];
},
clear() {
localStorageData = {};
},
};
const matchMedia = () => ({ matches: true });
window.EventSource = EventSource;
const globals = Object.assign({}, window, {
navigator,
localStorage,
matchMedia,
EventSource,
setInterval: noop,
console: {
log: noop,
warn: noop,
error: noop,
},
});
globals.global = globals;
return globals;
}
module.exports = getBrowserGlobals;
| const { JSDOM } = require('jsdom');
function getBrowserGlobals(html) {
const dom = new JSDOM(html);
const { window } = dom;
const noop = function noop() {};
const EventSource = noop;
const navigator = {
userAgent: 'loki',
};
let localStorageData = {};
const localStorage = {
setItem(id, val) {
localStorageData[id] = String(val);
},
getItem(id) {
return localStorageData[id] ? localStorageData[id] : undefined;
},
removeItem(id) {
delete localStorageData[id];
},
clear() {
localStorageData = {};
},
};
const matchMedia = () => ({ matches: true });
const globals = Object.assign({}, window, {
navigator,
localStorage,
matchMedia,
EventSource,
requestAnimationFrame: noop,
requestIdleCallback: noop,
console: {
log: noop,
warn: noop,
error: noop,
},
});
globals.window = globals;
globals.global = globals;
return globals;
}
module.exports = getBrowserGlobals;
| Add rAF and rIC to jsdom browser globals | Add rAF and rIC to jsdom browser globals
| JavaScript | mit | oblador/loki,oblador/loki,oblador/loki | ---
+++
@@ -29,20 +29,20 @@
const matchMedia = () => ({ matches: true });
- window.EventSource = EventSource;
-
const globals = Object.assign({}, window, {
navigator,
localStorage,
matchMedia,
EventSource,
- setInterval: noop,
+ requestAnimationFrame: noop,
+ requestIdleCallback: noop,
console: {
log: noop,
warn: noop,
error: noop,
},
});
+ globals.window = globals;
globals.global = globals;
return globals; |
d9c85070000c05c3237eb4ed93aaea3a254fed2e | source/Button.js | source/Button.js | /**
_moon.Button_ is an <a href="#enyo.Button">enyo.Button</a> with Moonstone
styling applied. The color of the button may be customized by specifying a
background color.
For more information, see the documentation on
<a href='https://github.com/enyojs/enyo/wiki/Buttons'>Buttons</a> in the
Enyo Developer Guide.
*/
enyo.kind({
name : 'moon.Button',
kind : 'enyo.Button',
classes : 'moon-button enyo-unselectable',
spotlight : true,
handlers: {
onSpotlightSelect : 'depress',
onSpotlightKeyUp : 'undepress'
},
depress: function() {
this.addClass('pressed');
},
undepress: function() {
this.removeClass('pressed');
}
}); | /**
_moon.Button_ is an <a href="#enyo.Button">enyo.Button</a> with Moonstone
styling applied. The color of the button may be customized by specifying a
background color.
For more information, see the documentation on
<a href='https://github.com/enyojs/enyo/wiki/Buttons'>Buttons</a> in the
Enyo Developer Guide.
*/
enyo.kind({
name : 'moon.Button',
kind : 'enyo.Button',
publiched : {
small : false,
},
classes : 'moon-button enyo-unselectable',
spotlight : true,
handlers: {
onSpotlightSelect : 'depress',
onSpotlightKeyUp : 'undepress'
},
depress: function() {
this.addClass('pressed');
},
undepress: function() {
this.removeClass('pressed');
},
smallChanged: function() {
this.addRemoveClass(this.small, 'small');
}
}); | Add small property and changed method | GF-5039: Add small property and changed method
Enyo-DCO-1.1-Signed-off-by: David Um <david.um@lge.com>
| JavaScript | apache-2.0 | mcanthony/moonstone,enyojs/moonstone,mcanthony/moonstone,mcanthony/moonstone | ---
+++
@@ -11,6 +11,9 @@
enyo.kind({
name : 'moon.Button',
kind : 'enyo.Button',
+ publiched : {
+ small : false,
+ },
classes : 'moon-button enyo-unselectable',
spotlight : true,
@@ -25,5 +28,9 @@
undepress: function() {
this.removeClass('pressed');
+ },
+
+ smallChanged: function() {
+ this.addRemoveClass(this.small, 'small');
}
}); |
93997bcd8207d567131327f4b773bd108e99ddb0 | week-9/dom-manipulation/home_page.js | week-9/dom-manipulation/home_page.js | // DOM Manipulation Challenge
// I worked on this challenge [by myself, with: ].
// Add your JavaScript calls to this page:
// Release 0:
// Release 1:
// Release 2:
// Release 3:
// Release 4:
// Release 5:
| // DOM Manipulation Challenge
// I worked on this challenge [by myself, with: ].
// Add your JavaScript calls to this page:
// Release 0:
// Release 1:
document.getElementById("release-0").className = 'done';
// Release 2:
document.getElementById("release-1").style.display = "none";
// Release 3:
var h1 = document.getElementsByTagName("h1")[0].innerHTML = "I completed Release 2";
// Release 4:
document.getElementById("release-3").style.backgroundColor = "#955251";
// Release 5:
var release_4 = document.getElementsByClassName("release-4");
for (var i; i < release_4.length; i++) {
release_4[i].style.fontSize = "2em";
}
// Relase 6:
var hidden = document.getElementById("hidden");
document.body.appendChild(hidden.content.cloneNode(true)); | Complete first pass of dom-manipulation | Complete first pass of dom-manipulation
| JavaScript | mit | dma315/phase-0,dma315/phase-0,dma315/phase-0 | ---
+++
@@ -10,26 +10,34 @@
-
// Release 1:
-
+document.getElementById("release-0").className = 'done';
// Release 2:
-
+document.getElementById("release-1").style.display = "none";
// Release 3:
-
+var h1 = document.getElementsByTagName("h1")[0].innerHTML = "I completed Release 2";
// Release 4:
-
+document.getElementById("release-3").style.backgroundColor = "#955251";
// Release 5:
+var release_4 = document.getElementsByClassName("release-4");
+for (var i; i < release_4.length; i++) {
+ release_4[i].style.fontSize = "2em";
+}
+
+// Relase 6:
+
+var hidden = document.getElementById("hidden");
+document.body.appendChild(hidden.content.cloneNode(true)); |
65277619b53bf29abbc21a971094695d547e7998 | ui/client/test/ProcessAttachments-test.js | ui/client/test/ProcessAttachments-test.js | import React from 'react';
import Enzyme, {mount} from 'enzyme';
import {ProcessAttachments} from '../components/ProcessAttachments'; //import redux-independent component
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
jest.mock('../containers/theme');
describe("ProcessAttachments suite", () => {
it("should render with no problems", () => {
Enzyme.configure({ adapter: new Adapter() });
//given
const attachments = [processAttachment(3), processAttachment(2), processAttachment(1)]
const processId = "proc1"
const processVersionId = 1
//when
const mountedProcessAttachments = mount(
<ProcessAttachments attachments={attachments} processId={processId} processVersionId={processVersionId} t={key => key}/>
)
//then
expect(mountedProcessAttachments.find('.download-attachment').length).toBe(3)
})
const processAttachment = (id) => {
return {
id: `${id}`,
processId: "proc1",
processVersionId: 1,
createDate: "2016-10-10T12:39:44.092",
user: "TouK",
fileName: `file ${id}`
}
}
});
| import React from 'react';
import Enzyme, {mount} from 'enzyme';
import {ProcessAttachments} from '../components/ProcessAttachments'; //import redux-independent component
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
jest.mock('../containers/theme');
describe("ProcessAttachments suite", () => {
it("should render with no problems", () => {
Enzyme.configure({ adapter: new Adapter() });
//given
const attachments = [processAttachment(3), processAttachment(2), processAttachment(1)]
const processId = "proc1"
const processVersionId = 1
//when
const mountedProcessAttachments = mount(
<ProcessAttachments attachments={attachments} processId={processId} processVersionId={processVersionId} t={key => key} capabilities={{write: true}}/>
)
//then
expect(mountedProcessAttachments.find('.download-attachment').length).toBe(3)
})
const processAttachment = (id) => {
return {
id: `${id}`,
processId: "proc1",
processVersionId: 1,
createDate: "2016-10-10T12:39:44.092",
user: "TouK",
fileName: `file ${id}`
}
}
});
| Fix for: comments and attachments adding only available for user with write permission - test fix | Fix for: comments and attachments adding only available for user with write permission - test fix
| JavaScript | apache-2.0 | TouK/nussknacker,TouK/nussknacker,TouK/nussknacker,TouK/nussknacker,TouK/nussknacker | ---
+++
@@ -16,7 +16,7 @@
//when
const mountedProcessAttachments = mount(
- <ProcessAttachments attachments={attachments} processId={processId} processVersionId={processVersionId} t={key => key}/>
+ <ProcessAttachments attachments={attachments} processId={processId} processVersionId={processVersionId} t={key => key} capabilities={{write: true}}/>
)
//then
expect(mountedProcessAttachments.find('.download-attachment').length).toBe(3) |
08e2f7143b556f8d635b4936373f7bd63d20b84c | samples/extensions/function.js | samples/extensions/function.js | /* global assert */
module.exports = function(runner, options) {
var called = {};
runner.on('setup', function (next) {
console.log('called "setup"');
called.setup = true;
next(null);
});
runner.on('new client', function (client, next) {
console.log('called "new client"');
called.newClient = true;
next(null);
});
runner.on('report', function (failures, next) {
console.log('called "report"');
called.report = true;
next(null, []);
});
runner.on('done', function (failures, next) {
console.log('called "done"');
assert(called.setup, 'should have called "setup" event');
assert(called.newClient, 'should have called "new client" event');
assert(called.report, 'should have called "report" event');
console.log('did call all events');
});
};
| /* global assert */
module.exports = function(runner, options) {
var called = {};
runner.on('setup', function (next) {
console.log('called "setup"');
called.setup = true;
next(null);
});
runner.on('new client', function (client, next) {
console.log('called "new client"');
called.newClient = true;
next(null);
});
runner.on('report', function (failures, next) {
console.log('called "report"');
called.report = true;
next(null, []);
});
runner.on('done', function (failures, next) {
console.log('called "done"');
assert(called.setup, 'should have called "setup" event');
assert(called.newClient, 'should have called "new client" event');
assert(called.report, 'should have called "report" event');
console.log('did call all events');
next();
});
};
| Fix sample event listener should call next | Fix sample event listener should call next
| JavaScript | mit | themouette/screenstory | ---
+++
@@ -23,5 +23,6 @@
assert(called.newClient, 'should have called "new client" event');
assert(called.report, 'should have called "report" event');
console.log('did call all events');
+ next();
});
}; |
7a93df93348c83a6c759d0af136e3d415382172a | src/types/bundled.js | src/types/bundled.js | import PropTypes from 'proptypes'
export default {
any: {
options: {
of: PropTypes.array.isRequired
},
parse(options, typeBuilders, schema) {
const containsTypes = options.of.map(typeDef => {
const typeBuilder = typeBuilders[typeDef.type]
if (!typeBuilder) {
throw new Error(`Invalid type: ${typeDef.type}.`)
}
return typeBuilder(typeDef, typeBuilders, schema)
})
return {of: containsTypes}
}
},
reference: {
primitive: 'string',
options: {
title: PropTypes.string,
to: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array
]).isRequired
},
parse(options, typeBuilders, schema) {
const toTypeDefs = Array.isArray(options.to) ? options.to : [options.to]
const toTypes = toTypeDefs.map(typeDef => {
const typeBuilder = typeBuilders[typeDef.type]
return typeBuilder(typeDef, typeBuilders, schema)
})
return {to: toTypes}
}
},
text: {
primitive: 'string',
options: {
title: PropTypes.string,
format: PropTypes.oneOf(['markdown', 'html', 'plain']),
maxLength: PropTypes.number
},
defaultOptions: {
format: 'plain'
}
}
}
| import PropTypes from 'proptypes'
export default {
any: {
options: {
of: PropTypes.array.isRequired
},
parse(options, typeBuilders, schema) {
const containsTypes = options.of.map(typeDef => {
const typeBuilder = typeBuilders[typeDef.type]
if (!typeBuilder) {
throw new Error(`Invalid type: ${typeDef.type}.`)
}
return typeBuilder(typeDef, typeBuilders, schema)
})
return {of: containsTypes}
}
},
reference: {
primitive: 'string',
options: {
title: PropTypes.string,
to: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array
]).isRequired
},
parse(options, typeBuilders, schema) {
const toTypeDefs = Array.isArray(options.to) ? options.to : [options.to]
const toTypes = toTypeDefs.map(typeDef => {
const typeBuilder = typeBuilders[typeDef.type]
if (!typeBuilder) {
throw new Error(
`Missing type builder for ${typeDef.type}. Did you forget to declare the type "${typeDef.type}" in the schema?`
)
}
return typeBuilder(typeDef, typeBuilders, schema)
})
return {to: toTypes}
}
},
text: {
primitive: 'string',
options: {
title: PropTypes.string,
format: PropTypes.oneOf(['markdown', 'html', 'plain']),
maxLength: PropTypes.number
},
defaultOptions: {
format: 'plain'
}
}
}
| Improve error message when encountering missing type builders | Improve error message when encountering missing type builders
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -29,6 +29,11 @@
const toTypeDefs = Array.isArray(options.to) ? options.to : [options.to]
const toTypes = toTypeDefs.map(typeDef => {
const typeBuilder = typeBuilders[typeDef.type]
+ if (!typeBuilder) {
+ throw new Error(
+ `Missing type builder for ${typeDef.type}. Did you forget to declare the type "${typeDef.type}" in the schema?`
+ )
+ }
return typeBuilder(typeDef, typeBuilders, schema)
})
return {to: toTypes} |
146901051de2547abf2d450c4ab49a201daf782b | SFcomicViewer.user.js | SFcomicViewer.user.js | // ==UserScript==
// @name SFcomic Viewer
// @namespace
// @version 0.2.1
// @description Auto load comic picture.
// @author AntonioTsai
// @match http://comic.sfacg.com/*
// @include http://comic.sfacg.com/*
// @grant none
// @downloadURL https://github.com/AntonioTsai/SFcomic-Viewer/raw/master/SFcomicViewer.user.js
// ==/UserScript==
(() => {
var imgtable = document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0];
var tempTr = document.createElement("tr");
var imgs = document.createElement("img");
tempTr.appendChild(document.createElement("td"));
tempTr.children[0].appendChild(imgs);
// remove original image
var tr = document.querySelector("tr");
tr.parentElement.removeChild(tr);
// generate all images
for (var i = 0; i < picCount; i++) {
var imgTr = tempTr.cloneNode(true);
imgTr.appendChild(document.createElement("img"));
imgTr.children[0].children[0].src = picAy[i];
imgtable.appendChild(imgTr);
}
})();
| // ==UserScript==
// @name SFcomic Viewer
// @namespace
// @version 0.2.1
// @description Auto load comic picture.
// @author AntonioTsai
// @match http://comic.sfacg.com/*
// @include http://comic.sfacg.com/*
// @grant none
// @downloadURL https://github.com/AntonioTsai/SFcomic-Viewer/raw/master/SFcomicViewer.user.js
// ==/UserScript==
/**
* picAy: The array store all image's url of the volume
* hosts: The array store possible host
* getHost(): Get the current host index
*/
(() => {
var imgtable = document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0];
var tempTr = document.createElement("tr");
var imgs = document.createElement("img");
tempTr.appendChild(document.createElement("td"));
tempTr.children[0].appendChild(imgs);
// remove original image
var tr = document.querySelector("tr");
tr.parentElement.removeChild(tr);
// generate all images
for (var i = 0; i < picCount; i++) {
var imgTr = tempTr.cloneNode(true);
imgTr.appendChild(document.createElement("img"));
imgTr.children[0].children[0].src = picAy[i];
imgtable.appendChild(imgTr);
}
})();
| Add comment how to use variable from the site | Add comment how to use variable from the site
| JavaScript | mit | AntonioTsai/SFcomic-Viewer | ---
+++
@@ -11,6 +11,11 @@
// ==/UserScript==
+/**
+ * picAy: The array store all image's url of the volume
+ * hosts: The array store possible host
+ * getHost(): Get the current host index
+ */
(() => {
var imgtable = document.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0];
var tempTr = document.createElement("tr"); |
3ec62bf0d143829d417e6f451ab88256551ee3a1 | app/javascript/app/components/ghg-emissions/ghg-emissions-actions.js | app/javascript/app/components/ghg-emissions/ghg-emissions-actions.js | import { createAction } from 'redux-actions';
import { createThunkAction } from 'utils/redux';
import qs from 'query-string';
const fetchGhgEmissionsInit = createAction('fetchGhgEmissionsInit');
const fetchGhgEmissionsFail = createAction('fetchGhgEmissionsFail');
const fetchGhgEmissionsDataReady = createAction('fetchGhgEmissionsDataReady');
const fetchGhgEmissionsData = createThunkAction(
'fetchGhgEmissionsData',
filters => dispatch => {
dispatch(fetchGhgEmissionsInit());
fetch(`/api/v1/emissions?${qs.stringify(filters)}`)
.then(response => {
if (response.ok) return response.json();
throw Error(response.statusText);
})
.then(data => {
dispatch(fetchGhgEmissionsDataReady(data));
})
.catch(error => {
console.warn(error);
dispatch(fetchGhgEmissionsFail());
});
}
);
export default {
fetchGhgEmissionsInit,
fetchGhgEmissionsFail,
fetchGhgEmissionsData,
fetchGhgEmissionsDataReady
};
| import { createAction } from 'redux-actions';
import { createThunkAction } from 'utils/redux';
import qs from 'query-string';
const fetchGhgEmissionsInit = createAction('fetchGhgEmissionsInit');
const fetchGhgEmissionsFail = createAction('fetchGhgEmissionsFail');
const fetchGhgEmissionsDataReady = createAction('fetchGhgEmissionsDataReady');
const fetchGhgEmissionsData = createThunkAction(
'fetchGhgEmissionsData',
filters => dispatch => {
dispatch(fetchGhgEmissionsInit());
fetch(`/api/v1/emissions?${qs.stringify(filters)}`)
.then(response => {
if (response.ok) return response.json();
throw Error(response.statusText);
})
.then(data => {
const parsedData = data.map(d => ({
...d,
gas: d.gas.trim(),
sector: d.sector.trim(),
location: d.location.trim()
}));
dispatch(fetchGhgEmissionsDataReady(parsedData));
})
.catch(error => {
console.warn(error);
dispatch(fetchGhgEmissionsFail());
});
}
);
export default {
fetchGhgEmissionsInit,
fetchGhgEmissionsFail,
fetchGhgEmissionsData,
fetchGhgEmissionsDataReady
};
| Trim fetch data to remove errors with extra spaces in data | Trim fetch data to remove errors with extra spaces in data
| JavaScript | mit | Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch | ---
+++
@@ -16,7 +16,13 @@
throw Error(response.statusText);
})
.then(data => {
- dispatch(fetchGhgEmissionsDataReady(data));
+ const parsedData = data.map(d => ({
+ ...d,
+ gas: d.gas.trim(),
+ sector: d.sector.trim(),
+ location: d.location.trim()
+ }));
+ dispatch(fetchGhgEmissionsDataReady(parsedData));
})
.catch(error => {
console.warn(error); |
838ebb7e7194a27ebb8b9d63211903b741b67938 | js/widgets/con10t_search_query.js | js/widgets/con10t_search_query.js | 'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
attrs.$observe('con10tSearchFacet', function(value) {
scope.fq = value;
updateHref();
});
function updateHref() {
var href = "http://arachne.dainst.org/search?q=" + scope.q;
if (scope.fq) {
var fqs = scope.fq.split(',');
fqs.forEach(function(fq) {
var split = fq.split(':');
href += '&fq='+split[0]+':"'+split[1]+'"';
});
}
element.attr("href", href);
}
}
}}); | 'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
attrs.$observe('con10tSearchFacet', function(value) {
scope.fq = value;
updateHref();
});
function updateHref() {
var href = "http://arachne.dainst.org/search?q=" + scope.q;
if (scope.fq) {
var split, fqs = scope.fq.split(',');
fqs.forEach(function(fq) {
split = fq.split(':');
href += '&fq='+split[0]+':"'+split[1]+'"';
});
}
element.attr("href", href);
}
}
}}); | Move variable declaration out of loop. | Move variable declaration out of loop.
| JavaScript | apache-2.0 | dainst/arachnefrontend,codarchlab/arachnefrontend,codarchlab/arachnefrontend,dainst/arachnefrontend | ---
+++
@@ -20,9 +20,9 @@
function updateHref() {
var href = "http://arachne.dainst.org/search?q=" + scope.q;
if (scope.fq) {
- var fqs = scope.fq.split(',');
+ var split, fqs = scope.fq.split(',');
fqs.forEach(function(fq) {
- var split = fq.split(':');
+ split = fq.split(':');
href += '&fq='+split[0]+':"'+split[1]+'"';
});
} |
39be5efe238d9f02172de94f5b2341d4f6c268b1 | tour/js/script.js | tour/js/script.js | introJs()
.start()
.onexit(function() {
window.location = "../../newtab/newtab.html";
})
.oncomplete(function() {
window.location = "../../newtab/newtab.html";
});
| introJs()
.start()
.onchange(function(targetElement) {
switch(this._currentStep) {
case 1:
break;
case 2:
break;
default:
break;
}
})
.onexit(function() {
window.location = "../../newtab/newtab.html";
})
.oncomplete(function() {
window.location = "../../newtab/newtab.html";
});
| Make framework for running JS between steps | Make framework for running JS between steps
| JavaScript | mit | matankb/one-main-thing,matankb/one-main-thing | ---
+++
@@ -1,5 +1,15 @@
introJs()
.start()
+ .onchange(function(targetElement) {
+ switch(this._currentStep) {
+ case 1:
+ break;
+ case 2:
+ break;
+ default:
+ break;
+ }
+ })
.onexit(function() {
window.location = "../../newtab/newtab.html";
}) |
883d9150ff88580088c4e9309ce757e1ae644a48 | app/models/invoice.js | app/models/invoice.js | var Invoice = DS.Model.extend({
tax: DS.attr('number'),
invoice_number: DS.attr('number', {default: new Date()}),
issued: DS.attr('date'),
items: DS.hasMany('InvoiceItem', {inverse: 'invoice'}),
customer: DS.belongsTo('Company'),
issuer: DS.belongsTo('Company'),
sub_total: function(){
return this.get('items').getEach('total').reduce(function(sum, partial) {
return sum + partial;
}, 0);
}.property("items.@each.total"),
tax_total: function(){
return this.get("sub_total")/100.0*this.get("tax");
}.property("sub_total"),
total: function(){
return this.get("sub_total")+this.get("tax_total");
}.property("sub_total", "tax_total")
});
export default Invoice;
| var Invoice = DS.Model.extend({
tax: DS.attr('number'),
invoice_number: DS.attr('number', {default: new Date()}),
issued: DS.attr('date'),
items: DS.hasMany('InvoiceItem', {inverse: 'invoice'}),
customer: DS.belongsTo('Company'),
issuer: DS.belongsTo('Company'),
sub_total: function(){
return this.get('items').getEach('total').reduce(function(sum, partial) {
return sum + partial;
}, 0);
}.property("items.@each.total"),
tax_total: function(){
return this.get("sub_total")/100.0*this.get("tax");
}.property("sub_total", "tax"),
total: function(){
return this.get("sub_total")+this.get("tax_total");
}.property("sub_total", "tax_total")
});
export default Invoice;
| Add tax to tax_total property in Invoice model | Add tax to tax_total property in Invoice model
| JavaScript | mit | dierbro/ember-invoice | ---
+++
@@ -15,7 +15,7 @@
tax_total: function(){
return this.get("sub_total")/100.0*this.get("tax");
- }.property("sub_total"),
+ }.property("sub_total", "tax"),
total: function(){
return this.get("sub_total")+this.get("tax_total"); |
6bf5b70bac76062aebe35c1951a23590710f902c | app/scripts/ripple.js | app/scripts/ripple.js | (function () {
document.addEventListener('mousedown', function (event) {
if (event.target && event.target.className.indexOf('ripple') !== -1) {
let $div = document.createElement('div'),
btnRect = event.target.getBoundingClientRect(),
height = event.target.clientHeight,
xPos = event.pageX - (btnRect.left + window.pageXOffset),
yPos = event.pageY - (btnRect.top + window.pageYOffset);
$div.className = 'ripple-effect';
$div.style.height = `${height}px`;
//noinspection JSSuspiciousNameCombination
$div.style.width = `${height}px`;
$div.style.top = `${yPos - (height / 2)}px`;
$div.style.left = `${xPos - (height / 2)}px`;
event.target.appendChild($div);
window.setTimeout(() => event.target.removeChild($div), 2000);
}
});
})();
| (function () {
document.addEventListener('mousedown', function (event) {
if (event.target &&
event.target.className &&
event.target.className.indexOf &&
event.target.className.indexOf('ripple') !== -1) {
let $div = document.createElement('div'),
btnRect = event.target.getBoundingClientRect(),
height = event.target.clientHeight,
xPos = event.pageX - (btnRect.left + window.pageXOffset),
yPos = event.pageY - (btnRect.top + window.pageYOffset);
$div.className = 'ripple-effect';
$div.style.height = `${height}px`;
//noinspection JSSuspiciousNameCombination
$div.style.width = `${height}px`;
$div.style.top = `${yPos - (height / 2)}px`;
$div.style.left = `${xPos - (height / 2)}px`;
event.target.appendChild($div);
window.setTimeout(() => event.target.removeChild($div), 2000);
}
});
})();
| Fix for error when clicking on browser market share pie charts | Fix for error when clicking on browser market share pie charts
| JavaScript | mit | NOtherDev/whatwebcando,NOtherDev/whatwebcando,NOtherDev/whatwebcando | ---
+++
@@ -1,7 +1,10 @@
(function () {
document.addEventListener('mousedown', function (event) {
- if (event.target && event.target.className.indexOf('ripple') !== -1) {
+ if (event.target &&
+ event.target.className &&
+ event.target.className.indexOf &&
+ event.target.className.indexOf('ripple') !== -1) {
let $div = document.createElement('div'),
btnRect = event.target.getBoundingClientRect(),
height = event.target.clientHeight, |
ef4183056f83a74e7a5b1d1ec3b7e84cf1db1016 | webpack.config.js | webpack.config.js | "use strict";
const webpack = require("webpack");
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
context: path.resolve("./src"),
entry: {
vendor: [ "jquery" ],
nm: [ "./nm/index.js", "./nm/resource/index.less" ]
},
output: {
path: path.resolve("./assets"),
publicPath: "/assets",
filename: "[name]/bundle.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
}
]
},
plugins: [
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery"
}),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
filename: "vendor.js",
minChunks: Infinity
}),
new ExtractTextPlugin("./[name]/resource/bundle.css")
],
devServer:
{
proxy: {
"/api/*": {
target: "http://music.163.com/",
host: "music.163.com",
secure: false
}
}
}
};
| "use strict";
const webpack = require("webpack");
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
context: path.resolve("./src"),
entry: {
vendor: [ "jquery" ],
nm: [ "./nm/index.js", "./nm/resource/index.less" ]
},
output: {
path: path.resolve("./assets"),
publicPath: "/assets",
filename: "[name]/bundle.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
}
]
},
plugins: [
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery"
}),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
filename: "vendor.js",
minChunks: Infinity
}),
new ExtractTextPlugin("./[name]/resource/bundle.css")
],
devServer:
{
proxy: {
"/api/*": {
target: "http://music.163.com/",
host: "music.163.com",
secure: false,
headers: {
"Referer": "http://music.163.com"
}
}
}
}
};
| Add Referer to proxy server. | Add Referer to proxy server.
| JavaScript | mit | dongrenguang/netease-music-juke-box,dongrenguang/netease-music-juke-box | ---
+++
@@ -51,7 +51,10 @@
"/api/*": {
target: "http://music.163.com/",
host: "music.163.com",
- secure: false
+ secure: false,
+ headers: {
+ "Referer": "http://music.163.com"
+ }
}
}
} |
587f270587a96a7c57dd63e356ab77c7f53050b6 | webpack.config.js | webpack.config.js | var webpack = require('webpack');
var path = require('path');
module.exports = {
context: __dirname + "/app",
entry: "./index.js",
output: {
path: __dirname + '/bin',
publicPath: "/",
filename: 'bundle.js',
},
stats: {
colors: true,
progress: true,
},
resolve: {
extensions: ['', '.webpack.js', '.js'],
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
query: {
presets: ['es2015'],
},
loader: 'babel',
},
],
},
};
| var webpack = require('webpack');
var path = require('path');
module.exports = {
context: __dirname + '/app',
entry: './index.js',
output: {
path: __dirname + '/bin',
publicPath: '/',
filename: 'bundle.js',
},
stats: {
colors: true,
progress: true,
},
resolve: {
extensions: ['', '.webpack.js', '.js'],
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
query: {
presets: ['es2015'],
},
loader: 'babel',
},
],
},
};
| Update web pack to using spaces | Update web pack to using spaces
| JavaScript | mit | oliverbenns/pong,oliverbenns/pong | ---
+++
@@ -2,34 +2,34 @@
var path = require('path');
module.exports = {
- context: __dirname + "/app",
- entry: "./index.js",
+ context: __dirname + '/app',
+ entry: './index.js',
- output: {
- path: __dirname + '/bin',
- publicPath: "/",
- filename: 'bundle.js',
- },
+ output: {
+ path: __dirname + '/bin',
+ publicPath: '/',
+ filename: 'bundle.js',
+ },
- stats: {
- colors: true,
- progress: true,
- },
+ stats: {
+ colors: true,
+ progress: true,
+ },
- resolve: {
- extensions: ['', '.webpack.js', '.js'],
- },
+ resolve: {
+ extensions: ['', '.webpack.js', '.js'],
+ },
- module: {
- loaders: [
- {
- test: /\.js$/,
- exclude: /node_modules/,
- query: {
- presets: ['es2015'],
- },
- loader: 'babel',
- },
- ],
- },
+ module: {
+ loaders: [
+ {
+ test: /\.js$/,
+ exclude: /node_modules/,
+ query: {
+ presets: ['es2015'],
+ },
+ loader: 'babel',
+ },
+ ],
+ },
}; |
0dfb53801e15e2c1458b12948fa58fd68226169d | webpack.config.js | webpack.config.js | var webpack = require('webpack');
module.exports = {
entry: {
app: './src/js/app.jsx',
vendors: ['react', 'react-dom', 'react-router', 'redux', 'redux-thunk', 'es6-promise-polyfill']
},
output: {
path: './public/js/',
publicPath: '/js/',
filename: 'app.js'
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loaders: ['eslint']
}
],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: '/node_modules/',
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true
})
]
};
| var webpack = require('webpack');
module.exports = {
entry: {
app: './src/js/app.jsx',
vendors: ['react', 'react-dom', 'react-router', 'redux', 'redux-thunk', 'es6-promise-polyfill']
},
output: {
path: './public/js/',
publicPath: '/js/',
filename: 'app.js'
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loaders: ['eslint']
}
],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: '/node_modules/',
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './public'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true
})
]
};
| Set public folder as the content base for webpack dev server | Set public folder as the content base for webpack dev server
| JavaScript | mit | Crevax/Charon,Crevax/Charon | ---
+++
@@ -33,7 +33,8 @@
extensions: ['', '.js', '.jsx']
},
devServer: {
- historyApiFallback: true
+ historyApiFallback: true,
+ contentBase: './public'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'), |
600c6ef9bae8b99e9c973cd69e1c6654463206d8 | app/assets/javascripts/tolk/application.js | app/assets/javascripts/tolk/application.js | //= require tolk/prototype.js
//= require tolk/controls.js
//= require tolk/dragdrop.js
//= require tolk/effects.js
| //= require tolk/prototype.js
//= require tolk/effects.js
//= require tolk/controls.js
//= require tolk/dragdrop.js
| Reorder assets to remove a js warning | Reorder assets to remove a js warning
| JavaScript | mit | joe-bader/tolk,rdunlop/tolk,MyMedsAndMe/tolk,tolk/tolk,munirent/tolk,munirent/tolk,rdunlop/tolk,tolk/tolk,rdunlop/tolk,joe-bader/tolk,MyMedsAndMe/tolk,MyMedsAndMe/tolk,tolk/tolk | ---
+++
@@ -1,4 +1,4 @@
//= require tolk/prototype.js
+//= require tolk/effects.js
//= require tolk/controls.js
//= require tolk/dragdrop.js
-//= require tolk/effects.js |
92cf4c6e1cb942eae7b1909d7cf7fc1e9f99770e | bin/programBuiider.js | bin/programBuiider.js | "use strict";
var program = require('commander');
var path = require('path');
var os = require('os');
var appDir = path.resolve(os.tmpDir(), 'cartridge');
var newCommand = require('./commands/new')(appDir);
var pkg = require(path.resolve(__dirname, '..', 'package.json'));
module.exports = function() {
setProgramBaseSettings();
setNewCommand();
initProgram();
}
function setNewCommand() {
program
.command('new')
.description('Create a new project')
.action(function() {
newCommand.init(getProgramOptions());
});
}
function initProgram() {
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}
}
function getProgramOptions() {
return {
silent: program.silent,
verbose: program.verbose
}
}
function setProgramBaseSettings() {
program
.version(pkg.version)
.option('-s, --silent', 'Surpress all on-screen messages')
.option('-v, --verbose', 'Show all on-screen messages');
}
| "use strict";
var program = require('commander');
var path = require('path');
var os = require('os');
var appDir = path.resolve(os.tmpDir(), 'cartridge');
var newCommand = require('./commands/new')(appDir);
var pkg = require(path.resolve(__dirname, '..', 'package.json'));
/**
* Get the ball-rolling for the whole program
*/
module.exports = function() {
setProgramBaseSettings();
setNewCommand();
initProgram();
}
/**
* Setup the 'new' command
*/
function setNewCommand() {
program
.command('new')
.description('Create a new project')
.action(function() {
newCommand.init(getProgramOptions());
});
}
/**
* Initialise program
*/
function initProgram() {
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}
}
/**
* Get program option flags
*/
function getProgramOptions() {
return {
silent: program.silent,
verbose: program.verbose
}
}
/**
* Set program base settings: version, option flags
*/
function setProgramBaseSettings() {
program
.version(pkg.version)
.option('-s, --silent', 'Surpress all on-screen messages')
.option('-v, --verbose', 'Show all on-screen messages');
}
| Add doc comments for program builder | docs: Add doc comments for program builder
| JavaScript | mit | code-computerlove/slate-cli,cartridge/cartridge-cli,code-computerlove/quarry | ---
+++
@@ -8,12 +8,18 @@
var newCommand = require('./commands/new')(appDir);
var pkg = require(path.resolve(__dirname, '..', 'package.json'));
+/**
+ * Get the ball-rolling for the whole program
+ */
module.exports = function() {
setProgramBaseSettings();
setNewCommand();
initProgram();
}
+/**
+ * Setup the 'new' command
+ */
function setNewCommand() {
program
.command('new')
@@ -23,6 +29,9 @@
});
}
+/**
+ * Initialise program
+ */
function initProgram() {
program.parse(process.argv);
@@ -31,6 +40,9 @@
}
}
+/**
+ * Get program option flags
+ */
function getProgramOptions() {
return {
silent: program.silent,
@@ -38,6 +50,9 @@
}
}
+/**
+ * Set program base settings: version, option flags
+ */
function setProgramBaseSettings() {
program
.version(pkg.version) |
5fcc7e0276755354d656754763ed72a58668b667 | examples/animation/app.js | examples/animation/app.js | const animationPage = require('./animation');
const peoplePage = require('./people');
const trayPage = require('./tray');
const {Button, NavigationView, Page, ui} = require('tabris');
const MARGIN = 8;
let navigationView = new NavigationView({
left: 0, top: 0, right: 0, bottom: 0
}).appendTo(ui.contentView);
let mainPage = new Page({
title: 'Animation Examples'
}).appendTo(navigationView);
[animationPage, peoplePage, trayPage].forEach((page) => {
new Button({
left: MARGIN, top: ['prev()', MARGIN],
text: page.title
}).on('select', () => page.appendTo(navigationView))
.appendTo(mainPage);
});
| const animationPage = require('./animation');
const peoplePage = require('./people');
const trayPage = require('./tray');
const {Button, NavigationView, Page, ui} = require('tabris');
let navigationView = new NavigationView({
left: 0, top: 0, right: 0, bottom: 0
}).appendTo(ui.contentView);
let mainPage = new Page({
title: 'Animation Examples'
}).appendTo(navigationView);
[animationPage, peoplePage, trayPage].forEach((page) => {
new Button({
left: 8, top: 'prev() 8', right: 8,
text: page.title
}).on('select', () => page.appendTo(navigationView))
.appendTo(mainPage);
});
| Improve layout of animation example index page | Improve layout of animation example index page
Make buttons full-width to make them easier to tap. Inline MARGIN
constants, since extracting sizes to constants in snippets and examples
may be introducing unnecessary complexity and making layout harder to
understand.
Change-Id: I05faec4e7bcc132dfbc5926eb3026af764581f9c
| JavaScript | bsd-3-clause | eclipsesource/tabris-js,eclipsesource/tabris-js,eclipsesource/tabris-js | ---
+++
@@ -2,8 +2,6 @@
const peoplePage = require('./people');
const trayPage = require('./tray');
const {Button, NavigationView, Page, ui} = require('tabris');
-
-const MARGIN = 8;
let navigationView = new NavigationView({
left: 0, top: 0, right: 0, bottom: 0
@@ -15,7 +13,7 @@
[animationPage, peoplePage, trayPage].forEach((page) => {
new Button({
- left: MARGIN, top: ['prev()', MARGIN],
+ left: 8, top: 'prev() 8', right: 8,
text: page.title
}).on('select', () => page.appendTo(navigationView))
.appendTo(mainPage); |
c0b708e8ee9e9bff3d04d89530a2b85c6c1a1f19 | src/components/Banner/index.js | src/components/Banner/index.js | import React from 'react';
import Banner from './Banner';
import { Link } from 'react-router';
export default () => (
<Banner>
<Banner.Element background='green'>BETA</Banner.Element>
<Banner.Element background='blue'>
<a
style={{ color: '#fff' }}
href={`mailto:${FEEDBACK_EMAIL}?subject=Tiedonohjaus-palaute`}
>
Anna palautetta
</a>
</Banner.Element>
<Banner.Element background='#ddd'>
<Link to='/info'>Tietoa palvelusta</Link>
</Banner.Element>
</Banner>
);
| import React from 'react';
import Banner from './Banner';
import { Link } from 'react-router';
export default () => (
<Banner>
<Banner.Element background='green'>BETA</Banner.Element>
<Banner.Element background='blue'>
<a
style={{ color: '#fff' }}
href={`mailto:${FEEDBACK_EMAIL}?subject=Tiedonohjaus-palaute`}
>
Anna palautetta
</a>
</Banner.Element>
<Banner.Element background='#ddd'>
<Link to='/info' target='_blank' rel='noopener norefer'>
Tietoa palvelusta
</Link>
</Banner.Element>
</Banner>
);
| Add target='_blank' to the info page link in the banner | Add target='_blank' to the info page link in the banner
| JavaScript | mit | City-of-Helsinki/helerm-ui,City-of-Helsinki/helerm-ui,City-of-Helsinki/helerm-ui | ---
+++
@@ -14,7 +14,9 @@
</a>
</Banner.Element>
<Banner.Element background='#ddd'>
- <Link to='/info'>Tietoa palvelusta</Link>
+ <Link to='/info' target='_blank' rel='noopener norefer'>
+ Tietoa palvelusta
+ </Link>
</Banner.Element>
</Banner>
); |
10956319bf96e6c3dafdcd736acdfa0609722982 | webpack.config.development.js | webpack.config.development.js | 'use strict';
var webpack = require('webpack');
var config = require('./webpack.config.base.js');
if (process.env.NODE_ENV !== 'test') {
config.entry = [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/dev-server'
].concat(config.entry);
}
config.devtool = 'cheap-module-eval-source-map';
config.plugins = config.plugins.concat([
new webpack.HotModuleReplacementPlugin()
]);
config.module.loaders = config.module.loaders.concat([
{test: /\.jsx?$/, loaders: [ 'react-hot', 'babel'], exclude: /node_modules/}
]);
module.exports = config;
| 'use strict';
var webpack = require('webpack');
var config = require('./webpack.config.base.js');
if (process.env.NODE_ENV !== 'test') {
config.entry = [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/dev-server'
].concat(config.entry);
}
config.devtool = '#cheap-module-eval-source-map';
config.plugins = config.plugins.concat([
new webpack.HotModuleReplacementPlugin()
]);
config.module.loaders = config.module.loaders.concat([
{test: /\.jsx?$/, loaders: [ 'react-hot', 'babel'], exclude: /node_modules/}
]);
module.exports = config;
| Update webpack dev config to fix sourcemap warning | Update webpack dev config to fix sourcemap warning
See this: https://github.com/webpack/webpack/issues/91 | JavaScript | mit | srn/react-webpack-boilerplate,srn/react-webpack-boilerplate | ---
+++
@@ -10,7 +10,7 @@
].concat(config.entry);
}
-config.devtool = 'cheap-module-eval-source-map';
+config.devtool = '#cheap-module-eval-source-map';
config.plugins = config.plugins.concat([
new webpack.HotModuleReplacementPlugin() |
f4d799725b97d135ad84b3b8811bf1e11376068f | packages/landing-scripts/scripts/start.js | packages/landing-scripts/scripts/start.js | process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
const WebpackServe = require('webpack-serve');
const config = require('../config/webpack.config.base');
function createDevServer() {
return WebpackServe({
config,
});
}
createDevServer();
| process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
const WebpackServe = require('webpack-serve');
const config = require('../config/webpack.config.dev');
function createDevServer() {
return WebpackServe({
config,
port: 3000,
});
}
createDevServer();
| Set port to dev server | Set port to dev server
| JavaScript | mit | kevindantas/create-landing-page,kevindantas/create-landing-page,kevindantas/create-landing-page | ---
+++
@@ -2,11 +2,12 @@
process.env.NODE_ENV = 'development';
const WebpackServe = require('webpack-serve');
-const config = require('../config/webpack.config.base');
+const config = require('../config/webpack.config.dev');
function createDevServer() {
return WebpackServe({
config,
+ port: 3000,
});
}
|
f353ea703751986bcade8ba211380b8a5eee8536 | modules/core/www/assets/js/loginuserpass.js | modules/core/www/assets/js/loginuserpass.js | document.addEventListener(
'DOMContentLoaded',
function () {
var button = document.getElementById("submit_button");
button.addEventListener(
'click',
function () {
var translation = document.getElementById("processing_trans");
this.disabled = true;
this.innerHTML = translation.value;
}
);
}
);
| document.addEventListener(
'DOMContentLoaded',
function () {
var button = document.getElementById("submit_button");
button.addEventListener(
'click',
function () {
var translation = document.getElementById("processing_trans");
this.disabled = true;
this.innerHTML = translation.value;
return true;
}
);
}
);
| Fix form submit-button for Chrome | Fix form submit-button for Chrome
| JavaScript | lgpl-2.1 | dnmvisser/simplesamlphp,ghalse/simplesamlphp,dnmvisser/simplesamlphp,simplesamlphp/simplesamlphp,ghalse/simplesamlphp,ghalse/simplesamlphp,dnmvisser/simplesamlphp,simplesamlphp/simplesamlphp,simplesamlphp/simplesamlphp,dnmvisser/simplesamlphp,simplesamlphp/simplesamlphp,ghalse/simplesamlphp | ---
+++
@@ -8,6 +8,7 @@
var translation = document.getElementById("processing_trans");
this.disabled = true;
this.innerHTML = translation.value;
+ return true;
}
);
} |
e6ab90e52d1605bf24e68835cf82d4a0e4d95ab4 | Resources/Public/Error/Exception.js | Resources/Public/Error/Exception.js | let backtrace = document.querySelector(".Flow-Debug-Exception-Backtrace-Code");
let localStorageItemIdentifier = 'Flow-Debug-Exception-Backtrace-Code-Open';
if (window.localStorage.getItem(localStorageItemIdentifier) === "true") {
backtrace.open = true;
}
backtrace.addEventListener("click", (event) => {
if (backtrace.open === true) {
window.localStorage.removeItem(localStorageItemIdentifier);
} else {
window.localStorage.setItem(localStorageItemIdentifier, true);
}
}); | const backtrace = document.querySelector(".Flow-Debug-Exception-Backtrace-Code");
const localStorageItemIdentifier = 'Flow-Debug-Exception-Backtrace-Code-Open';
if (window.localStorage.getItem(localStorageItemIdentifier) === "true") {
backtrace.open = true;
}
backtrace.addEventListener("click", (event) => {
if (backtrace.open === true) {
window.localStorage.removeItem(localStorageItemIdentifier);
} else {
window.localStorage.setItem(localStorageItemIdentifier, true);
}
});
| Change JS variables to constants | Change JS variables to constants
| JavaScript | mit | neos/flow,neos/flow,neos/flow,neos/flow | ---
+++
@@ -1,5 +1,5 @@
-let backtrace = document.querySelector(".Flow-Debug-Exception-Backtrace-Code");
-let localStorageItemIdentifier = 'Flow-Debug-Exception-Backtrace-Code-Open';
+const backtrace = document.querySelector(".Flow-Debug-Exception-Backtrace-Code");
+const localStorageItemIdentifier = 'Flow-Debug-Exception-Backtrace-Code-Open';
if (window.localStorage.getItem(localStorageItemIdentifier) === "true") {
backtrace.open = true; |
fc857c74d2fe8ce384157b46fb1c78b685e7dcc0 | src/components/form-radio-group/form-radio-group.config.js | src/components/form-radio-group/form-radio-group.config.js | module.exports = {
title: 'Form radio group',
status: 'wip',
context: {
setup: {
initScript: 'var $blockLabels = $(".gv-c-form-custom input[type=\'radio\'], .gv-c-form-custom input[type=\'checkbox\']"); new GOVUK.SelectionButtons($blockLabels);',
openWrapper: '<form>',
closeWrapper: '</form>'
},
id: 'contact',
name: 'contact-group',
legend: 'How do you want to be contacted?',
hint: '',
error: '',
radioGroup: [{
id: 'example-contact-by-email',
value: 'contact-by-email',
label: 'Email'
}, {
id: 'example-contact-by-phone',
value: 'contact-by-phone',
label: 'Phone'
}, {
id: 'example-contact-by-text',
value: 'contact-by-text',
label: 'Text'
}]
},
variants: [{
name: 'has hint',
context: {
hint: 'Hint text in here'
}
},
{
name: 'has error',
context: {
error: 'Error text in here'
}
},
{
name: 'has hint and error',
context: {
hint: 'Hint text in here',
error: 'Error text in here'
}
}],
arguments: ['id', 'name', 'legend', 'hint', 'error', 'radioGroup']
}
| module.exports = {
title: 'Form radio group',
status: 'wip',
context: {
setup: {
initScript: 'var $blockLabels = $(".gv-c-form-custom input[type=\'radio\']"); new GOVUK.SelectionButtons($blockLabels);',
openWrapper: '<form>',
closeWrapper: '</form>'
},
id: 'contact',
name: 'contact-group',
legend: 'How do you want to be contacted?',
hint: '',
error: '',
radioGroup: [{
id: 'example-contact-by-email',
value: 'contact-by-email',
label: 'Email'
}, {
id: 'example-contact-by-phone',
value: 'contact-by-phone',
label: 'Phone'
}, {
id: 'example-contact-by-text',
value: 'contact-by-text',
label: 'Text'
}]
},
variants: [{
name: 'has hint',
context: {
hint: 'Hint text in here'
}
},
{
name: 'has error',
context: {
error: 'Error text in here'
}
},
{
name: 'has hint and error',
context: {
hint: 'Hint text in here',
error: 'Error text in here'
}
}],
arguments: ['id', 'name', 'legend', 'hint', 'error', 'radioGroup']
}
| Update the init script for the checkbox component | Update the init script for the checkbox component
| JavaScript | mit | alphagov/govuk_frontend_alpha,alphagov/govuk_frontend_alpha,alphagov/govuk_frontend_alpha | ---
+++
@@ -3,7 +3,7 @@
status: 'wip',
context: {
setup: {
- initScript: 'var $blockLabels = $(".gv-c-form-custom input[type=\'radio\'], .gv-c-form-custom input[type=\'checkbox\']"); new GOVUK.SelectionButtons($blockLabels);',
+ initScript: 'var $blockLabels = $(".gv-c-form-custom input[type=\'radio\']"); new GOVUK.SelectionButtons($blockLabels);',
openWrapper: '<form>',
closeWrapper: '</form>'
}, |
6ead56f0cc7c82d7ecab9a41a0e36d2502005e57 | actions/norm-names.js | actions/norm-names.js | registerAction(function (node) {
if (!settings["fixNames"]) return;
node = node || document.body;
toArray(node.querySelectorAll(".content > .l_profile, .lbody > .l_profile, .name > .l_profile, .foaf > .l_profile"))
.forEach(function (node) {
var login = node.getAttribute("href").substr(1);
if (node.innerHTML != login) {
node.dataset["displayName"] = node.innerHTML;
node.innerHTML = login;
}
});
// В попапе показываем оригинальное имя
toArray(node.querySelectorAll("#popup .name > .l_profile"))
.forEach(function (node) {
node.innerHTML = node.dataset["displayName"];
});
});
| registerAction(function (node) {
if (!settings["fixNames"]) return;
node = node || document.body;
toArray(node.querySelectorAll(".content > .l_profile, .lbody > .l_profile, .name > .l_profile, .foaf > .l_profile"))
.forEach(function (node) {
var login = node.getAttribute("href").substr(1);
if (node.innerHTML != login) {
node.dataset["displayName"] = node.innerHTML;
node.innerHTML = login;
}
});
// В попапе показываем оригинальное имя
toArray(node.querySelectorAll("#popup .name > .l_profile"))
.forEach(function (node) {
var sn = node.dataset["displayName"];
if (sn !== undefined) node.innerHTML = node.dataset["displayName"];
});
});
| FIX Неправильно обрабатывались юзеры без дисплейнейма | FIX Неправильно обрабатывались юзеры без дисплейнейма
| JavaScript | mit | davidmz/friendfeed-and-co,davidmz/friendfeed-and-co | ---
+++
@@ -14,6 +14,7 @@
// В попапе показываем оригинальное имя
toArray(node.querySelectorAll("#popup .name > .l_profile"))
.forEach(function (node) {
- node.innerHTML = node.dataset["displayName"];
+ var sn = node.dataset["displayName"];
+ if (sn !== undefined) node.innerHTML = node.dataset["displayName"];
});
}); |
dffc8f86258e42c3e98609457f382a5e9b191e4b | app/web/shipitfile.js | app/web/shipitfile.js | module.exports = function (shipit) {
require('shipit-deploy')(shipit);
shipit.initConfig({
default: {
workspace: 'tmp',
deployTo: '/var/api/abcdef',
deployTo: '/var/www/fussball-react',
repositoryUrl: 'git@github.com:sping/abcd-electronic-fussball.git',
keepReleases: 10,
deleteOnRollback: false,
shallowClone: false
},
staging: {
branch: 'develop',
servers: 'root@adleman.servers.sping.nl'
},
production: {
branch: 'master',
servers: 'root@adleman.servers.sping.nl'
}
});
shipit.blTask('build', function() {
return shipit.local('cd tmp/app/web && npm install && npm run build');
});
shipit.on('fetched', function () {
return shipit.start('build');
});
};
| module.exports = function (shipit) {
require('shipit-deploy')(shipit);
shipit.initConfig({
default: {
workspace: 'tmp',
dirToCopy: 'app/web/build',
deployTo: '/var/www/abcdef-frontend',
repositoryUrl: 'git@github.com:sping/abcd-electronic-fussball.git',
keepReleases: 10,
deleteOnRollback: false,
shallowClone: false
},
staging: {
branch: 'develop',
servers: 'root@adleman.servers.sping.nl'
},
production: {
branch: 'master',
servers: 'root@adleman.servers.sping.nl'
}
});
shipit.blTask('build', function() {
return shipit.local('cd tmp/app/web && npm install && npm run build');
});
shipit.on('fetched', function () {
return shipit.start('build');
});
};
| Add the correct folder for deploy. | Add the correct folder for deploy.
| JavaScript | mit | sping/abcd-epic-fussball,sping/abcd-epic-fussball,sping/abcd-epic-fussball | ---
+++
@@ -4,8 +4,8 @@
shipit.initConfig({
default: {
workspace: 'tmp',
- deployTo: '/var/api/abcdef',
- deployTo: '/var/www/fussball-react',
+ dirToCopy: 'app/web/build',
+ deployTo: '/var/www/abcdef-frontend',
repositoryUrl: 'git@github.com:sping/abcd-electronic-fussball.git',
keepReleases: 10,
deleteOnRollback: false, |
3e1e12ba28b69e94ea876b12ca0c5dbb53188879 | config/environment.js | config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
environment: environment,
baseURL: '/dashboard',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// LOG_MODULE_RESOLVER is needed for pre-1.6.0
// ENV.LOG_MODULE_RESOLVER = true;
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_MODULE_RESOLVER = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV.WEBSITE_API_URL = "http://int-dev.withregard.io:3001";
ENV.WEBSITE_DATASTORE_URL = "http://int-dev.withregard.io:3002";
}
if (environment === 'production') {
ENV.WEBSITE_API_URL = "https://website-api.withregard.io";
ENV.WEBSITE_DATASTORE_URL = "https://regard-website-datastore.azurewebsite.net";
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
environment: environment,
baseURL: '/dashboard',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// LOG_MODULE_RESOLVER is needed for pre-1.6.0
// ENV.LOG_MODULE_RESOLVER = true;
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_MODULE_RESOLVER = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV.WEBSITE_API_URL = "http://int-dev.withregard.io:3001";
ENV.WEBSITE_DATASTORE_URL = "http://int-dev.withregard.io:3002";
}
if (environment === 'production') {
ENV.WEBSITE_API_URL = "https://website-api.withregard.io";
ENV.WEBSITE_DATASTORE_URL = "https://website-datastore.withregard.io";
}
return ENV;
};
| Use subdomain now it's setup | Use subdomain now it's setup
| JavaScript | apache-2.0 | with-regard/regard-website | ---
+++
@@ -35,7 +35,7 @@
if (environment === 'production') {
ENV.WEBSITE_API_URL = "https://website-api.withregard.io";
- ENV.WEBSITE_DATASTORE_URL = "https://regard-website-datastore.azurewebsite.net";
+ ENV.WEBSITE_DATASTORE_URL = "https://website-datastore.withregard.io";
}
return ENV; |
c5c931dee3909ad81812a2e754ca248e4e89254c | src/services/user-lesson-tokens/index.js | src/services/user-lesson-tokens/index.js | 'use strict';
const service = require('feathers-mongoose');
const user-lesson-tokens = require('./user-lesson-tokens-model');
const hooks = require('./hooks');
module.exports = function() {
const app = this;
const options = {
Model: user-lesson-tokens,
paginate: {
default: 5,
max: 25
}
};
// Initialize our service with any options it requires
app.use('/user-lesson-tokens', service(options));
// Get our initialize service to that we can bind hooks
const user-lesson-tokensService = app.service('/user-lesson-tokens');
// Set up our before hooks
user-lesson-tokensService.before(hooks.before);
// Set up our after hooks
user-lesson-tokensService.after(hooks.after);
};
| 'use strict';
const service = require('feathers-mongoose');
const userLessonTokens = require('./user-lesson-tokens-model');
const hooks = require('./hooks');
module.exports = function() {
const app = this;
const options = {
Model: user-lesson-tokens,
paginate: {
default: 5,
max: 25
}
};
// Initialize our service with any options it requires
app.use('/user-lesson-tokens', service(options));
// Get our initialize service to that we can bind hooks
const userLessonTokensService = app.service('/user-lesson-tokens');
// Set up our before hooks
user-lesson-tokensService.before(hooks.before);
// Set up our after hooks
user-lesson-tokensService.after(hooks.after);
};
| Correct syntax errors in user-lesson-tokens service | Correct syntax errors in user-lesson-tokens service
| JavaScript | mit | tum-ase-33/rest-server | ---
+++
@@ -1,7 +1,7 @@
'use strict';
const service = require('feathers-mongoose');
-const user-lesson-tokens = require('./user-lesson-tokens-model');
+const userLessonTokens = require('./user-lesson-tokens-model');
const hooks = require('./hooks');
module.exports = function() {
@@ -19,7 +19,7 @@
app.use('/user-lesson-tokens', service(options));
// Get our initialize service to that we can bind hooks
- const user-lesson-tokensService = app.service('/user-lesson-tokens');
+ const userLessonTokensService = app.service('/user-lesson-tokens');
// Set up our before hooks
user-lesson-tokensService.before(hooks.before); |
e33bb6ddd1929b2fcbe08f435ae0f5e1949f5263 | tests/dummy/app/templates/snippets/custom-position-1-js.js | tests/dummy/app/templates/snippets/custom-position-1-js.js | import Controller from 'ember-controller';
import $ from 'jquery';
export default Controller.extend({
calculatePosition(trigger, content) {
let { top, left, width, height } = trigger.getBoundingClientRect();
let { height: contentHeight } = content.getBoundingClientRect();
let $window = $(self.window);
let style = {
left: left + width,
top: top + $window.scrollTop() + (height / 2) - (contentHeight / 2)
};
return { style };
}
}); | import Controller from 'ember-controller';
import $ from 'jquery';
export default Controller.extend({
calculatePosition(trigger, content) {
let { top, left, width, height } = trigger.getBoundingClientRect();
let { height: contentHeight } = content.getBoundingClientRect();
let style = {
left: left + width,
top: top + $(window).scrollTop() + (height / 2) - (contentHeight / 2)
};
return { style };
}
}); | Simplify javascript a little bit | Simplify javascript a little bit
| JavaScript | mit | cibernox/ember-basic-dropdown,cibernox/ember-basic-dropdown,cibernox/ember-basic-dropdown,cibernox/ember-basic-dropdown | ---
+++
@@ -5,10 +5,9 @@
calculatePosition(trigger, content) {
let { top, left, width, height } = trigger.getBoundingClientRect();
let { height: contentHeight } = content.getBoundingClientRect();
- let $window = $(self.window);
let style = {
left: left + width,
- top: top + $window.scrollTop() + (height / 2) - (contentHeight / 2)
+ top: top + $(window).scrollTop() + (height / 2) - (contentHeight / 2)
};
return { style }; |
02a7914b0c8302cf6ed67d965ee7d3a809572215 | Implementation/WebTier/WebContent/JavaScript/JsUnit/app/JsTestClass.js | Implementation/WebTier/WebContent/JavaScript/JsUnit/app/JsTestClass.js |
JsHamcrest.Integration.JsUnit();
JsMockito.Integration.JsUnit();
var JsTestClass = new Class({
Implements: [Events, Options],
options: {
testCase: null,
testMethods: []
},
initialize: function( options ){
this.setOptions( options );
this.testCaseChain = new Chain();
this.tracer;
this.setUp();
},
afterAllTests: function(){
//Abstract method, should be overwritten by test the test class
},
afterEachTest: function(){
//Abstract method, should be overwritten by test the test class
},
beforeAllTests: function(){
//Abstract method, should be overwritten by test the test class
},
beforeEachTest: function(){
//Abstract method, should be overwritten by test the test class
},
//Properties
getTestMethods: function() { return this.options.testMethods; },
isJsTestClass: function() { return true; },
//Protected, private helper methods
debug : function( arguments ){
this.tracer.debug( arguments );
}.protect(),
inform : function( arguments ){
this.tracer.inform( arguments );
}.protect(),
setUp : function(){
this.tracer = top.tracer;
}.protect(),
testMethodReady: function( error ){
this.fireEvent( 'ready', error );
}.protect(),
warn : function( arguments ){
this.tracer.warn( arguments );
}.protect()
});
| var JsTestClass = new Class({
Implements: [Events, Options],
options: {
testCase: null,
testMethods: []
},
initialize: function( options ){
this.setOptions( options );
this.testCaseChain = new Chain();
this.tracer;
this.setUp();
},
afterAllTests: function(){
//Abstract method, should be overwritten by test the test class
},
afterEachTest: function(){
//Abstract method, should be overwritten by test the test class
},
beforeAllTests: function(){
//Abstract method, should be overwritten by test the test class
},
beforeEachTest: function(){
//Abstract method, should be overwritten by test the test class
},
//Properties
getTestMethods: function() { return this.options.testMethods; },
isJsTestClass: function() { return true; },
//Protected, private helper methods
debug : function( arguments ){
this.tracer.debug( arguments );
}.protect(),
inform : function( arguments ){
this.tracer.inform( arguments );
}.protect(),
setUp : function(){
this.tracer = top.tracer;
}.protect(),
testMethodReady: function( error ){
this.fireEvent( 'ready', error );
}.protect(),
warn : function( arguments ){
this.tracer.warn( arguments );
}.protect()
});
| Remove JsHamCrest and JsMockito initialization. | Remove JsHamCrest and JsMockito initialization. | JavaScript | agpl-3.0 | ZsZs/ProcessPuzzleUI,ZsZs/ProcessPuzzleUI | ---
+++
@@ -1,7 +1,3 @@
-
-JsHamcrest.Integration.JsUnit();
-JsMockito.Integration.JsUnit();
-
var JsTestClass = new Class({
Implements: [Events, Options],
options: { |
41cd00659205461d30551878d03ef81c1d407c6c | src/test/helpers/HttpServer.js | src/test/helpers/HttpServer.js | var http = require("http");
function HttpServer(config) {
this.port = config.port || 8181;
this.address = config.address || "localhost";
this.options = {
data: null,
resCode: 200
};
}
HttpServer.prototype.start = function (fn) {
this.server = http.createServer(function (req, res) {
res.writeHead(this.options.resCode, {"Content-Type": "application/json"});
res.end(JSON.stringify(this.options.data));
}.bind(this)).listen(this.port, this.address, fn);
return this;
};
HttpServer.prototype.setup = function (data, resCode) {
this.options.data = data;
this.options.resCode = resCode || 200;
return this;
};
HttpServer.prototype.on = function (event, fn) {
this.server.on(event, fn);
};
HttpServer.prototype.stop = function (fn) {
this.server.close();
if (fn) {
fn();
}
};
exports.HttpServer = HttpServer;
| var http = require("http");
function HttpServer(config) {
this.port = config.port || 8181;
this.address = config.address || "localhost";
this.options = {
data: null,
headers: {"Content-Type": "application/json"},
returnPayload: false,
resCode: 200
};
}
HttpServer.prototype.start = function (fn) {
this.server = http.createServer();
this.server.on("request", (req, res) => {
if (this.options.returnPayload === true) {
this.options.data = {
payload: "",
method: req.method
};
req.addListener("data", chunk => {
this.options.data.payload += chunk;
});
req.addListener("end", chunk => {
if (chunk) {
this.options.data.payload += chunk;
}
res.writeHead(this.options.resCode, this.options.headers);
res.end(JSON.stringify(this.options.data));
});
} else {
res.writeHead(this.options.resCode, this.options.headers);
res.end(JSON.stringify(this.options.data));
}
}).listen(this.port, this.address, fn);
return this;
};
HttpServer.prototype.on = function (event, fn) {
this.server.on(event, fn);
};
HttpServer.prototype.setup = function (data, resCode, returnPayload = false) {
this.options.data = data;
this.options.resCode = resCode || 200;
this.options.returnPayload = returnPayload;
return this;
};
HttpServer.prototype.stop = function (fn) {
this.server.close();
if (fn) {
fn();
}
};
exports.HttpServer = HttpServer;
| Add option to enable response with payload | Add option to enable response with payload
This allows the server to respond with an object representing the
.payload as sent by the request, and the corresponding .method used by
the caller.
| JavaScript | apache-2.0 | mesosphere/marathon-ui,cribalik/marathon-ui,mesosphere/marathon-ui,cribalik/marathon-ui | ---
+++
@@ -5,26 +5,54 @@
this.address = config.address || "localhost";
this.options = {
data: null,
+ headers: {"Content-Type": "application/json"},
+ returnPayload: false,
resCode: 200
};
}
HttpServer.prototype.start = function (fn) {
- this.server = http.createServer(function (req, res) {
- res.writeHead(this.options.resCode, {"Content-Type": "application/json"});
- res.end(JSON.stringify(this.options.data));
- }.bind(this)).listen(this.port, this.address, fn);
- return this;
-};
-HttpServer.prototype.setup = function (data, resCode) {
- this.options.data = data;
- this.options.resCode = resCode || 200;
+ this.server = http.createServer();
+
+ this.server.on("request", (req, res) => {
+
+ if (this.options.returnPayload === true) {
+ this.options.data = {
+ payload: "",
+ method: req.method
+ };
+
+ req.addListener("data", chunk => {
+ this.options.data.payload += chunk;
+ });
+
+ req.addListener("end", chunk => {
+ if (chunk) {
+ this.options.data.payload += chunk;
+ }
+ res.writeHead(this.options.resCode, this.options.headers);
+ res.end(JSON.stringify(this.options.data));
+ });
+ } else {
+ res.writeHead(this.options.resCode, this.options.headers);
+ res.end(JSON.stringify(this.options.data));
+ }
+ }).listen(this.port, this.address, fn);
+
return this;
};
HttpServer.prototype.on = function (event, fn) {
this.server.on(event, fn);
+};
+
+HttpServer.prototype.setup = function (data, resCode, returnPayload = false) {
+ this.options.data = data;
+ this.options.resCode = resCode || 200;
+ this.options.returnPayload = returnPayload;
+
+ return this;
};
HttpServer.prototype.stop = function (fn) { |
669eba40338eb8ed5dd908e616a2b2e183f80a76 | app/source/manage/views/apps/add.js | app/source/manage/views/apps/add.js | /**
* Add app view
*/
var _ = require('underscore');
var Backbone = require('backbone');
var templates = require('../../dist/');
var App = require('../../models/app');
module.exports = Backbone.View.extend({
tagName : 'article',
className : 'section',
template : templates.addAppForm,
$appName : null,
events : {
'click #addAppBtn' : 'addApp'
},
render : function () {
var tmpl = _.template(this.template, { variable : 'data' });
this.$el.html(tmpl());
this.$appName = this.$el.find('#addAppName');
return this;
},
addApp : function () {
var name = this.$appName.val();
var app = new App({
name : name
});
if(!app.isValid()) return;
app.save([], {
success : function (model) {
this.clean();
this.trigger('new_app', model);
}.bind(this),
error : function (model, response) {
alert('Error adding application');
console.log(response.responseText);
}.bind(this)
});
},
clean : function () {
this.$appName.val('');
}
});
| /**
* Add app view
*/
var _ = require('underscore');
var Backbone = require('backbone');
var templates = require('../../dist/');
var App = require('../../models/app');
module.exports = Backbone.View.extend({
tagName : 'article',
className : 'section',
template : templates.addAppForm,
$appName : null,
events : {
'click #addAppBtn' : 'addApp'
},
render : function () {
var tmpl = _.template(this.template, { variable : 'data' });
this.$el.html(tmpl({ formModel : 'application' }));
this.$appName = this.$el.find('#addAppName');
return this;
},
addApp : function () {
var name = this.$appName.val();
var app = new App({
name : name
});
if(!app.isValid()) return;
app.save([], {
success : function (model) {
this.clean();
this.trigger('new_app', model);
}.bind(this),
error : function (model, response) {
alert('Error adding application');
console.log(response.responseText);
}.bind(this)
});
},
clean : function () {
this.$appName.val('');
}
});
| Fix new form template requirement | Fix new form template requirement
| JavaScript | mit | lukkari/web,lukkari/web | ---
+++
@@ -23,7 +23,7 @@
render : function () {
var tmpl = _.template(this.template, { variable : 'data' });
- this.$el.html(tmpl());
+ this.$el.html(tmpl({ formModel : 'application' }));
this.$appName = this.$el.find('#addAppName');
|
006b3af4e90bb34e0857916513d39efaff545bb5 | ui/src/utils/ajax.js | ui/src/utils/ajax.js | import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logoutLink: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logoutLink: links.logout} // eslint-disable-line no-throw-literal
}
}
export const get = async url => {
try {
return await AJAX({
method: 'GET',
url,
})
} catch (error) {
console.error(error)
throw error
}
}
| import axios from 'axios'
let links
const AJAX = async ({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) => {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logoutLink: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logoutLink: links.logout} // eslint-disable-line no-throw-literal
}
}
export const get = async url => {
try {
return await AJAX({
method: 'GET',
url,
})
} catch (error) {
console.error(error)
throw error
}
}
export default AJAX
| Update AJAX fn to ES6 | Update AJAX fn to ES6
| JavaScript | mit | mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,influxdata/influxdb,nooproblem/influxdb | ---
+++
@@ -2,7 +2,7 @@
let links
-export default async function AJAX({
+const AJAX = async ({
url,
resource,
id,
@@ -10,7 +10,7 @@
data = {},
params = {},
headers = {},
-}) {
+}) => {
try {
const basepath = window.basepath || ''
let response
@@ -66,3 +66,5 @@
throw error
}
}
+
+export default AJAX |
763d9302711b0e3c6d3d9762d23faf8b632f4661 | blueprints/ember-cli-mocha/index.js | blueprints/ember-cli-mocha/index.js | var EOL = require('os').EOL;
module.exports = {
name: 'ember-cli-mocha',
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
},
afterInstall: function() {
var addonContext = this;
return this.addBowerPackagesToProject([
{ name: 'ember-mocha', source: 'ember-mocha', target: '~0.8.6' },
{ name: 'ember-cli-test-loader', source: 'ember-cli/ember-cli-test-loader', target: '0.1.3' },
{ name: 'ember-cli-shims', source: 'ember-cli/ember-cli-shims', target: '0.0.3' }
]).then(function() {
if ('removePackageFromProject' in addonContext) {
return addonContext.removePackageFromProject('ember-cli-qunit');
}
});
}
};
| var EOL = require('os').EOL;
module.exports = {
name: 'ember-cli-mocha',
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
},
afterInstall: function() {
var addonContext = this;
return this.addBowerPackagesToProject([
{ name: 'ember-mocha', source: 'ember-mocha', target: '~0.8.8' },
{ name: 'ember-cli-test-loader', source: 'ember-cli/ember-cli-test-loader', target: '0.2.2' },
{ name: 'ember-cli-shims', source: 'ember-cli/ember-cli-shims', target: '0.0.6' }
]).then(function() {
if ('removePackageFromProject' in addonContext) {
return addonContext.removePackageFromProject('ember-cli-qunit');
}
});
}
};
| Update blueprint to current versions. | Update blueprint to current versions.
| JavaScript | apache-2.0 | ember-cli/ember-cli-mocha,blimmer/ember-cli-mocha,switchfly/ember-cli-mocha,trentmwillis/ember-cli-mocha,trentmwillis/ember-cli-mocha,blimmer/ember-cli-mocha,ember-cli/ember-cli-mocha,switchfly/ember-cli-mocha | ---
+++
@@ -13,9 +13,9 @@
var addonContext = this;
return this.addBowerPackagesToProject([
- { name: 'ember-mocha', source: 'ember-mocha', target: '~0.8.6' },
- { name: 'ember-cli-test-loader', source: 'ember-cli/ember-cli-test-loader', target: '0.1.3' },
- { name: 'ember-cli-shims', source: 'ember-cli/ember-cli-shims', target: '0.0.3' }
+ { name: 'ember-mocha', source: 'ember-mocha', target: '~0.8.8' },
+ { name: 'ember-cli-test-loader', source: 'ember-cli/ember-cli-test-loader', target: '0.2.2' },
+ { name: 'ember-cli-shims', source: 'ember-cli/ember-cli-shims', target: '0.0.6' }
]).then(function() {
if ('removePackageFromProject' in addonContext) {
return addonContext.removePackageFromProject('ember-cli-qunit'); |
72e2a1967dfa0919afba7cc6a4fec5af39ac45a4 | app/components/user/graphql/codemirror.js | app/components/user/graphql/codemirror.js | export default from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/comment/comment';
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/edit/closebrackets';
import 'codemirror/addon/search/search';
import 'codemirror/addon/search/searchcursor';
import 'codemirror/addon/search/jump-to-line';
import 'codemirror/addon/dialog/dialog.css';
import 'codemirror/addon/dialog/dialog';
import 'codemirror/addon/lint/lint';
import 'codemirror/addon/lint/lint.css';
import 'codemirror/keymap/sublime';
import 'codemirror-graphql/results/mode';
import 'codemirror-graphql/hint';
import 'codemirror-graphql/lint';
import 'codemirror-graphql/mode';
| export { default } from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/comment/comment';
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/edit/closebrackets';
import 'codemirror/addon/search/search';
import 'codemirror/addon/search/searchcursor';
import 'codemirror/addon/search/jump-to-line';
import 'codemirror/addon/dialog/dialog.css';
import 'codemirror/addon/dialog/dialog';
import 'codemirror/addon/lint/lint';
import 'codemirror/addon/lint/lint.css';
import 'codemirror/keymap/sublime';
import 'codemirror-graphql/results/mode';
import 'codemirror-graphql/hint';
import 'codemirror-graphql/lint';
import 'codemirror-graphql/mode';
| Fix export syntax that is tripping compilation up for some reason | Fix export syntax that is tripping compilation up for some reason
| JavaScript | mit | buildkite/frontend,buildkite/frontend | ---
+++
@@ -1,4 +1,4 @@
-export default from 'codemirror';
+export { default } from 'codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/hint/show-hint.css'; |
dddbb3b7d2627d69e5e772c08ed7f09721dc3535 | src/database/DataTypes/InsurancePolicy.js | src/database/DataTypes/InsurancePolicy.js | import Realm from 'realm';
export class InsurancePolicy extends Realm.Object {
get policyNumber() {
return `${this.policyNumberPerson} ${this.policyNumberFamily}`;
}
}
InsurancePolicy.schema = {
name: 'InsurancePolicy',
primaryKey: 'id',
properties: {
id: 'string',
policyNumberFamily: 'string',
policyNumberPerson: 'string',
type: 'string',
discountRate: 'float',
isActive: { type: 'bool', default: true },
expiryDate: 'date',
enteredBy: { type: 'User', optional: true },
patient: { type: 'Name', optional: false },
insuranceProvider: { type: 'InsuranceProvider', optional: false },
},
};
export default InsurancePolicy;
| import Realm from 'realm';
export class InsurancePolicy extends Realm.Object {
get policyNumber() {
return `${this.policyNumberPerson} ${this.policyNumberFamily}`;
}
}
InsurancePolicy.schema = {
name: 'InsurancePolicy',
primaryKey: 'id',
properties: {
id: 'string',
policyNumberFamily: 'string',
policyNumberPerson: 'string',
type: 'string',
discountRate: 'double',
isActive: { type: 'bool', default: true },
expiryDate: 'date',
enteredBy: { type: 'User', optional: true },
patient: { type: 'Name', optional: false },
insuranceProvider: { type: 'InsuranceProvider', optional: false },
},
};
export default InsurancePolicy;
| Add bump insurancePolicy discount rate from float to double for better precision | Add bump insurancePolicy discount rate from float to double for better precision
| JavaScript | mit | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile | ---
+++
@@ -14,7 +14,7 @@
policyNumberFamily: 'string',
policyNumberPerson: 'string',
type: 'string',
- discountRate: 'float',
+ discountRate: 'double',
isActive: { type: 'bool', default: true },
expiryDate: 'date',
enteredBy: { type: 'User', optional: true }, |
3c32c2a446036dab674e76d6dad038b6e298bd22 | app/controllers/registrationController.js | app/controllers/registrationController.js | core.controller('RegistrationController', function ($controller, $location, $scope, $timeout, AlertService, RestApi) {
angular.extend(this, $controller('AbstractController', {$scope: $scope}));
$scope.registration = {
email: '',
token: ''
};
AlertService.create('auth/register');
AlertService.create('auth');
$scope.verifyEmail = function(email) {
RestApi.anonymousGet({
controller: 'auth',
method: 'register?email=' + email
}).then(function(data) {
$scope.registration.email = '';
});
};
if(typeof $location.search().token != 'undefined') {
$scope.registration.token = $location.search().token;
}
$scope.register = function() {
RestApi.anonymousGet({
'controller': 'auth',
'method': 'register',
'data': $scope.registration
}).then(function(data) {
$scope.registration = {
email: '',
token: ''
};
$location.path("/");
$timeout(function() {
AlertService.add(data.meta, 'auth/register');
});
});
};
}); | core.controller('RegistrationController', function ($controller, $location, $scope, $timeout, AlertService, RestApi) {
angular.extend(this, $controller('AbstractController', {$scope: $scope}));
$scope.registration = {
email: '',
token: ''
};
AlertService.create('auth/register');
AlertService.create('auth');
$scope.verifyEmail = function(email) {
RestApi.anonymousGet({
controller: 'auth',
method: 'register?email=' + email
}).then(function(data) {
$scope.registration.email = '';
$timeout(function() {
AlertService.add(data.meta, 'auth/register');
});
});
};
if(typeof $location.search().token != 'undefined') {
$scope.registration.token = $location.search().token;
}
$scope.register = function() {
RestApi.anonymousGet({
'controller': 'auth',
'method': 'register',
'data': $scope.registration
}).then(function(data) {
$scope.registration = {
email: '',
token: ''
};
$location.path("/");
$timeout(function() {
AlertService.add(data.meta, 'auth/register');
});
});
};
}); | Add success alert indicating registration began and to verify email. | Add success alert indicating registration began and to verify email.
| JavaScript | mit | TAMULib/Weaver-UI-Core,TAMULib/Weaver-UI-Core | ---
+++
@@ -16,6 +16,10 @@
method: 'register?email=' + email
}).then(function(data) {
$scope.registration.email = '';
+
+ $timeout(function() {
+ AlertService.add(data.meta, 'auth/register');
+ });
});
};
@@ -24,6 +28,7 @@
}
$scope.register = function() {
+
RestApi.anonymousGet({
'controller': 'auth',
'method': 'register', |
1c4211b1db275151a03c85ecf113d0e3e9065097 | tests/components/login.spec.js | tests/components/login.spec.js |
"use strict";
describe('Login component', () => {
let element = undefined;
let $rootScope = undefined;
let $compile = undefined;
let tpl = angular.element(`
<monad-login>
<h1>logged in</h1>
</monad-login>
`);
let mod = angular.module('tests.login', []).service('Authentication', function () {
this.check = false;
this.attempt = credentials => {
if (credentials.username == 'test' && credentials.password == 'test') {
this.check = true;
}
};
this.status = () => this.check;
});
beforeEach(angular.mock.module(mod.name));
beforeEach(inject((_$rootScope_, _$compile_) => {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
describe('Not logged in', () => {
it('should show the login form prior to authentication', () => {
$rootScope.$apply(() => {
$rootScope.credentials = {};
});
element = $compile(tpl)($rootScope);
$rootScope.$digest();
expect(element.find('form').length).toBe(1);
});
});
});
|
"use strict";
describe('Login component', () => {
let element = undefined;
let $rootScope = undefined;
let $compile = undefined;
let mod = angular.module('tests.login', []).service('Authentication', function () {
this.check = false;
this.attempt = credentials => {
if (credentials.username == 'test' && credentials.password == 'test') {
this.check = true;
}
};
this.status = () => this.check;
});
beforeEach(angular.mock.module(mod.name));
beforeEach(inject((_$rootScope_, _$compile_) => {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
describe('Not logged in', () => {
it('should show the login form prior to authentication', () => {
let tpl = angular.element(`
<monad-login>
<h1>logged in</h1>
</monad-login>
`);
element = $compile(tpl)($rootScope);
$rootScope.$digest();
expect(element.find('form').length).toBe(1);
});
});
describe('Logged in', () => {
it('should display a h1', () => {
let tpl = angular.element(`
<monad-login>
<h1>logged in</h1>
</monad-login>
`);
element = $compile(tpl)($rootScope);
$rootScope.$digest();
element.find('input').eq(0).val('test').triggerHandler('input');
element.find('input').eq(1).val('test').triggerHandler('input');
element.find('form').triggerHandler('submit');
expect(element.find('h1').length).toBe(1);
});
});
});
| Test login with valid credentials | Test login with valid credentials
| JavaScript | mit | monomelodies/monad,monomelodies/monad | ---
+++
@@ -5,11 +5,6 @@
let element = undefined;
let $rootScope = undefined;
let $compile = undefined;
- let tpl = angular.element(`
-<monad-login>
- <h1>logged in</h1>
-</monad-login>
- `);
let mod = angular.module('tests.login', []).service('Authentication', function () {
this.check = false;
@@ -29,13 +24,31 @@
describe('Not logged in', () => {
it('should show the login form prior to authentication', () => {
- $rootScope.$apply(() => {
- $rootScope.credentials = {};
- });
+ let tpl = angular.element(`
+ <monad-login>
+ <h1>logged in</h1>
+ </monad-login>
+ `);
element = $compile(tpl)($rootScope);
$rootScope.$digest();
expect(element.find('form').length).toBe(1);
});
});
+
+ describe('Logged in', () => {
+ it('should display a h1', () => {
+ let tpl = angular.element(`
+ <monad-login>
+ <h1>logged in</h1>
+ </monad-login>
+ `);
+ element = $compile(tpl)($rootScope);
+ $rootScope.$digest();
+ element.find('input').eq(0).val('test').triggerHandler('input');
+ element.find('input').eq(1).val('test').triggerHandler('input');
+ element.find('form').triggerHandler('submit');
+ expect(element.find('h1').length).toBe(1);
+ });
+ });
});
|
69bbf0975a443f49dc4bdeaa834a2f8b3845e1e6 | config/base.config.js | config/base.config.js | const paths = require('./paths');
const utils = require('../build/utils');
const vueLoaderConfig = require('../build/vue-loader.conf');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
module.exports = {
resolve: {
extensions: ['.js', '.vue', '.json', '.scss'],
alias: {
vue$: 'vue/dist/vue.esm.js',
'@': paths.src,
},
},
externals: {
firebase: 'firebase',
vue: 'Vue',
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig,
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]'),
},
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]'),
},
},
],
},
plugins: [
new FriendlyErrorsPlugin(),
],
};
| const paths = require('./paths');
const utils = require('../build/utils');
const vueLoaderConfig = require('../build/vue-loader.conf');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
module.exports = {
resolve: {
extensions: ['.js', '.vue', '.scss'],
alias: {
'@': paths.src,
},
},
externals: {
firebase: 'firebase',
vue: 'Vue',
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig,
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]'),
},
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]'),
},
},
],
},
plugins: [
new FriendlyErrorsPlugin(),
],
};
| Remove json and an unused alias | Remove json and an unused alias
| JavaScript | mit | tuelsch/bolg,tuelsch/bolg | ---
+++
@@ -5,9 +5,8 @@
module.exports = {
resolve: {
- extensions: ['.js', '.vue', '.json', '.scss'],
+ extensions: ['.js', '.vue', '.scss'],
alias: {
- vue$: 'vue/dist/vue.esm.js',
'@': paths.src,
},
}, |
446e4f4e0c8a88c01e4c505ed92c828d4c005d63 | client/app/starter.js | client/app/starter.js | var React = require("react");
var Router = require('react-router');
var App = require("./components/App");
var WallView = require("./components/WallView/WallView");
var NotFoundView = require("./components/NotFoundView/NotFoundView");
var DefaultRoute = Router.DefaultRoute;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var NotFoundRoute = Router.NotFoundRoute;
var routes = (
<Route name="app" path="/" handler={App}>
<DefaultRoute handler={WallView} />
<NotFoundRoute handler={NotFoundView} />
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.getElementById('main'));
});
| var React = require("react");
var Router = require('react-router');
var App = require("./components/App");
var WallView = require("./components/WallView/WallView");
var NotFoundView = require("./components/NotFoundView/NotFoundView");
var DefaultRoute = Router.DefaultRoute;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var NotFoundRoute = Router.NotFoundRoute;
var injectTapEventPlugin = require("react-tap-event-plugin");
injectTapEventPlugin();
var routes = (
<Route name="app" path="/" handler={App}>
<DefaultRoute handler={WallView} />
<NotFoundRoute handler={NotFoundView} />
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.getElementById('main'));
});
| Add in module to use react materialize-ui | Add in module to use react materialize-ui
| JavaScript | mit | ekeric13/pinterest-wall,ekeric13/pinterest-wall | ---
+++
@@ -9,6 +9,9 @@
var RouteHandler = Router.RouteHandler;
var NotFoundRoute = Router.NotFoundRoute;
+var injectTapEventPlugin = require("react-tap-event-plugin");
+injectTapEventPlugin();
+
var routes = (
<Route name="app" path="/" handler={App}>
<DefaultRoute handler={WallView} /> |
30077cecea82fddbbc6d2751846f081ef56f0452 | src/main/webapp/test/examSubmission.test.js | src/main/webapp/test/examSubmission.test.js | let {setExamSubmitting, setDirty, isUnsubmitted} =
require('../examSubmission.js');
test('check set exam submitting', () => {
expect(setExamSubmitting()).toBe(true);
});
test('check set dirty', () => {
expect(setDirty()).toBe(true);
});
test('isUnsubmitted when exam has not been submitted but filled in', () =>{
const reply = 'It looks like you have not submitted your exam';
expect(isUnsubmitted('event', false, true)).toBe(reply);
})
test('isUnsubmitted when exam has been submitted and filled in', () =>{
expect(isUnsubmitted('event',true, true )).toBe(undefined);
})
test('isUnsubmitted when exam has not been submitted and not filled in', () =>{
expect(isUnsubmitted('event', false, false)).toBe(undefined);
})
test('isUnsubmitted when exam has been submitted and not filled in', () =>{
expect(isUnsubmitted('event', true, false)).toBe(undefined);
})
| const {setExamSubmitting, setDirty, isUnsubmitted} =
require('../examSubmission.js');
test('check set exam submitting', () => {
expect(setExamSubmitting()).toBe(true);
});
test('check set dirty', () => {
expect(setDirty()).toBe(true);
});
test('isUnsubmitted when exam has not been submitted but filled in', () =>{
const reply = 'It looks like you have not submitted your exam';
expect(isUnsubmitted('event', false, true)).toBe(reply);
});
test('isUnsubmitted when exam has been submitted and filled in', () =>{
expect(isUnsubmitted('event', true, true )).toBe(undefined);
});
test('isUnsubmitted when exam has not been submitted and not filled in', () =>{
expect(isUnsubmitted('event', false, false)).toBe(undefined);
});
test('isUnsubmitted when exam has been submitted and not filled in', () =>{
expect(isUnsubmitted('event', true, false)).toBe(undefined);
});
| Update to comply with linter | Update to comply with linter | JavaScript | apache-2.0 | googleinterns/step254-2020,googleinterns/step254-2020,googleinterns/step254-2020 | ---
+++
@@ -1,4 +1,4 @@
-let {setExamSubmitting, setDirty, isUnsubmitted} =
+const {setExamSubmitting, setDirty, isUnsubmitted} =
require('../examSubmission.js');
test('check set exam submitting', () => {
@@ -12,17 +12,17 @@
test('isUnsubmitted when exam has not been submitted but filled in', () =>{
const reply = 'It looks like you have not submitted your exam';
expect(isUnsubmitted('event', false, true)).toBe(reply);
-})
+});
test('isUnsubmitted when exam has been submitted and filled in', () =>{
- expect(isUnsubmitted('event',true, true )).toBe(undefined);
-})
+ expect(isUnsubmitted('event', true, true )).toBe(undefined);
+});
test('isUnsubmitted when exam has not been submitted and not filled in', () =>{
expect(isUnsubmitted('event', false, false)).toBe(undefined);
-})
+});
test('isUnsubmitted when exam has been submitted and not filled in', () =>{
expect(isUnsubmitted('event', true, false)).toBe(undefined);
-})
+});
|
10bdeb786f87ecf54183123bff4d332ceb9567cb | turn_off_age_gate_on_amazon.co.jp.user.js | turn_off_age_gate_on_amazon.co.jp.user.js | // ==UserScript==
// @name Turn off age gate on Amazon.co.jp
// @namespace curipha
// @description Click "I'm over 18" automatically
// @include https://www.amazon.co.jp/gp/product/*
// @include https://www.amazon.co.jp/dp/*
// @include https://www.amazon.co.jp/*/dp/*
// @exclude https://www.amazon.co.jp/ap/*
// @exclude https://www.amazon.co.jp/mn/*
// @exclude https://www.amazon.co.jp/clouddrive*
// @version 0.5.2
// @grant none
// @noframes
// ==/UserScript==
(function() {
'use strict';
if (document.title === '警告:アダルトコンテンツ') {
const a = document.body.querySelector('center a[href*="black-curtain-redirect.html"]');
if (a) {
location.href = a.href;
}
}
})();
| // ==UserScript==
// @name Turn off age gate on Amazon.co.jp
// @namespace curipha
// @description Click "I'm over 18" automatically
// @include https://www.amazon.co.jp/gp/product/*
// @include https://www.amazon.co.jp/gp/browse.html*
// @include https://www.amazon.co.jp/dp/*
// @include https://www.amazon.co.jp/*/dp/*
// @exclude https://www.amazon.co.jp/ap/*
// @exclude https://www.amazon.co.jp/mn/*
// @exclude https://www.amazon.co.jp/clouddrive*
// @version 0.5.2
// @grant none
// @noframes
// ==/UserScript==
(function() {
'use strict';
if (document.title === '警告:アダルトコンテンツ') {
const a = document.body.querySelector('center a[href*="black-curtain-redirect.html"]');
if (a) {
location.href = a.href;
}
}
})();
| Change @include settings so that the script is not run on all pages | Change @include settings so that the script is not run on all pages
| JavaScript | unlicense | curipha/userscripts,curipha/userscripts | ---
+++
@@ -3,6 +3,7 @@
// @namespace curipha
// @description Click "I'm over 18" automatically
// @include https://www.amazon.co.jp/gp/product/*
+// @include https://www.amazon.co.jp/gp/browse.html*
// @include https://www.amazon.co.jp/dp/*
// @include https://www.amazon.co.jp/*/dp/*
// @exclude https://www.amazon.co.jp/ap/* |
2526ff69c061e96dbcd255c9361e5cd1bee369f3 | src/utilities/functional/merge.js | src/utilities/functional/merge.js | 'use strict';
// Like Lodash merge() but faster and does not mutate input
const deepMerge = function (objA, objB, ...objects) {
if (objects.length > 0) {
const newObjA = deepMerge(objA, objB);
return deepMerge(newObjA, ...objects);
}
if (!isObjectTypes(objA, objB)) { return objB; }
const rObjB = Object.entries(objB).map(([objBKey, objBVal]) => {
const newObjBVal = deepMerge(objA[objBKey], objBVal);
return { [objBKey]: newObjBVal };
});
return Object.assign({}, objA, ...rObjB);
};
const isObjectTypes = function (objA, objB) {
return objA && objA.constructor === Object &&
objB && objB.constructor === Object;
};
module.exports = {
deepMerge,
};
| 'use strict';
// Like Lodash merge() but faster and does not mutate input
const deepMerge = function (objA, objB, ...objects) {
if (objects.length > 0) {
const newObjA = deepMerge(objA, objB);
return deepMerge(newObjA, ...objects);
}
if (objB === undefined) { return objA; }
if (!isObjectTypes(objA, objB)) { return objB; }
const rObjB = Object.entries(objB).map(([objBKey, objBVal]) => {
const newObjBVal = deepMerge(objA[objBKey], objBVal);
return { [objBKey]: newObjBVal };
});
return Object.assign({}, objA, ...rObjB);
};
const isObjectTypes = function (objA, objB) {
return objA && objA.constructor === Object &&
objB && objB.constructor === Object;
};
module.exports = {
deepMerge,
};
| Fix deepMerge() with undefined arguments | Fix deepMerge() with undefined arguments
| JavaScript | apache-2.0 | autoserver-org/autoserver,autoserver-org/autoserver | ---
+++
@@ -6,6 +6,8 @@
const newObjA = deepMerge(objA, objB);
return deepMerge(newObjA, ...objects);
}
+
+ if (objB === undefined) { return objA; }
if (!isObjectTypes(objA, objB)) { return objB; }
|
c7cbfb331af99cae7460d54ad3f99597a2b437f8 | sencha-workspace/SlateAdmin/app/store/people/UserClasses.js | sencha-workspace/SlateAdmin/app/store/people/UserClasses.js | /*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.store.people.UserClasses', {
extend: 'Ext.data.Store',
requires: [
'SlateAdmin.proxy.API'
],
idProperty: 'value',
fields: [{
name: 'value',
type: 'string'
}],
proxy: {
type: 'slateapi',
url: '/people/*classes',
extraParams: {
interface: 'user'
},
reader: {
type: 'json',
transform: function(response) {
var records = [];
Ext.iterate(response.data, function(key, value) {
records.push({
value: value
});
});
return records;
}
}
}
}); | /*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.store.people.UserClasses', {
extend: 'Ext.data.Store',
requires: [
'SlateAdmin.proxy.API'
],
idProperty: 'value',
fields: [{
name: 'value',
type: 'string'
}],
proxy: {
type: 'slateapi',
url: '/people/*classes',
extraParams: {
interface: 'user'
},
reader: {
type: 'json',
transform: function(response) {
return Ext.Array.map(response.data, function (cls) {
return {
value: cls
}
});
}
}
}
}); | Use Array.map to transform classes response | Use Array.map to transform classes response
| JavaScript | mit | SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate-admin | ---
+++
@@ -20,15 +20,11 @@
reader: {
type: 'json',
transform: function(response) {
- var records = [];
-
- Ext.iterate(response.data, function(key, value) {
- records.push({
- value: value
- });
+ return Ext.Array.map(response.data, function (cls) {
+ return {
+ value: cls
+ }
});
-
- return records;
}
}
} |
33b1d0e5137075635249c6c63a82bb1f05745042 | tests/dummy/config/environment.js | tests/dummy/config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = '/liquid-fire-reveal';
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.rootURL = '/liquid-fire-reveal/';
}
return ENV;
};
| Update rootUrl for dummy app | Update rootUrl for dummy app
| JavaScript | mit | kpfefferle/liquid-fire-reveal,kpfefferle/liquid-fire-reveal | ---
+++
@@ -39,7 +39,7 @@
}
if (environment === 'production') {
- ENV.baseURL = '/liquid-fire-reveal';
+ ENV.rootURL = '/liquid-fire-reveal/';
}
return ENV; |
393385e15c69013d6ff1f19dca142a5765d28a1c | cu-build.config.js | cu-build.config.js | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
var name = 'cu-patcher-ui';
module.exports = {
type: 'library',
path: __dirname,
name: name,
bundle: {
copy: [
'src/**/!(*.js|*.jsx|*.ts|*.tsx|*.ui|*.styl|*.scss)',
'src/include/**'
]
}
};
| /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
var name = 'cu-patcher-ui';
module.exports = {
type: 'module',
path: __dirname,
name: name,
bundle: {
copy: [
'src/**/!(*.js|*.jsx|*.ts|*.tsx|*.ui|*.styl|*.scss)',
'src/include/**'
]
}
};
| Change build type to module | Change build type to module
| JavaScript | mpl-2.0 | stanley85/cu-patcher-ui,jamkoo/cu-patcher-ui,saddieeiddas/cu-patcher-ui,saddieeiddas/cu-patcher-ui,jamkoo/cu-patcher-ui,stanley85/cu-patcher-ui,saddieeiddas/cu-patcher-ui | ---
+++
@@ -7,7 +7,7 @@
var name = 'cu-patcher-ui';
module.exports = {
- type: 'library',
+ type: 'module',
path: __dirname,
name: name,
bundle: { |
0f4c4b7c8e7b3d4bbb214e1a91ca5081113be2b7 | server/channels/admin/__tests__/meeting.js | server/channels/admin/__tests__/meeting.js | jest.mock('../../../models/meeting');
const { toggleRegistration } = require('../meeting');
const { getActiveGenfors, toggleRegistrationStatus } = require('../../../models/meeting');
const { generateSocket, generateGenfors } = require('../../../utils/generateTestData');
describe('toggleRegistration', () => {
beforeEach(() => {
getActiveGenfors.mockImplementation(async () => generateGenfors());
toggleRegistrationStatus.mockImplementation(
async (genfors, registrationOpen) =>
generateGenfors({ ...genfors, registrationOpen: !registrationOpen }));
});
const generateData = data => (Object.assign({
registrationOpen: true,
}, data));
it('emits a toggle action that closes registration', async () => {
const socket = generateSocket();
await toggleRegistration(socket, generateData());
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits a toggle action that opens registration', async () => {
const socket = generateSocket();
await toggleRegistration(socket, generateData({ registrationOpen: false }));
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
});
| jest.mock('../../../models/meeting');
const { toggleRegistration } = require('../meeting');
const { getActiveGenfors, updateGenfors } = require('../../../models/meeting');
const { generateSocket, generateGenfors } = require('../../../utils/generateTestData');
describe('toggleRegistration', () => {
beforeEach(() => {
getActiveGenfors.mockImplementation(async () => generateGenfors());
updateGenfors.mockImplementation(async (genfors, data) =>
({ ...genfors, ...data, pin: genfors.pin }));
});
const generateData = data => (Object.assign({
registrationOpen: true,
}, data));
it('emits a toggle action that closes registration', async () => {
const socket = generateSocket();
await toggleRegistration(socket, generateData());
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits a toggle action that opens registration', async () => {
const socket = generateSocket();
await toggleRegistration(socket, generateData({ registrationOpen: false }));
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
});
| Update tests to mock generic helper function | Update tests to mock generic helper function
| JavaScript | mit | dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta | ---
+++
@@ -1,14 +1,13 @@
jest.mock('../../../models/meeting');
const { toggleRegistration } = require('../meeting');
-const { getActiveGenfors, toggleRegistrationStatus } = require('../../../models/meeting');
+const { getActiveGenfors, updateGenfors } = require('../../../models/meeting');
const { generateSocket, generateGenfors } = require('../../../utils/generateTestData');
describe('toggleRegistration', () => {
beforeEach(() => {
getActiveGenfors.mockImplementation(async () => generateGenfors());
- toggleRegistrationStatus.mockImplementation(
- async (genfors, registrationOpen) =>
- generateGenfors({ ...genfors, registrationOpen: !registrationOpen }));
+ updateGenfors.mockImplementation(async (genfors, data) =>
+ ({ ...genfors, ...data, pin: genfors.pin }));
});
const generateData = data => (Object.assign({ |
3e83a5606d57ac25b194f93fe602adee185d6418 | platform/android/.core.js | platform/android/.core.js | if (navigator.userAgent.indexOf('Android') >= 0) {
log = console.log.bind(console)
log("Android detected")
exports.core.vendor = "google"
exports.core.device = 2
exports.core.os = "android"
exports.core.keyCodes = {
4: 'Back',
13: 'Select',
27: 'Back',
37: 'Left',
32: 'Space',
38: 'Up',
39: 'Right',
40: 'Down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
179: 'Pause',
112: 'Red',
113: 'Green',
114: 'Yellow',
115: 'Blue'
}
if (window.cordova) {
document.addEventListener("backbutton", function(e) {
var event = new KeyboardEvent("keydown", { bubbles : true });
Object.defineProperty(event, 'keyCode', { get : function() { return 27; } })
document.dispatchEvent(event);
}, false);
} else {
log("'cordova' not defined. 'Back' button will be unhandable. It looks like you forget to include 'cordova.js'")
}
log("Android initialized")
}
| if (navigator.userAgent.indexOf('Android') >= 0) {
log = console.log.bind(console)
log("Android detected")
exports.core.vendor = "google"
exports.core.device = 2
exports.core.os = "android"
exports.core.keyCodes = {
4: 'Back',
13: 'Select',
37: 'Left',
32: 'Space',
38: 'Up',
39: 'Right',
40: 'Down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
179: 'Pause',
112: 'Red',
113: 'Green',
114: 'Yellow',
115: 'Blue'
}
if (window.cordova) {
document.addEventListener("backbutton", function(e) {
var event = new KeyboardEvent("keydown", { bubbles : true });
Object.defineProperty(event, 'keyCode', { get : function() { return 4; } })
document.dispatchEvent(event);
}, false);
} else {
log("'cordova' not defined. 'Back' button will be unhandable. It looks like you forget to include 'cordova.js'")
}
log("Android initialized")
}
| Use keyCode '4' instead of '27' to prevent conflicts in platforms where '27' key code works | Use keyCode '4' instead of '27' to prevent conflicts in platforms where '27' key code works
| JavaScript | mit | pureqml/qmlcore,pureqml/qmlcore,pureqml/qmlcore | ---
+++
@@ -9,7 +9,6 @@
exports.core.keyCodes = {
4: 'Back',
13: 'Select',
- 27: 'Back',
37: 'Left',
32: 'Space',
38: 'Up',
@@ -35,7 +34,7 @@
if (window.cordova) {
document.addEventListener("backbutton", function(e) {
var event = new KeyboardEvent("keydown", { bubbles : true });
- Object.defineProperty(event, 'keyCode', { get : function() { return 27; } })
+ Object.defineProperty(event, 'keyCode', { get : function() { return 4; } })
document.dispatchEvent(event);
}, false);
} else { |
4ed42119f5b556dc8fa1e8cfdc7e49fe9f5ea357 | app/assets/javascripts/ng-app/controllers/user-controller.js | app/assets/javascripts/ng-app/controllers/user-controller.js | angular.module('myApp')
.controller('UserCtrl', ['userService', '$scope', '$rootScope', 'ctrlPanelService',
function(userService, $scope, $rootScope, ctrlPanelService) {
// initialize data
$scope.users = ctrlPanelService.users;
// listeners waiting for control panel changes
$rootScope.$on('updateUsers', function() {
$scope.users = ctrlPanelService.users;
});
}]); | angular.module('myApp')
.controller('UserCtrl', ['userService', '$scope', '$rootScope', 'ctrlPanelService',
function(userService, $scope, $rootScope, ctrlPanelService) {
// initialize data
$scope.users = userService.users;
// listeners waiting for control panel changes
$rootScope.$on('usersUpdated', function() {
$scope.users = userService.users;
});
}]); | Update UserCtrl to user userService values | Update UserCtrl to user userService values
| JavaScript | mit | godspeedyoo/Breeze-Mapper,godspeedyoo/Breeze-Mapper,godspeedyoo/Breeze-Mapper | ---
+++
@@ -3,11 +3,11 @@
function(userService, $scope, $rootScope, ctrlPanelService) {
// initialize data
- $scope.users = ctrlPanelService.users;
+ $scope.users = userService.users;
// listeners waiting for control panel changes
- $rootScope.$on('updateUsers', function() {
- $scope.users = ctrlPanelService.users;
+ $rootScope.$on('usersUpdated', function() {
+ $scope.users = userService.users;
});
}]); |
36c0faf7b51eb701770b205b7d45c092b8489b2a | src/listeners/client/messageReactionAdd.js | src/listeners/client/messageReactionAdd.js | const { Listener } = require('discord-akairo');
class MessageReactionAddListener extends Listener {
constructor() {
super('messageReactionAdd', {
eventName: 'messageReactionAdd',
emitter: 'client',
category: 'client'
});
}
async exec(reaction, user) {
if (reaction.emoji.name === '⭐') {
const starboard = this.client.starboards.get(reaction.message.guild.id);
const error = await starboard.add(reaction.message, user);
if (error) {
reaction.message.channel.send(`${user}, ${error.message}`);
}
}
}
}
module.exports = MessageReactionAddListener;
| const { Listener } = require('discord-akairo');
class MessageReactionAddListener extends Listener {
constructor() {
super('messageReactionAdd', {
eventName: 'messageReactionAdd',
emitter: 'client',
category: 'client'
});
}
async exec(reaction, user) {
if (reaction.emoji.name === '⭐') {
const starboard = this.client.starboards.get(reaction.message.guild.id);
const error = await starboard.add(reaction.message, user);
if (error) {
reaction.remove(user);
reaction.message.channel.send(`${user}, ${error.message}`);
}
}
}
}
module.exports = MessageReactionAddListener;
| Remove reaction if there is some error | Remove reaction if there is some error
| JavaScript | mit | 1Computer1/hoshi | ---
+++
@@ -14,6 +14,7 @@
const starboard = this.client.starboards.get(reaction.message.guild.id);
const error = await starboard.add(reaction.message, user);
if (error) {
+ reaction.remove(user);
reaction.message.channel.send(`${user}, ${error.message}`);
}
} |
bcc1d50c96a2707fa66f8120598f1fcbc9051f5e | public/scripts/app/helpers/UserWreqr.js | public/scripts/app/helpers/UserWreqr.js | define([
"jquery",
"underscore",
"parse",
"backbone",
"marionette"
], function( $, _, Parse, Backbone, Marionette ) {
var userChannel = Backbone.Wreqr.radio.channel('user');
Backbone.Wreqr.radio.reqres.setHandler("user", "testing", function(id) {
return "deez" + id;
});
console.log(userChannel.reqres.request('testing', 'anid'));
return userChannel;
} );
| define([
"jquery",
"underscore",
"parse",
"backbone",
"marionette"
], function( $, _, Parse, Backbone, Marionette ) {
var userChannel = Backbone.Wreqr.radio.channel('user');
return userChannel;
} );
| Remove dumb logging stuff in initial radio channel | Remove dumb logging stuff in initial radio channel
| JavaScript | agpl-3.0 | gnu-lorien/yorick,gnu-lorien/yorick,gnu-lorien/twistedvines,gnu-lorien/twistedvines,gnu-lorien/yorick,gnu-lorien/yorick,gnu-lorien/twistedvines | ---
+++
@@ -8,11 +8,5 @@
var userChannel = Backbone.Wreqr.radio.channel('user');
- Backbone.Wreqr.radio.reqres.setHandler("user", "testing", function(id) {
- return "deez" + id;
- });
-
- console.log(userChannel.reqres.request('testing', 'anid'));
-
return userChannel;
} ); |
176519847555a6b4eb5ed9858b56580b516bdbb7 | client/aframeComponents/death-listener.js | client/aframeComponents/death-listener.js | AFRAME.registerComponent('death-listener', {
schema: {
characterId: {default: undefined}
},
init: function () {
const el = this.el;
const data = this.data;
window.addEventListener('characterDestroyed', function (e) {
if(data.characterId === e.detail.characterId) {
if(el.components.spawner) {
el.components.spawner.pause();
setTimeout(() => {
el.components.spawner.play();
}, 5000)
}
}
// const characterId = e.detail.characterId;
// console.log('character killed:', characterId);
// const blackPlane = document.createElement('a-plane');
// blackPlane.setAttribute('position', '0 0 -0.2');
// blackPlane.setAttribute('material', 'shader', 'flat');
// el.appendChild(blackPlane);
// const opacityAnimation = document.createElement('a-animation');
// opacityAnimation.setAttribute('attribute', 'material.opacity');
// opacityAnimation.setAttribute('from', 0);
// opacityAnimation.setAttribute('to', 1);
// opacityAnimation.setAttribute('dur', 1500);
// opacityAnimation.setAttribute('easing', 'ease-out');
// blackPlane.appendChild(opacityAnimation);
// el.appendChild(blackPlane);
// setTimeout(() => {
// el.removeChild(blackPlane)
// }, 3000);
});
}
});
| AFRAME.registerComponent('death-listener', {
schema: {
characterId: {default: undefined}
},
init: function () {
const el = this.el;
const data = this.data;
window.addEventListener('characterDestroyed', function (e) {
if(data.characterId === e.detail.characterId) {
if(el.components.spawner) {
el.components.spawner.pause();
setTimeout(() => {
el.components.spawner.play();
}, 5000)
}
if(el.components['data-emitter']) {
el.components['data-emitter'].pause();
setTimeout(() => {
el.components['data-emitter'].play();
}, 5000)
}
}
// const characterId = e.detail.characterId;
// console.log('character killed:', characterId);
// const blackPlane = document.createElement('a-plane');
// blackPlane.setAttribute('position', '0 0 -0.2');
// blackPlane.setAttribute('material', 'shader', 'flat');
// el.appendChild(blackPlane);
// const opacityAnimation = document.createElement('a-animation');
// opacityAnimation.setAttribute('attribute', 'material.opacity');
// opacityAnimation.setAttribute('from', 0);
// opacityAnimation.setAttribute('to', 1);
// opacityAnimation.setAttribute('dur', 1500);
// opacityAnimation.setAttribute('easing', 'ease-out');
// blackPlane.appendChild(opacityAnimation);
// el.appendChild(blackPlane);
// setTimeout(() => {
// el.removeChild(blackPlane)
// }, 3000);
});
}
});
| Enable death listener to disable data-emitter | Enable death listener to disable data-emitter
| JavaScript | mit | ourvrisrealerthanyours/tanks,elliotaplant/tanks,elliotaplant/tanks,ourvrisrealerthanyours/tanks | ---
+++
@@ -8,6 +8,7 @@
const data = this.data;
window.addEventListener('characterDestroyed', function (e) {
if(data.characterId === e.detail.characterId) {
+
if(el.components.spawner) {
el.components.spawner.pause();
setTimeout(() => {
@@ -15,6 +16,12 @@
}, 5000)
}
+ if(el.components['data-emitter']) {
+ el.components['data-emitter'].pause();
+ setTimeout(() => {
+ el.components['data-emitter'].play();
+ }, 5000)
+ }
}
// const characterId = e.detail.characterId;
// console.log('character killed:', characterId); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.