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 |
|---|---|---|---|---|---|---|---|---|---|---|
af9403793eefb5b3ee0217b077cb41a480251667 | test/helpers.js | test/helpers.js | const Bluebird = require('bluebird');
const mongoose = require('mongoose');
const Alternative = require('../app/models/alternative');
const Election = require('../app/models/election');
const Vote = require('../app/models/vote');
const User = require('../app/models/user');
exports.dropDatabase = () =>
mongoose.connection.dropDatabase().then(() => mongoose.disconnect());
exports.clearCollections = () =>
Bluebird.map([Alternative, Election, Vote, User], collection =>
collection.remove()
);
const hash = '$2a$10$qxTI.cWwa2kwcjx4SI9KAuV4KxuhtlGOk33L999UQf1rux.4PBz7y'; // 'password'
const testUser = (exports.testUser = {
username: 'testuser',
cardKey: '99TESTCARDKEY',
hash
});
const adminUser = (exports.adminUser = {
username: 'admin',
admin: true,
cardKey: '55TESTCARDKEY',
hash
});
exports.createUsers = () => User.create([testUser, adminUser]);
| const Bluebird = require('bluebird');
const mongoose = require('mongoose');
const Alternative = require('../app/models/alternative');
const Election = require('../app/models/election');
const Vote = require('../app/models/vote');
const User = require('../app/models/user');
exports.dropDatabase = () =>
mongoose.connection.dropDatabase().then(() => mongoose.disconnect());
exports.clearCollections = () =>
Bluebird.map([Alternative, Election, Vote, User], collection =>
collection.remove()
);
const hash = '$2a$10$qxTI.cWwa2kwcjx4SI9KAuV4KxuhtlGOk33L999UQf1rux.4PBz7y'; // 'password'
const testUser = (exports.testUser = {
username: 'testuser',
cardKey: '99TESTCARDKEY',
hash
});
const adminUser = (exports.adminUser = {
username: 'admin',
admin: true,
moderator: true,
cardKey: '55TESTCARDKEY',
hash
});
exports.createUsers = () => User.create([testUser, adminUser]);
| Make new code pass all new tests | Make new code pass all new tests
This was done by setting the moderator flag in the helper
function that creates admin users.
| JavaScript | mit | webkom/vote,webkom/vote,webkom/vote,webkom/vote | ---
+++
@@ -23,6 +23,7 @@
const adminUser = (exports.adminUser = {
username: 'admin',
admin: true,
+ moderator: true,
cardKey: '55TESTCARDKEY',
hash
}); |
35ba2674051ab6201382af6dda76e1531e8ef612 | test/es5.js | test/es5.js | import test from 'tape-catch';
var Symbol = require('es6-symbol');
var { curry, _ } = require('../module/index')({ Symbol });
test('The API is in good shape.', (is) => {
is.equal(
typeof curry,
'function',
'`curry_` is a function'
);
is.end();
});
test('basic usage', (is) => {
const sum = (a, b, c) => a + b + c;
is.equal(
sum::curry()(1, 2, 3),
6,
'curries a function'
);
is.equal(
sum::curry(1)(2, 3),
6,
'curries a function'
);
is.equal(
sum::curry(1, 2)(3),
6,
'curries a function'
);
is.equal(
sum::curry(1)(2)(3),
6,
'curries a function'
);
is.end();
});
test('placeholders', (is) => {
const strJoin = (a, b, c) => '' + a + b + c;
is.equal(
strJoin::curry()(1, 2, 3),
'123',
'curries a function'
);
is.equal(
strJoin::curry(1, _, 3)(2),
'123',
'curries a function'
);
is.equal(
strJoin::curry(_, _, 3)(1)(2),
'123',
'curries a function'
);
is.equal(
strJoin::curry(_, 2)(1)(3),
'123',
'curries a function'
);
is.end();
});
| Add ES5 test by @stoeffel | Add ES5 test by @stoeffel
| JavaScript | mit | thisables/curry,togusafish/stoeffel-_-curry-this,stoeffel/curry-this | ---
+++
@@ -0,0 +1,71 @@
+import test from 'tape-catch';
+
+var Symbol = require('es6-symbol');
+var { curry, _ } = require('../module/index')({ Symbol });
+
+test('The API is in good shape.', (is) => {
+ is.equal(
+ typeof curry,
+ 'function',
+ '`curry_` is a function'
+ );
+ is.end();
+});
+
+test('basic usage', (is) => {
+ const sum = (a, b, c) => a + b + c;
+
+ is.equal(
+ sum::curry()(1, 2, 3),
+ 6,
+ 'curries a function'
+ );
+
+ is.equal(
+ sum::curry(1)(2, 3),
+ 6,
+ 'curries a function'
+ );
+
+ is.equal(
+ sum::curry(1, 2)(3),
+ 6,
+ 'curries a function'
+ );
+
+ is.equal(
+ sum::curry(1)(2)(3),
+ 6,
+ 'curries a function'
+ );
+ is.end();
+});
+test('placeholders', (is) => {
+ const strJoin = (a, b, c) => '' + a + b + c;
+
+ is.equal(
+ strJoin::curry()(1, 2, 3),
+ '123',
+ 'curries a function'
+ );
+
+ is.equal(
+ strJoin::curry(1, _, 3)(2),
+ '123',
+ 'curries a function'
+ );
+
+ is.equal(
+ strJoin::curry(_, _, 3)(1)(2),
+ '123',
+ 'curries a function'
+ );
+
+ is.equal(
+ strJoin::curry(_, 2)(1)(3),
+ '123',
+ 'curries a function'
+ );
+
+ is.end();
+}); | |
9fd8b1cd47f6c9f03879427abf471f3d9be49738 | tools/tests/cordova-platforms.js | tools/tests/cordova-platforms.js | var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var files = require('../files.js');
// Add plugins to an app. Change the contents of the plugins and their
// dependencies, make sure that the app still refreshes.
selftest.define("add cordova platforms", function () {
var s = new Sandbox();
var run;
// Starting a run
s.createApp("myapp", "package-tests");
s.cd("myapp");
s.set("METEOR_TEST_TMP", files.mkdtemp());
run = s.run("run", "android");
run.matchErr("platform is not added");
run.matchErr("meteor add-platform android");
run.expectExit(1);
run = s.run("add-platform", "android");
run.match("Do you agree");
run.write("Y\n");
run.extraTime = 90; // Huge download
run.match("added");
run = s.run("remove-platform", "foo");
run.match("foo is not");
run = s.run("remove-platform", "android");
run.match("removed");
run = s.run("run", "android");
run.matchErr("platform is not added");
run.matchErr("meteor add-platform android");
run.expectExit(1);
});
| var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var files = require('../files.js');
// Add plugins to an app. Change the contents of the plugins and their
// dependencies, make sure that the app still refreshes.
selftest.define("add cordova platforms", function () {
var s = new Sandbox();
var run;
// Starting a run
s.createApp("myapp", "package-tests");
s.cd("myapp");
s.set("METEOR_TEST_TMP", files.mkdtemp());
run = s.run("run", "android");
run.matchErr("Platform is not added");
run.match("meteor add-platform android");
run.expectExit(1);
run = s.run("add-platform", "android");
run.match("Do you agree");
run.write("Y\n");
run.extraTime = 90; // Huge download
run.match("added");
run = s.run("remove-platform", "foo");
run.match("foo is not");
run = s.run("remove-platform", "android");
run.match("removed");
run = s.run("run", "android");
run.matchErr("Platform is not added");
run.match("meteor add-platform android");
run.expectExit(1);
});
| Update 'add cordova platforms' to match latest command output | Update 'add cordova platforms' to match latest command output
| JavaScript | mit | benstoltz/meteor,dandv/meteor,allanalexandre/meteor,brdtrpp/meteor,neotim/meteor,tdamsma/meteor,newswim/meteor,PatrickMcGuinness/meteor,4commerce-technologies-AG/meteor,DCKT/meteor,fashionsun/meteor,DAB0mB/meteor,emmerge/meteor,dfischer/meteor,ljack/meteor,servel333/meteor,lpinto93/meteor,deanius/meteor,benjamn/meteor,brettle/meteor,eluck/meteor,dboyliao/meteor,whip112/meteor,framewr/meteor,pandeysoni/meteor,planet-training/meteor,stevenliuit/meteor,lassombra/meteor,mauricionr/meteor,alphanso/meteor,jenalgit/meteor,jdivy/meteor,AnthonyAstige/meteor,shadedprofit/meteor,msavin/meteor,henrypan/meteor,kidaa/meteor,mubassirhayat/meteor,lpinto93/meteor,benjamn/meteor,shadedprofit/meteor,HugoRLopes/meteor,rozzzly/meteor,alexbeletsky/meteor,ljack/meteor,kencheung/meteor,vjau/meteor,planet-training/meteor,kencheung/meteor,PatrickMcGuinness/meteor,TechplexEngineer/meteor,sitexa/meteor,devgrok/meteor,whip112/meteor,johnthepink/meteor,IveWong/meteor,colinligertwood/meteor,calvintychan/meteor,chasertech/meteor,DAB0mB/meteor,akintoey/meteor,AnjirHossain/meteor,johnthepink/meteor,qscripter/meteor,Hansoft/meteor,sdeveloper/meteor,jeblister/meteor,brettle/meteor,katopz/meteor,shmiko/meteor,pandeysoni/meteor,zdd910/meteor,dfischer/meteor,emmerge/meteor,EduShareOntario/meteor,yinhe007/meteor,qscripter/meteor,jirengu/meteor,udhayam/meteor,whip112/meteor,GrimDerp/meteor,aldeed/meteor,youprofit/meteor,yinhe007/meteor,lorensr/meteor,tdamsma/meteor,yinhe007/meteor,cbonami/meteor,meteor-velocity/meteor,nuvipannu/meteor,katopz/meteor,codingang/meteor,williambr/meteor,hristaki/meteor,ndarilek/meteor,arunoda/meteor,saisai/meteor,Hansoft/meteor,elkingtonmcb/meteor,HugoRLopes/meteor,whip112/meteor,kengchau/meteor,mjmasn/meteor,DAB0mB/meteor,IveWong/meteor,ndarilek/meteor,daslicht/meteor,AnthonyAstige/meteor,jeblister/meteor,zdd910/meteor,michielvanoeffelen/meteor,dev-bobsong/meteor,dev-bobsong/meteor,wmkcc/meteor,chengxiaole/meteor,lawrenceAIO/meteor,yyx990803/meteor,jirengu/meteor,jdivy/meteor,henrypan/meteor,papimomi/meteor,ndarilek/meteor,Hansoft/meteor,LWHTarena/meteor,h200863057/meteor,jenalgit/meteor,meteor-velocity/meteor,yonas/meteor-freebsd,chasertech/meteor,Puena/meteor,neotim/meteor,mauricionr/meteor,yalexx/meteor,deanius/meteor,williambr/meteor,4commerce-technologies-AG/meteor,chmac/meteor,saisai/meteor,lieuwex/meteor,lpinto93/meteor,yonglehou/meteor,ashwathgovind/meteor,juansgaitan/meteor,servel333/meteor,HugoRLopes/meteor,DCKT/meteor,skarekrow/meteor,queso/meteor,yyx990803/meteor,D1no/meteor,jirengu/meteor,chasertech/meteor,D1no/meteor,modulexcite/meteor,lassombra/meteor,AlexR1712/meteor,dboyliao/meteor,TribeMedia/meteor,shrop/meteor,JesseQin/meteor,jdivy/meteor,mauricionr/meteor,juansgaitan/meteor,devgrok/meteor,meteor-velocity/meteor,aldeed/meteor,EduShareOntario/meteor,Urigo/meteor,kidaa/meteor,dandv/meteor,cherbst/meteor,yinhe007/meteor,yonglehou/meteor,papimomi/meteor,kencheung/meteor,cbonami/meteor,codingang/meteor,meteor-velocity/meteor,sclausen/meteor,saisai/meteor,daslicht/meteor,yonglehou/meteor,mjmasn/meteor,meonkeys/meteor,yiliaofan/meteor,skarekrow/meteor,yinhe007/meteor,devgrok/meteor,aramk/meteor,skarekrow/meteor,jeblister/meteor,EduShareOntario/meteor,alexbeletsky/meteor,dfischer/meteor,yiliaofan/meteor,Prithvi-A/meteor,aldeed/meteor,colinligertwood/meteor,luohuazju/meteor,sdeveloper/meteor,sitexa/meteor,chengxiaole/meteor,lpinto93/meteor,dboyliao/meteor,oceanzou123/meteor,jenalgit/meteor,Theviajerock/meteor,alexbeletsky/meteor,Prithvi-A/meteor,udhayam/meteor,wmkcc/meteor,somallg/meteor,aldeed/meteor,youprofit/meteor,imanmafi/meteor,pandeysoni/meteor,saisai/meteor,chinasb/meteor,JesseQin/meteor,Jonekee/meteor,michielvanoeffelen/meteor,tdamsma/meteor,allanalexandre/meteor,planet-training/meteor,yanisIk/meteor,benstoltz/meteor,kengchau/meteor,iman-mafi/meteor,cherbst/meteor,TribeMedia/meteor,Hansoft/meteor,kidaa/meteor,jagi/meteor,HugoRLopes/meteor,yalexx/meteor,dfischer/meteor,newswim/meteor,somallg/meteor,chiefninew/meteor,GrimDerp/meteor,dandv/meteor,sdeveloper/meteor,chinasb/meteor,Profab/meteor,wmkcc/meteor,Quicksteve/meteor,iman-mafi/meteor,SeanOceanHu/meteor,namho102/meteor,chmac/meteor,pjump/meteor,yalexx/meteor,Eynaliyev/meteor,servel333/meteor,framewr/meteor,namho102/meteor,guazipi/meteor,benjamn/meteor,fashionsun/meteor,deanius/meteor,lassombra/meteor,dev-bobsong/meteor,calvintychan/meteor,wmkcc/meteor,Jonekee/meteor,daltonrenaldo/meteor,whip112/meteor,daltonrenaldo/meteor,HugoRLopes/meteor,daslicht/meteor,brdtrpp/meteor,Jonekee/meteor,cog-64/meteor,jeblister/meteor,henrypan/meteor,zdd910/meteor,steedos/meteor,brdtrpp/meteor,namho102/meteor,cog-64/meteor,cog-64/meteor,juansgaitan/meteor,hristaki/meteor,mjmasn/meteor,yonglehou/meteor,jg3526/meteor,SeanOceanHu/meteor,sitexa/meteor,Profab/meteor,Prithvi-A/meteor,chengxiaole/meteor,Eynaliyev/meteor,framewr/meteor,deanius/meteor,aramk/meteor,rabbyalone/meteor,rozzzly/meteor,sdeveloper/meteor,sunny-g/meteor,colinligertwood/meteor,GrimDerp/meteor,evilemon/meteor,daltonrenaldo/meteor,modulexcite/meteor,ndarilek/meteor,Eynaliyev/meteor,joannekoong/meteor,ashwathgovind/meteor,Urigo/meteor,AnjirHossain/meteor,aleclarson/meteor,EduShareOntario/meteor,akintoey/meteor,juansgaitan/meteor,dev-bobsong/meteor,chiefninew/meteor,meonkeys/meteor,lawrenceAIO/meteor,vacjaliu/meteor,vjau/meteor,vacjaliu/meteor,dev-bobsong/meteor,elkingtonmcb/meteor,lieuwex/meteor,JesseQin/meteor,lieuwex/meteor,PatrickMcGuinness/meteor,planet-training/meteor,jrudio/meteor,ericterpstra/meteor,sitexa/meteor,daslicht/meteor,ashwathgovind/meteor,AnthonyAstige/meteor,Hansoft/meteor,h200863057/meteor,AlexR1712/meteor,aramk/meteor,mjmasn/meteor,evilemon/meteor,planet-training/meteor,jrudio/meteor,cherbst/meteor,jg3526/meteor,chengxiaole/meteor,codedogfish/meteor,judsonbsilva/meteor,esteedqueen/meteor,vjau/meteor,sclausen/meteor,Theviajerock/meteor,kengchau/meteor,newswim/meteor,mubassirhayat/meteor,Prithvi-A/meteor,elkingtonmcb/meteor,sdeveloper/meteor,SeanOceanHu/meteor,cherbst/meteor,williambr/meteor,DCKT/meteor,nuvipannu/meteor,TribeMedia/meteor,Paulyoufu/meteor-1,kidaa/meteor,DCKT/meteor,LWHTarena/meteor,cbonami/meteor,jenalgit/meteor,ericterpstra/meteor,steedos/meteor,zdd910/meteor,Paulyoufu/meteor-1,Jeremy017/meteor,dfischer/meteor,servel333/meteor,bhargav175/meteor,brettle/meteor,deanius/meteor,steedos/meteor,Eynaliyev/meteor,tdamsma/meteor,baysao/meteor,deanius/meteor,framewr/meteor,Urigo/meteor,namho102/meteor,lassombra/meteor,l0rd0fwar/meteor,mirstan/meteor,paul-barry-kenzan/meteor,ashwathgovind/meteor,HugoRLopes/meteor,benjamn/meteor,Urigo/meteor,Jonekee/meteor,chasertech/meteor,yyx990803/meteor,JesseQin/meteor,paul-barry-kenzan/meteor,dandv/meteor,pjump/meteor,Hansoft/meteor,brettle/meteor,codedogfish/meteor,TribeMedia/meteor,kidaa/meteor,pandeysoni/meteor,aleclarson/meteor,TechplexEngineer/meteor,chmac/meteor,HugoRLopes/meteor,yiliaofan/meteor,udhayam/meteor,modulexcite/meteor,baiyunping333/meteor,Jeremy017/meteor,Ken-Liu/meteor,luohuazju/meteor,jg3526/meteor,jdivy/meteor,codedogfish/meteor,dev-bobsong/meteor,arunoda/meteor,namho102/meteor,lorensr/meteor,kencheung/meteor,ljack/meteor,AlexR1712/meteor,yyx990803/meteor,alphanso/meteor,neotim/meteor,skarekrow/meteor,baysao/meteor,oceanzou123/meteor,fashionsun/meteor,msavin/meteor,chinasb/meteor,baysao/meteor,yiliaofan/meteor,DCKT/meteor,neotim/meteor,lieuwex/meteor,jdivy/meteor,hristaki/meteor,daslicht/meteor,aldeed/meteor,vacjaliu/meteor,chiefninew/meteor,brdtrpp/meteor,IveWong/meteor,yonas/meteor-freebsd,mubassirhayat/meteor,Puena/meteor,lorensr/meteor,lieuwex/meteor,alphanso/meteor,alexbeletsky/meteor,Jeremy017/meteor,papimomi/meteor,jeblister/meteor,daltonrenaldo/meteor,mubassirhayat/meteor,aramk/meteor,shadedprofit/meteor,PatrickMcGuinness/meteor,jeblister/meteor,Quicksteve/meteor,ndarilek/meteor,elkingtonmcb/meteor,emmerge/meteor,youprofit/meteor,evilemon/meteor,sitexa/meteor,kengchau/meteor,SeanOceanHu/meteor,daltonrenaldo/meteor,chinasb/meteor,yanisIk/meteor,neotim/meteor,shrop/meteor,chinasb/meteor,codedogfish/meteor,mauricionr/meteor,iman-mafi/meteor,colinligertwood/meteor,skarekrow/meteor,jdivy/meteor,l0rd0fwar/meteor,h200863057/meteor,mubassirhayat/meteor,bhargav175/meteor,framewr/meteor,planet-training/meteor,yonglehou/meteor,servel333/meteor,Urigo/meteor,justintung/meteor,zdd910/meteor,chinasb/meteor,henrypan/meteor,queso/meteor,oceanzou123/meteor,yanisIk/meteor,lawrenceAIO/meteor,hristaki/meteor,mubassirhayat/meteor,allanalexandre/meteor,pjump/meteor,calvintychan/meteor,aldeed/meteor,dboyliao/meteor,mubassirhayat/meteor,kengchau/meteor,esteedqueen/meteor,joannekoong/meteor,D1no/meteor,Quicksteve/meteor,yanisIk/meteor,queso/meteor,lawrenceAIO/meteor,iman-mafi/meteor,Eynaliyev/meteor,mauricionr/meteor,jagi/meteor,jirengu/meteor,mirstan/meteor,TechplexEngineer/meteor,elkingtonmcb/meteor,TechplexEngineer/meteor,cog-64/meteor,arunoda/meteor,shmiko/meteor,codingang/meteor,JesseQin/meteor,calvintychan/meteor,allanalexandre/meteor,baiyunping333/meteor,skarekrow/meteor,namho102/meteor,ndarilek/meteor,zdd910/meteor,AnthonyAstige/meteor,yiliaofan/meteor,rabbyalone/meteor,yalexx/meteor,tdamsma/meteor,dandv/meteor,meonkeys/meteor,bhargav175/meteor,cog-64/meteor,arunoda/meteor,shmiko/meteor,Profab/meteor,karlito40/meteor,jenalgit/meteor,codingang/meteor,judsonbsilva/meteor,joannekoong/meteor,AnthonyAstige/meteor,Theviajerock/meteor,saisai/meteor,calvintychan/meteor,AnjirHossain/meteor,alphanso/meteor,dandv/meteor,Paulyoufu/meteor-1,lawrenceAIO/meteor,arunoda/meteor,williambr/meteor,henrypan/meteor,modulexcite/meteor,msavin/meteor,rabbyalone/meteor,benjamn/meteor,Prithvi-A/meteor,guazipi/meteor,GrimDerp/meteor,cherbst/meteor,chiefninew/meteor,vjau/meteor,guazipi/meteor,TechplexEngineer/meteor,ericterpstra/meteor,lorensr/meteor,wmkcc/meteor,chengxiaole/meteor,lassombra/meteor,sitexa/meteor,chinasb/meteor,shmiko/meteor,guazipi/meteor,meonkeys/meteor,h200863057/meteor,chasertech/meteor,pjump/meteor,dboyliao/meteor,jg3526/meteor,meteor-velocity/meteor,katopz/meteor,Jonekee/meteor,IveWong/meteor,bhargav175/meteor,iman-mafi/meteor,pandeysoni/meteor,benstoltz/meteor,Profab/meteor,AnjirHossain/meteor,fashionsun/meteor,karlito40/meteor,HugoRLopes/meteor,aramk/meteor,devgrok/meteor,SeanOceanHu/meteor,tdamsma/meteor,ljack/meteor,johnthepink/meteor,katopz/meteor,williambr/meteor,Urigo/meteor,bhargav175/meteor,Eynaliyev/meteor,papimomi/meteor,shrop/meteor,alphanso/meteor,h200863057/meteor,allanalexandre/meteor,udhayam/meteor,Jeremy017/meteor,oceanzou123/meteor,joannekoong/meteor,tdamsma/meteor,jrudio/meteor,evilemon/meteor,sclausen/meteor,Paulyoufu/meteor-1,eluck/meteor,stevenliuit/meteor,esteedqueen/meteor,msavin/meteor,justintung/meteor,D1no/meteor,arunoda/meteor,LWHTarena/meteor,justintung/meteor,codingang/meteor,justintung/meteor,imanmafi/meteor,devgrok/meteor,IveWong/meteor,alexbeletsky/meteor,meteor-velocity/meteor,somallg/meteor,4commerce-technologies-AG/meteor,sunny-g/meteor,paul-barry-kenzan/meteor,D1no/meteor,somallg/meteor,yonas/meteor-freebsd,queso/meteor,elkingtonmcb/meteor,lorensr/meteor,henrypan/meteor,michielvanoeffelen/meteor,williambr/meteor,daslicht/meteor,Quicksteve/meteor,esteedqueen/meteor,SeanOceanHu/meteor,benjamn/meteor,bhargav175/meteor,shadedprofit/meteor,karlito40/meteor,jagi/meteor,yanisIk/meteor,Profab/meteor,GrimDerp/meteor,baiyunping333/meteor,chasertech/meteor,youprofit/meteor,Ken-Liu/meteor,chiefninew/meteor,iman-mafi/meteor,Profab/meteor,ljack/meteor,yonas/meteor-freebsd,ljack/meteor,guazipi/meteor,IveWong/meteor,hristaki/meteor,baysao/meteor,yonas/meteor-freebsd,AlexR1712/meteor,elkingtonmcb/meteor,daltonrenaldo/meteor,queso/meteor,chengxiaole/meteor,stevenliuit/meteor,Theviajerock/meteor,paul-barry-kenzan/meteor,vacjaliu/meteor,yyx990803/meteor,planet-training/meteor,judsonbsilva/meteor,eluck/meteor,sitexa/meteor,yonglehou/meteor,emmerge/meteor,l0rd0fwar/meteor,jg3526/meteor,JesseQin/meteor,benstoltz/meteor,nuvipannu/meteor,guazipi/meteor,baiyunping333/meteor,papimomi/meteor,qscripter/meteor,rabbyalone/meteor,oceanzou123/meteor,lawrenceAIO/meteor,Paulyoufu/meteor-1,eluck/meteor,udhayam/meteor,akintoey/meteor,cbonami/meteor,codedogfish/meteor,paul-barry-kenzan/meteor,newswim/meteor,judsonbsilva/meteor,brdtrpp/meteor,AnjirHossain/meteor,somallg/meteor,codedogfish/meteor,IveWong/meteor,saisai/meteor,eluck/meteor,jenalgit/meteor,Quicksteve/meteor,benstoltz/meteor,newswim/meteor,neotim/meteor,4commerce-technologies-AG/meteor,justintung/meteor,benstoltz/meteor,Quicksteve/meteor,eluck/meteor,Ken-Liu/meteor,benstoltz/meteor,steedos/meteor,yyx990803/meteor,Paulyoufu/meteor-1,colinligertwood/meteor,arunoda/meteor,framewr/meteor,AlexR1712/meteor,zdd910/meteor,judsonbsilva/meteor,ericterpstra/meteor,lawrenceAIO/meteor,l0rd0fwar/meteor,sunny-g/meteor,cbonami/meteor,codedogfish/meteor,hristaki/meteor,steedos/meteor,meonkeys/meteor,modulexcite/meteor,dandv/meteor,vjau/meteor,karlito40/meteor,imanmafi/meteor,ashwathgovind/meteor,AnthonyAstige/meteor,lpinto93/meteor,sunny-g/meteor,judsonbsilva/meteor,Quicksteve/meteor,esteedqueen/meteor,benjamn/meteor,sclausen/meteor,steedos/meteor,devgrok/meteor,sunny-g/meteor,fashionsun/meteor,chmac/meteor,Eynaliyev/meteor,kengchau/meteor,yanisIk/meteor,Profab/meteor,sunny-g/meteor,TribeMedia/meteor,cog-64/meteor,jenalgit/meteor,sclausen/meteor,imanmafi/meteor,skarekrow/meteor,baysao/meteor,dboyliao/meteor,Puena/meteor,katopz/meteor,aleclarson/meteor,juansgaitan/meteor,TechplexEngineer/meteor,michielvanoeffelen/meteor,sclausen/meteor,DCKT/meteor,shrop/meteor,allanalexandre/meteor,alexbeletsky/meteor,4commerce-technologies-AG/meteor,PatrickMcGuinness/meteor,somallg/meteor,D1no/meteor,alexbeletsky/meteor,Puena/meteor,LWHTarena/meteor,msavin/meteor,Jeremy017/meteor,GrimDerp/meteor,queso/meteor,oceanzou123/meteor,vacjaliu/meteor,justintung/meteor,karlito40/meteor,Jeremy017/meteor,youprofit/meteor,tdamsma/meteor,brdtrpp/meteor,D1no/meteor,cbonami/meteor,papimomi/meteor,rozzzly/meteor,JesseQin/meteor,baysao/meteor,chiefninew/meteor,lieuwex/meteor,yonglehou/meteor,emmerge/meteor,namho102/meteor,brdtrpp/meteor,jagi/meteor,michielvanoeffelen/meteor,aramk/meteor,Jonekee/meteor,Puena/meteor,DAB0mB/meteor,papimomi/meteor,chmac/meteor,chiefninew/meteor,EduShareOntario/meteor,emmerge/meteor,Ken-Liu/meteor,baiyunping333/meteor,mirstan/meteor,jagi/meteor,michielvanoeffelen/meteor,guazipi/meteor,baysao/meteor,jirengu/meteor,Ken-Liu/meteor,DAB0mB/meteor,lorensr/meteor,stevenliuit/meteor,luohuazju/meteor,vjau/meteor,ndarilek/meteor,mirstan/meteor,justintung/meteor,mirstan/meteor,qscripter/meteor,jagi/meteor,rozzzly/meteor,Jeremy017/meteor,pandeysoni/meteor,codingang/meteor,whip112/meteor,evilemon/meteor,mauricionr/meteor,williambr/meteor,shrop/meteor,fashionsun/meteor,brettle/meteor,karlito40/meteor,emmerge/meteor,kencheung/meteor,colinligertwood/meteor,shrop/meteor,pjump/meteor,daslicht/meteor,mubassirhayat/meteor,msavin/meteor,eluck/meteor,EduShareOntario/meteor,pjump/meteor,Prithvi-A/meteor,framewr/meteor,dboyliao/meteor,Hansoft/meteor,allanalexandre/meteor,joannekoong/meteor,juansgaitan/meteor,luohuazju/meteor,aldeed/meteor,udhayam/meteor,katopz/meteor,sclausen/meteor,calvintychan/meteor,nuvipannu/meteor,vacjaliu/meteor,chasertech/meteor,chmac/meteor,4commerce-technologies-AG/meteor,shadedprofit/meteor,eluck/meteor,neotim/meteor,johnthepink/meteor,sunny-g/meteor,cbonami/meteor,akintoey/meteor,luohuazju/meteor,yonas/meteor-freebsd,dfischer/meteor,l0rd0fwar/meteor,Prithvi-A/meteor,kencheung/meteor,cherbst/meteor,iman-mafi/meteor,AnjirHossain/meteor,Urigo/meteor,shmiko/meteor,vjau/meteor,TribeMedia/meteor,ljack/meteor,dev-bobsong/meteor,modulexcite/meteor,Puena/meteor,karlito40/meteor,johnthepink/meteor,stevenliuit/meteor,saisai/meteor,meteor-velocity/meteor,steedos/meteor,mirstan/meteor,aramk/meteor,vacjaliu/meteor,EduShareOntario/meteor,brdtrpp/meteor,esteedqueen/meteor,youprofit/meteor,AnthonyAstige/meteor,paul-barry-kenzan/meteor,calvintychan/meteor,wmkcc/meteor,imanmafi/meteor,jg3526/meteor,evilemon/meteor,chengxiaole/meteor,ashwathgovind/meteor,yalexx/meteor,mjmasn/meteor,somallg/meteor,chmac/meteor,LWHTarena/meteor,bhargav175/meteor,LWHTarena/meteor,lassombra/meteor,ericterpstra/meteor,kidaa/meteor,rabbyalone/meteor,evilemon/meteor,AlexR1712/meteor,planet-training/meteor,lorensr/meteor,qscripter/meteor,johnthepink/meteor,luohuazju/meteor,cog-64/meteor,servel333/meteor,DAB0mB/meteor,shrop/meteor,msavin/meteor,devgrok/meteor,Theviajerock/meteor,DAB0mB/meteor,dfischer/meteor,sunny-g/meteor,qscripter/meteor,akintoey/meteor,h200863057/meteor,luohuazju/meteor,imanmafi/meteor,michielvanoeffelen/meteor,judsonbsilva/meteor,shmiko/meteor,Puena/meteor,ericterpstra/meteor,AnjirHossain/meteor,ashwathgovind/meteor,yanisIk/meteor,nuvipannu/meteor,mjmasn/meteor,rozzzly/meteor,lieuwex/meteor,meonkeys/meteor,yalexx/meteor,whip112/meteor,chiefninew/meteor,shadedprofit/meteor,ndarilek/meteor,oceanzou123/meteor,jirengu/meteor,deanius/meteor,l0rd0fwar/meteor,akintoey/meteor,fashionsun/meteor,Theviajerock/meteor,johnthepink/meteor,joannekoong/meteor,AnthonyAstige/meteor,daltonrenaldo/meteor,yiliaofan/meteor,newswim/meteor,esteedqueen/meteor,baiyunping333/meteor,lassombra/meteor,yiliaofan/meteor,brettle/meteor,jirengu/meteor,DCKT/meteor,henrypan/meteor,ericterpstra/meteor,lpinto93/meteor,rabbyalone/meteor,alexbeletsky/meteor,jrudio/meteor,wmkcc/meteor,cherbst/meteor,queso/meteor,karlito40/meteor,mirstan/meteor,meonkeys/meteor,jdivy/meteor,LWHTarena/meteor,qscripter/meteor,jg3526/meteor,codingang/meteor,paul-barry-kenzan/meteor,rozzzly/meteor,rabbyalone/meteor,imanmafi/meteor,katopz/meteor,nuvipannu/meteor,kengchau/meteor,udhayam/meteor,dboyliao/meteor,TribeMedia/meteor,SeanOceanHu/meteor,brettle/meteor,newswim/meteor,GrimDerp/meteor,kencheung/meteor,PatrickMcGuinness/meteor,Ken-Liu/meteor,D1no/meteor,nuvipannu/meteor,stevenliuit/meteor,allanalexandre/meteor,joannekoong/meteor,jrudio/meteor,jrudio/meteor,servel333/meteor,daltonrenaldo/meteor,kidaa/meteor,shmiko/meteor,Ken-Liu/meteor,modulexcite/meteor,AlexR1712/meteor,stevenliuit/meteor,yalexx/meteor,lpinto93/meteor,youprofit/meteor,yinhe007/meteor,shadedprofit/meteor,alphanso/meteor,hristaki/meteor,akintoey/meteor,yanisIk/meteor,somallg/meteor,yonas/meteor-freebsd,l0rd0fwar/meteor,Jonekee/meteor,TechplexEngineer/meteor,pandeysoni/meteor,baiyunping333/meteor,yyx990803/meteor,mjmasn/meteor,4commerce-technologies-AG/meteor,sdeveloper/meteor,SeanOceanHu/meteor,pjump/meteor,rozzzly/meteor,yinhe007/meteor,Paulyoufu/meteor-1,jeblister/meteor,juansgaitan/meteor,h200863057/meteor,Theviajerock/meteor,mauricionr/meteor,jagi/meteor,ljack/meteor,colinligertwood/meteor,Eynaliyev/meteor,servel333/meteor,PatrickMcGuinness/meteor,alphanso/meteor,sdeveloper/meteor | ---
+++
@@ -14,8 +14,8 @@
s.set("METEOR_TEST_TMP", files.mkdtemp());
run = s.run("run", "android");
- run.matchErr("platform is not added");
- run.matchErr("meteor add-platform android");
+ run.matchErr("Platform is not added");
+ run.match("meteor add-platform android");
run.expectExit(1);
run = s.run("add-platform", "android");
@@ -30,7 +30,7 @@
run = s.run("remove-platform", "android");
run.match("removed");
run = s.run("run", "android");
- run.matchErr("platform is not added");
- run.matchErr("meteor add-platform android");
+ run.matchErr("Platform is not added");
+ run.match("meteor add-platform android");
run.expectExit(1);
}); |
1657a56ec025e6670d72c20f1cf87f80ab9c7de6 | lib/throttle.js | lib/throttle.js | 'use strict';
module.exports = (api) => {
api.metasync.throttle = (
// Function throttling
timeout, // time interval
fn, // function to be executed once per timeout
args // arguments array for fn (optional)
) => {
let timer = null;
let wait = false;
return function throttled() {
if (!timer) {
timer = setTimeout(() => {
timer = null;
if (wait) throttled();
}, timeout);
if (args) fn(...args);
else fn();
wait = false;
} else {
wait = true;
}
};
};
api.metasync.debounce = (
timeout,
fn,
args = []
) => {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), timeout);
};
};
api.metasync.timeout = (
// Set timeout for function execution
timeout, // time interval
asyncFunction, // async function to be executed
// done - callback function
done // callback function on done
) => {
let finished = false;
done = api.metasync.cb(done);
const timer = setTimeout(() => {
if (!finished) {
finished = true;
done();
}
}, timeout);
asyncFunction(() => {
if (!finished) {
clearTimeout(timer);
finished = true;
done();
}
});
};
};
| 'use strict';
module.exports = (api) => {
api.metasync.throttle = (
// Function throttling
timeout, // time interval
fn, // function to be executed once per timeout
args // arguments array for fn (optional)
) => {
let timer = null;
let wait = false;
return function throttled() {
if (!timer) {
timer = setTimeout(() => {
timer = null;
if (wait) throttled();
}, timeout);
if (args) fn(...args);
else fn();
wait = false;
} else {
wait = true;
}
};
};
api.metasync.debounce = (
timeout,
fn,
args = []
) => {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), timeout);
};
};
api.metasync.timeout = (
// Set timeout for function execution
timeout, // time interval
asyncFunction, // async function to be executed
// done - callback function
done // callback function on done
) => {
let finished = false;
done = api.metasync.cb(done);
const timer = setTimeout(() => {
if (!finished) {
finished = true;
done(null);
}
}, timeout);
asyncFunction((err, data) => {
if (!finished) {
clearTimeout(timer);
finished = true;
done(err, data);
}
});
};
};
| Add null as error argument for callback | Add null as error argument for callback
Refs: #13
PR-URL: https://github.com/metarhia/metasync/pull/152
Reviewed-By: Timur Shemsedinov <6dc7cb6a9fcface2186172df883b5c9ab417ae33@gmail.com>
| JavaScript | mit | metarhia/MetaSync,DzyubSpirit/MetaSync,DzyubSpirit/MetaSync | ---
+++
@@ -50,15 +50,15 @@
const timer = setTimeout(() => {
if (!finished) {
finished = true;
- done();
+ done(null);
}
}, timeout);
- asyncFunction(() => {
+ asyncFunction((err, data) => {
if (!finished) {
clearTimeout(timer);
finished = true;
- done();
+ done(err, data);
}
});
}; |
204918caff2feeff82f10300364edd43b8e1f4ea | lib/versions.js | lib/versions.js | var semver = require('semver');
var versions = module.exports;
/**
Returns a number representation of the version number that can be compared with other such representations
e.g. compareable('0.6.12') > compareable('0.6.10')
*/
versions.compareable = function compareable(ver) {
var parts = ver.split('.');
return parseInt(parts.map(function(d){ while(d.length < 3) d = '0'+d; return d; }).join(''), 10);
}
/*
Returns the matching version number in a list of sorted version numbers
*/
versions.find = function(version_spec, list, cb) {
var v, i = list.length-1;
if(version_spec.match(/^stable$/i)) {
if(i >= 0) do { v = list[i--] }while(v && parseInt(v.split('.')[1]) % 2 != 0 && i >= 0);// search for an even number: e.g. 0.2.0
}else
if(version_spec.match(/^latest$/i)) {
v = list[list.length-1];
}else{
if(i >= 0) do { v = list[i--] }while(v && !semver.satisfies(v, version_spec) && i >= 0);
if(!semver.satisfies(v, version_spec)) v = null;
}
if(!v) return cb(new Error('Version spec didn\'t match any available version'));
cb(null, v);
}; | var semver = require('semver');
var versions = module.exports;
/**
Returns a number representation of the version number that can be compared with other such representations
e.g. compareable('0.6.12') > compareable('0.6.10')
*/
versions.compareable = function compareable(ver) {
var parts = ver.split('.');
return parseInt(parts.map(function(d){ while(d.length < 3) d = '0'+d; return d; }).join(''), 10);
}
/*
Returns the matching version number in a list of sorted version numbers
*/
versions.find = function(version_spec, list, cb) {
var v, i = list.length-1;
if(version_spec.match(/^stable$/i)) {
if(i >= 0) do { v = list[i--] }while(v && parseInt(v.split('.')[1]) % 2 != 0 && i >= 0);// search for an even number: e.g. 0.2.0
}else
if(version_spec.match(/^latest$/i)) {
v = list[list.length-1];
}else{
if(i >= 0) do { v = list[i--] }while(v && !semver.satisfies(v, version_spec) && i >= 0);
if(!semver.satisfies(v, version_spec)) v = null;
}
if(!v) return cb(new Error('Version spec, "' + version_spec + '", didn\'t match any available version'));
cb(null, v);
};
| Write out version spec that's being used, to make version errors more intuitive. | Write out version spec that's being used, to make version errors more intuitive. | JavaScript | mit | marcelklehr/nodist,marcelklehr/nodist,marcelklehr/nodist,nullivex/nodist,nullivex/nodist,nullivex/nodist | ---
+++
@@ -26,6 +26,6 @@
if(i >= 0) do { v = list[i--] }while(v && !semver.satisfies(v, version_spec) && i >= 0);
if(!semver.satisfies(v, version_spec)) v = null;
}
- if(!v) return cb(new Error('Version spec didn\'t match any available version'));
+ if(!v) return cb(new Error('Version spec, "' + version_spec + '", didn\'t match any available version'));
cb(null, v);
}; |
b933f6e2ba5915d248a954c4c322b91d452d5182 | lib/errors/mfarequirederror.js | lib/errors/mfarequirederror.js | /**
* Module dependencies.
*/
var TokenError = require('./tokenerror');
/**
* `TokenError` error.
*
* @api public
*/
function MFARequiredError(message, uri, user) {
TokenError.call(this, message, 'mfa_required', uri);
Error.captureStackTrace(this, arguments.callee);
this.name = 'MFARequiredError';
this.user = user;
}
/**
* Inherit from `TokenError`.
*/
MFARequiredError.prototype.__proto__ = TokenError.prototype;
/**
* Expose `MFARequiredError`.
*/
module.exports = MFARequiredError;
| /**
* Module dependencies.
*/
var TokenError = require('./tokenerror');
/**
* `TokenError` error.
*
* @api public
*/
function MFARequiredError(message, uri, user, areq) {
TokenError.call(this, message, 'mfa_required', uri);
Error.captureStackTrace(this, arguments.callee);
this.name = 'MFARequiredError';
this.user = user;
this.req = areq;
}
/**
* Inherit from `TokenError`.
*/
MFARequiredError.prototype.__proto__ = TokenError.prototype;
/**
* Expose `MFARequiredError`.
*/
module.exports = MFARequiredError;
| Add request to MFA error for keeping session context. | Add request to MFA error for keeping session context.
| JavaScript | mit | jaredhanson/oauth2orize-2fa | ---
+++
@@ -8,11 +8,12 @@
*
* @api public
*/
-function MFARequiredError(message, uri, user) {
+function MFARequiredError(message, uri, user, areq) {
TokenError.call(this, message, 'mfa_required', uri);
Error.captureStackTrace(this, arguments.callee);
this.name = 'MFARequiredError';
this.user = user;
+ this.req = areq;
}
/** |
adaa54ca513706ad15f858d318dd02895b3a6445 | src/register-element.js | src/register-element.js | import * as privateMethods from './elements/private-methods.js';
const callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
export default function registerElement(tagName, Constructor) {
// The WebIDL bindings generated this, thinking that they were in an ES6 world where the constructor they created
// would be the same as the one registered with the system. So delete it and replace it with the one generated by
// `document.registerElement`.
delete window[Constructor.name];
const GeneratedConstructor = window[Constructor.name] = document.registerElement(tagName, Constructor);
// Delete any custom element callbacks since native elements don't have them and we don't want that kind of
// observable difference. Their presence only matters at registration time anyway.
for (const callback of callbacks) {
delete GeneratedConstructor[callback];
}
// Register the appropriate private methods under the generated constructor name, since when they are looked up at
// runtime it will be with that name. This is a band-aid until https://w3c.github.io/webcomponents/spec/custom/#es6
// lands.
const privateMethodsForConstructor = privateMethods.getAll(Constructor.name);
if (privateMethodsForConstructor) {
const registerElementGeneratedName = GeneratedConstructor.name;
privateMethods.setAll(registerElementGeneratedName, privateMethodsForConstructor);
}
}
| import * as privateMethods from './elements/private-methods.js';
const callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
export default function registerElement(tagName, Constructor) {
// The WebIDL bindings generated this, thinking that they were in an ES6 world where the constructor they created
// would be the same as the one registered with the system. So delete it and replace it with the one generated by
// `document.registerElement`.
delete window[Constructor.name];
const GeneratedConstructor = window[Constructor.name] = document.registerElement(tagName, Constructor);
// Delete any custom element callbacks since native elements don't have them and we don't want that kind of
// observable difference. Their presence only matters at registration time anyway.
for (const callback of callbacks) {
delete GeneratedConstructor.prototype[callback];
}
// Register the appropriate private methods under the generated constructor name, since when they are looked up at
// runtime it will be with that name. This is a band-aid until https://w3c.github.io/webcomponents/spec/custom/#es6
// lands.
const privateMethodsForConstructor = privateMethods.getAll(Constructor.name);
if (privateMethodsForConstructor) {
const registerElementGeneratedName = GeneratedConstructor.name;
privateMethods.setAll(registerElementGeneratedName, privateMethodsForConstructor);
}
}
| Fix logic for removing the custom element callbacks | Fix logic for removing the custom element callbacks
| JavaScript | apache-2.0 | domenic/html-as-custom-elements,domenic/html-as-custom-elements,zenorocha/html-as-custom-elements,valmzetvn/html-as-custom-elements,valmzetvn/html-as-custom-elements,valmzetvn/html-as-custom-elements,domenic/html-as-custom-elements,zenorocha/html-as-custom-elements | ---
+++
@@ -13,7 +13,7 @@
// Delete any custom element callbacks since native elements don't have them and we don't want that kind of
// observable difference. Their presence only matters at registration time anyway.
for (const callback of callbacks) {
- delete GeneratedConstructor[callback];
+ delete GeneratedConstructor.prototype[callback];
}
// Register the appropriate private methods under the generated constructor name, since when they are looked up at |
6e08a454f936d58fc5fc1720e7a74d94b3bc9c9e | demo/simple.js | demo/simple.js | 'use strict';
var sandboxFactory = require('..'),
MemoryFS = require('memory-fs'),
memoryFS = new MemoryFS(),
sandbox = sandboxFactory.create(memoryFS);
memoryFS.mkdirpSync('/my/dir');
memoryFS.writeFileSync(
'/my/dir/file1.js',
'console.log("File1"); require("./file2.js"); console.log("Then"); require("/my/dir"); console.log("End");'
);
memoryFS.writeFileSync(
'/my/dir/index.js',
'console.log("Index");'
);
memoryFS.writeFileSync(
'/my/dir/file2.js',
'console.log("File2");'
);
sandbox.execute('require("/my/dir/file1");');
| 'use strict';
var sandboxFactory = require('..'),
mockFS = require('mock-fs').fs(),
sandbox = sandboxFactory.create(mockFS);
mockFS.mkdirSync('/my');
mockFS.mkdirSync('/my/dir');
mockFS.writeFileSync(
'/my/dir/file1.js',
'console.log("File1"); require("./file2.js"); console.log("Then"); require("/my/dir"); console.log("End");'
);
mockFS.writeFileSync(
'/my/dir/index.js',
'console.log("Index");'
);
mockFS.writeFileSync(
'/my/dir/file2.js',
'console.log("File2");'
);
sandbox.execute('require("/my/dir/file1");');
| Switch demo to use mock-fs rather than memory-fs | Switch demo to use mock-fs rather than memory-fs
| JavaScript | mit | asmblah/playpit | ---
+++
@@ -1,20 +1,20 @@
'use strict';
var sandboxFactory = require('..'),
- MemoryFS = require('memory-fs'),
- memoryFS = new MemoryFS(),
- sandbox = sandboxFactory.create(memoryFS);
+ mockFS = require('mock-fs').fs(),
+ sandbox = sandboxFactory.create(mockFS);
-memoryFS.mkdirpSync('/my/dir');
-memoryFS.writeFileSync(
+mockFS.mkdirSync('/my');
+mockFS.mkdirSync('/my/dir');
+mockFS.writeFileSync(
'/my/dir/file1.js',
'console.log("File1"); require("./file2.js"); console.log("Then"); require("/my/dir"); console.log("End");'
);
-memoryFS.writeFileSync(
+mockFS.writeFileSync(
'/my/dir/index.js',
'console.log("Index");'
);
-memoryFS.writeFileSync(
+mockFS.writeFileSync(
'/my/dir/file2.js',
'console.log("File2");'
); |
f9069b0f601cfa508da172be105f1d0be35acd4c | js/views/ViewManager.js | js/views/ViewManager.js | import HomeView from './HomeView';
import JoinView from './JoinView';
export default class ViewManager {
constructor(target) {
this.target = target;
this.home = new HomeView();
this.join = new JoinView();
this.load('home');
}
load(viewName) {
this[viewName].init().then(view => {
// First remove all Childs
while(this.target.firstChild) {
this.target.removeChild(this.target.firstChild);
}
// Then load the view into it
view.show(this.target);
});
}
}
| import HomeView from './HomeView';
import JoinView from './JoinView';
export default class ViewManager {
constructor(target) {
this.target = target;
// Register all known views
this.home = new HomeView();
this.join = new JoinView();
// Define default view
this.DEFAULT_VIEW = 'home';
// Init URL bar and history
this.init();
}
init() {
if(location.hash == '')
location.hash = '/';
// Load the view given in the URL
this.load(location.hash.substr(2), true);
// Check history back and forward to load the correct view
window.addEventListener('popstate', event => {
this.load(location.hash.substr(2), true);
});
}
load(viewName = '', nohistory = false) {
// Check if view exists
if(!this[viewName || this.DEFAULT_VIEW])
viewName = 'notfound';
// Init the new view (load template etc.)
this[viewName || this.DEFAULT_VIEW].init().then(view => {
// Push the new view to the URL and the history
if(!nohistory)
history.pushState(null, viewName || this.DEFAULT_VIEW, `#/${viewName}`);
// Remove the old view
while(this.target.firstChild) {
this.target.removeChild(this.target.firstChild);
}
// Load the view
view.show(this.target);
});
}
}
| Add URL support with history.pushState | Add URL support with history.pushState
| JavaScript | mit | richterdennis/CastleCrush,richterdennis/CastleCrush | ---
+++
@@ -5,21 +5,49 @@
constructor(target) {
this.target = target;
+ // Register all known views
this.home = new HomeView();
this.join = new JoinView();
- this.load('home');
+ // Define default view
+ this.DEFAULT_VIEW = 'home';
+
+ // Init URL bar and history
+ this.init();
}
- load(viewName) {
- this[viewName].init().then(view => {
+ init() {
+ if(location.hash == '')
+ location.hash = '/';
- // First remove all Childs
+ // Load the view given in the URL
+ this.load(location.hash.substr(2), true);
+
+ // Check history back and forward to load the correct view
+ window.addEventListener('popstate', event => {
+ this.load(location.hash.substr(2), true);
+ });
+ }
+
+ load(viewName = '', nohistory = false) {
+
+ // Check if view exists
+ if(!this[viewName || this.DEFAULT_VIEW])
+ viewName = 'notfound';
+
+ // Init the new view (load template etc.)
+ this[viewName || this.DEFAULT_VIEW].init().then(view => {
+
+ // Push the new view to the URL and the history
+ if(!nohistory)
+ history.pushState(null, viewName || this.DEFAULT_VIEW, `#/${viewName}`);
+
+ // Remove the old view
while(this.target.firstChild) {
this.target.removeChild(this.target.firstChild);
}
- // Then load the view into it
+ // Load the view
view.show(this.target);
});
} |
e0fcee4687d0d97fefcef72bc828fcfb0a197da1 | src/validations/html.js | src/validations/html.js | var Promise = require('es6-promise').Promise;
var lodash = require('lodash');
var validateWithHtmllint = require('./html/htmllint.js');
var validateWithSlowparse = require('./html/slowparse.js');
function filterErrors(errors) {
var indexedErrors = lodash(errors).indexBy('reason');
var suppressedTypes = indexedErrors.
values().
map('suppresses').
flatten().
value();
return indexedErrors.omit(suppressedTypes).values().value();
}
module.exports = function(source) {
return Promise.all([
validateWithSlowparse(source),
validateWithHtmllint(source),
]).then(function(results) {
var filteredErrors = filterErrors(lodash.flatten(results));
return lodash.sortBy(filteredErrors, 'row');
});
};
| var Promise = require('es6-promise').Promise;
var lodash = require('lodash');
var validateWithHtmllint = require('./html/htmllint.js');
var validateWithSlowparse = require('./html/slowparse.js');
function filterErrors(errors) {
var groupedErrors = lodash(errors).groupBy('reason');
var suppressedTypes = groupedErrors.
values().
flatten().
map('suppresses').
flatten().
value();
return groupedErrors.omit(suppressedTypes).values().flatten().value();
}
module.exports = function(source) {
return Promise.all([
validateWithSlowparse(source),
validateWithHtmllint(source),
]).then(function(results) {
var filteredErrors = filterErrors(lodash.flatten(results));
return lodash.sortBy(filteredErrors, 'row');
});
};
| Allow the same error on different lines | Allow the same error on different lines
| JavaScript | mit | jwang1919/popcode,jwang1919/popcode,jwang1919/popcode,jwang1919/popcode,popcodeorg/popcode,outoftime/learnpad,outoftime/learnpad,popcodeorg/popcode,popcodeorg/popcode,popcodeorg/popcode | ---
+++
@@ -4,15 +4,16 @@
var validateWithSlowparse = require('./html/slowparse.js');
function filterErrors(errors) {
- var indexedErrors = lodash(errors).indexBy('reason');
+ var groupedErrors = lodash(errors).groupBy('reason');
- var suppressedTypes = indexedErrors.
+ var suppressedTypes = groupedErrors.
values().
+ flatten().
map('suppresses').
flatten().
value();
- return indexedErrors.omit(suppressedTypes).values().value();
+ return groupedErrors.omit(suppressedTypes).values().flatten().value();
}
module.exports = function(source) { |
87f7091e84b9cad0589160584f85d979b21df4e8 | lib/rules_inline/backticks.js | lib/rules_inline/backticks.js | // Parse backticks
'use strict';
module.exports = function backtick(state, silent) {
var start, max, marker, matchStart, matchEnd, token,
pos = state.pos,
ch = state.src.charCodeAt(pos);
if (ch !== 0x60/* ` */) { return false; }
start = pos;
pos++;
max = state.posMax;
while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; }
marker = state.src.slice(start, pos);
matchStart = matchEnd = pos;
while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) {
matchEnd = matchStart + 1;
while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; }
if (matchEnd - matchStart === marker.length) {
if (!silent) {
token = state.push('code_inline', 'code', 0);
token.markup = marker;
token.content = state.src.slice(pos, matchStart)
.replace(/\n/g, ' ')
.replace(/^ (.+) $/, '$1');
}
state.pos = matchEnd;
return true;
}
}
if (!silent) { state.pending += marker; }
state.pos += marker.length;
return true;
};
| // Parse backticks
'use strict';
module.exports = function backtick(state, silent) {
var start, max, marker, matchStart, matchEnd, token,
pos = state.pos,
ch = state.src.charCodeAt(pos);
if (ch !== 0x60/* ` */) { return false; }
start = pos;
pos++;
max = state.posMax;
while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; }
marker = state.src.slice(start, pos);
matchStart = matchEnd = pos;
while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) {
matchEnd = matchStart + 1;
while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; }
if (matchEnd - matchStart === marker.length) {
if (!silent) {
token = state.push('code_inline', 'code', 0);
token.markup = marker;
token.content = state.src.slice(pos, matchStart)
.replace(/\n/g, ' ')
.replace(/^ (.+) $/, '$1');
token.position = start;
token.size = (matchStart + 1) - token.position;
}
state.pos = matchEnd;
return true;
}
}
if (!silent) { state.pending += marker; }
state.pos += marker.length;
return true;
};
| Add position and size to code_inline | Add position and size to code_inline
| JavaScript | mit | GerHobbelt/markdown-it,GerHobbelt/markdown-it | ---
+++
@@ -31,6 +31,8 @@
token.content = state.src.slice(pos, matchStart)
.replace(/\n/g, ' ')
.replace(/^ (.+) $/, '$1');
+ token.position = start;
+ token.size = (matchStart + 1) - token.position;
}
state.pos = matchEnd;
return true; |
9b6c06ddb62f358a73e3d243c9533c068a5b0bda | app/assets/javascripts/directives/validation/reset_validation_status.js | app/assets/javascripts/directives/validation/reset_validation_status.js | ManageIQ.angular.app.directive('resetValidationStatus', ['$rootScope', function($rootScope) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
scope.$watch(attrs.ngModel, function() {
adjustValidationStatus(ctrl.$modelValue, scope, ctrl, attrs, $rootScope);
});
ctrl.$parsers.push(function(value) {
adjustValidationStatus(value, scope, ctrl, attrs, $rootScope);
return value;
});
}
}
}]);
var adjustValidationStatus = function(value, scope, ctrl, attrs, rootScope) {
if(scope.checkAuthentication === true && angular.isDefined(scope.postValidationModel)) {
var modelPostValidationObject = angular.copy(scope.postValidationModel[attrs.prefix]);
delete modelPostValidationObject[ctrl.$name];
var modelObject = angular.copy(scope[scope.model]);
if(angular.isDefined(modelObject[ctrl.$name])) {
delete modelObject[ctrl.$name];
}
if (value == scope.postValidationModel[attrs.prefix][ctrl.$name] && _.isMatch(modelObject, modelPostValidationObject)) {
scope[scope.model][attrs.resetValidationStatus] = true;
rootScope.$broadcast('clearErrorOnTab', {tab: attrs.prefix});
} else {
scope[scope.model][attrs.resetValidationStatus] = false;
rootScope.$broadcast('setErrorOnTab', {tab: attrs.prefix});
}
}
};
| ManageIQ.angular.app.directive('resetValidationStatus', ['$rootScope', function($rootScope) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
scope.$watch(attrs.ngModel, function() {
adjustValidationStatus(ctrl.$modelValue, scope, ctrl, attrs, $rootScope);
});
ctrl.$parsers.push(function(value) {
adjustValidationStatus(value, scope, ctrl, attrs, $rootScope);
return value;
});
}
}
}]);
var adjustValidationStatus = function(value, scope, ctrl, attrs, rootScope) {
if(scope.checkAuthentication === true &&
angular.isDefined(scope.postValidationModel) &&
angular.isDefined(scope.postValidationModel[attrs.prefix])) {
var modelPostValidationObject = angular.copy(scope.postValidationModel[attrs.prefix]);
delete modelPostValidationObject[ctrl.$name];
var modelObject = angular.copy(scope[scope.model]);
if(angular.isDefined(modelObject[ctrl.$name])) {
delete modelObject[ctrl.$name];
}
if (value == scope.postValidationModel[attrs.prefix][ctrl.$name] && _.isMatch(modelObject, modelPostValidationObject)) {
scope[scope.model][attrs.resetValidationStatus] = true;
rootScope.$broadcast('clearErrorOnTab', {tab: attrs.prefix});
} else {
scope[scope.model][attrs.resetValidationStatus] = false;
rootScope.$broadcast('setErrorOnTab', {tab: attrs.prefix});
}
}
};
| Check if postValidationModel is defined for the tab in question | Check if postValidationModel is defined for the tab in question
| JavaScript | apache-2.0 | fbladilo/manageiq,agrare/manageiq,durandom/manageiq,mkanoor/manageiq,borod108/manageiq,matobet/manageiq,NickLaMuro/manageiq,josejulio/manageiq,aufi/manageiq,maas-ufcg/manageiq,maas-ufcg/manageiq,d-m-u/manageiq,tinaafitz/manageiq,matobet/manageiq,mzazrivec/manageiq,kbrock/manageiq,ilackarms/manageiq,jvlcek/manageiq,romaintb/manageiq,ManageIQ/manageiq,romaintb/manageiq,billfitzgerald0120/manageiq,mkanoor/manageiq,gmcculloug/manageiq,romanblanco/manageiq,jameswnl/manageiq,djberg96/manageiq,NickLaMuro/manageiq,pkomanek/manageiq,jntullo/manageiq,d-m-u/manageiq,israel-hdez/manageiq,fbladilo/manageiq,josejulio/manageiq,tinaafitz/manageiq,israel-hdez/manageiq,skateman/manageiq,lpichler/manageiq,mresti/manageiq,gmcculloug/manageiq,mzazrivec/manageiq,chessbyte/manageiq,KevinLoiseau/manageiq,juliancheal/manageiq,mzazrivec/manageiq,KevinLoiseau/manageiq,kbrock/manageiq,skateman/manageiq,jvlcek/manageiq,romanblanco/manageiq,fbladilo/manageiq,maas-ufcg/manageiq,gerikis/manageiq,durandom/manageiq,matobet/manageiq,jntullo/manageiq,pkomanek/manageiq,romaintb/manageiq,branic/manageiq,branic/manageiq,d-m-u/manageiq,jrafanie/manageiq,branic/manageiq,ailisp/manageiq,romaintb/manageiq,ManageIQ/manageiq,jameswnl/manageiq,mfeifer/manageiq,juliancheal/manageiq,djberg96/manageiq,ailisp/manageiq,jameswnl/manageiq,gerikis/manageiq,syncrou/manageiq,lpichler/manageiq,jrafanie/manageiq,hstastna/manageiq,KevinLoiseau/manageiq,matobet/manageiq,tinaafitz/manageiq,romanblanco/manageiq,kbrock/manageiq,romaintb/manageiq,syncrou/manageiq,mresti/manageiq,mfeifer/manageiq,gmcculloug/manageiq,billfitzgerald0120/manageiq,yaacov/manageiq,mfeifer/manageiq,NaNi-Z/manageiq,syncrou/manageiq,gmcculloug/manageiq,mzazrivec/manageiq,KevinLoiseau/manageiq,josejulio/manageiq,kbrock/manageiq,juliancheal/manageiq,agrare/manageiq,ailisp/manageiq,mresti/manageiq,mfeifer/manageiq,josejulio/manageiq,skateman/manageiq,tzumainn/manageiq,djberg96/manageiq,andyvesel/manageiq,mresti/manageiq,ManageIQ/manageiq,andyvesel/manageiq,mkanoor/manageiq,d-m-u/manageiq,maas-ufcg/manageiq,yaacov/manageiq,tinaafitz/manageiq,lpichler/manageiq,romanblanco/manageiq,aufi/manageiq,jrafanie/manageiq,gerikis/manageiq,gerikis/manageiq,jntullo/manageiq,pkomanek/manageiq,maas-ufcg/manageiq,skateman/manageiq,ilackarms/manageiq,maas-ufcg/manageiq,djberg96/manageiq,hstastna/manageiq,mkanoor/manageiq,borod108/manageiq,NaNi-Z/manageiq,NaNi-Z/manageiq,borod108/manageiq,billfitzgerald0120/manageiq,tzumainn/manageiq,tzumainn/manageiq,chessbyte/manageiq,hstastna/manageiq,romaintb/manageiq,borod108/manageiq,branic/manageiq,ilackarms/manageiq,jameswnl/manageiq,NickLaMuro/manageiq,syncrou/manageiq,andyvesel/manageiq,NaNi-Z/manageiq,hstastna/manageiq,juliancheal/manageiq,KevinLoiseau/manageiq,durandom/manageiq,fbladilo/manageiq,NickLaMuro/manageiq,aufi/manageiq,agrare/manageiq,ailisp/manageiq,tzumainn/manageiq,durandom/manageiq,jvlcek/manageiq,aufi/manageiq,israel-hdez/manageiq,ilackarms/manageiq,yaacov/manageiq,billfitzgerald0120/manageiq,yaacov/manageiq,agrare/manageiq,jntullo/manageiq,andyvesel/manageiq,chessbyte/manageiq,jvlcek/manageiq,ManageIQ/manageiq,pkomanek/manageiq,israel-hdez/manageiq,lpichler/manageiq,KevinLoiseau/manageiq,chessbyte/manageiq,jrafanie/manageiq | ---
+++
@@ -15,7 +15,9 @@
}]);
var adjustValidationStatus = function(value, scope, ctrl, attrs, rootScope) {
- if(scope.checkAuthentication === true && angular.isDefined(scope.postValidationModel)) {
+ if(scope.checkAuthentication === true &&
+ angular.isDefined(scope.postValidationModel) &&
+ angular.isDefined(scope.postValidationModel[attrs.prefix])) {
var modelPostValidationObject = angular.copy(scope.postValidationModel[attrs.prefix]);
delete modelPostValidationObject[ctrl.$name];
|
93f2591b913d31cf6521812f1fed6969efe0401e | app/routes/course-materials.js | app/routes/course-materials.js | import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
const { Route, RSVP } = Ember;
const { Promise, all, map } = RSVP;
export default Route.extend(AuthenticatedRouteMixin, {
afterModel(course){
return all([
this.loadCourseLearhingMaterials(course),
this.loadSessionLearhingMaterials(course),
])
},
loadCourseLearhingMaterials(course){
return new Promise(resolve => {
course.get('learningMaterials').then(courseLearningMaterials => {
all(courseLearningMaterials.getEach('learningMaterial')).then(()=> {
resolve();
})
});
});
},
loadSessionLearhingMaterials(course){
return new Promise(resolve => {
course.get('sessions').then(sessions => {
map(sessions.toArray(), session => {
return all([
session.get('learningMaterials'),
session.get('firstOfferingDate')
]);
}).then(()=>{
resolve();
})
});
});
}
});
| import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
const { Route, RSVP } = Ember;
const { Promise, all, map } = RSVP;
export default Route.extend(AuthenticatedRouteMixin, {
afterModel(course){
return all([
this.loadCourseLearningMaterials(course),
this.loadSessionLearningMaterials(course),
])
},
loadCourseLearningMaterials(course){
return new Promise(resolve => {
course.get('learningMaterials').then(courseLearningMaterials => {
all(courseLearningMaterials.getEach('learningMaterial')).then(()=> {
resolve();
})
});
});
},
loadSessionLearningMaterials(course){
return new Promise(resolve => {
course.get('sessions').then(sessions => {
map(sessions.toArray(), session => {
return all([
session.get('learningMaterials'),
session.get('firstOfferingDate')
]);
}).then(()=>{
resolve();
})
});
});
}
});
| Fix typo/miss spell in method names | Fix typo/miss spell in method names
| JavaScript | mit | gboushey/frontend,ilios/frontend,jrjohnson/frontend,stopfstedt/frontend,dartajax/frontend,jrjohnson/frontend,dartajax/frontend,stopfstedt/frontend,ilios/frontend,djvoa12/frontend,gabycampagna/frontend,thecoolestguy/frontend,thecoolestguy/frontend,gboushey/frontend,djvoa12/frontend,gabycampagna/frontend | ---
+++
@@ -7,12 +7,12 @@
export default Route.extend(AuthenticatedRouteMixin, {
afterModel(course){
return all([
- this.loadCourseLearhingMaterials(course),
- this.loadSessionLearhingMaterials(course),
+ this.loadCourseLearningMaterials(course),
+ this.loadSessionLearningMaterials(course),
])
},
- loadCourseLearhingMaterials(course){
+ loadCourseLearningMaterials(course){
return new Promise(resolve => {
course.get('learningMaterials').then(courseLearningMaterials => {
all(courseLearningMaterials.getEach('learningMaterial')).then(()=> {
@@ -21,7 +21,7 @@
});
});
},
- loadSessionLearhingMaterials(course){
+ loadSessionLearningMaterials(course){
return new Promise(resolve => {
course.get('sessions').then(sessions => {
map(sessions.toArray(), session => { |
9a5eede1ae59e712eb17aec182af1468fd409a15 | render.js | render.js | gRenderer = {
frame: 0,
render: function() {
this.context.fillStyle = '#000';
this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height);
switch (gScene.scene) {
case 'title':
gScene.renderTitle();
break;
case 'hangar':
case 'game':
gScene.renderBack();
if (gPlayer.life > 0) gPlayer.render();
gScene.renderFore();
gPlayer.projectiles.forEach(function(p) { p.render() }.bind(this));
if (gScene.inTransition) gScene.renderTransition();
break;
case 'levelTitle':
gScene.renderLevelTitle();
break;
}
if (!gScene.inTransition) gInput.render();
// Debug display
// this.context.font = '16px monospace';
// this.context.textAlign = 'left';
// this.context.fillStyle = '#FFF';
// this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12);
// this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36);
this.frame = (this.frame + 1) % 60;
}
}
| gRenderer = {
frame: 0,
render: function() {
this.context.fillStyle = '#000';
this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height);
switch (gScene.scene) {
case 'title':
gScene.renderTitle();
break;
case 'hangar':
case 'game':
gScene.renderBack();
if (gPlayer.life > 0) gPlayer.render();
gScene.renderFore();
gPlayer.projectiles.forEach(function(p) { p.render() }.bind(this));
if (gScene.inTransition) gScene.renderTransition();
break;
case 'levelTitle':
gScene.renderLevelTitle();
break;
}
if (!gScene.inTransition) gInput.render();
// Debug display
// this.context.font = '16px monospace';
// this.context.textAlign = 'left';
// this.context.fillStyle = '#FFF';
// this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12);
// this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36);
this.frame = (this.frame + 1) % 240;
}
}
| Increase gRenderer frame max to 240 | Increase gRenderer frame max to 240
| JavaScript | mit | peternatewood/shmup,peternatewood/shmup,peternatewood/shmup | ---
+++
@@ -29,6 +29,6 @@
// this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12);
// this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36);
- this.frame = (this.frame + 1) % 60;
+ this.frame = (this.frame + 1) % 240;
}
} |
cdf0bab5f02a914e51be806680e5c7252b873d76 | plugins/meta.js | plugins/meta.js | const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
const serverhostname = "http://localhost:16001";
//const serverhostname = "https://api.repkam09.com";
class MetaEndpoints extends LifeforcePlugin {
constructor(restifyserver, logger, name) {
super(restifyserver, logger, name);
this.apiMap = [
{
path: "/api/about",
type: "get",
handler: handleAboutApi
},
{
path: "/",
type: "get",
handler: handleAboutApi
}
];
}
}
function handleAboutApi(req, res, next) {
var apis = [];
var keys = Object.keys(this.restifyserver.router.mounts);
keys.forEach((key) => {
var current = this.restifyserver.router.mounts[key];
apis.push({ path: serverhostname + current.spec.path, method: current.method });
});
res.send(200, apis);
}
module.exports = MetaEndpoints; | const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
//const serverhostname = "http://localhost:16001";
const serverhostname = "https://api.repkam09.com";
class MetaEndpoints extends LifeforcePlugin {
constructor(restifyserver, logger, name) {
super(restifyserver, logger, name);
this.apiMap = [
{
path: "/api/about",
type: "get",
handler: handleAboutApi
},
{
path: "/",
type: "get",
handler: handleAboutApi
}
];
}
}
function handleAboutApi(req, res, next) {
var apis = [];
var keys = Object.keys(this.restifyserver.router.mounts);
keys.forEach((key) => {
var current = this.restifyserver.router.mounts[key];
apis.push({ path: serverhostname + current.spec.path, method: current.method });
});
res.send(200, apis);
}
module.exports = MetaEndpoints;
| Fix url to real production url | Fix url to real production url
| JavaScript | mit | repkam09/repka-lifeforce,repkam09/repka-lifeforce,repkam09/repka-lifeforce | ---
+++
@@ -1,7 +1,7 @@
const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
-const serverhostname = "http://localhost:16001";
-//const serverhostname = "https://api.repkam09.com";
+//const serverhostname = "http://localhost:16001";
+const serverhostname = "https://api.repkam09.com";
class MetaEndpoints extends LifeforcePlugin {
constructor(restifyserver, logger, name) { |
d9ff1a08d3c89cc88b7436ca97ffda589d322f82 | test/retrieve.js | test/retrieve.js | 'use strict';
var should = require('should');
var config = require('../config/configuration.js');
var retrieve = require('../lib/provider-google-drive/helpers/retrieve.js');
describe("Retrieve files", function () {
it("should list files when no id passed and return the id of the last document", function(done) {
retrieve(config.test_refresh_token, null, config, function(err, files, lastId) {
if(err) {
throw err;
}
files.should.have.lengthOf(4);
should.exist(files[0]);
lastId.should.equal("49");
files[0].should.have.property('id', '1wnEFyXM4bSaSqMORS0NycszCse9dJvhYoiZnITRMeCE');
files[0].should.have.property('title', 'Test');
files[0].should.have.property('mimeType', 'application/vnd.google-apps.document');
done();
});
});
it("should list files from a given id", function(done) {
retrieve(config.test_refresh_token, "44", config, function(err, files, lastId) {
if(err) {
throw err;
}
files.length.should.equal(3);
done();
});
});
});
| 'use strict';
var should = require('should');
var config = require('../config/configuration.js');
var retrieve = require('../lib/provider-google-drive/helpers/retrieve.js');
describe("Retrieve files", function () {
it("should list files when no id passed and return the id of the last document", function(done) {
retrieve(config.test_refresh_token, null, config, function(err, files, lastId) {
if(err) {
throw err;
}
files.should.have.lengthOf(4);
should.exist(files[0]);
lastId.should.equal("82");
files[0].should.have.property('id', '1wnEFyXM4bSaSqMORS0NycszCse9dJvhYoiZnITRMeCE');
files[0].should.have.property('title', 'Test');
files[0].should.have.property('mimeType', 'application/vnd.google-apps.document');
done();
});
});
it("should list files from a given id", function(done) {
retrieve(config.test_refresh_token, "44", config, function(err, files, lastId) {
if(err) {
throw err;
}
files.length.should.equal(4);
done();
});
});
});
| Update to the new drive state | Update to the new drive state
| JavaScript | mit | AnyFetch/gdrive-provider.anyfetch.com | ---
+++
@@ -12,7 +12,7 @@
}
files.should.have.lengthOf(4);
should.exist(files[0]);
- lastId.should.equal("49");
+ lastId.should.equal("82");
files[0].should.have.property('id', '1wnEFyXM4bSaSqMORS0NycszCse9dJvhYoiZnITRMeCE');
files[0].should.have.property('title', 'Test');
files[0].should.have.property('mimeType', 'application/vnd.google-apps.document');
@@ -24,7 +24,7 @@
if(err) {
throw err;
}
- files.length.should.equal(3);
+ files.length.should.equal(4);
done();
});
}); |
9dd0b0983b9ae8cf45d9505494e0e0afad9094f7 | oui.js | oui.js | #!/usr/bin/env node
"use strict";
process.title = "oui";
var arg = process.argv[2],
oui = require("./"),
spin = require("char-spinner");
if (arg === "--update") {
var interval = spin();
oui.update(true, function (err) {
clearInterval(interval);
if (err) process.stdout.write(err + "\n");
process.exit(err ? 1 : 0);
});
} else if (!arg || arg === "--help") {
process.stdout.write([
"",
" Usage: oui mac [options]",
"",
" Options:",
"",
" --help display this help",
" --update update the database",
"",
""
].join("\n"));
process.exit(1);
} else {
var result;
try {
result = oui(arg);
} catch (err) {
process.stdout.write(err.message + "\n");
process.exit(1);
}
if (result) {
process.stdout.write(result + "\n");
} else {
process.stdout.write(arg + " not found in database\n");
}
process.exit(0);
}
| #!/usr/bin/env node
"use strict";
process.title = "oui";
var arg = process.argv[2],
oui = require("./"),
spin = require("char-spinner");
if (arg === "--update") {
var interval = spin();
oui.update(true, function (err) {
clearInterval(interval);
if (err) process.stdout.write(err + "\n");
process.exit(err ? 1 : 0);
});
} else if (!arg || arg === "--help") {
process.stdout.write([
"",
" Usage: oui mac [options]",
"",
" Options:",
"",
" --help display this help",
" --update update the database",
"",
""
].join("\n"));
process.exit(0);
} else {
var result;
try {
result = oui(arg);
} catch (err) {
process.stdout.write(err.message + "\n");
process.exit(1);
}
if (result)
process.stdout.write(result + "\n");
else
process.stdout.write(arg + " not found in database\n");
process.exit(0);
}
| Correct exit code on help | Correct exit code on help
| JavaScript | bsd-2-clause | silverwind/oui | ---
+++
@@ -26,7 +26,7 @@
"",
""
].join("\n"));
- process.exit(1);
+ process.exit(0);
} else {
var result;
try {
@@ -36,10 +36,10 @@
process.exit(1);
}
- if (result) {
+ if (result)
process.stdout.write(result + "\n");
- } else {
+ else
process.stdout.write(arg + " not found in database\n");
- }
+
process.exit(0);
} |
dd2ac1fb52cb9c154d0b9bf354fd22d250413d94 | date.polyfill.js | date.polyfill.js | /**
* Date.prototype.toISOString()
* version 0.0.0
* Feature Chrome Firefox Internet Explorer Opera Safari Edge
* Basic support 3 1 9 10.5 5 12
* -------------------------------------------------------------------------------
*/
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function () {
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
'Z';
};
} | /**
* Date.prototype.toISOString()
* version 0.0.0
* Feature Chrome Firefox Internet Explorer Opera Safari Edge
* Basic support 3 1 9 10.5 5 12
* -------------------------------------------------------------------------------
*/
if (!Date.prototype.toISOString) {
Object.defineProperty(Array.prototype, 'toISOString', {
configurable : true,
writable : true,
value : function () {
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
'Z';
} });
}
| Define all Date toISOString properties with Object.defineProperty, using the descriptors configurable, writable and non-enumerable. | Define all Date toISOString properties with Object.defineProperty, using the descriptors configurable, writable and non-enumerable.
| JavaScript | mit | uxitten/polyfill | ---
+++
@@ -6,7 +6,10 @@
* -------------------------------------------------------------------------------
*/
if (!Date.prototype.toISOString) {
- Date.prototype.toISOString = function () {
+ Object.defineProperty(Array.prototype, 'toISOString', {
+ configurable : true,
+ writable : true,
+ value : function () {
function pad(number) {
if (number < 10) {
return '0' + number;
@@ -22,5 +25,5 @@
':' + pad(this.getUTCSeconds()) +
'.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
'Z';
- };
+ } });
} |
df3f7f36a5dce3e85660106e79953facfd0c7555 | assets/javascripts/p_slides.js | assets/javascripts/p_slides.js | $(".presentation").each(function() {
var md = new Remarkable('full', { html: true });
var markup = md.render($(this).html());
var slides = markup.split('<hr>');
var new_document = [];
for (var j = 0; j < slides.length; j++)
new_document.push('<div class=slide>' + slides[j] + '</div>');
document.write(new_document.join(""));
});
$(".presentation").remove();
// If you want to syntax highlight all your code in the same way then
// you can uncomment and customize the next line
//
//$("pre>code").parent().addClass("syntax cpp");
w3c_slidy.add_listener(document.body, "touchend", w3c_slidy.mouse_button_click);
$.syntax();
// Automatic detection for theme javascript. It will run after slides
// have been generated
for(i in document.styleSheets) {
stylesheet = document.styleSheets[i].href;
if (stylesheet && stylesheet.indexOf("theme") != -1) {
theme = stylesheet.slice(stylesheet.lastIndexOf("/")+1, stylesheet.length);
eval(theme.replace(".css", "()"));
}
}
| $(".presentation").each(function() {
var md = new Remarkable('full', { html: true//,
// Here goes a real syntax highlighter
//highlight: function (str, lang) {
// return str;
//}
});
var markup = md.render($(this).html());
var slides = markup.split('<hr>');
var new_document = [];
for (var j = 0; j < slides.length; j++)
new_document.push('<div class=slide>' + slides[j] + '</div>');
document.write(new_document.join(""));
});
$(".presentation").remove();
// If you want to syntax highlight all your code in the same way then
// you can uncomment and customize the next line
//
//$("pre>code").parent().addClass("syntax cpp");
w3c_slidy.add_listener(document.body, "touchend", w3c_slidy.mouse_button_click);
// XXX: Work Around
// RemarkableJS above translates content of <pre> Tags into HTML.
// Therefore empty lines will create new paragraphs. Remove those
// paragraphs, so that the newlines stay intact for code highlighting.
// Note: Indentation is lost and cannot be retrieved here
// Note: The better solution is to ditch jquery-syntax and go with
// something that can be used together with RemarkableJS.
$("pre.syntax").map(function(element) {
$(this).html($(this).
html().
replace(/<p>/g, "\n").
replace(/<\/p>/g, ""));
});
$.syntax();
// Automatic detection for theme javascript. It will run after slides
// have been generated
for(i in document.styleSheets) {
stylesheet = document.styleSheets[i].href;
if (stylesheet && stylesheet.indexOf("theme") != -1) {
theme = stylesheet.slice(stylesheet.lastIndexOf("/")+1, stylesheet.length);
eval(theme.replace(".css", "()"));
}
}
| Add workaround to introduce slightly better syntax highlighting. | Add workaround to introduce slightly better syntax
highlighting.
| JavaScript | agpl-3.0 | munen/p_slides,munen/p_slides | ---
+++
@@ -1,5 +1,10 @@
$(".presentation").each(function() {
- var md = new Remarkable('full', { html: true });
+ var md = new Remarkable('full', { html: true//,
+ // Here goes a real syntax highlighter
+ //highlight: function (str, lang) {
+ // return str;
+ //}
+ });
var markup = md.render($(this).html());
var slides = markup.split('<hr>');
var new_document = [];
@@ -16,6 +21,22 @@
w3c_slidy.add_listener(document.body, "touchend", w3c_slidy.mouse_button_click);
+// XXX: Work Around
+// RemarkableJS above translates content of <pre> Tags into HTML.
+// Therefore empty lines will create new paragraphs. Remove those
+// paragraphs, so that the newlines stay intact for code highlighting.
+
+// Note: Indentation is lost and cannot be retrieved here
+
+// Note: The better solution is to ditch jquery-syntax and go with
+// something that can be used together with RemarkableJS.
+$("pre.syntax").map(function(element) {
+ $(this).html($(this).
+ html().
+ replace(/<p>/g, "\n").
+ replace(/<\/p>/g, ""));
+});
+
$.syntax();
// Automatic detection for theme javascript. It will run after slides |
7556ac4105736e6414933cc6bc928c696a625083 | readFile.js | readFile.js | /**
* Created by Kanthanarasimhaiah on 14/11/13.
*/
fs = require('fs');
var num_of_tasks;
var total_time;
var fileName = process.argv[2];
fs.readFile(fileName, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
//console.log(data);
var input=data.split('\n');
var line1 = input[0].split(' ');
num_of_tasks=parseInt(line1[0], 10);
total_time=parseInt(line1[1], 10);
console.log("Numer of Tasks:", num_of_tasks);
console.log("Total Time:", total_time);
// read in the tasks
var queue= [];
for(var j=1;j<num_of_tasks;j++) {
var task_data=input[j].split(' ');
var task = {id : task_data[0],
start_time : parseInt(task_data[1], 10),
duration : parseInt(task_data[2], 10)};
queue.push(task);
}
function sort_function (a, b) {
return a.start_time - b.start_time;
}
queue.sort(sort_function);
console.log("Tasks:");
console.log(queue);
});
| /**
* Created by Kanthanarasimhaiah on 14/11/13.
*/
fs = require('fs');
function readTasks (file) {
var data = fs.readFileSync(file, 'utf8');
var input=data.split('\n');
var line1 = input[0].split(' ');
var num_of_tasks=parseInt(line1[0], 10);
var total_time=parseInt(line1[1], 10);
// read in the tasks
var queue= [];
for(var j=1;j<num_of_tasks;j++) {
var task_data=input[j].split(' ');
var task = {id : task_data[0],
start_time : parseInt(task_data[1], 10),
duration : parseInt(task_data[2], 10)};
queue.push(task);
}
function sort_function (a, b) {
return a.start_time - b.start_time;
}
queue.sort(sort_function);
return {num_of_tasks: num_of_tasks,
total_time: total_time,
task_queue: queue};
}
var fileName = process.argv[2];
var tasks = readTasks(fileName);
console.log("Numer of Tasks:", tasks.num_of_tasks);
console.log("Total Time:", tasks.total_time);
console.log("Task Queue:");
console.log(tasks.task_queue);
| Move task reading into a standalone function. | Move task reading into a standalone function.
- Also, use readFileSync (synchronous).
| JavaScript | mpl-2.0 | kanaka/rbt_cfs | ---
+++
@@ -3,22 +3,13 @@
*/
fs = require('fs');
-var num_of_tasks;
-var total_time;
-var fileName = process.argv[2];
-
-fs.readFile(fileName, 'utf8', function (err,data) {
- if (err) {
- return console.log(err);
- }
- //console.log(data);
+function readTasks (file) {
+ var data = fs.readFileSync(file, 'utf8');
var input=data.split('\n');
var line1 = input[0].split(' ');
- num_of_tasks=parseInt(line1[0], 10);
- total_time=parseInt(line1[1], 10);
- console.log("Numer of Tasks:", num_of_tasks);
- console.log("Total Time:", total_time);
+ var num_of_tasks=parseInt(line1[0], 10);
+ var total_time=parseInt(line1[1], 10);
// read in the tasks
var queue= [];
@@ -30,11 +21,21 @@
duration : parseInt(task_data[2], 10)};
queue.push(task);
}
+
function sort_function (a, b) {
return a.start_time - b.start_time;
}
queue.sort(sort_function);
- console.log("Tasks:");
- console.log(queue);
-});
+ return {num_of_tasks: num_of_tasks,
+ total_time: total_time,
+ task_queue: queue};
+}
+var fileName = process.argv[2];
+var tasks = readTasks(fileName);
+
+console.log("Numer of Tasks:", tasks.num_of_tasks);
+console.log("Total Time:", tasks.total_time);
+console.log("Task Queue:");
+console.log(tasks.task_queue);
+ |
b6bc9e62d615242ef0eaa438d961d08a3ea9c72a | server/controllers/usersController.js | server/controllers/usersController.js | let UserRecipes = require(`${__dirname}/../schemas.js`).UserRecipes;
module.exports = {
signup: (req, res) => {
},
login: (req, res) => {
},
logout: (req, res) => {
},
//Gets all the recipes that belong to that user
getProfile: (req, res) => {
UserRecipes.findOne({
username: req.params.username
}).then(result => {
res.status(200).send(result);
}).catch(error => {
res.status(404).send(error);
});
}
}; | let UserRecipe = require(`${__dirname}/../schemas.js`).UserRecipe;
module.exports = {
signup: (req, res) => {
},
login: (req, res) => {
},
logout: (req, res) => {
},
//Gets all the recipes that belong to that user
getProfile: (req, res) => {
UserRecipe.findOne({
username: req.params.username
}).then(result => {
res.status(200).send(result);
}).catch(error => {
res.status(404).send(error);
});
}
}; | Remove 's' from UserRecipe(s) in user controller | Remove 's' from UserRecipe(s) in user controller
| JavaScript | mit | JAC-Labs/SkilletHub,JAC-Labs/SkilletHub | ---
+++
@@ -1,4 +1,4 @@
-let UserRecipes = require(`${__dirname}/../schemas.js`).UserRecipes;
+let UserRecipe = require(`${__dirname}/../schemas.js`).UserRecipe;
module.exports = {
signup: (req, res) => {
@@ -15,7 +15,7 @@
//Gets all the recipes that belong to that user
getProfile: (req, res) => {
- UserRecipes.findOne({
+ UserRecipe.findOne({
username: req.params.username
}).then(result => {
res.status(200).send(result); |
8abac9363de638edb93bfd3e9744ccb78930aace | Honeybee/EventHandler.js | Honeybee/EventHandler.js | 'use strict';
//Import events
const events = require('events');
//Create EventHandler function
class EventHandler extends events.EventEmitter {
constructor() {
super()
}
registered() {
this.emit('registered')
}
request(callback) {
this.emit('request', callback)
}
submit(data, callback) {
this.emit('submit', data, callback)
}
}
module.exports = EventHandler;
| 'use strict';
//Import events
const events = require('events');
//Create EventHandler function
class EventHandler extends events.EventEmitter {
constructor() {
super();
}
registered() {
this.emit('registered');
}
request(callback) {
this.emit('request', callback);
}
submit(data, callback) {
this.emit('submit', data, callback);
}
}
module.exports = EventHandler;
| Fix conventional errors from previos commit | Fix conventional errors from previos commit
| JavaScript | isc | Kurimizumi/Honeybee-Hive | ---
+++
@@ -5,19 +5,19 @@
//Create EventHandler function
class EventHandler extends events.EventEmitter {
constructor() {
- super()
+ super();
}
registered() {
- this.emit('registered')
+ this.emit('registered');
}
request(callback) {
- this.emit('request', callback)
+ this.emit('request', callback);
}
submit(data, callback) {
- this.emit('submit', data, callback)
+ this.emit('submit', data, callback);
}
}
|
76a4a74053b07d7fe6a1d98ee0271173dbc58cf8 | App/data/CaretakerRolesGateway/index.js | App/data/CaretakerRolesGateway/index.js | /*
Makes API calls to fetch caretaker roles.
However, until there is an API to call, it returns canned data.
*/
export default class CaretakerRolesGateway {
static allRoles = null;
static getAll() {
if(this.allRoles === null) {
//api call to get roles
this.allRoles = [
{id: 1, name: 'Driver', description: 'Gives rides to things'},
{id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'},
{id: 3, name: 'Groceries', description: 'Picks up groceries'},
{id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'},
{id: 5, name: 'Chef', description: 'Cooks food cause yum'}
]
}
return this.allRoles;
}
}
| /*
Makes API calls to fetch caretaker roles.
However, until there is an API to call, it returns canned data.
*/
const createCaretakerRolesGateway = () => {
let allRoles = null;
return {
getAll: () => {
if(allRoles === null) {
//api call to get roles
allRoles = [
{id: 1, name: 'Driver', description: 'Gives rides to things'},
{id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'},
{id: 3, name: 'Groceries', description: 'Picks up groceries'},
{id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'},
{id: 5, name: 'Chef', description: 'Cooks food cause yum'}
]
}
return allRoles;
}
}
}
export default createCaretakerRolesGateway();
| Refactor CaretakerRolesGateway to use factory pattern | Refactor CaretakerRolesGateway to use factory pattern
| JavaScript | mit | araneforseti/caretaker-app,araneforseti/caretaker-app,araneforseti/caretaker-app,araneforseti/caretaker-app | ---
+++
@@ -4,21 +4,25 @@
However, until there is an API to call, it returns canned data.
*/
-export default class CaretakerRolesGateway {
+const createCaretakerRolesGateway = () => {
- static allRoles = null;
+ let allRoles = null;
- static getAll() {
- if(this.allRoles === null) {
- //api call to get roles
- this.allRoles = [
- {id: 1, name: 'Driver', description: 'Gives rides to things'},
- {id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'},
- {id: 3, name: 'Groceries', description: 'Picks up groceries'},
- {id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'},
- {id: 5, name: 'Chef', description: 'Cooks food cause yum'}
- ]
+ return {
+ getAll: () => {
+ if(allRoles === null) {
+ //api call to get roles
+ allRoles = [
+ {id: 1, name: 'Driver', description: 'Gives rides to things'},
+ {id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'},
+ {id: 3, name: 'Groceries', description: 'Picks up groceries'},
+ {id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'},
+ {id: 5, name: 'Chef', description: 'Cooks food cause yum'}
+ ]
+ }
+ return allRoles;
}
- return this.allRoles;
}
}
+
+export default createCaretakerRolesGateway(); |
5fccae541140aa7d96be0566c97165cc84a6fd5f | to-title-case.js | to-title-case.js | /*
* To Title Case 2.0 – http://individed.com/code/to-title-case/
* Copyright © 2008–2012 David Gouch. Licensed under the MIT License.
*/
String.prototype.toTitleCase = function() {
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;
return this.replace(/([^\W_]+[^\s-]*) */g, function(match, p1, index, title) {
if (index > 0 && index + p1.length !== title.length &&
p1.search(smallWords) > -1 && title[index - 2] !== ":" &&
title[index - 1].search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (p1.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
};
| /*
* To Title Case 2.0 – http://individed.com/code/to-title-case/
* Copyright © 2008–2012 David Gouch. Licensed under the MIT License.
*/
String.prototype.toTitleCase = function () {
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;
return this.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) {
if (index > 0 && index + p1.length !== title.length &&
p1.search(smallWords) > -1 && title[index - 2] !== ":" &&
title[index - 1].search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (p1.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
};
| Add space between anon function and parens. | Add space between anon function and parens.
| JavaScript | mit | rvagg/titlecase,fiatjaf/titulo,gouch/to-title-case,rvagg/titlecase,SaintPeter/titlecase,SaintPeter/titlecase,gouch/to-title-case | ---
+++
@@ -3,10 +3,10 @@
* Copyright © 2008–2012 David Gouch. Licensed under the MIT License.
*/
-String.prototype.toTitleCase = function() {
+String.prototype.toTitleCase = function () {
var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;
- return this.replace(/([^\W_]+[^\s-]*) */g, function(match, p1, index, title) {
+ return this.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) {
if (index > 0 && index + p1.length !== title.length &&
p1.search(smallWords) > -1 && title[index - 2] !== ":" &&
title[index - 1].search(/[^\s-]/) < 0) { |
d8867d259040ce0eb240ede3edf9fc15415b299e | .eslintrc.js | .eslintrc.js | module.exports = {
"extends": "airbnb",
"parser": "babel-eslint",
"plugins": [
"react"
],
"rules": {
"react/prop-types": 0,
"space-before-function-paren": [2, { "anonymous": "never", "named": "always" }]
}
};
| module.exports = {
"extends": "airbnb",
"parser": "babel-eslint",
"plugins": [
"react"
],
"rules": {
"react/prop-types": 0,
"react/jsx-boolean-value": 0,
"consistent-return": 0,
"space-before-function-paren": [2, { "anonymous": "never", "named": "always" }]
}
};
| Add react rules to eslint file | Add react rules to eslint file
| JavaScript | mit | mersocarlin/react-webpack-template,mersocarlin/react-webpack-template | ---
+++
@@ -6,6 +6,8 @@
],
"rules": {
"react/prop-types": 0,
+ "react/jsx-boolean-value": 0,
+ "consistent-return": 0,
"space-before-function-paren": [2, { "anonymous": "never", "named": "always" }]
}
}; |
8f3ea6b47eb1f4d0265676527652c333c36a21ca | app/latexCommands.js | app/latexCommands.js | module.exports = [
{ action: '\\sqrt', label: '\\sqrt{X}' },
{ action: '^', label: 'x^{X}' },
{ action: '\\frac', label: '\\frac{X}{X}' },
{ action: '\\int', label: '\\int_{X}^{X}' },
{ action: '\\lim_', label: '\\lim_{X}' },
{ action: '\\overrightarrow', label: '\\overrightarrow{X}' },
{ action: '_', label: 'x_X' },
{ action: '\\nthroot', label: '\\sqrt[X]{X}' },
{ action: '\\sum', label: '\\sum_{X}^{X}' },
{ action: '\\binom', label: '\\binom{X}{X}' },
{ action: '\\sin' },
{ action: '\\cos' },
{ action: '\\tan' },
{ action: '\\arcsin' },
{ action: '\\arccos' },
{ action: '\\arctan' },
{ action: '\\not' },
{ action: '\\vec', label: '\\vec{X}' },
{ action: '\\bar', label: '\\bar{X}' },
{ action: '\\underline', label: '\\underline{X}' },
{ action: '\\overleftarrow', label: '\\overleftarrow{X}' },
{ action: '|', label: '|X|'},
{ action: '(', label: '(X)'}
]
| module.exports = [
{ action: '\\sqrt', label: '\\sqrt{X}' },
{ action: '^', label: 'x^{X}' },
{ action: '\\frac', label: '\\frac{X}{X}' },
{ action: '\\int', label: '\\int_{X}^{X}' },
{ action: '\\lim_', label: '\\lim_{X}' },
{ action: '\\overrightarrow', label: '\\overrightarrow{X}' },
{ action: '_', label: 'x_X' },
{ action: '\\nthroot', label: '\\sqrt[X]{X}' },
{ action: '\\sum', label: '\\sum_{X}^{X}' },
{ action: '\\binom', label: '\\binom{X}{X}' },
{ action: '\\sin' },
{ action: '\\cos' },
{ action: '\\tan' },
{ action: '\\arcsin' },
{ action: '\\arccos' },
{ action: '\\arctan' },
{ action: '\\vec', label: '\\vec{X}' },
{ action: '\\bar', label: '\\bar{X}' },
{ action: '\\underline', label: '\\underline{X}' },
{ action: '\\overleftarrow', label: '\\overleftarrow{X}' },
{ action: '|', label: '|X|'},
{ action: '(', label: '(X)'}
]
| Remove problematic not tool from the equation toolbar; | Remove problematic not tool from the equation toolbar;
\not is used in conjunction with other commands such as \equiv or
\infty. Mathquill however does not support this and changes \not to
\neg.
| JavaScript | mit | digabi/rich-text-editor,digabi/math-editor,digabi/math-editor,digabi/rich-text-editor,digabi/rich-text-editor | ---
+++
@@ -15,7 +15,6 @@
{ action: '\\arcsin' },
{ action: '\\arccos' },
{ action: '\\arctan' },
- { action: '\\not' },
{ action: '\\vec', label: '\\vec{X}' },
{ action: '\\bar', label: '\\bar{X}' },
{ action: '\\underline', label: '\\underline{X}' }, |
2030607c7012d78233deb3882f94bdac1fb6aff2 | routes/index.js | routes/index.js | const UserController = require('../src/Http/Controllers/User');
const { define, wrap, post, get } = require('spirit-router');
const { json } = require('body-parser');
const express = require('spirit-express');
module.exports = define('/api', [
get('/users', UserController.index),
get('/users/:user_id', ['user_id'], UserController.show),
wrap(post('/users', ['body'], UserController.store), express(json())),
]);
| const UserController = require('../src/Http/Controllers/User');
const { define, wrap, post, get, any, notFound } = require('spirit-router');
const { json } = require('body-parser');
const express = require('spirit-express');
const api = define('/api', [
get('/users', UserController.index),
get('/users/:user_id', ['user_id'], UserController.show),
wrap(post('/users', ['body'], UserController.store), express(json())),
]);
module.exports = define([api, any('*', notFound())]);
| Add default not found route | feat: Add default not found route
| JavaScript | mit | diogoazevedos/corpus,diogoazevedos/corpus | ---
+++
@@ -1,11 +1,13 @@
const UserController = require('../src/Http/Controllers/User');
-const { define, wrap, post, get } = require('spirit-router');
+const { define, wrap, post, get, any, notFound } = require('spirit-router');
const { json } = require('body-parser');
const express = require('spirit-express');
-module.exports = define('/api', [
+const api = define('/api', [
get('/users', UserController.index),
get('/users/:user_id', ['user_id'], UserController.show),
wrap(post('/users', ['body'], UserController.store), express(json())),
]);
+
+module.exports = define([api, any('*', notFound())]); |
b69ee85c892ef3ff7a0542e3ce4a799051a1ea8a | services/web/src/main/ember/app/components/draggable-dropzone.js | services/web/src/main/ember/app/components/draggable-dropzone.js | import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['draggable-dropzone'],
classNameBindings: ['dragClass'],
dragClass: 'deactivated',
dragLeave: function(event) {
event.preventDefault();
this.set('dragClass', 'deactivated');
},
dragOver: function(event) {
event.preventDefault();
this.set('dragClass', 'activated');
},
drop: function(event) {
event.preventDefault();
this.set('dragClass', 'deactivated');
data = event.dataTransfer.getData('text/data');
// default drop action - change with {{draggable-dropzone dropped=xyz}}
this.sendAction('dropped', data);
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['draggable-dropzone'],
classNameBindings: ['dragClass'],
dragClass: 'deactivated',
dragLeave: function(event) {
event.preventDefault();
this.set('dragClass', 'deactivated');
},
dragOver: function(event) {
event.preventDefault();
this.set('dragClass', 'activated');
},
drop: function(event) {
event.preventDefault();
this.set('dragClass', 'deactivated');
var data = event.dataTransfer.getData('text/data');
// default drop action - change with {{draggable-dropzone dropped=xyz}}
this.sendAction('dropped', data);
}
});
| Fix small issue with ember dropzone | Fix small issue with ember dropzone
| JavaScript | agpl-3.0 | MarSik/shelves,MarSik/shelves,MarSik/shelves,MarSik/shelves | ---
+++
@@ -18,7 +18,7 @@
drop: function(event) {
event.preventDefault();
this.set('dragClass', 'deactivated');
- data = event.dataTransfer.getData('text/data');
+ var data = event.dataTransfer.getData('text/data');
// default drop action - change with {{draggable-dropzone dropped=xyz}}
this.sendAction('dropped', data);
} |
212b6c3a0ffb9eb7595b3987fa77040cadd92054 | .eslintrc.js | .eslintrc.js | module.exports = {
extends: ["matrix-org"],
plugins: [
"babel",
],
env: {
browser: true,
node: true,
},
rules: {
"no-var": ["warn"],
"prefer-rest-params": ["warn"],
"prefer-spread": ["warn"],
"one-var": ["warn"],
"padded-blocks": ["warn"],
"no-extend-native": ["warn"],
"camelcase": ["warn"],
"no-multi-spaces": ["error", { "ignoreEOLComments": true }],
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always",
}],
"arrow-parens": "off",
"prefer-promise-reject-errors": "off",
"quotes": "off",
"indent": "off",
"no-constant-condition": "off",
"no-async-promise-executor": "off",
// We use a `logger` intermediary module
"no-console": "error",
},
overrides: [{
"files": ["src/**/*.ts"],
"extends": ["matrix-org/ts"],
"rules": {
// While we're converting to ts we make heavy use of this
"@typescript-eslint/no-explicit-any": "off",
"quotes": "off",
},
}],
};
| module.exports = {
extends: ["matrix-org"],
plugins: [
"babel",
],
env: {
browser: true,
node: true,
},
rules: {
"no-var": ["warn"],
"prefer-rest-params": ["warn"],
"prefer-spread": ["warn"],
"one-var": ["warn"],
"padded-blocks": ["warn"],
"no-extend-native": ["warn"],
"camelcase": ["warn"],
"no-multi-spaces": ["error", { "ignoreEOLComments": true }],
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always",
}],
"arrow-parens": "off",
"prefer-promise-reject-errors": "off",
"quotes": "off",
"indent": "off",
"no-constant-condition": "off",
"no-async-promise-executor": "off",
// We use a `logger` intermediary module
"no-console": "error",
},
overrides: [{
"files": ["src/**/*.ts"],
"extends": ["matrix-org/ts"],
"rules": {
// We're okay being explicit at the moment
"@typescript-eslint/no-empty-interface": "off",
// While we're converting to ts we make heavy use of this
"@typescript-eslint/no-explicit-any": "off",
"quotes": "off",
},
}],
};
| Resolve linting errors after upgrades | Resolve linting errors after upgrades
| JavaScript | apache-2.0 | matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk | ---
+++
@@ -35,6 +35,8 @@
"files": ["src/**/*.ts"],
"extends": ["matrix-org/ts"],
"rules": {
+ // We're okay being explicit at the moment
+ "@typescript-eslint/no-empty-interface": "off",
// While we're converting to ts we make heavy use of this
"@typescript-eslint/no-explicit-any": "off",
"quotes": "off", |
8a22be70adca8bd7dd632f07451b878515dcfd58 | .eslintrc.js | .eslintrc.js | module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
plugins: [
'html' // required to lint *.vue files
],
// add your custom rules here
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
| module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
plugins: [
'html' // required to lint *.vue files
],
// add your custom rules here
'rules': {
// allow no-spaces between function name and argument parethesis list
'space-before-function-paren': 0,
// allow paren-less arrow functions
'arrow-parens': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
| Update eslint rules to allow no-spaces between function name and argument parenthesis | Update eslint rules to allow no-spaces between function name and argument parenthesis
| JavaScript | mit | cngu/vue-typer,cngu/vue-typer | ---
+++
@@ -11,6 +11,8 @@
],
// add your custom rules here
'rules': {
+ // allow no-spaces between function name and argument parethesis list
+ 'space-before-function-paren': 0,
// allow paren-less arrow functions
'arrow-parens': 0,
// allow debugger during development |
f3ab92fb8626916d7824409c9b514854d28ab51e | www/js/Controllers/nearby.js | www/js/Controllers/nearby.js | angular.module('gitphaser')
.controller('NearbyCtrl', NearbyCtrl);
// @controller NearbyCtrl
// @params: $scope, $reactive
// @route: /tab/nearby
//
// Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter'
// Subscription to 'connections' is handled in the route resolve. Also
// exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user
// clicks on list item to see profile)
function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){
$reactive(this).attach($scope);
var self = this;
// Slide constants bound to the GeoLocate directive
// and other DOM events, trigger updates based on
// whether we are looking at List || Map view.
self.listSlide = 0
self.mapSlide = 1;
self.slide = 0;
// Services
self.geolocate = GeoLocate;
self.notify = Notify;
self.helpers({
connections: function () {
if (Meteor.userId()){
return Connections.find( {transmitter: Meteor.userId() } );
}
}
});
};
| angular.module('gitphaser').controller('NearbyCtrl', NearbyCtrl);
/**
* Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter'
* Subscription to 'connections' is handled in the route resolve. Also
* exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user
* clicks on list item to see profile)
* @controller NearbyCtrl
* @route: /tab/nearby
*/
function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){
$reactive(this).attach($scope);
var self = this;
// Slide constants bound to the GeoLocate directive
// and other DOM events, trigger updates based on
// whether we are looking at List || Map view.
self.listSlide = 0
self.mapSlide = 1;
self.slide = 0;
// Services
self.geolocate = GeoLocate;
self.notify = Notify;
self.helpers({
connections: function () {
if (Meteor.userId()){
return Connections.find( {transmitter: Meteor.userId() } );
}
}
});
};
| Test push after changing local remote | Test push after changing local remote
| JavaScript | mit | git-phaser/git-phaser,git-phaser/git-phaser,git-phaser/git-phaser,git-phaser/git-phaser | ---
+++
@@ -1,14 +1,13 @@
-angular.module('gitphaser')
- .controller('NearbyCtrl', NearbyCtrl);
+angular.module('gitphaser').controller('NearbyCtrl', NearbyCtrl);
-// @controller NearbyCtrl
-// @params: $scope, $reactive
-// @route: /tab/nearby
-//
-// Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter'
-// Subscription to 'connections' is handled in the route resolve. Also
-// exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user
-// clicks on list item to see profile)
+/**
+ * Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter'
+ * Subscription to 'connections' is handled in the route resolve. Also
+ * exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user
+ * clicks on list item to see profile)
+ * @controller NearbyCtrl
+ * @route: /tab/nearby
+ */
function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){
$reactive(this).attach($scope);
|
d6b8f2f017d2f28854d51ff3210c734352b8ca6a | VotingApplication/VotingApplication.Web/Scripts/Controllers/CreateBasicPageController.js | VotingApplication/VotingApplication.Web/Scripts/Controllers/CreateBasicPageController.js | (function () {
angular
.module('GVA.Creation')
.controller('CreateBasicPageController', ['$scope', 'AccountService', 'PollService',
function ($scope, AccountService, PollService) {
$scope.openLoginDialog = function () {
AccountService.openLoginDialog($scope);
};
$scope.openRegisterDialog = function () {
AccountService.openRegisterDialog($scope);
};
$scope.createPoll = function (question) {
PollService.createPoll(question, function (data) {
window.location.href = "/Manage/" + data.ManageId;
});
};
}]);
})();
| (function () {
angular
.module('GVA.Creation')
.controller('CreateBasicPageController', ['$scope', 'AccountService', 'PollService',
function ($scope, AccountService, PollService) {
$scope.openLoginDialog = function () {
AccountService.openLoginDialog($scope);
};
$scope.openRegisterDialog = function () {
AccountService.openRegisterDialog($scope);
};
$scope.createPoll = function (question) {
PollService.createPoll(question, function (data) {
window.location.href = "/#/Manage/" + data.ManageId;
});
};
}]);
})();
| Fix redirect after poll creation | Fix redirect after poll creation
Redirect to /#/Manage/<ManageId> rather than /Manage/<ManageId>
| JavaScript | apache-2.0 | Generic-Voting-Application/voting-application,stevenhillcox/voting-application,JDawes-ScottLogic/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,Generic-Voting-Application/voting-application,tpkelly/voting-application,stevenhillcox/voting-application | ---
+++
@@ -14,7 +14,7 @@
$scope.createPoll = function (question) {
PollService.createPoll(question, function (data) {
- window.location.href = "/Manage/" + data.ManageId;
+ window.location.href = "/#/Manage/" + data.ManageId;
});
};
|
1883460122f4690d84f673ef083d23b95f3abcd5 | app/student.front.js | app/student.front.js | const $answer = $('.answer')
const {makeRichText} = require('./math-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type, id}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}&id=${id}`,
data: data,
processData: false,
contentType: type
}).then(res => {
console.log('heh', res)
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data)
}
})
$answer.each((i, answer) => {
makeRichText(answer, richTextOptions(answer.id))
$.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html))
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
| const $answer = $('.answer')
const {makeRichText} = require('./math-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type, id}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}&id=${id}`,
data: data,
processData: false,
contentType: type
}).then(res => {
console.log('heh', res)
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data)
}
})
$answer.each((i, answer) => {
makeRichText(answer, richTextOptions(answer.id))
$.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html))
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
$('#answer1').focus()
| Set focus automatically to first field | Set focus automatically to first field
| JavaScript | mit | digabi/rich-text-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/math-editor,digabi/math-editor | ---
+++
@@ -36,3 +36,4 @@
save($(e.target))
}
})
+$('#answer1').focus() |
7dfbb87add262139525d9981f6024a46bbc52190 | src/jupyter_contrib_nbextensions/nbextensions/export_embedded/main.js | src/jupyter_contrib_nbextensions/nbextensions/export_embedded/main.js | // toggle display of all code cells' inputs
define([
'jquery',
'base/js/namespace',
'base/js/events'
], function(
$,
Jupyter,
events
) {
"use strict";
function initialize () {
console.log("Embedded HTML Exporter loaded!");
}
var load_ipython_extension = function() {
var dwm = $("#download_menu")
var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>')
dwm.append(downloadEntry)
downloadEntry.click(function () {
Jupyter.menubar._nbconvert('html_embed', true);
});
Jupyter.toolbar.add_buttons_group([{
id : 'export_embeddedhtml',
label : 'Embedded HTML Export',
icon : 'fa-save',
callback : function() {
Jupyter.menubar._nbconvert('html_embed', true);
}
}]);
if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) {
// notebook_loaded.Notebook event has already happened
initialize();
}
events.on('notebook_loaded.Notebook', initialize);
};
return {
load_ipython_extension : load_ipython_extension
};
});
| // toggle display of all code cells' inputs
define([
'jquery',
'base/js/namespace',
'base/js/events'
], function(
$,
Jupyter,
events
) {
"use strict";
function initialize () {
}
var load_ipython_extension = function() {
/* Add an entry in the download menu */
var dwm = $("#download_menu")
var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>')
dwm.append(downloadEntry)
downloadEntry.click(function () {
Jupyter.menubar._nbconvert('html_embed', true);
});
/* Add also a Button, currently disabled */
/*
Jupyter.toolbar.add_buttons_group([{
id : 'export_embeddedhtml',
label : 'Embedded HTML Export',
icon : 'fa-save',
callback : function() {
Jupyter.menubar._nbconvert('html_embed', true);
}
}]);
*/
if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) {
// notebook_loaded.Notebook event has already happened
initialize();
}
events.on('notebook_loaded.Notebook', initialize);
};
return {
load_ipython_extension : load_ipython_extension
};
});
| Remove Button, only in Download Menu | Remove Button, only in Download Menu | JavaScript | bsd-3-clause | ipython-contrib/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,juhasch/IPython-notebook-extensions | ---
+++
@@ -12,18 +12,20 @@
"use strict";
function initialize () {
- console.log("Embedded HTML Exporter loaded!");
}
var load_ipython_extension = function() {
+ /* Add an entry in the download menu */
var dwm = $("#download_menu")
var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>')
dwm.append(downloadEntry)
downloadEntry.click(function () {
Jupyter.menubar._nbconvert('html_embed', true);
});
-
+
+ /* Add also a Button, currently disabled */
+ /*
Jupyter.toolbar.add_buttons_group([{
id : 'export_embeddedhtml',
label : 'Embedded HTML Export',
@@ -32,6 +34,7 @@
Jupyter.menubar._nbconvert('html_embed', true);
}
}]);
+ */
if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) {
// notebook_loaded.Notebook event has already happened
initialize(); |
86de60799199c39949c6f862997752c688572c91 | src/apps/contacts/middleware/interactions.js | src/apps/contacts/middleware/interactions.js | const { getContact } = require('../../contacts/repos')
function setInteractionsDetails (req, res, next) {
res.locals.interactions = {
returnLink: `/contacts/${req.params.contactId}/interactions/`,
entityName: `${res.locals.contact.first_name} ${res.locals.contact.last_name}`,
query: { contacts_id: req.params.contactId },
view: 'contacts/views/interactions',
canAdd: true,
}
next()
}
async function setCompanyDetails (req, res, next) {
try {
const contact = await getContact(req.session.token, req.params.contactId)
res.locals.company = contact.company
next()
} catch (error) {
next(error)
}
}
module.exports = {
setInteractionsDetails,
setCompanyDetails,
}
| const { getContact } = require('../../contacts/repos')
function setInteractionsDetails (req, res, next) {
res.locals.interactions = {
returnLink: `/contacts/${req.params.contactId}/interactions/`,
entityName: `${res.locals.contact.first_name} ${res.locals.contact.last_name}`,
query: { contacts__id: req.params.contactId },
view: 'contacts/views/interactions',
canAdd: true,
}
next()
}
async function setCompanyDetails (req, res, next) {
try {
const contact = await getContact(req.session.token, req.params.contactId)
res.locals.company = contact.company
next()
} catch (error) {
next(error)
}
}
module.exports = {
setInteractionsDetails,
setCompanyDetails,
}
| Add missing underscore on query param to contacts | Add missing underscore on query param to contacts
| JavaScript | mit | uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend | ---
+++
@@ -4,7 +4,7 @@
res.locals.interactions = {
returnLink: `/contacts/${req.params.contactId}/interactions/`,
entityName: `${res.locals.contact.first_name} ${res.locals.contact.last_name}`,
- query: { contacts_id: req.params.contactId },
+ query: { contacts__id: req.params.contactId },
view: 'contacts/views/interactions',
canAdd: true,
} |
ca0425c4149e8a3dd736abef6a13967d8d656f20 | src/audits/UnfocusableElementsWithOnClick.js | src/audits/UnfocusableElementsWithOnClick.js | // Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
AuditRules.addRule({
name: 'unfocusableElementsWithOnClick',
severity: Severity.Warning,
opt_shouldRunInDevtools: true,
relevantNodesSelector: function() {
var potentialOnclickElements = document.querySelectorAll('span, div, img');
var unfocusableClickableElements = [];
for (var i = 0; i < potentialOnclickElements.length; i++) {
var element = potentialOnclickElements[i];
if (AccessibilityUtils.isElementOrAncestorHidden)
continue;
var eventListeners = getEventListeners(element);
if ('click' in eventListeners) {
unfocusableClickableElements.push(element);
}
}
return unfocusableClickableElements;
},
test: function(element) {
return element.tabIndex == null;
}
});
| // Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
AuditRules.addRule({
name: 'unfocusableElementsWithOnClick',
severity: Severity.Warning,
opt_shouldRunInDevtools: true,
relevantNodesSelector: function() {
var potentialOnclickElements = document.querySelectorAll('*');
var unfocusableClickableElements = [];
for (var i = 0; i < potentialOnclickElements.length; i++) {
var element = potentialOnclickElements[i];
if (AccessibilityUtils.isElementOrAncestorHidden)
continue;
var eventListeners = getEventListeners(element);
if ('click' in eventListeners) {
unfocusableClickableElements.push(element);
}
}
return unfocusableClickableElements;
},
test: function(element) {
return element.tabIndex == null;
}
});
| Check all elements, not just [span, div, img], for unfocusableElementsWithOnClick | Check all elements, not just [span, div, img], for unfocusableElementsWithOnClick
| JavaScript | apache-2.0 | japacible/accessibility-developer-tools-extension,modulexcite/accessibility-developer-tools,alice/accessibility-developer-tools,modulexcite/accessibility-developer-tools-extension,ckundo/accessibility-developer-tools,modulexcite/accessibility-developer-tools-extension,kublaj/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,seksanman/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools-extension,googlearchive/accessibility-developer-tools-extension,japacible/accessibility-developer-tools,Khan/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,alice/accessibility-developer-tools,garcialo/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,japacible/accessibility-developer-tools,ckundo/accessibility-developer-tools,japacible/accessibility-developer-tools,alice/accessibility-developer-tools,seksanman/accessibility-developer-tools,t9nf/accessibility-developer-tools,hmrc/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,japacible/accessibility-developer-tools-extension,seksanman/accessibility-developer-tools,hmrc/accessibility-developer-tools,Khan/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,garcialo/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,Khan/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools-extension,kublaj/accessibility-developer-tools,ckundo/accessibility-developer-tools,minorninth/accessibility-developer-tools,dylanb/accessibility-developer-tools-extension,modulexcite/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,hmrc/accessibility-developer-tools,t9nf/accessibility-developer-tools,modulexcite/accessibility-developer-tools,garcialo/accessibility-developer-tools,googlearchive/accessibility-developer-tools-extension,GabrielDuque/accessibility-developer-tools,minorninth/accessibility-developer-tools,t9nf/accessibility-developer-tools,kublaj/accessibility-developer-tools,dylanb/accessibility-developer-tools-extension,kristapsmelderis/accessibility-developer-tools,ricksbrown/accessibility-developer-tools | ---
+++
@@ -18,7 +18,7 @@
severity: Severity.Warning,
opt_shouldRunInDevtools: true,
relevantNodesSelector: function() {
- var potentialOnclickElements = document.querySelectorAll('span, div, img');
+ var potentialOnclickElements = document.querySelectorAll('*');
var unfocusableClickableElements = [];
for (var i = 0; i < potentialOnclickElements.length; i++) { |
8f5dda30829b7439f0fc49d8e1fe86623980dc3b | dev/grunt/postcss.js | dev/grunt/postcss.js | module.exports = {
options: {
map: true, // inline sourcemaps
processors: [
require('pixrem')(), // add fallbacks for rem units
require('autoprefixer-core')({
// add vendor prefixes
browsers: [
'last 3 version',
'ie 8',
'ff 3.6',
'opera 11.1',
'ios 4',
'android 2.3'
]
}),
require('cssnano')() // minify the result
]
},
dist: {
src: '<%= destCSSDir %>' + '/*.css'
}
};
| module.exports = {
options: {
map: true, // inline sourcemaps
processors: [
require('pixrem')(), // add fallbacks for rem units
require('autoprefixer-core')({
// add vendor prefixes
browsers: [
'last 3 version',
'ie 8',
'ff 3.6',
'opera 11.1',
'ios 4',
'android 2.3'
]
}),
require('cssnano')({
convertValues: false
}) // minify the result
]
},
dist: {
src: '<%= destCSSDir %>' + '/*.css'
}
};
| Disable not-safe PostCSS value conversions | Disable not-safe PostCSS value conversions
| JavaScript | mit | ideus-team/html-framework,ideus-team/html-framework | ---
+++
@@ -15,7 +15,9 @@
'android 2.3'
]
}),
- require('cssnano')() // minify the result
+ require('cssnano')({
+ convertValues: false
+ }) // minify the result
]
},
dist: { |
6cdb0bf0cb4872dae918175851b1fec4341bfb97 | violet/violet.js | violet/violet.js | #!/usr/bin/env node
var ncp = require('ncp').ncp;
var path = require('path');
require('yargs')
.usage('$0 <cmd> [args]')
.option('directory', {
alias: 'd',
describe: 'Provide the directory to install Violet to'
})
.command('install', 'Install violet', {}, function (argv) {
var directory = 'violet';
if (argv.directory != null) {
directory = argv.directory;
}
ncp(path.resolve(__dirname, './source'), directory, function (err) {
if (err) {
return console.error(err);
}
console.log('Installed Violet!');
});
})
.help('help')
.argv;
| #!/usr/bin/env node
var ncp = require('ncp').ncp;
var path = require('path');
var fs = require('fs');
require('yargs')
.usage('$0 <cmd> [args]')
.option('directory', {
alias: 'd',
describe: 'Provide the directory to install Violet to'
})
.command('install', 'Install Violet', {}, function (argv) {
var directory = 'violet';
if (argv.directory != null) {
directory = argv.directory;
}
install(directory);
})
.command('update', 'Update Violet', {}, function (argv) {
var directory = 'violet';
if (argv.directory != null) {
directory = argv.directory;
}
deleteFolderRecursive(directory);
install(directory);
})
.help('help')
.argv;
function install(directory) {
ncp(path.resolve(__dirname, './source'), directory, function (err) {
if (err) {
return console.error(err);
}
console.log('Installed Violet!');
});
}
// thanks to http://www.geedew.com/remove-a-directory-that-is-not-empty-in-nodejs/
function deleteFolderRecursive(path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file, index) {
var curPath = path + "/" + file;
if (fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
| Add update fucntion to CLI | Add update fucntion to CLI
| JavaScript | mit | Lexteam/lexteam.github.io,Lexteam/lexteam.github.io,Lexteam/lexteam.github.io | ---
+++
@@ -2,6 +2,7 @@
var ncp = require('ncp').ncp;
var path = require('path');
+var fs = require('fs');
require('yargs')
.usage('$0 <cmd> [args]')
@@ -9,18 +10,46 @@
alias: 'd',
describe: 'Provide the directory to install Violet to'
})
- .command('install', 'Install violet', {}, function (argv) {
+ .command('install', 'Install Violet', {}, function (argv) {
var directory = 'violet';
if (argv.directory != null) {
directory = argv.directory;
}
- ncp(path.resolve(__dirname, './source'), directory, function (err) {
- if (err) {
- return console.error(err);
- }
- console.log('Installed Violet!');
- });
+ install(directory);
+ })
+ .command('update', 'Update Violet', {}, function (argv) {
+ var directory = 'violet';
+ if (argv.directory != null) {
+ directory = argv.directory;
+ }
+
+ deleteFolderRecursive(directory);
+ install(directory);
})
.help('help')
.argv;
+
+function install(directory) {
+ ncp(path.resolve(__dirname, './source'), directory, function (err) {
+ if (err) {
+ return console.error(err);
+ }
+ console.log('Installed Violet!');
+ });
+}
+
+// thanks to http://www.geedew.com/remove-a-directory-that-is-not-empty-in-nodejs/
+function deleteFolderRecursive(path) {
+ if (fs.existsSync(path)) {
+ fs.readdirSync(path).forEach(function (file, index) {
+ var curPath = path + "/" + file;
+ if (fs.lstatSync(curPath).isDirectory()) { // recurse
+ deleteFolderRecursive(curPath);
+ } else { // delete file
+ fs.unlinkSync(curPath);
+ }
+ });
+ fs.rmdirSync(path);
+ }
+}; |
482508f2927d05f2be0c58b20d7f9acd35606bc4 | scripts/docs.js | scripts/docs.js | #!/usr/bin/env node
var _ = require('lodash');
var docdown = require('docdown');
var fs = require('fs');
var path = require('path');
var srcPath = path.join(__dirname, '../src');
var outPath = path.join(__dirname, '../docs');
// Define which files to scan
var sourceFiles = [
'tree.js',
'treenode.js',
'treenodes.js'
];
// Create output directory
if (!fs.existsSync(outPath)) {
fs.mkdirSync(outPath);
}
_.each(sourceFiles, function(sourceFile) {
var markdown = docdown({
title: '',
toc: 'categories',
path: path.join(srcPath, sourceFile),
url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile
});
var docName = sourceFile.split('/').pop().replace('.js', '.md');
// Write file
fs.writeFile(path.join(outPath, docName), markdown, function(err) {
if (err) {
console.log('Error writing to file:');
console.log(err);
return;
}
console.log('Wrote output for ' + sourceFile);
});
});
| #!/usr/bin/env node
var _ = require('lodash');
var docdown = require('docdown');
var fs = require('fs');
var path = require('path');
var srcPath = path.join(__dirname, '../src');
var outPath = path.join(__dirname, '../docs');
// Define which files to scan
var sourceFiles = [
'tree.js',
'treenode.js',
'treenodes.js'
];
// Create output directory
if (!fs.existsSync(outPath)) {
fs.mkdirSync(outPath);
}
_.each(sourceFiles, function(sourceFile) {
var markdown = docdown({
title: '',
toc: 'categories',
path: path.join(srcPath, sourceFile),
style: 'github',
url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile
});
var docName = sourceFile.split('/').pop().replace('.js', '.md');
// Write file
fs.writeFile(path.join(outPath, docName), markdown, function(err) {
if (err) {
console.log('Error writing to file:');
console.log(err);
return;
}
console.log('Wrote output for ' + sourceFile);
});
});
| Set docdown style to github. | Set docdown style to github. [ci skip]
| JavaScript | mit | helion3/inspire-tree,helion3/inspire-tree | ---
+++
@@ -24,6 +24,7 @@
title: '',
toc: 'categories',
path: path.join(srcPath, sourceFile),
+ style: 'github',
url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile
});
|
70fab2cf5426def9114bdd40727f4a72593df9e4 | src/core.js | src/core.js | (function(global) {
'use strict';
define([
], function() {
// $HEADER$
/**
* This will be the <code>warmsea</code> namespace.
* @namespace
* @alias warmsea
*/
var w = _.extend({}, _);
/**
* The unmodified underlying underscore object.
*/
w._ = w.underscore = _;
/**
* The version of this WarmseaJS.
* @type {string}
*/
w.VERSION = '$VERSION$';
/**
* The global object of the executing environment.
* @type {object}
*/
w.global = global;
/**
* Save the previous `warmsea`.
*/
var previousWarmsea = global.warmsea;
/**
* Return the current `warmsea` and restore the previous global one.
* @return {warmsea} This warmsea object.
*/
w.noConflict = function() {
global.warmsea = previousWarmsea;
return this;
};
/**
* A function that throws an error with the message "Unimplemented".
*/
w.unimplemented = function() {
w.error('Unimplemented');
};
/**
* Throws an Error.
* @method
* @param {string} msg
* @throws {Error}
*/
w.error = function(msg) {
throw new Error(msg);
};
// $FOOTER$
return w;
});
})(this);
| (function(global) {
'use strict';
define([
], function() {
// $HEADER$
/**
* This will be the <code>warmsea</code> namespace.
* @namespace
* @alias warmsea
*/
var w = _.extend({}, _);
/**
* The unmodified underlying underscore object.
*/
w._ = w.underscore = _;
/**
* The version of this WarmseaJS.
* @type {string}
*/
w.VERSION = '$VERSION$';
/**
* The global object of the executing environment.
* @type {object}
*/
w.global = global;
/**
* Save the previous `warmsea`.
*/
var previousWarmsea = global.warmsea;
/**
* Return the current `warmsea` and restore the previous global one.
* @return {warmsea} This warmsea object.
*/
w.noConflict = function() {
global.warmsea = previousWarmsea;
return this;
};
/**
* A function that throws an error with the message "Unimplemented".
*/
w.unimplemented = function() {
w.error('Unimplemented');
};
/**
* Throws an Error.
* @method
* @param {string} msg
* @throws {Error}
*/
w.error = function(msg) {
if (w.isFunction(w.format)) {
msg = w.format.apply(w, arguments);
}
throw new Error(msg);
};
// $FOOTER$
return w;
});
})(this);
| Format support for w.error() if possible. | Format support for w.error() if possible.
| JavaScript | mit | warmsea/WarmseaJS | ---
+++
@@ -56,6 +56,9 @@
* @throws {Error}
*/
w.error = function(msg) {
+ if (w.isFunction(w.format)) {
+ msg = w.format.apply(w, arguments);
+ }
throw new Error(msg);
};
|
a0bd12dab161141e958e5d437694a7b22283fe8f | routes/index.js | routes/index.js | /*
* Module dependencies
*/
var app = module.parent.exports,
Joiner = require('../libs/joiner').Joiner;
/*
* Middlewares
*/
function isAnotherFile (req, res, next) {
var folder = req.params.version;
if (folder === 'assets' || folder === 'vendor' || folder === 'test' || folder === 'libs') {
next('route');
} else {
next();
}
};
function isView (req, res, next) {
if (req.params.type === undefined) {
res.render(req.params.version + '.html');
} else {
next();
}
};
/*
* Views
*/
app.get('/:version/:type?/:min?', isAnotherFile, isView, function (req, res, next) {
var name = req.params.version + req.params.type.toUpperCase(),
min = ((req.params.min) ? true : false),
joiner = new Joiner();
joiner.on('joined', function (data) {
res.set('Content-Type', 'text/' + (req.params.type === 'js' ? 'javascript' : 'css'));
res.send(data.raw);
});
joiner.run(name, min);
});
/*
* Index
*/
app.get('/', function (req, res, next) {
res.redirect('/ui')
}); | /*
* Module dependencies
*/
var app = module.parent.exports,
Joiner = require('../libs/joiner').Joiner;
/*
* Middlewares
*/
function isAnotherFile (req, res, next) {
var folder = req.params.version;
if (folder === 'assets' || folder === 'vendor' || folder === 'test' || folder === 'libs') {
next('route');
} else {
next();
}
};
function isView (req, res, next) {
if (req.params.type === undefined) {
res.render(req.params.version + '.html');
} else {
next();
}
};
/*
* Views
*/
app.get('/:version/:type?', isAnotherFile, isView, function (req, res, next) {
var name = req.params.version + req.params.type.toUpperCase(),
min = ((req.query.min) ? req.query.min : false),
joiner = new Joiner();
joiner.on('joined', function (data) {
res.set('Content-Type', 'text/' + (req.params.type === 'js' ? 'javascript' : 'css'));
res.send(data.raw);
});
joiner.run(name, min);
});
/*
* Index
*/
app.get('/', function (req, res, next) {
res.redirect('/ui')
}); | Change the min feature to a parameter as ?min=true to get data form joiner. | Change the min feature to a parameter as ?min=true to get data form joiner.
| JavaScript | mit | amireynoso/uxtest,vrleonel/ml-test,atma/chico,mercadolibre/chico,amireynoso/uxtest,vrleonel/chico,vrleonel/chico,vrleonel/ml-test,mercadolibre/chico,atma/chico | ---
+++
@@ -29,9 +29,9 @@
/*
* Views
*/
-app.get('/:version/:type?/:min?', isAnotherFile, isView, function (req, res, next) {
+app.get('/:version/:type?', isAnotherFile, isView, function (req, res, next) {
var name = req.params.version + req.params.type.toUpperCase(),
- min = ((req.params.min) ? true : false),
+ min = ((req.query.min) ? req.query.min : false),
joiner = new Joiner();
joiner.on('joined', function (data) { |
70f456cc5409b296cfe481c16614c6444f88b69b | lib/actions/clean-cache.js | lib/actions/clean-cache.js | 'use babel';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
const cleanCache = async () => {
const success = await yarnExec(null, 'cache', ['clean']);
if (!success) {
atom.notifications.addError(
'An error occurred whilst cleaning cache. See output for more information.',
);
return;
}
atom.notifications.addSuccess('Global package cache has been cleaned');
};
const confirmation = async () => {
atom.confirm({
message: 'Are you sure you want to clean the global Yarn cache?',
detailedMessage:
'Cleaning your global package cache will force Yarn to download packages from the npm registry the next time a package is requested.',
buttons: {
'Clean Cache': () => {
cleanCache().catch(reportError);
},
Cancel: null,
},
});
};
export default confirmation;
| 'use babel';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
import addProgressNotification from '../add-progress-notification';
const cleanCache = async () => {
let progress;
const options = {
onStart: () => {
progress = addProgressNotification('Cleaning global package cache...');
},
};
const success = await yarnExec(null, 'cache', ['clean'], options);
progress.dismiss();
if (!success) {
atom.notifications.addError(
'An error occurred whilst cleaning global cache. See output for more information.',
);
return;
}
atom.notifications.addSuccess('Global package cache has been cleaned');
};
const confirmation = async () => {
atom.confirm({
message: 'Are you sure you want to clean the global Yarn cache?',
detailedMessage:
'Cleaning your global package cache will force Yarn to download packages from the npm registry the next time a package is requested.',
buttons: {
'Clean Cache': () => {
cleanCache().catch(reportError);
},
Cancel: null,
},
});
};
export default confirmation;
| Add progress notification to clean cache command | Add progress notification to clean cache command
| JavaScript | mit | cbovis/atom-yarn | ---
+++
@@ -2,13 +2,24 @@
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
+import addProgressNotification from '../add-progress-notification';
const cleanCache = async () => {
- const success = await yarnExec(null, 'cache', ['clean']);
+ let progress;
+
+ const options = {
+ onStart: () => {
+ progress = addProgressNotification('Cleaning global package cache...');
+ },
+ };
+
+ const success = await yarnExec(null, 'cache', ['clean'], options);
+
+ progress.dismiss();
if (!success) {
atom.notifications.addError(
- 'An error occurred whilst cleaning cache. See output for more information.',
+ 'An error occurred whilst cleaning global cache. See output for more information.',
);
return; |
1c7c0d1635747f12b82c202155045958907ec0c6 | tests/unit/src/defur.js | tests/unit/src/defur.js | (function() {
var defur = require('../../../src/defur');
var assert = require('chai').assert;
suite('defur:', function() {
var services = null;
setup(function() {
services = {};
});
test('`defur` is a function', function() {
assert.isFunction(defur);
});
test('`defur` defers execution of definition', function() {
defur('foo', services, function() {
throw new Error('This should be deferred.');
});
assert.throws(function() {
services.foo;
});
});
test('`defur` creates the service only once', function() {
defur('foo', services, function() {
return {};
});
assert.strictEqual(services.foo, services.foo);
});
test('`defur` works with multiple service containers', function() {
var otherServices = {};
defur('foo', services, function() {
return {};
});
defur('foo', otherServices, function() {
return {};
});
assert.notEqual(services.foo, otherServices.foo);
});
});
})();
| (function() {
var defur = require('../../../src/defur');
var assert = require('chai').assert;
suite('defur:', function() {
var services = null;
setup(function() {
services = {};
});
test('`defur` is a function', function() {
assert.isFunction(defur);
});
test('`defur` defers execution of definition', function() {
defur('foo', services, function() {
throw new Error('This should be deferred.');
});
assert.throws(function() {
services.foo;
});
});
test('`defur` creates the service only once', function() {
defur('foo', services, function() {
return {};
});
assert.strictEqual(services.foo, services.foo);
});
test('`defur` services don\'t collide', function() {
defur('foo', services, function() {
return {};
});
defur('bar', services, function() {
return {};
});
assert.notEqual(services.foo, services.bar);
});
test('`defur` works with multiple service containers', function() {
var otherServices = {};
defur('foo', services, function() {
return {};
});
defur('foo', otherServices, function() {
return {};
});
assert.notEqual(services.foo, otherServices.foo);
});
});
})();
| Add test to cover container collisions | Add test to cover container collisions
| JavaScript | mit | adlawson/js-defur,adlawson/js-defur | ---
+++
@@ -32,6 +32,17 @@
assert.strictEqual(services.foo, services.foo);
});
+ test('`defur` services don\'t collide', function() {
+ defur('foo', services, function() {
+ return {};
+ });
+ defur('bar', services, function() {
+ return {};
+ });
+
+ assert.notEqual(services.foo, services.bar);
+ });
+
test('`defur` works with multiple service containers', function() {
var otherServices = {};
|
c4e58fda577b4f7f9165a788df9204d2646d26a3 | lib/ext/patch-ember-app.js | lib/ext/patch-ember-app.js | /**
* Monkeypatches the EmberApp instance from Ember CLI to contain the hooks we
* need to filter environment-specific initializers. Hopefully we can upstream
* similar hooks to Ember CLI and eventually remove these patches.
*/
function patchEmberApp(emberApp) {
// App was already patched
if (emberApp.addonPreconcatTree) { return; }
// Save off original implementation of the `concatFiles` hook
var originalConcatFiles = emberApp.concatFiles;
// Install method to invoke `preconcatTree` hook on each addon
emberApp.addonPreconcatTree = addonPreconcatTree;
// Install patched `concatFiles` method. This checks options passed to it
// and, if it detects that it's a concat for the app tree, invokes our
// preconcat hook. Afterwards, we invoke the original implementation to
// return a tree concating the files.
emberApp.concatFiles = function(tree, options) {
if (options.annotation === 'Concat: App') {
tree = this.addonPreconcatTree(tree);
}
return originalConcatFiles.call(this, tree, options);
};
}
function addonPreconcatTree(tree) {
var workingTree = tree;
this.project.addons.forEach(function(addon) {
if (addon.preconcatTree) {
workingTree = addon.preconcatTree(workingTree);
}
});
return workingTree;
}
module.exports = patchEmberApp;
| /**
* Monkeypatches the EmberApp instance from Ember CLI to contain the hooks we
* need to filter environment-specific initializers. Hopefully we can upstream
* similar hooks to Ember CLI and eventually remove these patches.
*/
function patchEmberApp(emberApp) {
// App was already patched
if (emberApp.addonPreconcatTree) { return; }
// Save off original implementation of the `concatFiles` hook
var originalConcatFiles = emberApp.concatFiles;
// Install method to invoke `preconcatTree` hook on each addon
emberApp.addonPreconcatTree = addonPreconcatTree;
// Install patched `concatFiles` method. This checks options passed to it
// and, if it detects that it's a concat for the app tree, invokes our
// preconcat hook. Afterwards, we invoke the original implementation to
// return a tree concating the files.
emberApp.concatFiles = function(tree, options) {
if (options.annotation === 'Concat: App') {
tree = this.addonPreconcatTree(tree);
}
return originalConcatFiles.apply(this, arguments);
};
}
function addonPreconcatTree(tree) {
var workingTree = tree;
this.project.addons.forEach(function(addon) {
if (addon.preconcatTree) {
workingTree = addon.preconcatTree(workingTree);
}
});
return workingTree;
}
module.exports = patchEmberApp;
| Fix deprecation warning in for using EmberApp.concatFiles | Fix deprecation warning in for using EmberApp.concatFiles
| JavaScript | mit | tildeio/ember-cli-fastboot,rwjblue/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot,kratiahuja/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot,kratiahuja/ember-cli-fastboot,josemarluedke/ember-cli-fastboot,tildeio/ember-cli-fastboot,rwjblue/ember-cli-fastboot,josemarluedke/ember-cli-fastboot | ---
+++
@@ -21,7 +21,7 @@
if (options.annotation === 'Concat: App') {
tree = this.addonPreconcatTree(tree);
}
- return originalConcatFiles.call(this, tree, options);
+ return originalConcatFiles.apply(this, arguments);
};
}
|
520b14ea01edc333dff77bf0822729be2ae14d1d | step-capstone/src/Components/TravelObject.js | step-capstone/src/Components/TravelObject.js | import React from 'react'
export default function TravelObject(props) {
let content = null;
switch(props.type) {
case 'event':
content = <div>Event!</div>;
break;
case 'flight':
content = <div>Flight!</div>
break;
case 'hotel':
content = <div>Hotel!</div>
break;
default:
console.log("Invalid type");
break;
}
return (
<div>
{content}
<button onClick={() => console.log("editing")}>Edit</button>
<button onClick={() => console.log("deleting")}>Delete</button>
</div>
)
} | import React from 'react'
import Flight from './Flight'
export default function TravelObject(props) {
let content = null;
switch(props.type) {
case 'event':
content = <div>Event!</div>;
break;
case 'flight':
content = <Flight />
break;
case 'hotel':
content = <div>Hotel!</div>
break;
default:
console.log("Invalid type");
break;
}
return (
<div>
{content}
<button onClick={() => console.log("editing")}>Edit</button>
<button onClick={() => console.log("deleting")}>Delete</button>
</div>
)
} | Replace dummy code for flight case with flight component | Replace dummy code for flight case with flight component
| JavaScript | apache-2.0 | googleinterns/step98-2020,googleinterns/step98-2020 | ---
+++
@@ -1,4 +1,5 @@
import React from 'react'
+import Flight from './Flight'
export default function TravelObject(props) {
let content = null;
@@ -7,7 +8,7 @@
content = <div>Event!</div>;
break;
case 'flight':
- content = <div>Flight!</div>
+ content = <Flight />
break;
case 'hotel':
content = <div>Hotel!</div> |
fd1791e92808b2e5b8cf69fc4af7c2a780c76a0d | gulp/config.js | gulp/config.js | var historyApiFallback = require("connect-history-api-fallback");
var dest = "./build";
var src = './src';
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest,
middleware: [historyApiFallback()]
}
},
js: {
src: src + '/js/app.js'
},
templates: {
src: src + '/templates/**/*.html'
},
css: {
src: src + "/js/vendor/highlight.js/styles/docco.css",
dest: dest
},
sass: {
src: src + "/sass/**/*.scss",
dest: dest,
settings: {
outputStyle: "compressed",
indentedSyntax: false, // Disable .sass syntax!
imagePath: 'img' // Used by the image-url helper
}
},
images: {
src: src + "/img/**",
dest: dest + "/img"
},
markup: {
src: src + "/{index.html,favicon.ico,/platform/**,/resources/**}",
dest: dest
},
browserify: {
bundleConfigs: [{
entries: src + '/js/app.js',
dest: dest,
outputName: 'worker_ui.js',
extensions: [],
transform: ["ractivate"]
}]
},
production: {
cssSrc: dest + '/*.css',
jsSrc: dest + '/*.js',
dest: dest
}
}; | var historyApiFallback = require("connect-history-api-fallback");
var dest = "./build";
var src = './src';
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest,
middleware: [historyApiFallback()]
}
},
js: {
src: src + '/js/app.js'
},
templates: {
src: src + '/templates/**/*.html'
},
css: {
src: src + "/js/vendor/highlight.js/styles/docco.css",
dest: dest
},
sass: {
src: src + "/sass/**/*.scss",
dest: dest,
settings: {
outputStyle: "compressed",
indentedSyntax: false, // Disable .sass syntax!
imagePath: 'img' // Used by the image-url helper
}
},
images: {
src: src + "/img/**",
dest: dest + "/img"
},
markup: {
src: src + "/{index.html,debug.html,favicon.ico,/platform/**,/resources/**}",
dest: dest
},
browserify: {
bundleConfigs: [{
entries: src + '/js/app.js',
dest: dest,
outputName: 'worker_ui.js',
extensions: [],
transform: ["ractivate"]
}]
},
production: {
cssSrc: dest + '/*.css',
jsSrc: dest + '/*.js',
dest: dest
}
}; | Add debug.html to build script | Add debug.html to build script
| JavaScript | apache-2.0 | coolcrowd/worker-ui,coolcrowd/worker-ui | ---
+++
@@ -37,7 +37,7 @@
dest: dest + "/img"
},
markup: {
- src: src + "/{index.html,favicon.ico,/platform/**,/resources/**}",
+ src: src + "/{index.html,debug.html,favicon.ico,/platform/**,/resources/**}",
dest: dest
},
browserify: { |
304b03a879b0b427214b90e7ae9f0d576876e954 | app/javascript/app/utils/redux.js | app/javascript/app/utils/redux.js | import isFunction from 'lodash/isFunction';
import { createAction as CA, handleActions as handle } from 'redux-actions';
// matches action names with reducers and returns an object to
// be used with handleActions
// passes all state as a third argument
export const bindActionsToReducers = (actions, reducerList, appState) =>
Object.keys(actions).reduce((result, k) => {
const c = {};
const name = actions[k];
c[name] = (state, action) =>
reducerList.reduce((r, reducer) => {
if (!reducer.hasOwnProperty(k) || !isFunction(reducer[k])) return r;
return reducer[k](r, action, appState);
}, state);
return { ...result, ...c };
}, {});
export const handleActions = (key, actions, reducers, state) =>
handle(bindActionsToReducers(actions, [reducers], state), state[key] || {});
// our own actioncreattor that can handle thunks
// fires the action as init
// and leaves resolve/reject to the thunk creator
export const createThunkAction = (name, thunkAction) => {
if (!thunkAction) return CA(name);
thunkAction.toString = () => name;
return thunkAction;
};
| import isFunction from 'lodash/isFunction';
import { createAction as CA, handleActions as handle } from 'redux-actions';
// matches action names with reducers and returns an object to
// be used with handleActions
// passes all state as a third argument
export const bindActionsToReducers = (actions, reducerList) =>
Object.keys(actions).reduce((result, k) => {
const c = {};
const name = actions[k];
c[name] = (state, action) =>
reducerList.reduce((r, reducer) => {
const hasProperty = Object.prototype.hasOwnProperty.call(reducer, k);
if (!hasProperty || !isFunction(reducer[k])) return r;
return reducer[k](r, action);
}, state);
return { ...result, ...c };
}, {});
export const handleActions = (key, actions, reducers, state) =>
handle(bindActionsToReducers(actions, [reducers], state), state[key] || {});
// our own actioncreattor that can handle thunks
// fires the action as init
// and leaves resolve/reject to the thunk creator
export const createThunkAction = (name, thunkAction) => {
if (!thunkAction) return CA(name);
thunkAction.toString = () => name; // eslint-disable-line
return thunkAction;
};
| Stop passing all store in each action | Stop passing all store in each action
| JavaScript | mit | Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch | ---
+++
@@ -4,14 +4,15 @@
// matches action names with reducers and returns an object to
// be used with handleActions
// passes all state as a third argument
-export const bindActionsToReducers = (actions, reducerList, appState) =>
+export const bindActionsToReducers = (actions, reducerList) =>
Object.keys(actions).reduce((result, k) => {
const c = {};
const name = actions[k];
c[name] = (state, action) =>
reducerList.reduce((r, reducer) => {
- if (!reducer.hasOwnProperty(k) || !isFunction(reducer[k])) return r;
- return reducer[k](r, action, appState);
+ const hasProperty = Object.prototype.hasOwnProperty.call(reducer, k);
+ if (!hasProperty || !isFunction(reducer[k])) return r;
+ return reducer[k](r, action);
}, state);
return { ...result, ...c };
@@ -25,6 +26,6 @@
// and leaves resolve/reject to the thunk creator
export const createThunkAction = (name, thunkAction) => {
if (!thunkAction) return CA(name);
- thunkAction.toString = () => name;
+ thunkAction.toString = () => name; // eslint-disable-line
return thunkAction;
}; |
e3b80778bf188ac19ab4d698621864d52819085f | app/js/util/arethusa_generator.js | app/js/util/arethusa_generator.js | "use strict";
// Generators for Arethusa code for things such as
// - useful directives
function ArethusaGenerator() {
this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
function toggle() {
scope.$apply(service.toggle());
}
var parent = element.parent();
trsl(trslKey, function(translation) {
parent.attr('title', translation);
});
element.bind('click', toggle);
},
template: template
};
};
}
var arethusaGenerator = new ArethusaGenerator();
var aG = arethusaGenerator;
| "use strict";
// Generators for Arethusa code for things such as
// - useful directives
function ArethusaGenerator() {
this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) {
return {
restrict: 'A',
compile: function(element) {
var parent = element.parent();
function updateTitle(translation) {
parent.attr('title', translation);
}
return function link(scope, element, attrs) {
function toggle() {
scope.$apply(service.toggle());
}
trsl(trslKey, updateTitle);
element.bind('click', toggle);
};
},
template: template
};
};
}
var arethusaGenerator = new ArethusaGenerator();
var aG = arethusaGenerator;
| Refactor panel triggers for speed | Refactor panel triggers for speed
| JavaScript | mit | latin-language-toolkit/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,Masoumeh/arethusa | ---
+++
@@ -7,17 +7,22 @@
this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) {
return {
restrict: 'A',
- link: function(scope, element, attrs) {
- function toggle() {
- scope.$apply(service.toggle());
+ compile: function(element) {
+ var parent = element.parent();
+
+ function updateTitle(translation) {
+ parent.attr('title', translation);
}
- var parent = element.parent();
- trsl(trslKey, function(translation) {
- parent.attr('title', translation);
- });
+ return function link(scope, element, attrs) {
+ function toggle() {
+ scope.$apply(service.toggle());
+ }
- element.bind('click', toggle);
+ trsl(trslKey, updateTitle);
+
+ element.bind('click', toggle);
+ };
},
template: template
}; |
d2f251b8a375ab011688d740113b8c09c79c5612 | src/ex.js | src/ex.js | import _ from "lodash";
import jQuery from "jquery";
import moment from "moment";
import Config from "./config.js";
import DText from "./dtext.js";
import Tag from "./tag.js";
import UI from "./ui.js";
import "./danbooru-ex.css";
export default class EX {
static get Config() { return Config; }
static get DText() { return DText; }
static get Tag() { return Tag; }
static get UI() { return UI; }
static search(url, search, { limit, page } = {}) {
return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 });
}
static initialize() {
EX.config = new Config();
EX.config.enableHeader && UI.Header.initialize();
EX.UI.initialize();
EX.UI.Artists.initialize();
EX.UI.Comments.initialize();
EX.UI.ForumPosts.initialize();
EX.UI.Pools.initialize();
EX.UI.Posts.initialize();
EX.UI.PostVersions.initialize();
EX.UI.WikiPages.initialize();
}
}
window.EX = EX;
jQuery(function () {
try {
EX.initialize();
} catch(e) {
$("footer").append(`<div class="ex-error">Danbooru EX error: ${e}</div>`);
throw e;
}
});
| import _ from "lodash";
import jQuery from "jquery";
import moment from "moment";
import Config from "./config.js";
import DText from "./dtext.js";
import Tag from "./tag.js";
import UI from "./ui.js";
import "./danbooru-ex.css";
export default class EX {
static get Config() { return Config; }
static get DText() { return DText; }
static get Tag() { return Tag; }
static get UI() { return UI; }
static search(url, search, { limit, page } = {}) {
return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 });
}
static initialize() {
EX.config = new Config();
EX.config.enableHeader && UI.Header.initialize();
EX.UI.initialize();
EX.UI.Artists.initialize();
EX.UI.Comments.initialize();
EX.UI.ForumPosts.initialize();
EX.UI.Pools.initialize();
EX.UI.Posts.initialize();
EX.UI.PostVersions.initialize();
EX.UI.WikiPages.initialize();
}
}
window.EX = EX;
window.moment = moment;
jQuery(function () {
try {
EX.initialize();
} catch(e) {
$("footer").append(`<div class="ex-error">Danbooru EX error: ${e}</div>`);
throw e;
}
});
| Make moment global for debugging. | [fix] Make moment global for debugging.
| JavaScript | mit | evazion/danbooru-ex,evazion/danbooru-ex | ---
+++
@@ -35,6 +35,8 @@
}
window.EX = EX;
+window.moment = moment;
+
jQuery(function () {
try {
EX.initialize(); |
0ae0be0b2a0124d19c73f3d1814d92470b1f4960 | src/send.js | src/send.js | import { busy, scheduleRetry } from './actions';
import { JS_ERROR } from './constants';
import type { Config, OfflineAction, ResultAction } from './types';
const complete = (
action: ResultAction,
success: boolean,
payload: {}
): ResultAction => ({
...action,
payload,
meta: { ...action.meta, success, completed: true }
});
const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => {
const metadata = action.meta.offline;
dispatch(busy(true));
return config
.effect(metadata.effect, action)
.then(result => {
const commitAction = metadata.commit || config.defaultCommit;
try {
dispatch(complete(commitAction, true, result));
} catch (e) {
dispatch(complete({ type: JS_ERROR, payload: e }, false));
}
})
.catch(error => {
const rollbackAction = metadata.rollback || config.defaultRollback;
// discard
if (config.discard(error, action, retries)) {
dispatch(complete(rollbackAction, false, error));
return;
}
const delay = config.retry(action, retries);
if (delay != null) {
dispatch(scheduleRetry(delay));
return;
}
dispatch(complete(rollbackAction, false, error));
});
};
export default send;
| import { busy, scheduleRetry } from './actions';
import { JS_ERROR } from './constants';
import type { Config, OfflineAction, ResultAction } from './types';
const complete = (
action: ResultAction,
success: boolean,
payload: {}
): ResultAction => ({
...action,
payload,
meta: { ...action.meta, success, completed: true }
});
const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => {
const metadata = action.meta.offline;
dispatch(busy(true));
return config
.effect(metadata.effect, action)
.then(result => {
const commitAction = metadata.commit || {
...config.defaultCommit,
meta: { ...config.defaultCommit.meta, offlineAction: action }
};
try {
dispatch(complete(commitAction, true, result));
} catch (e) {
dispatch(complete({ type: JS_ERROR, payload: e }, false));
}
})
.catch(error => {
const rollbackAction = metadata.rollback || {
...config.defaultRollback,
meta: { ...config.defaultRollback.meta, offlineAction: action }
};
// discard
if (config.discard(error, action, retries)) {
dispatch(complete(rollbackAction, false, error));
return;
}
const delay = config.retry(action, retries);
if (delay != null) {
dispatch(scheduleRetry(delay));
return;
}
dispatch(complete(rollbackAction, false, error));
});
};
export default send;
| Add offline action to default commit and rollback actions | Add offline action to default commit and rollback actions
| JavaScript | mit | redux-offline/redux-offline,jevakallio/redux-offline | ---
+++
@@ -18,7 +18,10 @@
return config
.effect(metadata.effect, action)
.then(result => {
- const commitAction = metadata.commit || config.defaultCommit;
+ const commitAction = metadata.commit || {
+ ...config.defaultCommit,
+ meta: { ...config.defaultCommit.meta, offlineAction: action }
+ };
try {
dispatch(complete(commitAction, true, result));
} catch (e) {
@@ -26,7 +29,10 @@
}
})
.catch(error => {
- const rollbackAction = metadata.rollback || config.defaultRollback;
+ const rollbackAction = metadata.rollback || {
+ ...config.defaultRollback,
+ meta: { ...config.defaultRollback.meta, offlineAction: action }
+ };
// discard
if (config.discard(error, action, retries)) { |
7f68b7980f1af0e5e2ac8f19022bb3b2e71675cb | src/api/link.js | src/api/link.js | import props from './props';
function getValue (elem) {
const type = elem.type;
if (type === 'checkbox' || type === 'radio') {
return elem.checked ? elem.value || true : false;
}
return elem.value;
}
export default function (elem, target) {
return (e) => {
// We fallback to checking the composed path. Unfortunately this behaviour
// is difficult to impossible to reproduce as it seems to be a possible
// quirk in the shadydom polyfill that incorrectly returns null for the
// target but has the target as the first point in the path.
// TODO revisit once all browsers have native support.
const localTarget = target || e.target || e.composedPath()[0];
const value = getValue(localTarget);
const localTargetName = e.target.name || 'value';
if (localTargetName.indexOf('.') > -1) {
const parts = localTargetName.split('.');
const firstPart = parts[0];
const propName = parts.pop();
const obj = parts.reduce((prev, curr) => (prev && prev[curr]), elem);
obj[propName || e.target.name] = value;
props(elem, {
[firstPart]: elem[firstPart]
});
} else {
props(elem, {
[localTargetName]: value
});
}
};
}
| import props from './props';
function getValue (elem) {
const type = elem.type;
if (type === 'checkbox' || type === 'radio') {
return elem.checked ? elem.value || true : false;
}
return elem.value;
}
export default function (elem, target) {
return (e) => {
// We fallback to checking the composed path. Unfortunately this behaviour
// is difficult to impossible to reproduce as it seems to be a possible
// quirk in the shadydom polyfill that incorrectly returns null for the
// target but has the target as the first point in the path.
// TODO revisit once all browsers have native support.
const localTarget = e.target || e.composedPath()[0];
const value = getValue(localTarget);
const localTargetName = target || localTarget.name || 'value';
if (localTargetName.indexOf('.') > -1) {
const parts = localTargetName.split('.');
const firstPart = parts[0];
const propName = parts.pop();
const obj = parts.reduce((prev, curr) => (prev && prev[curr]), elem);
obj[propName || e.target.name] = value;
props(elem, {
[firstPart]: elem[firstPart]
});
} else {
props(elem, {
[localTargetName]: value
});
}
};
}
| Fix issue only exposed by certain situations with the shadydom polyfill. | fix: Fix issue only exposed by certain situations with the shadydom polyfill.
| JavaScript | mit | chrisdarroch/skatejs,skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -15,9 +15,9 @@
// quirk in the shadydom polyfill that incorrectly returns null for the
// target but has the target as the first point in the path.
// TODO revisit once all browsers have native support.
- const localTarget = target || e.target || e.composedPath()[0];
+ const localTarget = e.target || e.composedPath()[0];
const value = getValue(localTarget);
- const localTargetName = e.target.name || 'value';
+ const localTargetName = target || localTarget.name || 'value';
if (localTargetName.indexOf('.') > -1) {
const parts = localTargetName.split('.'); |
7de0c1782ac690461693aa308364ac3aa996712a | tests/e2e/utils/activate-amp-and-set-mode.js | tests/e2e/utils/activate-amp-and-set-mode.js |
/**
* WordPress dependencies
*/
import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils';
/**
* The allow list of AMP modes.
*
*/
export const allowedAmpModes = {
standard: 'standard',
transitional: 'transitional',
reader: 'disabled',
};
/**
* Activate AMP and set it to the correct mode.
*
* @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader.
*/
export const activateAmpAndSetMode = async ( mode ) => {
// Test to be sure that the passed mode is known.
expect( Object.keys( allowedAmpModes ) ).toContain( mode );
// Active AMP and set the passed mode.
await activatePlugin( 'amp' );
await visitAdminPage( 'admin.php', 'page=amp-options' );
await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` );
await expect( page ).toClick( '#submit' );
await page.waitForSelector( '#setting-error-settings_updated' );
await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } );
};
|
/**
* WordPress dependencies
*/
import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils';
/**
* The allow list of AMP modes.
*
*/
export const allowedAmpModes = {
standard: 'standard',
transitional: 'transitional',
reader: 'disabled',
};
/**
* Activate AMP and set it to the correct mode.
*
* @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader.
*/
export const activateAmpAndSetMode = async ( mode ) => {
await activatePlugin( 'amp' );
await setAMPMode( mode );
};
/**
* Set AMP Mode
*
* @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader.
*/
export const setAMPMode = async ( mode ) => {
// Test to be sure that the passed mode is known.
expect( Object.keys( allowedAmpModes ) ).toContain( mode );
// Set the AMP mode
await visitAdminPage( 'admin.php', 'page=amp-options' );
await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` );
await expect( page ).toClick( '#submit' );
await page.waitForSelector( '#setting-error-settings_updated' );
await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } );
};
| Add helper to change AMP mode. | Add helper to change AMP mode.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -20,10 +20,19 @@
* @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader.
*/
export const activateAmpAndSetMode = async ( mode ) => {
+ await activatePlugin( 'amp' );
+ await setAMPMode( mode );
+};
+
+/**
+ * Set AMP Mode
+ *
+ * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader.
+ */
+export const setAMPMode = async ( mode ) => {
// Test to be sure that the passed mode is known.
expect( Object.keys( allowedAmpModes ) ).toContain( mode );
- // Active AMP and set the passed mode.
- await activatePlugin( 'amp' );
+ // Set the AMP mode
await visitAdminPage( 'admin.php', 'page=amp-options' );
await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` );
await expect( page ).toClick( '#submit' ); |
41460b6e776e8d3b6cac28c63a4ce4b73541fb27 | require-best.js | require-best.js | module.exports = function(moduleName) {
var majorVersion = parseInt(process.version.match(/^v(\d+)/) || [])[1]
if (majorVersion >= 8) {
return require('./src/' + moduleName)
} else {
return require('./node6/' + moduleName)
}
} |
module.exports = function(moduleName) {
var majorVersion = parseInt((process.version.match(/^v(\d+)/) || [])[1])
if (majorVersion >= 8) {
return require('./src/' + moduleName)
} else {
return require('./node6/' + moduleName)
}
} | Fix using "native" code on node 8+ | Fix using "native" code on node 8+
| JavaScript | mit | BaronaGroup/migsi,BaronaGroup/migsi | ---
+++
@@ -1,5 +1,7 @@
+
module.exports = function(moduleName) {
- var majorVersion = parseInt(process.version.match(/^v(\d+)/) || [])[1]
+ var majorVersion = parseInt((process.version.match(/^v(\d+)/) || [])[1])
+
if (majorVersion >= 8) {
return require('./src/' + moduleName)
} else { |
dc390d2733adb5c57866626125a04f1a6e9b5da3 | js/cooldown.js | js/cooldown.js | var seconds_match = /^(\d)*s$/;
function Cooldown(frames)
{
frames = frames || 10
if ($.type(frames) == "string")
{
var seconds = frames.match(seconds_match)
if (seconds)
{
frames = seconds[1] * runtime.fps
}
else
{
frames = parseInt(frames)
}
}
var total = frames
var result = false
this.set_result = function(new_result)
{
result = new_result
}
this.frame = function()
{
frames--
if (frames <= 0)
return result
return this
}
this.get_remaining = function()
{
return total - frames
}
this.get_pctdone = function()
{
return (total - frames) / total
}
}
| var seconds_match = /^(\d)*s$/;
function Cooldown(frames, inital_result)
{
frames = frames || 10
if ($.type(frames) == "string")
{
var seconds = frames.match(seconds_match)
if (seconds)
{
frames = seconds[1] * runtime.fps
}
else
{
frames = parseInt(frames)
}
}
var total = frames
var result = false
this.set_result = function(new_result)
{
result = new_result
}
if ($.isFunction(inital_result))
this.set_result(inital_result)
this.frame = function()
{
frames--
if (frames <= 0)
return result
return this
}
this.reset = function()
{
frames = total
}
this.is_done = function()
{
return frames >= total
}
this.get_remaining = function()
{
return total - frames
}
this.get_pctdone = function()
{
return (total - frames) / total
}
}
| Add a shortcut to set the result function in Cooldown | Add a shortcut to set the result function in Cooldown
| JavaScript | artistic-2.0 | atrodo/fission_engine,atrodo/fission_engine | ---
+++
@@ -1,5 +1,5 @@
var seconds_match = /^(\d)*s$/;
- function Cooldown(frames)
+ function Cooldown(frames, inital_result)
{
frames = frames || 10
if ($.type(frames) == "string")
@@ -21,6 +21,10 @@
{
result = new_result
}
+
+ if ($.isFunction(inital_result))
+ this.set_result(inital_result)
+
this.frame = function()
{
frames--
@@ -29,6 +33,14 @@
return this
}
+ this.reset = function()
+ {
+ frames = total
+ }
+ this.is_done = function()
+ {
+ return frames >= total
+ }
this.get_remaining = function()
{
return total - frames |
1d6be34ff63350aa3e3c0cdeb163d653bec307dc | js/services.js | js/services.js | angular.module('services', [])
.filter('file', function () {
return function (input) {
return input.split(' ').join('_').toLowerCase()
}
})
.factory('responsive', function () {
var resizeTimer
return {
run: function (apply, main, input, output) {
main(input, output)
$(window).on('resize', function(e) {
clearTimeout(resizeTimer)
resizeTimer = setTimeout(function () {
main(input, output)
apply()
}, 100)
})
}
}
})
| angular.module('services', [])
.directive('done', ['$parse', function($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var fn = $parse(attrs.done)
if (scope.$last){
scope.done()
}
}
}
}])
.filter('file', function () {
return function (input) {
return input.split(' ').join('_').toLowerCase()
}
})
.filter('first', function () {
return function (input) {
var output = input.split(': ')
return output[0]
}
})
.filter('second', function () {
return function (input) {
var output = input.split(': ')
return output[1]
}
})
.filter('info', function () {
return function (input) {
return input.split(', ').join(',\ \ ')
}
})
.factory('responsive', function () {
var resizeTimer
return {
run: function (apply, init, main, input, output) {
init(main, input, output)
$(window).on('resize', function(e) {
window.requestAnimationFrame(function () {
main(input, output)
apply()
})
})
}
}
})
| Add filter/directives for about page | Add filter/directives for about page
| JavaScript | mit | Cwejman/martina,Cwejman/martina | ---
+++
@@ -1,4 +1,17 @@
angular.module('services', [])
+
+.directive('done', ['$parse', function($parse) {
+ return {
+ restrict: 'A',
+ link: function(scope, element, attrs) {
+ var fn = $parse(attrs.done)
+ if (scope.$last){
+ scope.done()
+ }
+ }
+ }
+
+}])
.filter('file', function () {
@@ -9,22 +22,47 @@
})
+.filter('first', function () {
+
+ return function (input) {
+ var output = input.split(': ')
+ return output[0]
+ }
+
+})
+
+.filter('second', function () {
+
+ return function (input) {
+ var output = input.split(': ')
+ return output[1]
+ }
+
+})
+
+.filter('info', function () {
+
+ return function (input) {
+ return input.split(', ').join(',\ \ ')
+ }
+
+})
+
.factory('responsive', function () {
var resizeTimer
return {
- run: function (apply, main, input, output) {
+ run: function (apply, init, main, input, output) {
- main(input, output)
+ init(main, input, output)
$(window).on('resize', function(e) {
- clearTimeout(resizeTimer)
- resizeTimer = setTimeout(function () {
+ window.requestAnimationFrame(function () {
main(input, output)
apply()
- }, 100)
+ })
})
|
6594bafa373173d987271d51833bcbb45ea4cda1 | js/settings.js | js/settings.js | var possibleStates = [
'P,Pipeline',
'R,Request Evaluation',
'Rm,Requirements',
'C,Concept',
'D,Development',
'Dy,Deployment',
'L,Live'
];
var possible_colors = 4; | var possibleStates = [
'B,Backlog',
'P,Pending ',
'Cs,Current Sprint',
'D,Doing',
'Bl,Blocked',
'Q,QA',
'L,Live'
];
var possible_colors = 4;
| Set up more common Kanban columns | Set up more common Kanban columns | JavaScript | mit | rapsli/simple-kanban,rapsli/simple-kanban | ---
+++
@@ -1,10 +1,10 @@
var possibleStates = [
- 'P,Pipeline',
- 'R,Request Evaluation',
- 'Rm,Requirements',
- 'C,Concept',
- 'D,Development',
- 'Dy,Deployment',
+ 'B,Backlog',
+ 'P,Pending ',
+ 'Cs,Current Sprint',
+ 'D,Doing',
+ 'Bl,Blocked',
+ 'Q,QA',
'L,Live'
];
|
5de4f9dde7d1100e4db600c55748278c003df004 | lib/profile.js | lib/profile.js | /**
* Parse profile.
*
* @param {Object|String} json
* @return {Object}
* @api private
*/
exports.parse = function(json) {
if ('string' == typeof json) {
json = JSON.parse(json);
}
var profile = {};
profile.id = json.iupi;
profile.email = json.email;
return profile;
};
| /**
* Parse profile.
*
* @param {Object|String} json
* @return {Object}
* @api private
*/
exports.parse = function(json) {
if ('string' === typeof json) {
json = JSON.parse(json);
}
var profile = {};
profile.id = json.iupi;
profile.email = json.email;
return profile;
};
| Improve code quality by change '==' into '===' | Improve code quality by change '==' into '==='
| JavaScript | mit | poliveira89/passport-identityua,poliveira89/passport-identityua | ---
+++
@@ -6,7 +6,7 @@
* @api private
*/
exports.parse = function(json) {
- if ('string' == typeof json) {
+ if ('string' === typeof json) {
json = JSON.parse(json);
}
|
a3aff6a41a08614ba68fb590aefbc6e2cb5067a4 | routers/download/constants.js | routers/download/constants.js | const ALLOWED_CSV_FIELD_PATHS = [
'ids.GB-CHC',
'ids.charityId',
'name',
'contact.email',
'contact.person',
'contact.postcode',
'contact.address',
'contact.geo.longitude',
'contact.geo.latitude',
'people.volunteers',
'people.employees',
'people.trustees',
'activities',
'website',
'income.annual',
'areaOfBenefit',
'causes',
'beneficiaries',
'operations',
]
const FY_END_YEARS = [
2008,
2009,
2010,
2011,
2012,
2013,
2014,
2015,
2016,
2017,
2018,
]
module.exports = {
ALLOWED_CSV_FIELD_PATHS,
FY_END_YEARS,
}
| const ALLOWED_CSV_FIELD_PATHS = [
'ids.GB-CHC',
'ids.charityId',
'name',
'contact.address',
'contact.email',
'contact.geo.latitude',
'contact.geo.longitude',
'contact.person',
'contact.phone',
'contact.postcode',
'people.volunteers',
'people.employees',
'people.trustees',
'activities',
'website',
'income.annual',
'areaOfBenefit',
'causes',
'beneficiaries',
'operations',
'objectives',
]
const FY_END_YEARS = [
2008,
2009,
2010,
2011,
2012,
2013,
2014,
2015,
2016,
2017,
2018,
]
module.exports = {
ALLOWED_CSV_FIELD_PATHS,
FY_END_YEARS,
}
| Allow downloading objectives & phone | Allow downloading objectives & phone
| JavaScript | mit | tithebarn/charity-base,tithebarn/open-charities,tythe-org/charity-base-api | ---
+++
@@ -2,12 +2,13 @@
'ids.GB-CHC',
'ids.charityId',
'name',
+ 'contact.address',
'contact.email',
+ 'contact.geo.latitude',
+ 'contact.geo.longitude',
'contact.person',
+ 'contact.phone',
'contact.postcode',
- 'contact.address',
- 'contact.geo.longitude',
- 'contact.geo.latitude',
'people.volunteers',
'people.employees',
'people.trustees',
@@ -18,6 +19,7 @@
'causes',
'beneficiaries',
'operations',
+ 'objectives',
]
const FY_END_YEARS = [ |
3cd2d32ca72775777962a912fe539cbb540274b0 | delay.safariextension/start.js | delay.safariextension/start.js | (function () {
"use strict";
var settings, display;
if (window !== window.top) {
return;
}
safari.self.tab.dispatchMessage('getSettings');
safari.self.addEventListener('message', function (event) {
if (event.name === 'settings') {
settings = event.message;
if (settings.blacklist.indexOf(window.location.hostname) !== -1) {
display = document.documentElement.style.display;
document.documentElement.style.display = 'none';
window.setTimeout(function () {
document.documentElement.style.display = display;
}, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter)));
}
}
}, false);
}());
| (function () {
"use strict";
var settings, visibility;
if (window !== window.top) {
return;
}
safari.self.tab.dispatchMessage('getSettings');
safari.self.addEventListener('message', function (event) {
if (event.name === 'settings') {
settings = event.message;
if (settings.blacklist.indexOf(window.location.hostname) !== -1) {
visibility = document.documentElement.style.visibility;
document.documentElement.style.visibility = 'hidden';
window.setTimeout(function () {
document.documentElement.style.visibility = visibility;
}, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter)));
}
}
}, false);
}());
| Switch from "display:none" to "visibility:hidden". | Switch from "display:none" to "visibility:hidden".
That way the page layout won't be affected but it will still be hidden.
| JavaScript | mit | tfausak/delay | ---
+++
@@ -1,6 +1,6 @@
(function () {
"use strict";
- var settings, display;
+ var settings, visibility;
if (window !== window.top) {
return;
@@ -13,10 +13,10 @@
settings = event.message;
if (settings.blacklist.indexOf(window.location.hostname) !== -1) {
- display = document.documentElement.style.display;
- document.documentElement.style.display = 'none';
+ visibility = document.documentElement.style.visibility;
+ document.documentElement.style.visibility = 'hidden';
window.setTimeout(function () {
- document.documentElement.style.display = display;
+ document.documentElement.style.visibility = visibility;
}, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter)));
}
} |
1200f59759531802d41cf1674d0a22ccaec21ca8 | examples/src/examples/YearCalendar.js | examples/src/examples/YearCalendar.js | import React from 'react';
import DayPicker from '../../../src';
import '../../../src/style.css';
import '../styles/year.css';
export default class YearCalendar extends React.Component {
constructor(props) {
super(props);
this.showPrevious = this.showPrevious.bind(this);
this.showNext = this.showNext.bind(this);
}
state = {
year: (new Date()).getFullYear(),
};
showPrevious() {
this.setState({
year: this.state.year - 1,
});
}
showNext() {
this.setState({
year: this.state.year + 1,
});
}
render() {
const { year } = this.state;
return (
<div className="YearCalendar">
<h1>
<a onClick={ this.showPrevious }>{ year - 1 }</a>
{ year }
<a onClick={ this.showNext }>{ year + 1 }</a>
</h1>
<DayPicker
canChangeMonth={ false }
initialMonth={ new Date(year, 0, 1) }
numberOfMonths={ 12 }
/>
</div>
);
}
}
| import React from 'react';
import DayPicker from '../../../src';
import '../../../src/style.css';
import '../styles/year.css';
export default class YearCalendar extends React.Component {
constructor(props) {
super(props);
this.showPrevious = this.showPrevious.bind(this);
this.showNext = this.showNext.bind(this);
}
state = {
year: (new Date()).getFullYear(),
};
showPrevious() {
this.setState({
year: this.state.year - 1,
});
}
showNext() {
this.setState({
year: this.state.year + 1,
});
}
render() {
const { year } = this.state;
return (
<div className="YearCalendar">
<h1>
<a onClick={ this.showPrevious }>{ year - 1 }</a>
{ year }
<a onClick={ this.showNext }>{ year + 1 }</a>
</h1>
<DayPicker
canChangeMonth={ false }
month={ new Date(year, 0, 1) }
numberOfMonths={ 12 }
/>
</div>
);
}
}
| Use month instead of initialMonth | Use month instead of initialMonth
| JavaScript | mit | saenglert/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker | ---
+++
@@ -35,7 +35,7 @@
</h1>
<DayPicker
canChangeMonth={ false }
- initialMonth={ new Date(year, 0, 1) }
+ month={ new Date(year, 0, 1) }
numberOfMonths={ 12 }
/>
</div> |
cbd505bf2749c62d6baba3e9278a92143b1fc255 | example/build.js | example/build.js | var thumbsup = require('../src/index');
thumbsup.build({
// the input folder
// with all photos/videos
input: 'example/media',
// the output folder
// for the thumbnails and static pages
output: 'example/website',
// website title
// the first word will be in color
title: 'Photo gallery',
// main site color
// for the title and links
css: null,
// size of the square thumbnails
// in pixels
thumbSize: 120,
// size of the "fullscreen" view
// in pixels
largeSize: 400
});
| var thumbsup = require('../src/index');
thumbsup.build({
// the input folder
// with all photos/videos
input: 'example/media',
// the output folder
// for the thumbnails and static pages
output: '_site',
// website title
// the first word will be in color
title: 'Photo gallery',
// main site color
// for the title and links
css: null,
// size of the square thumbnails
// in pixels
thumbSize: 120,
// size of the "fullscreen" view
// in pixels
largeSize: 400
});
| Build the example site into _site (published as Github pages) | Build the example site into _site (published as Github pages)
| JavaScript | mit | kremlinkev/thumbsup,thumbsup/node-thumbsup,dravenst/thumbsup,rprieto/thumbsup,dravenst/thumbsup,thumbsup/thumbsup,kremlinkev/thumbsup,thumbsup/thumbsup,thumbsup/node-thumbsup,rprieto/thumbsup,thumbsup/node-thumbsup | ---
+++
@@ -9,7 +9,7 @@
// the output folder
// for the thumbnails and static pages
- output: 'example/website',
+ output: '_site',
// website title
// the first word will be in color |
c5b6ac00c1d05bc69f4dcbd9f999baf43421f0fe | tasks/styles.js | tasks/styles.js | 'use strict';
var sass = require('gulp-sass');
var bourbon = require('node-bourbon');
var rev = require('gulp-rev');
var minify = require('gulp-minify-css');
/*
compile sass with bourbon
*/
module.exports = function (stream) {
return stream
.pipe(sass({
includePaths: bourbon.includePaths
}))
.pipe(env.not('development', rev()))
.pipe(env.not('development', minify()));
};
| 'use strict';
var sass = require('gulp-sass');
var bourbon = require('node-bourbon');
var rev = require('gulp-rev');
var minify = require('gulp-minify-css');
var env = require('../utils/env');
var manifest = require('../utils/manifest');
/*
compile sass with bourbon
*/
module.exports = function (stream) {
return stream
.pipe(sass({
includePaths: bourbon.includePaths
}))
.pipe(env.not('development', rev()))
.pipe(env.not('development', manifest()))
.pipe(env.not('development', minify()));
};
| Add CSS to asset manifest | Add CSS to asset manifest
| JavaScript | mit | bendrucker/gulp-tasks | ---
+++
@@ -1,9 +1,11 @@
'use strict';
-var sass = require('gulp-sass');
-var bourbon = require('node-bourbon');
-var rev = require('gulp-rev');
-var minify = require('gulp-minify-css');
+var sass = require('gulp-sass');
+var bourbon = require('node-bourbon');
+var rev = require('gulp-rev');
+var minify = require('gulp-minify-css');
+var env = require('../utils/env');
+var manifest = require('../utils/manifest');
/*
compile sass with bourbon
@@ -15,5 +17,6 @@
includePaths: bourbon.includePaths
}))
.pipe(env.not('development', rev()))
+ .pipe(env.not('development', manifest()))
.pipe(env.not('development', minify()));
}; |
4a92a6850aa2827cf3d7adf6be530c5329582018 | app/assets/javascripts/icons.js | app/assets/javascripts/icons.js | $(document).ready(function() {
// Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't
// respect up/down key selections in a dropdown as a valid change() trigger
$("#icon_dropdown").change(function() { setIconFromId($(this).val()); });
$("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); });
});
function setIconFromId(id) {
$("#new_icon").attr('src', gon.gallery[id].url);
$("#new_icon").attr('alt', gon.gallery[id].keyword);
$("#new_icon").attr('title', gon.gallery[id].keyword);
if(gon.gallery[id].aliases !== undefined) {
var aliases = gon.gallery[id].aliases;
if (aliases.length > 0) {
$("#alias_dropdown").show().empty().append('<option value="">— No alias —</option>');
for(var i = 0; i < aliases.length; i++) {
$("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name));
}
} else { $("#alias_dropdown").hide(); }
}
};
| $(document).ready(function() {
// Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't
// respect up/down key selections in a dropdown as a valid change() trigger
$("#icon_dropdown").change(function() { setIconFromId($(this).val()); });
$("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); });
});
function setIconFromId(id) {
$("#new_icon").attr('src', gon.gallery[id].url);
$("#new_icon").attr('alt', gon.gallery[id].keyword);
$("#new_icon").attr('title', gon.gallery[id].keyword);
if(gon.gallery[id].aliases !== undefined) {
var aliases = gon.gallery[id].aliases;
if (aliases.length > 0) {
$("#alias_dropdown").show().empty().append('<option value="">— No alias —</option>');
for(var i = 0; i < aliases.length; i++) {
$("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name));
}
} else { $("#alias_dropdown").hide().val(''); }
}
};
| Make sure to reset alias when switching between characters if the new one has no alias | Make sure to reset alias when switching between characters if the new one has no alias
| JavaScript | mit | Marri/glowfic,Marri/glowfic,Marri/glowfic,Marri/glowfic | ---
+++
@@ -16,6 +16,6 @@
for(var i = 0; i < aliases.length; i++) {
$("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name));
}
- } else { $("#alias_dropdown").hide(); }
+ } else { $("#alias_dropdown").hide().val(''); }
}
}; |
18264d202fb2a48c3f8952246708af1b5e941fbf | app/assets/javascripts/icons.js | app/assets/javascripts/icons.js | /* global gon */
$(document).ready(function() {
// Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't
// respect up/down key selections in a dropdown as a valid change() trigger
$("#icon_dropdown").change(function() { setIconFromId($(this).val()); });
$("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); });
$('.gallery-minmax').click(function() {
var elem = $(this);
var id = elem.data('id');
if (elem.html().trim() === '-') {
$('#gallery' + id).hide();
$('#gallery-tags-' + id).hide();
elem.html('+');
} else {
$('#gallery' + id).show();
$('#gallery-tags-' + id).show();
elem.html('-');
}
});
});
function setIconFromId(id) {
$("#new_icon").attr('src', gon.gallery[id].url);
$("#new_icon").attr('alt', gon.gallery[id].keyword);
$("#new_icon").attr('title', gon.gallery[id].keyword);
if (typeof gon.gallery[id].aliases !== "undefined") {
var aliases = gon.gallery[id].aliases;
if (aliases.length > 0) {
$("#alias_dropdown").show().empty().append('<option value="">— No alias —</option>');
for (var i = 0; i < aliases.length; i++) {
$("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name));
}
} else {
$("#alias_dropdown").hide().val('');
}
}
}
| /* global gon */
$(document).ready(function() {
// Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't
// respect up/down key selections in a dropdown as a valid change() trigger
$("#icon_dropdown").change(function() { setIconFromId($(this).val()); });
$("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); });
});
function setIconFromId(id) {
$("#new_icon").attr('src', gon.gallery[id].url);
$("#new_icon").attr('alt', gon.gallery[id].keyword);
$("#new_icon").attr('title', gon.gallery[id].keyword);
if (typeof gon.gallery[id].aliases !== "undefined") {
var aliases = gon.gallery[id].aliases;
if (aliases.length > 0) {
$("#alias_dropdown").show().empty().append('<option value="">— No alias —</option>');
for (var i = 0; i < aliases.length; i++) {
$("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name));
}
} else {
$("#alias_dropdown").hide().val('');
}
}
}
| Remove dead duplicate code for gallery minmax | Remove dead duplicate code for gallery minmax
| JavaScript | mit | Marri/glowfic,Marri/glowfic,Marri/glowfic,Marri/glowfic | ---
+++
@@ -4,20 +4,6 @@
// respect up/down key selections in a dropdown as a valid change() trigger
$("#icon_dropdown").change(function() { setIconFromId($(this).val()); });
$("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); });
-
- $('.gallery-minmax').click(function() {
- var elem = $(this);
- var id = elem.data('id');
- if (elem.html().trim() === '-') {
- $('#gallery' + id).hide();
- $('#gallery-tags-' + id).hide();
- elem.html('+');
- } else {
- $('#gallery' + id).show();
- $('#gallery-tags-' + id).show();
- elem.html('-');
- }
- });
});
function setIconFromId(id) { |
bd223902c3d3f4bc07257ec4c49a540cfd654a95 | test/feature.js | test/feature.js | var assert = require('assert');
var Feature = require('../feature');
describe('Feature', function () {
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document');
});
describe('.search()', function () {
it('performs an empty search, returning all commands', function (done) {
Feature.search('', function (docs) {
assert.equal(7, docs.length);
done();
});
});
it('performs a case-insensitive search for a command', function (done) {
Feature.search('git ADD', function (docs) {
assert.equal(1, docs.length)
done();
});
});
it('performs a search for a command that does not exist', function (done) {
Feature.search('git yolo', function (docs) {
assert.equal(0, docs.length);
done();
});
});
});
});
| var assert = require('assert');
var seeds = require('../seeds');
var Feature = require('../feature');
describe('Feature', function () {
before(function (done) {
seeds(done);
});
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document');
});
describe('.search()', function () {
it('performs an empty search, returning all commands', function (done) {
Feature.search('', function (docs) {
assert.equal(7, docs.length);
done();
});
});
it('performs a case-insensitive search for a command', function (done) {
Feature.search('git ADD', function (docs) {
assert.equal(1, docs.length)
done();
});
});
it('performs a search for a command that does not exist', function (done) {
Feature.search('git yolo', function (docs) {
assert.equal(0, docs.length);
done();
});
});
});
});
| Use the database seeds from the Feature spec | Use the database seeds from the Feature spec
| JavaScript | mit | nickmccurdy/rose,nicolasmccurdy/rose,nicolasmccurdy/rose,nickmccurdy/rose | ---
+++
@@ -1,7 +1,12 @@
var assert = require('assert');
+var seeds = require('../seeds');
var Feature = require('../feature');
describe('Feature', function () {
+ before(function (done) {
+ seeds(done);
+ });
+
describe('schema', function () {
it('successfully creates a valid document');
it('fails at creating an invalid document'); |
d70cfc735c3fdaf9c65c6bd6fa27f9ec6f9ea2de | test/package.js | test/package.js | import fs from 'fs';
import test from 'ava';
import pify from 'pify';
import index from '../';
test('Every rule is defined in index file', async t => {
const files = await pify(fs.readdir, Promise)('../rules/');
const rules = files.filter(file => file.indexOf('.js') === file.length - 3);
rules.forEach(file => {
const name = file.slice(0, -3);
t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`);
t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`);
});
t.is(Object.keys(index.rules).length, rules.length,
'There are more exported rules than rule files.');
});
| import fs from 'fs';
import test from 'ava';
import pify from 'pify';
import index from '../';
test('every rule should defined in the index file and recommended settings', async t => {
const files = await pify(fs.readdir, Promise)('../rules/');
const rules = files.filter(file => file.indexOf('.js') === file.length - 3);
rules.forEach(file => {
const name = file.slice(0, -3);
t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`);
t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`);
});
t.is(Object.keys(index.rules).length, rules.length,
'There are more exported rules than rule files.');
});
test('no-var should be turned on in the recommended settings', async t => {
t.true(index.configs.recommended.rules['no-var'] === 'error');
});
| Add test to make sure `no-var` is in the recommended config | Add test to make sure `no-var` is in the recommended config
| JavaScript | mit | eslint-plugin-cleanjs/eslint-plugin-cleanjs,jfmengels/eslint-plugin-fp | ---
+++
@@ -3,7 +3,7 @@
import pify from 'pify';
import index from '../';
-test('Every rule is defined in index file', async t => {
+test('every rule should defined in the index file and recommended settings', async t => {
const files = await pify(fs.readdir, Promise)('../rules/');
const rules = files.filter(file => file.indexOf('.js') === file.length - 3);
@@ -16,3 +16,7 @@
t.is(Object.keys(index.rules).length, rules.length,
'There are more exported rules than rule files.');
});
+
+test('no-var should be turned on in the recommended settings', async t => {
+ t.true(index.configs.recommended.rules['no-var'] === 'error');
+}); |
4af27a810903abd4ec127f9b0799f9dc02674a91 | source/demo/demo.js | source/demo/demo.js | import React from 'react'
import { render } from 'react-dom'
import FlexTableExample from '../FlexTable/FlexTable.example'
import VirtualScrollExample from '../VirtualScroll/VirtualScroll.example'
require('./demo.less')
render((
<div className='demo__row'>
<VirtualScrollExample/>
<FlexTableExample/>
</div>
),
document.getElementById('root')
)
| import React from 'react'
import { render } from 'react-dom'
import FlexTableExample from '../FlexTable/FlexTable.example'
import VirtualScrollExample from '../VirtualScroll/VirtualScroll.example'
import './demo.less'
render((
<div className='demo__row'>
<VirtualScrollExample/>
<FlexTableExample/>
</div>
),
document.getElementById('root')
)
| Use ES6 style modules for consistency | Use ES6 style modules for consistency
| JavaScript | mit | bvaughn/react-virtualized,nicholasrq/react-virtualized,cesarandreu/react-virtualized,edulan/react-virtualized,cesarandreu/react-virtualized,nicholasrq/react-virtualized,edulan/react-virtualized,bvaughn/react-virtualized | ---
+++
@@ -2,8 +2,7 @@
import { render } from 'react-dom'
import FlexTableExample from '../FlexTable/FlexTable.example'
import VirtualScrollExample from '../VirtualScroll/VirtualScroll.example'
-
-require('./demo.less')
+import './demo.less'
render((
<div className='demo__row'> |
1012fb705859f61eb097f34a258050b837a593df | core/cb.project/parse/index.js | core/cb.project/parse/index.js | var path = require("path");
module.exports = {
id: "parse",
name: "Parse",
sample: path.resolve(__dirname, "sample"),
detector: path.resolve(__dirname, "detector.sh"),
runner: [
{
id: "run",
script: path.resolve(__dirname, "run.sh")
}
]
}; | var path = require("path");
module.exports = {
id: "parse",
name: "Parse",
otherIds: ["mobile"],
sample: path.resolve(__dirname, "sample"),
detector: path.resolve(__dirname, "detector.sh"),
runner: [
{
id: "run",
script: path.resolve(__dirname, "run.sh")
}
]
}; | Add id of mobile stack to parse sample | Add id of mobile stack to parse sample
| JavaScript | apache-2.0 | kustomzone/codebox,CodeboxIDE/codebox,rodrigues-daniel/codebox,smallbal/codebox,ronoaldo/codebox,Ckai1991/codebox,lcamilo15/codebox,LogeshEswar/codebox,quietdog/codebox,Ckai1991/codebox,blubrackets/codebox,rajthilakmca/codebox,blubrackets/codebox,ronoaldo/codebox,nobutakaoshiro/codebox,smallbal/codebox,listepo/codebox,listepo/codebox,code-box/codebox,lcamilo15/codebox,ahmadassaf/Codebox,kustomzone/codebox,fly19890211/codebox,fly19890211/codebox,indykish/codebox,quietdog/codebox,indykish/codebox,etopian/codebox,CodeboxIDE/codebox,rodrigues-daniel/codebox,code-box/codebox,ahmadassaf/Codebox,nobutakaoshiro/codebox,etopian/codebox,LogeshEswar/codebox,rajthilakmca/codebox | ---
+++
@@ -3,6 +3,7 @@
module.exports = {
id: "parse",
name: "Parse",
+ otherIds: ["mobile"],
sample: path.resolve(__dirname, "sample"),
detector: path.resolve(__dirname, "detector.sh"), |
c8fa6d7743e990f9b943ec045cada74403944d72 | lib/webhook.js | lib/webhook.js | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const request = require('request')
const colors = require('colors/safe')
const logger = require('../lib/logger')
const utils = require('../lib/utils')
const os = require('os')
const config = require('config')
exports.notify = (challenge) => {
request.post(process.env.SOLUTIONS_WEBHOOK, {
json: {
solution:
{
issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`,
challenge: challenge.key,
evidence: null,
issuedOn: new Date().toISOString()
}
}
}, (error, res) => {
if (error) {
console.error(error)
return
}
logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`)
})
}
| /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const request = require('request')
const colors = require('colors/safe')
const logger = require('../lib/logger')
const utils = require('../lib/utils')
const os = require('os')
exports.notify = (challenge) => {
request.post(process.env.SOLUTIONS_WEBHOOK, {
json: {
solution:
{
issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`,
challenge: challenge.key,
evidence: null,
issuedOn: new Date().toISOString()
}
}
}, (error, res) => {
if (error) {
console.error(error)
return
}
logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`)
})
}
| Remove unused config module import | Remove unused config module import
| JavaScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -8,7 +8,6 @@
const logger = require('../lib/logger')
const utils = require('../lib/utils')
const os = require('os')
-const config = require('config')
exports.notify = (challenge) => {
request.post(process.env.SOLUTIONS_WEBHOOK, { |
f182bb037d49003a42cc8fefa10d849b1145b15a | src/app/components/msp/application/personal-info/i18n/data/en/index.js | src/app/components/msp/application/personal-info/i18n/data/en/index.js | module.exports = {
pageTitle: 'Tell us a bit about who is applying for health care coverage',
addSpouseButton: 'Add Spouse/Common-Law Partner',
addChildUnder19Button: 'Add Child (0-18)',
addChild19To24Button: 'Add Child (19-24)',
continueButton: 'Continue'
} | module.exports = {
pageTitle: 'Tell us a bit about who is applying for health care coverage',
addSpouseButton: 'Add Spouse/Common-Law Partner',
addChildUnder19Button: 'Add Child (0-18)',
addChild19To24Button: 'Add Child (19-24) who is a full-time student',
continueButton: 'Continue'
}
| Clarify student status of older children | Clarify student status of older children
Re: MoH legal feedback | JavaScript | apache-2.0 | bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP | ---
+++
@@ -2,6 +2,6 @@
pageTitle: 'Tell us a bit about who is applying for health care coverage',
addSpouseButton: 'Add Spouse/Common-Law Partner',
addChildUnder19Button: 'Add Child (0-18)',
- addChild19To24Button: 'Add Child (19-24)',
+ addChild19To24Button: 'Add Child (19-24) who is a full-time student',
continueButton: 'Continue'
} |
62513397441fd0af5614a18e4cb6037479b744f2 | models/User.js | models/User.js | 'use strict';
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// export a mongoose model
var userSchema = new Schema({
userName : String,
passwordDigest : String
});
userSchema.virtual('password').set(function(password) {
var self = this;
var saltPromise = new Promise(function saltExec(res, rej) {
bcrypt.genSalt(16, function(err, salt) {
if(err) {
rej(err);
return;
}
res(salt);
});
});
var returnedPromise = saltPromise.then(function(salt) {
return new Promise(function hashExec(res, rej) {
bcrypt.hash(password, salt, function(err, digest) {
if(err) {
rej(err);
return;
}
res(digest);
});
});
}).then(function(digest) {
self.passwordDigest = digest;
});
return returnedPromise;
});
module.exports = userSchema;
| 'use strict';
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// export a mongoose model
var userSchema = new Schema({
userName : String,
passwordDigest : String
});
userSchema.methods.setPassword = function(password) {
var self = this;
var saltPromise = new Promise(function saltExec(res, rej) {
bcrypt.genSalt(16, function(err, salt) {
if(err) {
rej(err);
return;
}
res(salt);
});
});
var returnedPromise = saltPromise.then(function(salt) {
return new Promise(function hashExec(res, rej) {
bcrypt.hash(password, salt, function(err, digest) {
if(err) {
rej(err);
return;
}
res(digest);
});
});
}).then(function(digest) {
self.passwordDigest = digest;
return self.save();
});
return returnedPromise;
};
module.exports = userSchema;
| Change virtual prop to an instance method | Change virtual prop to an instance method
| JavaScript | mit | dhuddell/teachers-lounge-back-end | ---
+++
@@ -10,7 +10,7 @@
passwordDigest : String
});
-userSchema.virtual('password').set(function(password) {
+userSchema.methods.setPassword = function(password) {
var self = this;
var saltPromise = new Promise(function saltExec(res, rej) {
@@ -37,9 +37,10 @@
});
}).then(function(digest) {
self.passwordDigest = digest;
+ return self.save();
});
return returnedPromise;
-});
+};
module.exports = userSchema; |
1810afeeeb0f678d6968f8849a1932a547e966eb | test/test_ss.js | test/test_ss.js | /*global seqJS:true */
(function() {
/*
======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/
Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfequalions)
stop(increment)
start(decrement)
Test equalions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
throws(block, [expected], [message])
*/
module('seqJS.ss');
test('Test ss', function(){
equal(seqJS.ss.predict('GGGAAATCC'), '.(((..)))', 'secondary structure incorrect');
});
}());
| /*global seqJS:true */
(function() {
/*
======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/
Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfequalions)
stop(increment)
start(decrement)
Test equalions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
throws(block, [expected], [message])
*/
module('seqJS.ss');
test('Test ss', function(){
var s = new seqJS.Seq('GGGAAATCC', 'DNA');
equal(seqJS.ss.predict(s), '.(((..)))', 'secondary structure incorrect');
});
}());
| Test passes a seqJS.Seq, not String | Test passes a seqJS.Seq, not String
| JavaScript | mit | haydnKing/seqJS,haydnKing/seqJS | ---
+++
@@ -25,7 +25,8 @@
module('seqJS.ss');
test('Test ss', function(){
- equal(seqJS.ss.predict('GGGAAATCC'), '.(((..)))', 'secondary structure incorrect');
+ var s = new seqJS.Seq('GGGAAATCC', 'DNA');
+ equal(seqJS.ss.predict(s), '.(((..)))', 'secondary structure incorrect');
});
}()); |
86b1e11b31c57bf51dd779c8ffc7e8ad5803de9a | client/src/views/member.js | client/src/views/member.js | _kiwi.view.Member = Backbone.View.extend({
tagName: "li",
initialize: function (options) {
this.model.bind('change', this.render, this);
this.render();
},
render: function () {
var $this = this.$el,
prefix_css_class = (this.model.get('modes') || []).join(' '),
max_prefix = (this.model.get('modes') || [])[0];
$this.attr('class', 'mode ' + prefix_css_class + ' member member-' + max_prefix);
$this.html('<a class="nick"><span class="prefix prefix-' + max_prefix + '">' + this.model.get("prefix") + '</span>' + this.model.get("nick") + '</a>');
return this;
}
}); | _kiwi.view.Member = Backbone.View.extend({
tagName: "li",
initialize: function (options) {
this.model.bind('change', this.render, this);
this.render();
},
render: function () {
var $this = this.$el,
max_prefix = (this.model.get('modes') || [])[0];
$this.attr('class', 'member member-' + max_prefix);
$this.html('<a class="nick"><span class="prefix prefix-' + max_prefix + '">' + this.model.get("prefix") + '</span>' + this.model.get("nick") + '</a>');
return this;
}
}); | Remove old CSS classes (breaks stuff) | Remove old CSS classes (breaks stuff)
| JavaScript | agpl-3.0 | MDTech-us-MAN/KiwiIRC,MDTech-us-MAN/KiwiIRC,MDTech-us-MAN/KiwiIRC | ---
+++
@@ -6,10 +6,9 @@
},
render: function () {
var $this = this.$el,
- prefix_css_class = (this.model.get('modes') || []).join(' '),
max_prefix = (this.model.get('modes') || [])[0];
- $this.attr('class', 'mode ' + prefix_css_class + ' member member-' + max_prefix);
+ $this.attr('class', 'member member-' + max_prefix);
$this.html('<a class="nick"><span class="prefix prefix-' + max_prefix + '">' + this.model.get("prefix") + '</span>' + this.model.get("nick") + '</a>');
return this; |
53cf51e0c7671750985ee2b88ddf51905897d9c7 | node/server.js | node/server.js | var mongo = require('mongodb').MongoClient;
mongo.connect('mongodb://localhost:27017/akkavsnode', function(err, db) {
var http = require('http');
http.createServer(function (req, res) {
if (req.url === '/api/user') {
var i = Math.ceil(Math.random() * 10000);
db.collection('users').findOne({ name: 'user-' + i }, function (err, user) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(user));
});
} else {
res.writeHead(404, {'Content-Type': 'application/json'});
res.end();
}
}).listen(8081, '0.0.0.0');
});
| var mongo = require('mongodb').MongoClient;
mongo.connect('mongodb://localhost:27017/akkavsnode', function(err, db) {
var http = require('http');
http.createServer(function (req, res) {
if (req.url === '/api/user') {
var i = Math.ceil(Math.random() * 10000);
db.collection('users').findOne({ name: 'user-' + i }, function (err, user) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(user, true, 2));
});
} else {
res.writeHead(404, {'Content-Type': 'application/json'});
res.end();
}
}).listen(8081, '0.0.0.0');
});
| Make node also response with pretty JSON | Make node also response with pretty JSON
| JavaScript | mit | choffmeister/akka-vs-node,choffmeister/akka-vs-node | ---
+++
@@ -8,7 +8,7 @@
var i = Math.ceil(Math.random() * 10000);
db.collection('users').findOne({ name: 'user-' + i }, function (err, user) {
res.writeHead(200, {'Content-Type': 'application/json'});
- res.end(JSON.stringify(user));
+ res.end(JSON.stringify(user, true, 2));
});
} else {
res.writeHead(404, {'Content-Type': 'application/json'}); |
e01ceaf62d2ee3dbdb7cce9988a55742c348bd31 | client/karma.conf.js | client/karma.conf.js | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
var configuration = {
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
customLaunchers: {
ChromeHeadless: {
base: 'Chrome',
flags: [
'--headless',
'--disable-gpu',
'--remote-debugging-port=9222',
'--no-sandbox'
]
}
},
browsers: ['Chrome'],
singleRun: false
};
if (process.env.TRAVIS) {
configuration.autoWatch = false;
configuration.browsers = ['ChromeHeadless'];
}
config.set(configuration);
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
var configuration = {
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
customLaunchers: {
ChromeHeadless: {
base: 'Chrome',
flags: [
'--headless',
'--disable-gpu',
'--remote-debugging-port=9222',
'--no-sandbox'
]
}
},
browsers: ['Chrome'],
singleRun: false
};
if (process.env.TRAVIS) {
configuration.singleRun = true;
configuration.browsers = ['ChromeHeadless'];
}
config.set(configuration);
};
| Set up Travis test environment (cont. 3) | Set up Travis test environment (cont. 3)
Autowatch didn't help. Seeing if `singleRun = true` causes
it to stop after running the tests.
| JavaScript | mit | UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo | ---
+++
@@ -42,7 +42,7 @@
singleRun: false
};
if (process.env.TRAVIS) {
- configuration.autoWatch = false;
+ configuration.singleRun = true;
configuration.browsers = ['ChromeHeadless'];
}
|
b5efd8cd8eeab78442e210ab7d51d4a310a1678d | src/jquery.clone_form_template.js | src/jquery.clone_form_template.js | (function ($) {
$.fn.clone_form_template = function (options) {
if (!options) {
options = {};
}
return $(this).map(function () {
return update($(this).clone(), options)[0];
});
};
// updates a template clone according to conventions
function update($clone, options) {
var index = new Date().getTime();
$clone.find('label,input,textarea,select').each(function (i, obj) {
update_attrs($(obj), index, options);
});
return $clone.removeClass('template').show();
}
function update_attrs($element, identifier, options) {
if ($element.attr('id')) {
$element.attr('id',
$element.attr('id').replace(/_-?\d+_/, '_' + identifier + '_')
);
}
if ($element.attr('for')) {
$element.attr('for',
$element.attr('for').replace(/_-?\d+_/, '_' + identifier + '_')
);
}
if ($element.attr('name')) {
if (options.copy_values) {
$element.val($('[name="' + $element.attr('name') + '"]').val());
}
$element.attr('name',
$element.attr('name').replace(/\[-?\d+\]/, '[' + identifier + ']')
);
}
}
}(jQuery));
| (function ($) {
var DEFAULT_PATTERN = '-1';
$.fn.clone_form_template = function (options, cb) {
if (!options) {
options = {};
}
return $(this).map(function () {
return update($(this).clone(), options, cb)[0];
});
};
// updates a template clone according to conventions
function update($clone, options, cb) {
var index = new Date().getTime();
$clone.find('label,input,textarea,select').each(function (i, obj) {
update_attrs($(obj), index, options, cb);
});
return $clone.removeClass('template').show();
}
function update_attrs($element, identifier, options, cb) {
var pattern = options.pattern || DEFAULT_PATTERN,
underscore_pattern = new RegExp('_' + pattern + '_'),
bracket_pattern = new RegExp('\\[' + pattern + '\\]');
if ($element.attr('id')) {
$element.attr('id',
$element.attr('id').replace(underscore_pattern, '_' + identifier + '_')
);
}
if ($element.attr('for')) {
$element.attr('for',
$element.attr('for').replace(underscore_pattern, '_' + identifier + '_')
);
}
if ($element.attr('name')) {
if (options.copy_values) {
$element.val($('[name="' + $element.attr('name') + '"]').val());
}
$element.attr('name',
$element.attr('name').replace(bracket_pattern, '[' + identifier + ']')
);
}
if (typeof cb === 'function') {
cb.apply($element, $element);
}
}
}(jQuery));
| Allow customizable pattern and callback | Allow customizable pattern and callback
| JavaScript | mit | samuelcole/jquery-livesearch,samuelcole/jquery-livesearch | ---
+++
@@ -1,33 +1,39 @@
(function ($) {
- $.fn.clone_form_template = function (options) {
+ var DEFAULT_PATTERN = '-1';
+
+ $.fn.clone_form_template = function (options, cb) {
if (!options) {
options = {};
}
return $(this).map(function () {
- return update($(this).clone(), options)[0];
+ return update($(this).clone(), options, cb)[0];
});
};
// updates a template clone according to conventions
- function update($clone, options) {
+ function update($clone, options, cb) {
var index = new Date().getTime();
$clone.find('label,input,textarea,select').each(function (i, obj) {
- update_attrs($(obj), index, options);
+ update_attrs($(obj), index, options, cb);
});
return $clone.removeClass('template').show();
}
- function update_attrs($element, identifier, options) {
+ function update_attrs($element, identifier, options, cb) {
+ var pattern = options.pattern || DEFAULT_PATTERN,
+ underscore_pattern = new RegExp('_' + pattern + '_'),
+ bracket_pattern = new RegExp('\\[' + pattern + '\\]');
+
if ($element.attr('id')) {
$element.attr('id',
- $element.attr('id').replace(/_-?\d+_/, '_' + identifier + '_')
+ $element.attr('id').replace(underscore_pattern, '_' + identifier + '_')
);
}
if ($element.attr('for')) {
$element.attr('for',
- $element.attr('for').replace(/_-?\d+_/, '_' + identifier + '_')
+ $element.attr('for').replace(underscore_pattern, '_' + identifier + '_')
);
}
if ($element.attr('name')) {
@@ -35,8 +41,11 @@
$element.val($('[name="' + $element.attr('name') + '"]').val());
}
$element.attr('name',
- $element.attr('name').replace(/\[-?\d+\]/, '[' + identifier + ']')
+ $element.attr('name').replace(bracket_pattern, '[' + identifier + ']')
);
+ }
+ if (typeof cb === 'function') {
+ cb.apply($element, $element);
}
}
}(jQuery)); |
a8f98d8df125bbfaade27e606d5e75f72b158228 | commons/CitationModal.js | commons/CitationModal.js | import { $$ } from '../dom'
import { Form, FormRow, Modal, MultiSelect } from '../ui'
export default function CitationModal (props) {
const { document, node, mode } = props
const confirmLabel = mode === 'edit' ? 'Update' : 'Create'
const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation'
const value = mode === 'edit' ? node.target : []
const root = document.root
const referencesList = root.resolve('references')
const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, size: 'large' }
return $$(Modal, modalProps,
$$(Form, {},
$$(FormRow, {},
$$(MultiSelect, {
options: referencesList.map(ref => {
return { value: ref.id, label: ref.content }
}),
value,
label: 'Add Reference',
placeholder: 'Please select one or more references'
}).ref('references')
)
)
)
}
| import { $$, Component } from '../dom'
import { Form, FormRow, Modal, MultiSelect } from '../ui'
export default class CitationModal extends Component {
getInitialState () {
const { mode, node } = this.props
const value = mode === 'edit' ? node.target : []
return { value }
}
render () {
const { document, mode } = this.props
const { value } = this.state
const confirmLabel = mode === 'edit' ? 'Update' : 'Create'
const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation'
const root = document.root
const referencesList = root.resolve('references')
const disableConfirm = value.length === 0
const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' }
return $$(Modal, modalProps,
$$(Form, {},
$$(FormRow, {},
$$(MultiSelect, {
options: referencesList.map(ref => {
return { value: ref.id, label: ref.content }
}),
value,
label: 'Add Reference',
placeholder: 'Please select one or more references',
onchange: this._updateReferencess
}).ref('references')
)
)
)
}
_updateReferencess () {
const value = this.refs.references.val()
this.extendState({ value })
}
}
| Disable modal confirmation without values. | Disable modal confirmation without values.
| JavaScript | mit | michael/substance-1,substance/substance,substance/substance,michael/substance-1 | ---
+++
@@ -1,28 +1,43 @@
-import { $$ } from '../dom'
+import { $$, Component } from '../dom'
import { Form, FormRow, Modal, MultiSelect } from '../ui'
-export default function CitationModal (props) {
- const { document, node, mode } = props
- const confirmLabel = mode === 'edit' ? 'Update' : 'Create'
- const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation'
- const value = mode === 'edit' ? node.target : []
+export default class CitationModal extends Component {
+ getInitialState () {
+ const { mode, node } = this.props
+ const value = mode === 'edit' ? node.target : []
+ return { value }
+ }
- const root = document.root
- const referencesList = root.resolve('references')
+ render () {
+ const { document, mode } = this.props
+ const { value } = this.state
+ const confirmLabel = mode === 'edit' ? 'Update' : 'Create'
+ const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation'
- const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, size: 'large' }
- return $$(Modal, modalProps,
- $$(Form, {},
- $$(FormRow, {},
- $$(MultiSelect, {
- options: referencesList.map(ref => {
- return { value: ref.id, label: ref.content }
- }),
- value,
- label: 'Add Reference',
- placeholder: 'Please select one or more references'
- }).ref('references')
+ const root = document.root
+ const referencesList = root.resolve('references')
+ const disableConfirm = value.length === 0
+
+ const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' }
+ return $$(Modal, modalProps,
+ $$(Form, {},
+ $$(FormRow, {},
+ $$(MultiSelect, {
+ options: referencesList.map(ref => {
+ return { value: ref.id, label: ref.content }
+ }),
+ value,
+ label: 'Add Reference',
+ placeholder: 'Please select one or more references',
+ onchange: this._updateReferencess
+ }).ref('references')
+ )
)
)
- )
+ }
+
+ _updateReferencess () {
+ const value = this.refs.references.val()
+ this.extendState({ value })
+ }
} |
76842f742608a29d5bd1460aeb983265e807d197 | src/build/supportedFolders.js | src/build/supportedFolders.js | /* eslint-disable max-len */
exports.extensions = {
supported: [
{ icon: 'dist', extensions: ['dist', 'out'] },
{ icon: 'git', extensions: ['git', 'github'] },
{ icon: 'node', extensions: ['node_modules'] },
{ icon: 'meteor', extensions: ['meteor'] },
{ icon: 'src', extensions: ['src'] },
{ icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] },
{ icon: 'typings', extensions: ['typings'] },
{ icon: 'vscode', extensions: ['vscode'] }
],
parse: function () {
var s = this.replace(/\./g, '_');
if ((/^\d/).test(s)) return 'n' + s;
return s;
}
};
| /* eslint-disable max-len */
exports.extensions = {
supported: [
{ icon: 'dist', extensions: ['dist', 'out'] },
{ icon: 'git', extensions: ['git', 'github'] },
{ icon: 'node', extensions: ['node_modules'] },
{ icon: 'meteor', extensions: ['meteor'] },
{ icon: 'src', extensions: ['src', 'source'] },
{ icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] },
{ icon: 'typings', extensions: ['typings'] },
{ icon: 'vscode', extensions: ['vscode'] }
],
parse: function () {
var s = this.replace(/\./g, '_');
if ((/^\d/).test(s)) return 'n' + s;
return s;
}
};
| Support "source" as a src folder | Support "source" as a src folder | JavaScript | mit | robertohuertasm/vscode-icons,jens1o/vscode-icons,JimiC/vscode-icons,vscode-icons/vscode-icons,vscode-icons/vscode-icons,JimiC/vscode-icons,olzaragoza/vscode-icons | ---
+++
@@ -5,7 +5,7 @@
{ icon: 'git', extensions: ['git', 'github'] },
{ icon: 'node', extensions: ['node_modules'] },
{ icon: 'meteor', extensions: ['meteor'] },
- { icon: 'src', extensions: ['src'] },
+ { icon: 'src', extensions: ['src', 'source'] },
{ icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] },
{ icon: 'typings', extensions: ['typings'] },
{ icon: 'vscode', extensions: ['vscode'] } |
2717beda255cb4f474ef141397cadf1592d2246a | blueprints/flexberry-model-init/files/__root__/models/__name__.js | blueprints/flexberry-model-init/files/__root__/models/__name__.js | import { Model as <%= className %>Mixin<%if (projections) {%>, defineProjections<%}%> } from '../mixins/regenerated/models/<%= name %>';
import <%if(parentModelName) {%><%= parentClassName %>Model from './<%= parentModelName %>';<%}else{%>__Projection from 'ember-flexberry-data';<%}%>
let Model = <%if(parentModelName) {%><%= parentClassName %>Model.extend<%}else{%>__Projection.Model.extend<%}%>(<%= className %>Mixin, {
});
<%if(projections) {%>defineProjections(Model);<%}%>
export default Model;
| import { Model as <%= className %>Mixin<%if (projections) {%>, defineProjections<%}%> } from '../mixins/regenerated/models/<%= name %>';
import <%if(parentModelName) {%><%= parentClassName %>Model from './<%= parentModelName %>';<%}else{%>{ __Projection } from 'ember-flexberry-data';<%}%>
let Model = <%if(parentModelName) {%><%= parentClassName %>Model.extend<%}else{%>__Projection.Model.extend<%}%>(<%= className %>Mixin, {
});
<%if(projections) {%>defineProjections(Model);<%}%>
export default Model;
| Rollback blueprints for base model | Rollback blueprints for base model
tfs #116013
| JavaScript | mit | Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry | ---
+++
@@ -1,5 +1,5 @@
import { Model as <%= className %>Mixin<%if (projections) {%>, defineProjections<%}%> } from '../mixins/regenerated/models/<%= name %>';
-import <%if(parentModelName) {%><%= parentClassName %>Model from './<%= parentModelName %>';<%}else{%>__Projection from 'ember-flexberry-data';<%}%>
+import <%if(parentModelName) {%><%= parentClassName %>Model from './<%= parentModelName %>';<%}else{%>{ __Projection } from 'ember-flexberry-data';<%}%>
let Model = <%if(parentModelName) {%><%= parentClassName %>Model.extend<%}else{%>__Projection.Model.extend<%}%>(<%= className %>Mixin, {
}); |
d9f7edd951b7c69db4623ade722f71b751a65143 | connectors/v2/pitchfork.js | connectors/v2/pitchfork.js | 'use strict';
/* global Connector */
Connector.artistSelector = '.track-title .artist';
Connector.trackSelector = '.track-title .title';
Connector.isPlaying = function () {
return $('.playback-button > div').attr('title') == 'Pause Track';
};
(function() {
var playerObserver = new MutationObserver(function() {
var playerElement = document.querySelector('#player-container');
if (playerElement !== null) {
playerObserver.disconnect();
var actualObserver = new MutationObserver(Connector.onStateChanged);
actualObserver.observe(playerElement, {
childList: true,
subtree: true,
attributes: true,
characterData: true
});
}
});
playerObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
characterData: false,
});
})();
| 'use strict';
/* global Connector */
Connector.artistSelector = '.track-title .artist';
Connector.trackSelector = '.track-title .title';
Connector.isPlaying = function () {
return $('.playback-button > div').attr('title') === 'Pause Track';
};
(function() {
var playerObserver = new MutationObserver(function() {
var playerElement = document.querySelector('#player-container');
if (playerElement !== null) {
playerObserver.disconnect();
var actualObserver = new MutationObserver(Connector.onStateChanged);
actualObserver.observe(playerElement, {
childList: true,
subtree: true,
attributes: true,
characterData: true
});
}
});
playerObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
characterData: false,
});
})();
| Use strict equality in Pitchfork connector | Use strict equality in Pitchfork connector
| JavaScript | mit | alexesprit/web-scrobbler,inverse/web-scrobbler,usdivad/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,ex47/web-scrobbler,galeksandrp/web-scrobbler,ex47/web-scrobbler,carpet-berlin/web-scrobbler,alexesprit/web-scrobbler,Paszt/web-scrobbler,carpet-berlin/web-scrobbler,inverse/web-scrobbler,david-sabata/web-scrobbler,galeksandrp/web-scrobbler,usdivad/web-scrobbler,david-sabata/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,Paszt/web-scrobbler | ---
+++
@@ -7,7 +7,7 @@
Connector.trackSelector = '.track-title .title';
Connector.isPlaying = function () {
- return $('.playback-button > div').attr('title') == 'Pause Track';
+ return $('.playback-button > div').attr('title') === 'Pause Track';
};
(function() { |
f2fd025793df508f7980c5c4f21bfc5745cf9d08 | src/fs/__tests__/test-base.js | src/fs/__tests__/test-base.js | jest.autoMockOff();
jest.unmock('../base.js');
const base = require('../base.js');
describe('Base', () => {
it('does a lot of cool stuff', () => {
});
});
| jest.autoMockOff();
jest.unmock('../base.js');
const base = require('../base.js');
jest.unmock('node-fetch');
const fetch = require('node-fetch');
global.Response = fetch.Response;
describe('Base', () => {
it('constructs correctly', () => {
let path = Object.create(null);
let name = Object.create(null);
let options = Object.create(null);
expect(path).not.toBe(name);
expect(path).not.toBe(options);
expect(name).not.toBe(options);
let bfs = new base.Base(name, path, options);
expect(bfs).toBeDefined();
expect(bfs.path).toBe(path);
expect(bfs.name).toBe(name);
expect(bfs.options).toBe(options);
});
it('does not stat paths', () => {
let path = Object.create(null);
let name = Object.create(null);
let options = Object.create(null);
let bfs = new base.Base(name, path, options);
let ret = Object.create(null);
spyOn(Promise, 'resolve').and.returnValue(ret);
let val = bfs.stat('');
expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405}));
expect(val).toBe(ret);
});
it('does not read paths', () => {
let path = Object.create(null);
let name = Object.create(null);
let options = Object.create(null);
let bfs = new base.Base(name, path, options);
let ret = Object.create(null);
spyOn(Promise, 'resolve').and.returnValue(ret);
let val = bfs.read('');
expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405}));
expect(val).toBe(ret);
});
it('does not write paths', () => {
let path = Object.create(null);
let name = Object.create(null);
let options = Object.create(null);
let bfs = new base.Base(name, path, options);
let ret = Object.create(null);
spyOn(Promise, 'resolve').and.returnValue(ret);
let val = bfs.write('', '');
expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405}));
expect(val).toBe(ret);
});
});
| Add tests for Base fs | Add tests for Base fs
| JavaScript | mit | LivelyKernel/lively4-core,LivelyKernel/lively4-core | ---
+++
@@ -3,7 +3,73 @@
const base = require('../base.js');
+jest.unmock('node-fetch');
+const fetch = require('node-fetch');
+global.Response = fetch.Response;
+
describe('Base', () => {
- it('does a lot of cool stuff', () => {
+
+ it('constructs correctly', () => {
+ let path = Object.create(null);
+ let name = Object.create(null);
+ let options = Object.create(null);
+
+ expect(path).not.toBe(name);
+ expect(path).not.toBe(options);
+ expect(name).not.toBe(options);
+
+ let bfs = new base.Base(name, path, options);
+ expect(bfs).toBeDefined();
+ expect(bfs.path).toBe(path);
+ expect(bfs.name).toBe(name);
+ expect(bfs.options).toBe(options);
+ });
+
+ it('does not stat paths', () => {
+ let path = Object.create(null);
+ let name = Object.create(null);
+ let options = Object.create(null);
+ let bfs = new base.Base(name, path, options);
+
+ let ret = Object.create(null);
+
+ spyOn(Promise, 'resolve').and.returnValue(ret);
+
+ let val = bfs.stat('');
+
+ expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405}));
+ expect(val).toBe(ret);
+ });
+
+ it('does not read paths', () => {
+ let path = Object.create(null);
+ let name = Object.create(null);
+ let options = Object.create(null);
+ let bfs = new base.Base(name, path, options);
+
+ let ret = Object.create(null);
+
+ spyOn(Promise, 'resolve').and.returnValue(ret);
+
+ let val = bfs.read('');
+
+ expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405}));
+ expect(val).toBe(ret);
+ });
+
+ it('does not write paths', () => {
+ let path = Object.create(null);
+ let name = Object.create(null);
+ let options = Object.create(null);
+ let bfs = new base.Base(name, path, options);
+
+ let ret = Object.create(null);
+
+ spyOn(Promise, 'resolve').and.returnValue(ret);
+
+ let val = bfs.write('', '');
+
+ expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405}));
+ expect(val).toBe(ret);
});
}); |
af85171d2c488bbaa851815ffd8a8aafb0e52f8e | .eleventy.js | .eleventy.js | const CleanCSS = require("clean-css");
module.exports = function (eleventyConfig) {
eleventyConfig.addPassthroughCopy("src/img");
eleventyConfig.addPassthroughCopy("src/webfonts");
eleventyConfig.addFilter("cssmin", function (code) {
return new CleanCSS({}).minify(code).styles;
});
eleventyConfig.addPairedShortcode("cssPostProcess", function (code) {
return `${code}`;
});
return {
dir: {
data: "data",
input: "src",
output: "dist",
},
};
};
| const CleanCSS = require("clean-css");
module.exports = function (eleventyConfig) {
eleventyConfig.addPassthroughCopy("src/img");
eleventyConfig.addPassthroughCopy("src/webfonts");
eleventyConfig.addFilter("cssmin", function (code) {
return new CleanCSS({}).minify(code).styles;
});
eleventyConfig.addPairedShortcode("cssPostProcess", function (code) {
return code;
});
return {
dir: {
data: "data",
input: "src",
output: "dist",
},
};
};
| Remove template literal as it isn't necessary | Remove template literal as it isn't necessary
| JavaScript | mit | stevecochrane/stevecochrane.com,stevecochrane/stevecochrane.com | ---
+++
@@ -9,7 +9,7 @@
});
eleventyConfig.addPairedShortcode("cssPostProcess", function (code) {
- return `${code}`;
+ return code;
});
return { |
8831374a514314c64f52822c1be393f396bc415f | .eslintrc.js | .eslintrc.js | module.exports = {
root: true,
parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
project: ["./tsconfig.json"]
},
plugins: ["@typescript-eslint"],
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"prettier",
"prettier/@typescript-eslint"
],
rules: {
"@typescript-eslint/no-non-null-assertion": 0
}
};
| module.exports = {
root: true,
parser: "@typescript-eslint/parser",
parserOptions: {
tsconfigRootDir: __dirname,
project: ["./tsconfig.json"]
},
plugins: ["@typescript-eslint"],
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"prettier",
"prettier/@typescript-eslint"
],
rules: {
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/no-unsafe-assignment": 0,
"@typescript-eslint/no-unsafe-call": 0,
"@typescript-eslint/no-unsafe-member-access": 0,
"@typescript-eslint/no-unsafe-return": 0,
}
};
| Disable eslint rules disallowing `any` to be used | Disable eslint rules disallowing `any` to be used
| JavaScript | lgpl-2.1 | SoftCreatR/WCF,WoltLab/WCF,SoftCreatR/WCF,Cyperghost/WCF,Cyperghost/WCF,SoftCreatR/WCF,Cyperghost/WCF,SoftCreatR/WCF,WoltLab/WCF,Cyperghost/WCF,WoltLab/WCF,WoltLab/WCF,Cyperghost/WCF | ---
+++
@@ -14,6 +14,11 @@
"prettier/@typescript-eslint"
],
rules: {
- "@typescript-eslint/no-non-null-assertion": 0
+ "@typescript-eslint/no-explicit-any": 0,
+ "@typescript-eslint/no-non-null-assertion": 0,
+ "@typescript-eslint/no-unsafe-assignment": 0,
+ "@typescript-eslint/no-unsafe-call": 0,
+ "@typescript-eslint/no-unsafe-member-access": 0,
+ "@typescript-eslint/no-unsafe-return": 0,
}
}; |
f1992db7234513a86b07e53b30a160342e0bb9fc | docs/_book/gitbook/gitbook-plugin-sharing/buttons.js | docs/_book/gitbook/gitbook-plugin-sharing/buttons.js | require(['gitbook', 'jquery'], function(gitbook, $) {
var SITES = {
'facebook': {
'label': 'Facebook',
'icon': 'fa fa-facebook',
'onClick': function(e) {
e.preventDefault();
window.open('http://www.facebook.com/sharer/sharer.php?s=100&p[url]='+encodeURIComponent(location.href));
}
},
'twitter': {
'label': 'Twitter',
'icon': 'fa fa-twitter',
'onClick': function(e) {
e.preventDefault();
window.open('http://twitter.com/home?status='+encodeURIComponent(document.title+' '+location.href));
}
},
'google': {
'label': 'Google+',
'icon': 'fa fa-google-plus',
'onClick': function(e) {
e.preventDefault();
window.open('https://plus.google.com/share?url='+encodeURIComponent(location.href));
}
},
'weibo': {
'label': 'Weibo',
'icon': 'fa fa-weibo',
'onClick': function(e) {
e.preventDefault();
window.open('http://service.weibo.com/share/share.php?content=utf-8&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title));
}
},
'instapaper': {
'label': 'Instapaper',
'icon': 'fa fa-instapaper',
'onClick': function(e) {
e.preventDefault();
window.open('http://www.instapaper.com/text?u='+encodeURIComponent(location.href));
}
},
'vk': {
'label': 'VK',
'icon': 'fa fa-vk',
'onClick': function(e) {
e.preventDefault();
window.open('http://vkontakte.ru/share.php?url='+encodeURIComponent(location.href));
}
}
};
gitbook.events.bind('start', function(e, config) {
var opts = config.sharing;
// Create dropdown menu
var menu = $.map(opts.all, function(id) {
var site = SITES[id];
return {
text: site.label,
onClick: site.onClick
};
});
// Create main button with dropdown
if (menu.length > 0) {
gitbook.toolbar.createButton({
icon: 'fa fa-share-alt',
label: 'Share',
position: 'right',
dropdown: [menu]
});
}
// Direct actions to share
$.each(SITES, function(sideId, site) {
if (!opts[sideId]) return;
gitbook.toolbar.createButton({
icon: site.icon,
label: site.text,
position: 'right',
onClick: site.onClick
});
});
});
});
| Update HTML files with the updates. | Update HTML files with the updates.
| JavaScript | mit | HIT2GAP-EU-PROJECT/HIT2GAPOnt | ---
+++
@@ -0,0 +1,90 @@
+require(['gitbook', 'jquery'], function(gitbook, $) {
+ var SITES = {
+ 'facebook': {
+ 'label': 'Facebook',
+ 'icon': 'fa fa-facebook',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open('http://www.facebook.com/sharer/sharer.php?s=100&p[url]='+encodeURIComponent(location.href));
+ }
+ },
+ 'twitter': {
+ 'label': 'Twitter',
+ 'icon': 'fa fa-twitter',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open('http://twitter.com/home?status='+encodeURIComponent(document.title+' '+location.href));
+ }
+ },
+ 'google': {
+ 'label': 'Google+',
+ 'icon': 'fa fa-google-plus',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open('https://plus.google.com/share?url='+encodeURIComponent(location.href));
+ }
+ },
+ 'weibo': {
+ 'label': 'Weibo',
+ 'icon': 'fa fa-weibo',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open('http://service.weibo.com/share/share.php?content=utf-8&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title));
+ }
+ },
+ 'instapaper': {
+ 'label': 'Instapaper',
+ 'icon': 'fa fa-instapaper',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open('http://www.instapaper.com/text?u='+encodeURIComponent(location.href));
+ }
+ },
+ 'vk': {
+ 'label': 'VK',
+ 'icon': 'fa fa-vk',
+ 'onClick': function(e) {
+ e.preventDefault();
+ window.open('http://vkontakte.ru/share.php?url='+encodeURIComponent(location.href));
+ }
+ }
+ };
+
+
+
+ gitbook.events.bind('start', function(e, config) {
+ var opts = config.sharing;
+
+ // Create dropdown menu
+ var menu = $.map(opts.all, function(id) {
+ var site = SITES[id];
+
+ return {
+ text: site.label,
+ onClick: site.onClick
+ };
+ });
+
+ // Create main button with dropdown
+ if (menu.length > 0) {
+ gitbook.toolbar.createButton({
+ icon: 'fa fa-share-alt',
+ label: 'Share',
+ position: 'right',
+ dropdown: [menu]
+ });
+ }
+
+ // Direct actions to share
+ $.each(SITES, function(sideId, site) {
+ if (!opts[sideId]) return;
+
+ gitbook.toolbar.createButton({
+ icon: site.icon,
+ label: site.text,
+ position: 'right',
+ onClick: site.onClick
+ });
+ });
+ });
+}); | |
c09772fb4d1523f2171ddfe0858605e79d4516a3 | src/js/controller/Contacts.js | src/js/controller/Contacts.js | var ContactModel = require('../model/Contacts');
var ContactView = require('../view/Contact');
var AddContactForm = require('../view/AddContactForm');
/**
* Controller Object to dispatch actions to view/Contact and model/Contacts.
* @constructor
*/
var ContactsController = function() {
this.init();
};
ContactsController.remove = function(id) {
console.log('Controller Remove');
//ContactModel.remove(id);
//ContactView.remove(id);
};
ContactsController.prototype = {
init: function() {
console.log('new controller');
},
setup: function() {
var addContact = new AddContactForm();
},
/**
* @description Fetches all existing contacts from LocalStorage.
*/
fetchAll: function() {
var contacts = [];
var total = localStorage.length;
for (i = 0; i < total; i++) {
var contact = {};
var key = localStorage.key(i);
if (key !== 'debug') {
contact.key = key;
contact.value = JSON.parse(localStorage.getItem((i + 1).toString()));
contacts.push(contact);
}
}
return contacts;
},
/**
* @description Adds all existing contacts to table. Intended for use
* on startup.
*/
renderAll: function() {
var contacts = this.fetchAll();
contacts.forEach(function(currentValue) {
var contact = new ContactView(currentValue.key, currentValue.value);
});
}
};
module.exports = ContactsController;
| var ContactModel = require('../model/Contacts');
var ContactView = require('../view/Contact');
var AddContactForm = require('../view/AddContactForm');
/**
* Controller Object to dispatch actions to view/Contact and model/Contacts.
* @constructor
*/
var ContactsController = function() {
};
ContactsController.remove = function(id) {
console.log('Controller Remove');
//ContactModel.remove(id);
//ContactView.remove(id);
};
ContactsController.render = function(id, contact) {
var contactView = new ContactView(id, contact);
};
ContactsController.prototype = {
setup: function() {
var addContact = new AddContactForm();
},
/**
* @description Fetches all existing contacts from LocalStorage.
*/
fetchAll: function() {
var contacts = [];
var total = localStorage.length;
for (i = 0; i < total; i++) {
var contact = {};
var key = localStorage.key(i);
if (key !== 'debug') {
contact.key = key;
contact.value = JSON.parse(localStorage.getItem((i + 1).toString()));
contacts.push(contact);
}
}
return contacts;
},
/**
* @description Adds all existing contacts to table. Intended for use
* on startup.
*/
renderAll: function() {
var contacts = this.fetchAll();
contacts.forEach(function(currentValue) {
var contact = new ContactView(currentValue.key, currentValue.value);
});
}
};
module.exports = ContactsController;
| Remove unused init() add render() method | Remove unused init() add render() method
| JavaScript | isc | bitfyre/contacts | ---
+++
@@ -7,7 +7,6 @@
* @constructor
*/
var ContactsController = function() {
- this.init();
};
ContactsController.remove = function(id) {
@@ -16,12 +15,11 @@
//ContactView.remove(id);
};
+ContactsController.render = function(id, contact) {
+ var contactView = new ContactView(id, contact);
+};
ContactsController.prototype = {
- init: function() {
- console.log('new controller');
- },
-
setup: function() {
var addContact = new AddContactForm();
}, |
be8ed28b34bcd1b9a7666b9dc9ec0da64ff28a30 | js/locales/bootstrap-datepicker.mk.js | js/locales/bootstrap-datepicker.mk.js | /**
* Macedonian translation for bootstrap-datepicker
* Marko Aleksic <psybaron@gmail.com>
*/
;(function($){
$.fn.datepicker.dates['mk'] = {
days: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела"],
daysShort: ["Нед", "Пон", "Вто", "Сре", "Чет", "Пет", "Саб", "Нед"],
daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"],
months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"],
monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"],
today: "Денес"
};
}(jQuery));
| /**
* Macedonian translation for bootstrap-datepicker
* Marko Aleksic <psybaron@gmail.com>
*/
;(function($){
$.fn.datepicker.dates['mk'] = {
days: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела"],
daysShort: ["Нед", "Пон", "Вто", "Сре", "Чет", "Пет", "Саб", "Нед"],
daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"],
months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"],
monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"],
today: "Денес",
format: "dd.MM.yyyy"
};
}(jQuery));
| Add Macedonian date format (with leading zero). | Add Macedonian date format (with leading zero). | JavaScript | apache-2.0 | bitzesty/bootstrap-datepicker,HNygard/bootstrap-datepicker,gn0st1k4m/bootstrap-datepicker,aldano/bootstrap-datepicker,zhaoyan158567/bootstrap-datepicker,acrobat/bootstrap-datepicker,TheJumpCloud/bootstrap-datepicker,cherylyan/bootstrap-datepicker,huang-x-h/bootstrap-datepicker,cherylyan/bootstrap-datepicker,defrian8/bootstrap-datepicker,mreiden/bootstrap-datepicker,xutongtong/bootstrap-datepicker,daniyel/bootstrap-datepicker,Tekzenit/bootstrap-datepicker,vegardok/bootstrap-datepicker,parkeugene/bootstrap-datepicker,Youraiseme/bootstrap-datepicker,Azaret/bootstrap-datepicker,Doublemedia/bootstrap-datepicker,saurabh27125/bootstrap-datepicker,tcrossland/bootstrap-datepicker,hemp/bootstrap-datepicker,Mteuahasan/bootstrap-datepicker,NFC-DITO/bootstrap-datepicker,riyan8250/bootstrap-datepicker,CherryDT/bootstrap-datepicker,josegomezr/bootstrap-datepicker,otnavle/bootstrap-datepicker,jesperronn/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,otnavle/bootstrap-datepicker,Invulner/bootstrap-datepicker,Mteuahasan/bootstrap-datepicker,inukshuk/bootstrap-datepicker,mfunkie/bootstrap-datepicker,dckesler/bootstrap-datepicker,1000hz/bootstrap-datepicker,hebbet/bootstrap-datepicker,osama9/bootstrap-datepicker,keiwerkgvr/bootstrap-datepicker,MartijnDwars/bootstrap-datepicker,kiwiupover/bootstrap-datepicker,jhalak/bootstrap-datepicker,HuBandiT/bootstrap-datepicker,1000hz/bootstrap-datepicker,dswitzer/bootstrap-datepicker,inspur-tobacco/bootstrap-datepicker,stenmuchow/bootstrap-datepicker,christophercaburog/bootstrap-datepicker,CheapSk8/bootstrap-datepicker,chengky/bootstrap-datepicker,bitzesty/bootstrap-datepicker,pacozaa/bootstrap-datepicker,abnovak/bootstrap-sass-datepicker,uxsolutions/bootstrap-datepicker,steffendietz/bootstrap-datepicker,Doublemedia/bootstrap-datepicker,mfunkie/bootstrap-datepicker,nerionavea/bootstrap-datepicker,ashleymcdonald/bootstrap-datepicker,NFC-DITO/bootstrap-datepicker,oller/foundation-datepicker-sass,huang-x-h/bootstrap-datepicker,wetet2/bootstrap-datepicker,jhalak/bootstrap-datepicker,rocLv/bootstrap-datepicker,acrobat/bootstrap-datepicker,champierre/bootstrap-datepicker,inway/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,janusnic/bootstrap-datepicker,parkeugene/bootstrap-datepicker,CheapSk8/bootstrap-datepicker,inway/bootstrap-datepicker,yangyichen/bootstrap-datepicker,rocLv/bootstrap-datepicker,ashleymcdonald/bootstrap-datepicker,dswitzer/bootstrap-datepicker,WeiLend/bootstrap-datepicker,Invulner/bootstrap-datepicker,HNygard/bootstrap-datepicker,inspur-tobacco/bootstrap-datepicker,tcrossland/bootstrap-datepicker,kevintvh/bootstrap-datepicker,TheJumpCloud/bootstrap-datepicker,hemp/bootstrap-datepicker,abnovak/bootstrap-sass-datepicker,martinRjs/bootstrap-datepicker,mfunkie/bootstrap-datepicker,inukshuk/bootstrap-datepicker,menatoric59/bootstrap-datepicker,darluc/bootstrap-datepicker,janusnic/bootstrap-datepicker,Youraiseme/bootstrap-datepicker,oller/foundation-datepicker-sass,thetimbanks/bootstrap-datepicker,cbryer/bootstrap-datepicker,champierre/bootstrap-datepicker,thetimbanks/bootstrap-datepicker,christophercaburog/bootstrap-datepicker,Sprinkle7/bootstrap-datepicker,josegomezr/bootstrap-datepicker,nilbus/bootstrap-datepicker,chengky/bootstrap-datepicker,gn0st1k4m/bootstrap-datepicker,uxsolutions/bootstrap-datepicker,Azaret/bootstrap-datepicker,osama9/bootstrap-datepicker,rstone770/bootstrap-datepicker,defrian8/bootstrap-datepicker,nilbus/bootstrap-datepicker,stenmuchow/bootstrap-datepicker,wulinmengzhu/bootstrap-datepicker,Sprinkle7/bootstrap-datepicker,daniyel/bootstrap-datepicker,joubertredrat/bootstrap-datepicker,xutongtong/bootstrap-datepicker,wetet2/bootstrap-datepicker,hebbet/bootstrap-datepicker,riyan8250/bootstrap-datepicker,zhaoyan158567/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,mreiden/bootstrap-datepicker,i-am-kenny/bootstrap-datepicker,wulinmengzhu/bootstrap-datepicker,Tekzenit/bootstrap-datepicker,oller/foundation-datepicker-sass,vgrish/bootstrap-datepicker,kevintvh/bootstrap-datepicker,joubertredrat/bootstrap-datepicker,vegardok/bootstrap-datepicker,aldano/bootstrap-datepicker,cbryer/bootstrap-datepicker,SimpleUpdates/bootstrap-datepicker,ibcooley/bootstrap-datepicker,steffendietz/bootstrap-datepicker,WeiLend/bootstrap-datepicker,eternicode/bootstrap-datepicker,ibcooley/bootstrap-datepicker,vsn4ik/bootstrap-datepicker,darluc/bootstrap-datepicker,pacozaa/bootstrap-datepicker,eternicode/bootstrap-datepicker,CherryDT/bootstrap-datepicker,wearespindle/datepicker-js,josegomezr/bootstrap-datepicker,dckesler/bootstrap-datepicker,menatoric59/bootstrap-datepicker,i-am-kenny/bootstrap-datepicker,yangyichen/bootstrap-datepicker,rstone770/bootstrap-datepicker,kiwiupover/bootstrap-datepicker,jesperronn/bootstrap-datepicker,nerionavea/bootstrap-datepicker,martinRjs/bootstrap-datepicker,SimpleUpdates/bootstrap-datepicker,vgrish/bootstrap-datepicker,vsn4ik/bootstrap-datepicker,1000hz/bootstrap-datepicker,saurabh27125/bootstrap-datepicker,keiwerkgvr/bootstrap-datepicker,HuBandiT/bootstrap-datepicker,MartijnDwars/bootstrap-datepicker | ---
+++
@@ -9,6 +9,7 @@
daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"],
months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"],
monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"],
- today: "Денес"
+ today: "Денес",
+ format: "dd.MM.yyyy"
};
}(jQuery)); |
6c504b7a54518d498d256caa3801df0df49a4a87 | server/tests/seed/auth_seed.js | server/tests/seed/auth_seed.js | // auth_seed.js
const User = require('./../../database/models').User;
module.exports = {
emptyDB(done) {
User.destroy({ truncate: true })
.then((rows) => {
console.log(rows);
return done();
})
.catch(err => done(err));
},
setData(fullname, username, email, mobile, password, confirmPassword) {
return {
fullname,
username,
email,
mobile,
password,
confirm_password: confirmPassword
};
},
addUserToDb(done) {
User.create({
fullname: 'jimoh hadi',
username: 'ovenje',
email: 'ovenje@yahoo.com',
mobile: '8163041269',
password: '11223344' })
.then((user) => {
done();
})
.catch((err) => {
done(err);
});
}
};
| // auth_seed.js
const User = require('./../../database/models').User;
module.exports = {
emptyDB(done) {
User.destroy({ truncate: true })
.then(() => done())
.catch(err => done(err));
},
setData(fullname, username, email, mobile, password, confirmPassword) {
return {
fullname,
username,
email,
mobile,
password,
confirm_password: confirmPassword
};
},
addUserToDb(done) {
User.create({
fullname: 'jimoh hadi',
username: 'ovenje',
email: 'ovenje@yahoo.com',
mobile: '8163041269',
password: '11223344' })
.then((user) => {
done();
})
.catch((err) => {
done(err);
});
}
};
| Remove unnecessary argument from seeder file | Remove unnecessary argument from seeder file
| JavaScript | mit | johadi10/PostIt,johadi10/PostIt | ---
+++
@@ -4,10 +4,7 @@
module.exports = {
emptyDB(done) {
User.destroy({ truncate: true })
- .then((rows) => {
- console.log(rows);
- return done();
- })
+ .then(() => done())
.catch(err => done(err));
},
setData(fullname, username, email, mobile, password, confirmPassword) { |
890bdbb025bcf7ec6121c58d6b6882cdbd6dd6ee | src/handlers.js | src/handlers.js | const pkg = require('../package.json');
const Identify = require('./identifyPeople.js');
function handlers() {
function index(req, reply) {
reply.view('index', {
users: [
'hello'
]
});
}
function version(req, reply) {
reply({version: pkg.version}).code(200);
}
function identifyPeople(req, reply) {
if (!req.payload || !req.payload.url) {
reply("Expected 'url' parameter").code(400);
return;
}
let imageUrl = req.payload.url;
Identify.findFace(imageUrl)
.then((names) => {
reply({"Identification results: " : JSON.stringify(names)}).code(200);
})
.catch((err) => {
console.log(JSON.stringify(err, null, 2));
reply({"Identification results" : []}).code(500);
});
}
return {
index,
version,
identifyPeople
};
}
module.exports = handlers;
| const pkg = require('../package.json');
const Identify = require('./identifyPeople.js');
function handlers() {
function index(req, reply) {
reply.view('index', {
users: [
'hello'
]
});
}
function version(req, reply) {
reply({version: pkg.version}).code(200);
}
function identifyPeople(req, reply) {
if (!req.payload || !req.payload.url) {
reply("Expected 'url' parameter").code(400);
return;
}
let imageUrl = req.payload.url;
Identify.findFace(imageUrl)
.then((names) => {
reply({"identities" : names}).code(200);
})
.catch((err) => {
console.log(JSON.stringify(err, null, 2));
reply({"identities" : []}).code(500);
});
}
return {
index,
version,
identifyPeople
};
}
module.exports = handlers;
| Return names as json array | Return names as json array
Now the identify results are returned as json.
| JavaScript | mit | alsalo1/walls-have-ears,alsalo1/walls-have-ears | ---
+++
@@ -22,11 +22,11 @@
let imageUrl = req.payload.url;
Identify.findFace(imageUrl)
.then((names) => {
- reply({"Identification results: " : JSON.stringify(names)}).code(200);
+ reply({"identities" : names}).code(200);
})
.catch((err) => {
console.log(JSON.stringify(err, null, 2));
- reply({"Identification results" : []}).code(500);
+ reply({"identities" : []}).code(500);
});
}
|
76b57bed027fb3cb16bd24f9bb6fef4011fd9ebd | src/routes/product-group.routes.js | src/routes/product-group.routes.js | import express from 'express';
import * as controller from '../controllers/product-group.controller';
import { createAuthMiddleware } from '../auth';
import { MODERATOR } from '../auth/constants';
const router = express.Router();
router.use(createAuthMiddleware(MODERATOR));
router.get('/', controller.list);
router.post('/', controller.create);
router.put('/:id', controller.update);
router.delete('/:id', controller.destroy);
export default router;
| import express from 'express';
import * as controller from '../controllers/product-group.controller';
import { createAuthMiddleware } from '../auth';
import { MODERATOR, TOKEN } from '../auth/constants';
const router = express.Router();
router.get('/', createAuthMiddleware(TOKEN), controller.list);
router.post('/', createAuthMiddleware(MODERATOR), controller.create);
router.put('/:id', createAuthMiddleware(MODERATOR), controller.update);
router.delete('/:id', createAuthMiddleware(MODERATOR), controller.destroy);
export default router;
| Change product group api authentication | Change product group api authentication
| JavaScript | mit | abakusbackup/abacash-api,abakusbackup/abacash-api | ---
+++
@@ -1,14 +1,13 @@
import express from 'express';
import * as controller from '../controllers/product-group.controller';
import { createAuthMiddleware } from '../auth';
-import { MODERATOR } from '../auth/constants';
+import { MODERATOR, TOKEN } from '../auth/constants';
const router = express.Router();
-router.use(createAuthMiddleware(MODERATOR));
-router.get('/', controller.list);
-router.post('/', controller.create);
-router.put('/:id', controller.update);
-router.delete('/:id', controller.destroy);
+router.get('/', createAuthMiddleware(TOKEN), controller.list);
+router.post('/', createAuthMiddleware(MODERATOR), controller.create);
+router.put('/:id', createAuthMiddleware(MODERATOR), controller.update);
+router.delete('/:id', createAuthMiddleware(MODERATOR), controller.destroy);
export default router; |
da2614a96f6e78133ae6e7441557a470dc27fde0 | src/components/Editor/index.js | src/components/Editor/index.js | import './index.css';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Viewer from '../Viewer';
class Editor extends Component {
render() {
const { presId } = this.props;
return (
<div className="editor-wrapper">
<Viewer presId={presId}/>
</div>
)
}
}
Editor.propTypes = {
presId: PropTypes.string.isRequired
};
export default Editor; | import './index.css';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Viewer from '../Viewer';
import presentations from '../../data/presentations';
import PreviewPanel from './components/PreviewPanel';
class Editor extends Component {
constructor(props) {
super(props);
this.state = {
presentation: null,
loading: true,
activeSlideIndex: 0,
error: null,
};
}
componentDidMount() {
const { presId } = this.props;
presentations.get(presId)
.then(presentation => {
this.setState({
presentation,
loading: false,
activeSlideIndex: 0,
})
})
.catch(err => {
this.setState({
error: err,
loading: false,
})
})
}
render() {
const { presId } = this.props;
const { loading, error, presentation } = this.state;
return (
<div className="editor-wrapper">
<Viewer presId={presId}/>
</div>
)
}
}
Editor.propTypes = {
presId: PropTypes.string.isRequired
};
export default Editor; | Add logic to getting the presentation to the editor | Add logic to getting the presentation to the editor
| JavaScript | mit | jacobwindsor/pathway-presenter,jacobwindsor/pathway-presenter | ---
+++
@@ -2,10 +2,42 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Viewer from '../Viewer';
+import presentations from '../../data/presentations';
+import PreviewPanel from './components/PreviewPanel';
class Editor extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ presentation: null,
+ loading: true,
+ activeSlideIndex: 0,
+ error: null,
+ };
+ }
+
+ componentDidMount() {
+ const { presId } = this.props;
+ presentations.get(presId)
+ .then(presentation => {
+ this.setState({
+ presentation,
+ loading: false,
+ activeSlideIndex: 0,
+ })
+ })
+ .catch(err => {
+ this.setState({
+ error: err,
+ loading: false,
+ })
+ })
+ }
+
render() {
const { presId } = this.props;
+ const { loading, error, presentation } = this.state;
+
return (
<div className="editor-wrapper">
<Viewer presId={presId}/> |
c13e26870627291988d144ff9d77f1b1b05ec264 | src/config/app-config.index.js | src/config/app-config.index.js | import Config from './app-config.module';
import './base.config';
/**
* Optionally include a file
*/
((_require) => {
if (_require.keys().find(x => x.indexOf('local.config.js') > -1)) {
_require('./local.config.js');
}
})(require.context('./', false, /local\.config\.js$/));
export default Config;
| import Config from './app-config.module';
import './base.config';
/**
* Optionally include a file
*/
((_require) => {
if (_require.keys().indexOf('./local.config.js') > -1) {
_require('./local.config.js');
}
})(require.context('./', false, /local\.config\.js$/));
export default Config;
| Simplify check for local.config.js file | Simplify check for local.config.js file
| JavaScript | mit | tijhaart/webpack-foundation,tijhaart/webpack-foundation | ---
+++
@@ -5,7 +5,7 @@
* Optionally include a file
*/
((_require) => {
- if (_require.keys().find(x => x.indexOf('local.config.js') > -1)) {
+ if (_require.keys().indexOf('./local.config.js') > -1) {
_require('./local.config.js');
}
})(require.context('./', false, /local\.config\.js$/)); |
f1cd45736986db9362750ac3061ee4113c8ba3f2 | test/unit/vdom/incremental-dom.js | test/unit/vdom/incremental-dom.js | import * as IncrementalDOM from 'incremental-dom';
import { vdom } from '../../../src/index';
describe('IncrementalDOM', function () {
it('should export all the same members as the incremental-dom we consume', function () {
// Ensure we export the element functions.
expect(vdom.attr).to.be.a('function');
expect(vdom.elementClose).to.be.a('function');
expect(vdom.elementOpenEnd).to.be.a('function');
expect(vdom.elementOpenStart).to.be.a('function');
expect(vdom.elementVoid).to.be.a('function');
expect(vdom.text).to.be.a('function');
// Ensure they're not the same as Incremental DOM's implementation.
expect(vdom.attr).not.to.equal(IncrementalDOM.attr);
expect(vdom.elementClose).not.to.equal(IncrementalDOM.elementClose);
expect(vdom.elementOpenEnd).not.to.equal(IncrementalDOM.elementOpenEnd);
expect(vdom.elementOpenStart).not.to.equal(IncrementalDOM.elementOpenStart);
expect(vdom.elementVoid).not.to.equal(IncrementalDOM.elementVoid);
expect(vdom.text).not.to.equal(IncrementalDOM.text);
});
});
| import * as IncrementalDOM from 'incremental-dom';
import { vdom } from '../../../src/index';
function testBasicApi (name) {
it('should be a function', () => expect(vdom[name]).to.be.a('function'));
it('should not be the same one as in Incremental DOM', () => expect(vdom[name]).not.to.equal(IncrementalDOM[name]));
}
describe('IncrementalDOM', function () {
describe('attr', () => {
testBasicApi('attr');
});
describe('elementClose', () => {
testBasicApi('elementClose');
});
describe('elementOpen', () => {
testBasicApi('elementOpen');
});
describe('elementOpenEnd', () => {
testBasicApi('elementOpenEnd');
});
describe('elementOpenStart', () => {
testBasicApi('elementOpenStart');
});
describe('elementVoid', () => {
testBasicApi('elementVoid');
});
describe('text', () => {
testBasicApi('text');
});
});
| Add basic tests for all api points that override Incremental DOM. | test(vdom): Add basic tests for all api points that override Incremental DOM.
| JavaScript | mit | chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs | ---
+++
@@ -1,22 +1,37 @@
import * as IncrementalDOM from 'incremental-dom';
import { vdom } from '../../../src/index';
+function testBasicApi (name) {
+ it('should be a function', () => expect(vdom[name]).to.be.a('function'));
+ it('should not be the same one as in Incremental DOM', () => expect(vdom[name]).not.to.equal(IncrementalDOM[name]));
+}
+
describe('IncrementalDOM', function () {
- it('should export all the same members as the incremental-dom we consume', function () {
- // Ensure we export the element functions.
- expect(vdom.attr).to.be.a('function');
- expect(vdom.elementClose).to.be.a('function');
- expect(vdom.elementOpenEnd).to.be.a('function');
- expect(vdom.elementOpenStart).to.be.a('function');
- expect(vdom.elementVoid).to.be.a('function');
- expect(vdom.text).to.be.a('function');
+ describe('attr', () => {
+ testBasicApi('attr');
+ });
- // Ensure they're not the same as Incremental DOM's implementation.
- expect(vdom.attr).not.to.equal(IncrementalDOM.attr);
- expect(vdom.elementClose).not.to.equal(IncrementalDOM.elementClose);
- expect(vdom.elementOpenEnd).not.to.equal(IncrementalDOM.elementOpenEnd);
- expect(vdom.elementOpenStart).not.to.equal(IncrementalDOM.elementOpenStart);
- expect(vdom.elementVoid).not.to.equal(IncrementalDOM.elementVoid);
- expect(vdom.text).not.to.equal(IncrementalDOM.text);
+ describe('elementClose', () => {
+ testBasicApi('elementClose');
+ });
+
+ describe('elementOpen', () => {
+ testBasicApi('elementOpen');
+ });
+
+ describe('elementOpenEnd', () => {
+ testBasicApi('elementOpenEnd');
+ });
+
+ describe('elementOpenStart', () => {
+ testBasicApi('elementOpenStart');
+ });
+
+ describe('elementVoid', () => {
+ testBasicApi('elementVoid');
+ });
+
+ describe('text', () => {
+ testBasicApi('text');
});
}); |
933d14bd3764d570477af932604f8243ff406aa3 | index-browser.js | index-browser.js | const assert = require('assert')
function createGL (opts) {
assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object')
if (!opts) opts = {}
let canvas = opts.canvas
if (!canvas) {
canvas = document.createElement('canvas')
canvas.width = opts.width || window.innerWidth
canvas.height = opts.height || window.innerHeight
if (!opts.width && !opts.height) {
// fullscreen
document.body.style.margin = '0px'
}
if (document.body) {
document.body.appendChild(canvas)
} else {
// just in case our script is included above <body>
document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(canvas)
})
}
}
const gl = canvas.getContext('webgl', opts)
return gl
}
module.exports = createGL
| const assert = require('assert')
function createGL (opts) {
assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object')
if (!opts) opts = {}
let canvas = opts.canvas
if (!canvas) {
canvas = document.createElement('canvas')
canvas.width = opts.width || window.innerWidth
canvas.height = opts.height || window.innerHeight
const appendCanvas = () => {
if (!opts.width && !opts.height) {
// fullscreen
document.body.style.margin = '0px'
}
document.body.appendChild(canvas)
}
if (document.body) {
appendCanvas()
} else {
// just in case our script is included above <body>
document.addEventListener('DOMContentLoaded', appendCanvas)
}
}
const gl = canvas.getContext('webgl', opts)
return gl
}
module.exports = createGL
| Change the way properties on document.body are set while loading canvas. | Change the way properties on document.body are set while loading canvas.
In the default setup, when no width and height options are passed and
`createGL` is called on page load, it throws an error if the script is
included before the body element, since `document.body.style` is null.
The function already accounts for this fact while appending the canvas
to the page, but not while setting `style.margin = '0px'`. This PR
changes that.
| JavaScript | mit | pex-gl/pex-gl | ---
+++
@@ -10,17 +10,20 @@
canvas = document.createElement('canvas')
canvas.width = opts.width || window.innerWidth
canvas.height = opts.height || window.innerHeight
- if (!opts.width && !opts.height) {
- // fullscreen
- document.body.style.margin = '0px'
+
+ const appendCanvas = () => {
+ if (!opts.width && !opts.height) {
+ // fullscreen
+ document.body.style.margin = '0px'
+ }
+ document.body.appendChild(canvas)
}
+
if (document.body) {
- document.body.appendChild(canvas)
+ appendCanvas()
} else {
// just in case our script is included above <body>
- document.addEventListener('DOMContentLoaded', () => {
- document.body.appendChild(canvas)
- })
+ document.addEventListener('DOMContentLoaded', appendCanvas)
}
}
const gl = canvas.getContext('webgl', opts) |
cc43c6c9e5be06cd77a26015e519f72ae4f3e918 | test/replace.js | test/replace.js | var replace = require( "../src/str-replace" );
module.exports = {
replaceAll: function( assert ) {
var actual = replace.all( "/" ).from( "/home/dir" ).to( "\\" );
var expected = "\\home\\dir";
assert.strictEqual( actual, expected );
assert.done();
}
};
| var replace = require( "../src/str-replace" );
module.exports = {
replace_all: function( assert ) {
var actual = replace.all( "/" ).from( "/home/dir" ).to( "\\" );
var expected = "\\home\\dir";
assert.strictEqual( actual, expected );
assert.done();
}
};
| Use dash pattern in tests for better console visibility | Use dash pattern in tests for better console visibility
| JavaScript | mit | FagnerMartinsBrack/str-replace | ---
+++
@@ -1,7 +1,7 @@
var replace = require( "../src/str-replace" );
module.exports = {
- replaceAll: function( assert ) {
+ replace_all: function( assert ) {
var actual = replace.all( "/" ).from( "/home/dir" ).to( "\\" );
var expected = "\\home\\dir";
assert.strictEqual( actual, expected ); |
16479fe5e89eb332f015eaba6344140142a5959f | lib/endpoint/UploadEndpoint.js | lib/endpoint/UploadEndpoint.js |
var loadTemplate = require('../loadTemplate')
var getRepository = require('./getRepository')
function UploadEndpoint(req, res, next) {
var repo = getRepository(req)
repo.post(req.body, 'application/rdf+xml', (err, callback) => {
if(err) {
return next(err)
}
res.status(200).send('ok')
})
}
module.exports = UploadEndpoint
|
var loadTemplate = require('../loadTemplate')
var getRepository = require('./getRepository')
function UploadEndpoint(req, res, next) {
var repo = getRepository(req)
repo.post(req.body, req.headers['content-type'], (err, callback) => {
if(err) {
return next(err)
}
res.status(200).send('ok')
})
}
module.exports = UploadEndpoint
| Use content-type header in upload endpoint | Use content-type header in upload endpoint
| JavaScript | bsd-2-clause | ICO2S/sbolstack-api,ICO2S/sbolstack-api,ICO2S/sbolstack-api | ---
+++
@@ -7,7 +7,7 @@
var repo = getRepository(req)
- repo.post(req.body, 'application/rdf+xml', (err, callback) => {
+ repo.post(req.body, req.headers['content-type'], (err, callback) => {
if(err) {
return next(err) |
d6761e50b6285b3ba0d7371a61be6712cdc6fac3 | src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Framework/Tabs.js | src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Framework/Tabs.js | export class Tabs {
initEventListeners () {
this.loadTab()
$('.nav-tabs a').on('click', $.proxy(this.changeTab, this))
}
changeTab (event) {
let $current = $(event.currentTarget)
/* if the browser supports history.pushState(), use it to update the URL
with the fragment identifier, without triggering a scroll/jump */
if (window.history && window.history.pushState) {
/* an empty state object for now — either we implement a proper
popstate handler ourselves, or wait for jQuery UI upstream */
window.history.pushState({}, document.title, $current.href)
} else {
let scrolled = $(window).scrollTop()
window.location.hash = '#' + $current.href.split('#')[1]
$(window).scrollTop(scrolled)
}
$current.tab('show')
}
loadTab () {
let url = document.location.toString()
if (url.match('#')) {
let anchor = '#' + url.split('#')[1]
if ($('.nav-tabs a[href=' + anchor + ']').length > 0) {
$('.nav-tabs a[href=' + anchor + ']').tab('show')
}
}
}
}
| export class Tabs {
initEventListeners () {
this.loadTab()
$('.nav-tabs a').on('click', $.proxy(this.changeTab, this))
}
changeTab (event) {
let $current = $(event.currentTarget)
/* if the browser supports history.pushState(), use it to update the URL
with the fragment identifier, without triggering a scroll/jump */
if (window.history && window.history.pushState) {
/* an empty state object for now — either we implement a proper
popstate handler ourselves, or wait for jQuery UI upstream */
window.history.pushState({}, document.title, $current.attr('href'))
} else {
let scrolled = $(window).scrollTop()
window.location.hash = '#' + $current.attr('href').split('#')[1]
$(window).scrollTop(scrolled)
}
$current.tab('show')
}
loadTab () {
let url = document.location.toString()
if (url.match('#')) {
let anchor = '#' + url.split('#')[1]
if ($('.nav-tabs a[href=' + anchor + ']').length > 0) {
$('.nav-tabs a[href=' + anchor + ']').tab('show')
}
}
}
}
| Fix url hash when changing tabs | Fix url hash when changing tabs
| JavaScript | mit | sumocoders/Framework,jonasdekeukelaere/Framework,sumocoders/Framework,jonasdekeukelaere/Framework,jonasdekeukelaere/Framework,sumocoders/Framework,sumocoders/Framework,jonasdekeukelaere/Framework | ---
+++
@@ -11,10 +11,10 @@
if (window.history && window.history.pushState) {
/* an empty state object for now — either we implement a proper
popstate handler ourselves, or wait for jQuery UI upstream */
- window.history.pushState({}, document.title, $current.href)
+ window.history.pushState({}, document.title, $current.attr('href'))
} else {
let scrolled = $(window).scrollTop()
- window.location.hash = '#' + $current.href.split('#')[1]
+ window.location.hash = '#' + $current.attr('href').split('#')[1]
$(window).scrollTop(scrolled)
}
$current.tab('show') |
6bce932ca8d3b10cfa00231f0719c92262282dc9 | Gruntfile.js | Gruntfile.js | 'use strict';
module.exports = function (grunt) {
// Show elapsed time at the end
require('time-grunt')(grunt);
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
gruntfile: {
src: ['Gruntfile.js']
},
js: {
src: ['*.js']
},
test: {
src: ['test/**/*.js']
}
},
mochacli: {
options: {
reporter: 'nyan',
bail: true
},
all: ['test/*.js']
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
js: {
files: '<%= jshint.js.src %>',
tasks: ['jshint:js', 'mochacli']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'mochacli']
}
}
});
grunt.registerTask('default', ['jshint', 'mochacli']);
};
| 'use strict';
module.exports = function (grunt) {
// Show elapsed time at the end
require('time-grunt')(grunt);
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish'),
ignores: 'browser.js'
},
gruntfile: {
src: ['Gruntfile.js']
},
js: {
src: ['*.js']
},
test: {
src: ['test/**/*.js']
}
},
mochacli: {
options: {
reporter: 'nyan',
bail: true
},
all: ['test/*.js']
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
js: {
files: '<%= jshint.js.src %>',
tasks: ['jshint:js', 'mochacli']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'mochacli']
}
}
});
grunt.registerTask('default', ['jshint', 'mochacli']);
};
| Make ignore browser.js from jshint | Make ignore browser.js from jshint
| JavaScript | mit | hakatashi/japanese.js,hakatashi/japanese.js | ---
+++
@@ -9,7 +9,8 @@
jshint: {
options: {
jshintrc: '.jshintrc',
- reporter: require('jshint-stylish')
+ reporter: require('jshint-stylish'),
+ ignores: 'browser.js'
},
gruntfile: {
src: ['Gruntfile.js'] |
1d16098e3bba07210d0e561124a67a0c1c2b139c | src/reducers/index.js | src/reducers/index.js | import { combineReducers } from 'redux'
import counter from './counter'
const reducer = combineReducers({
counter
})
export default reducer
| import { combineReducers } from 'redux'
import counter from './counter'
import todos from './todos'
const reducer = combineReducers({
counter,
todos
})
export default reducer
| Put the todos reducer into the root reducer | Put the todos reducer into the root reducer
| JavaScript | mit | RSS-Dev/live-html,epicsharp/react-boilerplate,epicsharp/react-boilerplate,RSS-Dev/live-html | ---
+++
@@ -1,9 +1,11 @@
import { combineReducers } from 'redux'
import counter from './counter'
+import todos from './todos'
const reducer = combineReducers({
- counter
+ counter,
+ todos
})
export default reducer |
abec1e3b7b21eb8a7fc4ca301050f5703c3b61d7 | src/DefaultSpecimens.js | src/DefaultSpecimens.js | import Audio from './specimens/Audio';
import Code from './specimens/Code';
import Color from './specimens/Color';
import Html from './specimens/Html';
import Hint from './specimens/Hint';
import Image from './specimens/Image';
import Type from './specimens/Type';
import Download from './specimens/Download';
import Video from './specimens/Video';
export default {
audio: Audio,
code: Code,
color: Color,
html: Html,
hint: Hint,
image: Image,
type: Type,
download: Download,
video: Video
};
| import Audio from './specimens/Audio';
import Code from './specimens/Code';
import Color from './specimens/Color';
import Html from './specimens/Html';
import Hint from './specimens/Hint';
import Image from './specimens/Image';
import Type from './specimens/Type';
import Download from './specimens/Download';
import Video from './specimens/Video';
export default {
audio: Audio,
code: Code,
// color: Color,
// html: Html,
hint: Hint,
// image: Image,
// type: Type,
// download: Download,
// video: Video
};
| Disable specimens which are not upgraded yet | Disable specimens which are not upgraded yet
| JavaScript | bsd-3-clause | interactivethings/catalog,interactivethings/catalog,interactivethings/catalog,interactivethings/catalog | ---
+++
@@ -11,11 +11,11 @@
export default {
audio: Audio,
code: Code,
- color: Color,
- html: Html,
+ // color: Color,
+ // html: Html,
hint: Hint,
- image: Image,
- type: Type,
- download: Download,
- video: Video
+ // image: Image,
+ // type: Type,
+ // download: Download,
+ // video: Video
}; |
59195df3b093746478e0077bddbc913ebb63cb45 | pre-build.js | pre-build.js | 'use strict';
var Mocha = require('mocha');
var colors = require('colors');
var build = require('./build.js');
var mocha = new Mocha({ui: 'bdd', reporter: 'list'});
mocha.addFile('test/test-optipng-path.js');
mocha.run(function (failures) {
if (failures > 0) {
build();
} else {
console.log('pre-build test passed successfully, skipping build'.green);
}
});
| 'use strict';
var Mocha = require('mocha');
var colors = require('colors');
var build = require('./build.js');
var mocha = new Mocha({ui: 'bdd', reporter: 'min'});
mocha.addFile('test/test-optipng-path.js');
mocha.run(function (failures) {
if (failures > 0) {
console.log('pre-build test failed, compiling from source...'.red);
build();
} else {
console.log('pre-build test passed successfully, skipping build...'.green);
}
});
| Improve message on prebuild test failure | Improve message on prebuild test failure
| JavaScript | mit | jmnarloch/optipng-bin,imagemin/optipng-bin,inversion/optipng-bin | ---
+++
@@ -1,16 +1,16 @@
'use strict';
-
var Mocha = require('mocha');
var colors = require('colors');
var build = require('./build.js');
-var mocha = new Mocha({ui: 'bdd', reporter: 'list'});
+var mocha = new Mocha({ui: 'bdd', reporter: 'min'});
mocha.addFile('test/test-optipng-path.js');
mocha.run(function (failures) {
if (failures > 0) {
+ console.log('pre-build test failed, compiling from source...'.red);
build();
} else {
- console.log('pre-build test passed successfully, skipping build'.green);
+ console.log('pre-build test passed successfully, skipping build...'.green);
}
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.