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 |
|---|---|---|---|---|---|---|---|---|---|---|
0f3a4183d62b62f288cc9614fe52bc03ba33d01b | test/directory.js | test/directory.js | /* global beforeEach, describe, it */
var watch = require('..');
var join = require('path').join;
var fs = require('fs');
var rimraf = require('rimraf');
require('should');
function fixtures(glob) {
return join(__dirname, 'fixtures', glob);
}
describe.skip('directories', function () {
beforeEach(function () {
rimraf.sync(fixtures('test'));
});
it('should directory on creation', function (done) {
var w = watch(fixtures('**'));
w.on('ready', function () {
fs.mkdirSync(fixtures('test'));
});
w.on('data', function () {
w.on('end', done);
w.close();
});
});
});
| /* global beforeEach, describe, it */
var watch = require('..');
var join = require('path').join;
var fs = require('fs');
var rimraf = require('rimraf');
require('should');
function fixtures(glob) {
return join(__dirname, 'fixtures', glob);
}
describe.skip('directories', function () {
beforeEach(function () {
rimraf.sync(fixtures('test'));
});
// This test is not responding on directories creation
it('should directory on creation', function (done) {
var w = watch(fixtures('**'));
w.on('ready', function () {
fs.mkdirSync(fixtures('test'));
});
w.on('data', function () {
w.on('end', done);
w.close();
});
});
});
| Add comment in directories test | Add comment in directories test
| JavaScript | mit | devm33/gulp-watch,UltCombo/gulp-watch,operatino/gulp-watch,moander/gulp-watch,floatdrop/gulp-watch | ---
+++
@@ -15,6 +15,7 @@
rimraf.sync(fixtures('test'));
});
+ // This test is not responding on directories creation
it('should directory on creation', function (done) {
var w = watch(fixtures('**'));
w.on('ready', function () { |
cd70ccc9aeb8cb3e26315cd627863ff67e5759f5 | rules/inject-local-id.js | rules/inject-local-id.js | /**
* Adds the ID of the user object stored on our database
* to the token returned from Auth0
*/
function (user, context, callback) {
var namespace = 'https://techbikers.com/';
context.idToken[namespace + 'user_id'] = user.app_metadata.id;
callback(null, user, context);
}
| /**
* Adds the ID of the user object stored on our database
* to the token returned from Auth0
*/
function (user, context, callback) {
var namespace = 'https://techbikers.com/';
// If the user has app_metadata then inject the ID into the token
if (user.app_metadata) {
context.idToken[namespace + 'user_id'] = user.app_metadata.id;
}
callback(null, user, context);
}
| Check to make sure app_metadata exists | Check to make sure app_metadata exists
There shouldn’t be cases where app_metadata doesn’t exist but if it doesn’t then it will cause an error that prevents the user from being logged in.
Signed-off-by: Michael Willmott <4063ad43ea4e0ae77bf35022808393a246bdfa61@gmail.com>
| JavaScript | mit | Techbikers/authentication | ---
+++
@@ -4,6 +4,11 @@
*/
function (user, context, callback) {
var namespace = 'https://techbikers.com/';
- context.idToken[namespace + 'user_id'] = user.app_metadata.id;
+
+ // If the user has app_metadata then inject the ID into the token
+ if (user.app_metadata) {
+ context.idToken[namespace + 'user_id'] = user.app_metadata.id;
+ }
+
callback(null, user, context);
} |
e4b0d2b5ef01904c7206e855f730a5f3b31a0988 | examples/01-add-user.js | examples/01-add-user.js | // use level-dyno and open a new datastore
var dyno = require('../level-dyno.js');
var flake = require('flake')('eth0');
// open a new database
var db = dyno('/tmp/users');
// do the above sequence
db.putItem('chilts', { nick : 'chilts', email : 'me@example.com' }, flake(), function(err) {
console.log('putItem(): done');
});
db.incAttrBy('chilts', 'logins', 1, flake(), function(err) {
console.log('incAttrBy(): done');
});
db.delAttrs('chilts', [ 'email' ], flake(), function(err) {
console.log('delAttrs(): done');
});
db.putAttrs('chilts', { name : 'Andy Chilton' }, flake(), function(err) {
console.log('putAttrs(): done');
});
db.putAttrs('chilts', { email : 'me@example.net' }, flake(), function(err) {
console.log('putAttrs(): done');
});
| // use level-dyno and open a new datastore
var dyno = require('../level-dyno.js');
var flake = require('flake')('eth0');
// open a new database
var db = dyno('/tmp/users');
var user = 'chilts';
// do the above sequence
db.putItem(user, { nick : 'chilts', email : 'me@example.com' }, flake(), function(err) {
console.log('putItem(): done');
});
db.incAttrBy(user, 'logins', 1, flake(), function(err) {
console.log('incAttrBy(): done');
});
db.delAttrs(user, [ 'email' ], flake(), function(err) {
console.log('delAttrs(): done');
});
db.putAttrs(user, { name : 'Andy Chilton' }, flake(), function(err) {
console.log('putAttrs(): done');
});
db.putAttrs(user, { email : 'me@example.net' }, flake(), function(err) {
console.log('putAttrs(): done');
});
| Make the example a bit nicer | Make the example a bit nicer
| JavaScript | mit | chilts/modb-dyno-leveldb | ---
+++
@@ -5,23 +5,25 @@
// open a new database
var db = dyno('/tmp/users');
+var user = 'chilts';
+
// do the above sequence
-db.putItem('chilts', { nick : 'chilts', email : 'me@example.com' }, flake(), function(err) {
+db.putItem(user, { nick : 'chilts', email : 'me@example.com' }, flake(), function(err) {
console.log('putItem(): done');
});
-db.incAttrBy('chilts', 'logins', 1, flake(), function(err) {
+db.incAttrBy(user, 'logins', 1, flake(), function(err) {
console.log('incAttrBy(): done');
});
-db.delAttrs('chilts', [ 'email' ], flake(), function(err) {
+db.delAttrs(user, [ 'email' ], flake(), function(err) {
console.log('delAttrs(): done');
});
-db.putAttrs('chilts', { name : 'Andy Chilton' }, flake(), function(err) {
+db.putAttrs(user, { name : 'Andy Chilton' }, flake(), function(err) {
console.log('putAttrs(): done');
});
-db.putAttrs('chilts', { email : 'me@example.net' }, flake(), function(err) {
+db.putAttrs(user, { email : 'me@example.net' }, flake(), function(err) {
console.log('putAttrs(): done');
}); |
6bbea72f596cfa83b8cf50d3f546fff1bb3ff900 | src/nls/de/urls.js | src/nls/de/urls.js | /*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define({
// Relative to the samples folder
"GETTING_STARTED" : "de/Erste Schritte"
});
| /*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define({
// Relative to the samples folder
"GETTING_STARTED" : "de/Erste Schritte",
"ADOBE_THIRD_PARTY" : "http://www.adobe.com/go/thirdparty_de/",
"WEB_PLATFORM_DOCS_LICENSE" : "http://creativecommons.org/licenses/by/3.0/deed.de"
});
| Add third-party and CC-BY license URLs for 'de' locale | Add third-party and CC-BY license URLs for 'de' locale
| JavaScript | mit | Cartman0/brackets,ralic/brackets,MantisWare/brackets,y12uc231/brackets,Mosoc/brackets,iamchathu/brackets,nucliweb/brackets,flukeout/brackets,sophiacaspar/brackets,fronzec/brackets,pkdevbox/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,zaggino/brackets-electron,mjurczyk/brackets,82488059/brackets,2youyouo2/cocoslite,jiimaho/brackets,ls2uper/brackets,mozilla/brackets,arduino-org/ArduinoStudio,pomadgw/brackets,RobertJGabriel/brackets,Live4Code/brackets,ryanackley/tailor,resir014/brackets,sedge/nimble,pomadgw/brackets,brianjking/brackets,RamirezWillow/brackets,Pomax/brackets,shal1y/brackets,shiyamkumar/brackets,petetnt/brackets,L0g1k/brackets,jmarkina/brackets,No9/brackets,Fcmam5/brackets,resir014/brackets,arduino-org/ArduinoStudio,L0g1k/brackets,Fcmam5/brackets,jiawenbo/brackets,L0g1k/brackets,ralic/brackets,fcjailybo/brackets,sgupta7857/brackets,m66n/brackets,phillipalexander/brackets,fvntr/brackets,sgupta7857/brackets,raygervais/brackets,zhukaixy/brackets,raygervais/brackets,wesleifreitas/brackets,quasto/ArduinoStudio,FTG-003/brackets,netlams/brackets,ecwebservices/brackets,GHackAnonymous/brackets,fvntr/brackets,fastrde/brackets,busykai/brackets,MahadevanSrinivasan/brackets,chrisle/brackets,gupta-tarun/brackets,MarcelGerber/brackets,agreco/brackets,ScalaInc/brackets,TylerL-uxai/brackets,shiyamkumar/brackets,jiimaho/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,tan9/brackets,kilroy23/brackets,MantisWare/brackets,FTG-003/brackets,rafaelstz/brackets,brianjking/brackets,jiawenbo/brackets,Pomax/brackets,keir-rex/brackets,emanziano/brackets,ScalaInc/brackets,revi/brackets,show0017/brackets,ScalaInc/brackets,kolipka/brackets,hanmichael/brackets,jacobnash/brackets,Cartman0/brackets,iamchathu/brackets,sprintr/brackets,2youyouo2/cocoslite,andrewnc/brackets,richmondgozarin/brackets,weebygames/brackets,brianjking/brackets,fastrde/brackets,nucliweb/brackets,ForkedRepos/brackets,Lojsan123/brackets,gcommetti/brackets,fronzec/brackets,goldcase/brackets,jiimaho/brackets,baig/brackets,Rynaro/brackets,82488059/brackets,lunode/brackets,netlams/brackets,IAmAnubhavSaini/brackets,Lojsan123/brackets,simon66/brackets,treejames/brackets,Th30/brackets,mozilla/brackets,marcominetti/brackets,JordanTheriault/brackets,baig/brackets,srinivashappy/brackets,RamirezWillow/brackets,raygervais/brackets,Fcmam5/brackets,jacobnash/brackets,mjurczyk/brackets,thehogfather/brackets,NGHGithub/brackets,zaggino/brackets-electron,alexkid64/brackets,lovewitty/brackets,jiimaho/brackets,fabricadeaplicativos/brackets,m66n/brackets,macdg/brackets,gideonthomas/brackets,2youyouo2/cocoslite,Live4Code/brackets,NKcentinel/brackets,No9/brackets,rafaelstz/brackets,ashleygwilliams/brackets,mozilla/brackets,Mosoc/brackets,busykai/brackets,Andrey-Pavlov/brackets,xantage/brackets,RamirezWillow/brackets,fastrde/brackets,ryanackley/tailor,humphd/brackets,StephanieMak/brackets,malinkie/brackets,gideonthomas/brackets,andrewnc/brackets,phillipalexander/brackets,Wikunia/brackets,No9/brackets,netlams/brackets,siddharta1337/brackets,srhbinion/brackets,RobertJGabriel/brackets,raygervais/brackets,cosmosgenius/brackets,zhukaixy/brackets,shiyamkumar/brackets,amrelnaggar/brackets,ashleygwilliams/brackets,bidle/brackets,zLeonjo/brackets,lunode/brackets,IAmAnubhavSaini/brackets,IAmAnubhavSaini/brackets,alicoding/nimble,NickersF/brackets,richmondgozarin/brackets,Denisov21/brackets,FTG-003/brackets,ryanackley/tailor,sprintr/brackets,ralic/brackets,falcon1812/brackets,macdg/brackets,Th30/brackets,busykai/brackets,chrismoulton/brackets,alicoding/nimble,rafaelstz/brackets,abhisekp/brackets,albertinad/brackets,ChaofengZhou/brackets,albertinad/brackets,tan9/brackets,stowball/brackets,2youyouo2/cocoslite,michaeljayt/brackets,pratts/brackets,Denisov21/brackets,revi/brackets,xantage/brackets,uwsd/brackets,chambej/brackets,zLeonjo/brackets,gwynndesign/brackets,ficristo/brackets,2youyouo2/cocoslite,fabricadeaplicativos/brackets,robertkarlsson/brackets,fvntr/brackets,ggusman/present,ls2uper/brackets,richmondgozarin/brackets,chrisle/brackets,massimiliano76/brackets,ralic/brackets,phillipalexander/brackets,JordanTheriault/brackets,RobertJGabriel/brackets,fashionsun/brackets,albertinad/brackets,albertinad/brackets,NKcentinel/brackets,cosmosgenius/brackets,xantage/brackets,rlugojr/brackets,IAmAnubhavSaini/brackets,thehogfather/brackets,ecwebservices/brackets,flukeout/brackets,uwsd/brackets,mcanthony/brackets,adobe/brackets,kolipka/brackets,chrisle/brackets,falcon1812/brackets,chinnyannieb/brackets,chrismoulton/brackets,NGHGithub/brackets,fcjailybo/brackets,agreco/brackets,macdg/brackets,stowball/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,rlugojr/brackets,arduino-org/ArduinoStudio,m66n/brackets,wakermahmud/brackets,IAmAnubhavSaini/brackets,fcjailybo/brackets,humphd/brackets,nucliweb/brackets,chinnyannieb/brackets,udhayam/brackets,nucliweb/brackets,alicoding/nimble,simon66/brackets,Pomax/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,MahadevanSrinivasan/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,phillipalexander/brackets,busykai/brackets,srinivashappy/brackets,jmarkina/brackets,gcommetti/brackets,iamchathu/brackets,abhisekp/brackets,wakermahmud/brackets,Rajat-dhyani/brackets,show0017/brackets,ls2uper/brackets,SidBala/brackets,thr0w/brackets,revi/brackets,pkdevbox/brackets,RobertJGabriel/brackets,MahadevanSrinivasan/brackets,Jonavin/brackets,fvntr/brackets,bidle/brackets,malinkie/brackets,chambej/brackets,pratts/brackets,macdg/brackets,82488059/brackets,pomadgw/brackets,Jonavin/brackets,fashionsun/brackets,sedge/nimble,adobe/brackets,gcommetti/brackets,y12uc231/brackets,adrianhartanto0/brackets,pratts/brackets,TylerL-uxai/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,ecwebservices/brackets,sophiacaspar/brackets,stowball/brackets,rlugojr/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,kolipka/brackets,emanziano/brackets,jiawenbo/brackets,ScalaInc/brackets,Real-Currents/brackets,MarcelGerber/brackets,y12uc231/brackets,iamchathu/brackets,Denisov21/brackets,revi/brackets,RobertJGabriel/brackets,gupta-tarun/brackets,Th30/brackets,dtcom/MyPSDBracket,dangkhue27/brackets,wakermahmud/brackets,brianjking/brackets,karevn/brackets,NickersF/brackets,chrisle/brackets,NGHGithub/brackets,pratts/brackets,resir014/brackets,ficristo/brackets,JordanTheriault/brackets,Rajat-dhyani/brackets,keir-rex/brackets,thehogfather/brackets,Denisov21/brackets,alexkid64/brackets,TylerL-uxai/brackets,ChaofengZhou/brackets,richmondgozarin/brackets,ggusman/present,ls2uper/brackets,srhbinion/brackets,treejames/brackets,petetnt/brackets,brianjking/brackets,dangkhue27/brackets,massimiliano76/brackets,Rynaro/brackets,fabricadeaplicativos/brackets,rlugojr/brackets,zhukaixy/brackets,weebygames/brackets,mcanthony/brackets,ropik/brackets,JordanTheriault/brackets,hanmichael/brackets,sgupta7857/brackets,m66n/brackets,82488059/brackets,shal1y/brackets,zLeonjo/brackets,FTG-003/brackets,m66n/brackets,lovewitty/brackets,Jonavin/brackets,ficristo/brackets,jacobnash/brackets,treejames/brackets,zLeonjo/brackets,sophiacaspar/brackets,humphd/brackets,mjurczyk/brackets,wesleifreitas/brackets,pkdevbox/brackets,fashionsun/brackets,kolipka/brackets,ecwebservices/brackets,Andrey-Pavlov/brackets,kilroy23/brackets,youprofit/brackets,veveykocute/brackets,Th30/brackets,JordanTheriault/brackets,veveykocute/brackets,baig/brackets,phillipalexander/brackets,fashionsun/brackets,fronzec/brackets,ChaofengZhou/brackets,shal1y/brackets,mozilla/brackets,NGHGithub/brackets,GHackAnonymous/brackets,Rajat-dhyani/brackets,abhisekp/brackets,fabricadeaplicativos/brackets,Rynaro/brackets,fvntr/brackets,sgupta7857/brackets,GHackAnonymous/brackets,dangkhue27/brackets,Live4Code/brackets,MarcelGerber/brackets,FTG-003/brackets,adrianhartanto0/brackets,Mosoc/brackets,hanmichael/brackets,udhayam/brackets,CapeSepias/brackets,adrianhartanto0/brackets,Free-Technology-Guild/brackets,revi/brackets,andrewnc/brackets,quasto/ArduinoStudio,pratts/brackets,netlams/brackets,andrewnc/brackets,Free-Technology-Guild/brackets,petetnt/brackets,alexkid64/brackets,michaeljayt/brackets,chambej/brackets,falcon1812/brackets,karevn/brackets,malinkie/brackets,youprofit/brackets,Real-Currents/brackets,weebygames/brackets,jiimaho/brackets,lunode/brackets,Pomax/brackets,MarcelGerber/brackets,cdot-brackets-extensions/nimble-htmlLint,sgupta7857/brackets,hanmichael/brackets,chinnyannieb/brackets,wesleifreitas/brackets,ryanackley/tailor,y12uc231/brackets,NickersF/brackets,youprofit/brackets,wangjun/brackets,ChaofengZhou/brackets,NKcentinel/brackets,Rajat-dhyani/brackets,chrismoulton/brackets,Denisov21/brackets,gideonthomas/brackets,fcjailybo/brackets,simon66/brackets,fronzec/brackets,petetnt/brackets,macdg/brackets,NickersF/brackets,massimiliano76/brackets,mat-mcloughlin/brackets,adrianhartanto0/brackets,Free-Technology-Guild/brackets,MarcelGerber/brackets,mcanthony/brackets,eric-stanley/brackets,malinkie/brackets,flukeout/brackets,uwsd/brackets,lovewitty/brackets,zaggino/brackets-electron,lovewitty/brackets,malinkie/brackets,sprintr/brackets,thr0w/brackets,wesleifreitas/brackets,lunode/brackets,bidle/brackets,amrelnaggar/brackets,thr0w/brackets,falcon1812/brackets,simon66/brackets,treejames/brackets,michaeljayt/brackets,srhbinion/brackets,rafaelstz/brackets,cdot-brackets-extensions/nimble-htmlLint,ashleygwilliams/brackets,chrisle/brackets,nucliweb/brackets,siddharta1337/brackets,pomadgw/brackets,pkdevbox/brackets,chambej/brackets,Fcmam5/brackets,lunode/brackets,andrewnc/brackets,goldcase/brackets,StephanieMak/brackets,sedge/nimble,uwsd/brackets,agreco/brackets,xantage/brackets,Real-Currents/brackets,gupta-tarun/brackets,alexkid64/brackets,chrismoulton/brackets,zLeonjo/brackets,dangkhue27/brackets,TylerL-uxai/brackets,busykai/brackets,sprintr/brackets,humphd/brackets,kolipka/brackets,emanziano/brackets,gwynndesign/brackets,ropik/brackets,weebygames/brackets,ashleygwilliams/brackets,adobe/brackets,alicoding/nimble,fabricadeaplicativos/brackets,y12uc231/brackets,sedge/nimble,Jonavin/brackets,stowball/brackets,thr0w/brackets,gupta-tarun/brackets,youprofit/brackets,Free-Technology-Guild/brackets,veveykocute/brackets,mat-mcloughlin/brackets,dtcom/MyPSDBracket,Lojsan123/brackets,karevn/brackets,shiyamkumar/brackets,dangkhue27/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,Cartman0/brackets,zaggino/brackets-electron,Th30/brackets,robertkarlsson/brackets,CapeSepias/brackets,weebygames/brackets,wangjun/brackets,udhayam/brackets,falcon1812/brackets,abhisekp/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,kilroy23/brackets,amrelnaggar/brackets,ecwebservices/brackets,82488059/brackets,kilroy23/brackets,arduino-org/ArduinoStudio,SebastianBoyd/sebastianboyd.github.io-OLD,bidle/brackets,srinivashappy/brackets,goldcase/brackets,gcommetti/brackets,wangjun/brackets,zhukaixy/brackets,uwsd/brackets,agreco/brackets,ls2uper/brackets,ForkedRepos/brackets,zhukaixy/brackets,xantage/brackets,amrelnaggar/brackets,MantisWare/brackets,fastrde/brackets,ropik/brackets,ficristo/brackets,siddharta1337/brackets,humphd/brackets,chambej/brackets,siddharta1337/brackets,udhayam/brackets,keir-rex/brackets,karevn/brackets,amrelnaggar/brackets,Cartman0/brackets,eric-stanley/brackets,baig/brackets,karevn/brackets,robertkarlsson/brackets,mcanthony/brackets,ralic/brackets,NKcentinel/brackets,veveykocute/brackets,rlugojr/brackets,shal1y/brackets,Andrey-Pavlov/brackets,GHackAnonymous/brackets,Rajat-dhyani/brackets,gwynndesign/brackets,srhbinion/brackets,StephanieMak/brackets,jacobnash/brackets,udhayam/brackets,jmarkina/brackets,ggusman/present,CapeSepias/brackets,fcjailybo/brackets,gupta-tarun/brackets,Wikunia/brackets,gcommetti/brackets,MantisWare/brackets,show0017/brackets,Rynaro/brackets,wangjun/brackets,eric-stanley/brackets,Lojsan123/brackets,SidBala/brackets,sedge/nimble,ForkedRepos/brackets,ficristo/brackets,emanziano/brackets,gideonthomas/brackets,ashleygwilliams/brackets,RamirezWillow/brackets,NKcentinel/brackets,flukeout/brackets,shiyamkumar/brackets,Cartman0/brackets,ChaofengZhou/brackets,quasto/ArduinoStudio,emanziano/brackets,chinnyannieb/brackets,hanmichael/brackets,Real-Currents/brackets,ricciozhang/brackets,pkdevbox/brackets,Real-Currents/brackets,jiawenbo/brackets,mat-mcloughlin/brackets,veveykocute/brackets,netlams/brackets,Jonavin/brackets,MantisWare/brackets,abhisekp/brackets,stowball/brackets,marcominetti/brackets,Wikunia/brackets,Andrey-Pavlov/brackets,bidle/brackets,albertinad/brackets,iamchathu/brackets,srinivashappy/brackets,richmondgozarin/brackets,fronzec/brackets,NGHGithub/brackets,lovewitty/brackets,L0g1k/brackets,NickersF/brackets,cdot-brackets-extensions/nimble-htmlLint,sophiacaspar/brackets,Live4Code/brackets,TylerL-uxai/brackets,Rynaro/brackets,sophiacaspar/brackets,arduino-org/ArduinoStudio,ricciozhang/brackets,No9/brackets,wakermahmud/brackets,chrismoulton/brackets,resir014/brackets,srhbinion/brackets,jacobnash/brackets,zaggino/brackets-electron,cosmosgenius/brackets,sprintr/brackets,mat-mcloughlin/brackets,goldcase/brackets,robertkarlsson/brackets,treejames/brackets,RamirezWillow/brackets,thehogfather/brackets,jmarkina/brackets,StephanieMak/brackets,ricciozhang/brackets,Mosoc/brackets,mozilla/brackets,MahadevanSrinivasan/brackets,ggusman/present,ricciozhang/brackets,michaeljayt/brackets,CapeSepias/brackets,gwynndesign/brackets,goldcase/brackets,kilroy23/brackets,youprofit/brackets,Andrey-Pavlov/brackets,gideonthomas/brackets,jiawenbo/brackets,ricciozhang/brackets,Real-Currents/brackets,SidBala/brackets,ScalaInc/brackets,fashionsun/brackets,StephanieMak/brackets,mcanthony/brackets,CapeSepias/brackets,tan9/brackets,dtcom/MyPSDBracket,Fcmam5/brackets,flukeout/brackets,tan9/brackets,No9/brackets,pomadgw/brackets,mjurczyk/brackets,tan9/brackets,SidBala/brackets,thr0w/brackets,keir-rex/brackets,jmarkina/brackets,michaeljayt/brackets,ForkedRepos/brackets,chinnyannieb/brackets,simon66/brackets,quasto/ArduinoStudio,Lojsan123/brackets,massimiliano76/brackets,resir014/brackets,adobe/brackets,Live4Code/brackets,Wikunia/brackets,alexkid64/brackets,eric-stanley/brackets,petetnt/brackets,wesleifreitas/brackets,eric-stanley/brackets,mjurczyk/brackets,robertkarlsson/brackets,srinivashappy/brackets,MahadevanSrinivasan/brackets,Mosoc/brackets,show0017/brackets,wangjun/brackets,dtcom/MyPSDBracket,Wikunia/brackets,ropik/brackets,zaggino/brackets-electron,GHackAnonymous/brackets,ForkedRepos/brackets,SidBala/brackets,cosmosgenius/brackets,baig/brackets,thehogfather/brackets,fastrde/brackets,cdot-brackets-extensions/nimble-htmlLint,Free-Technology-Guild/brackets,wakermahmud/brackets,shal1y/brackets,quasto/ArduinoStudio,massimiliano76/brackets,adobe/brackets,siddharta1337/brackets,rafaelstz/brackets,adrianhartanto0/brackets,keir-rex/brackets,Pomax/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,raygervais/brackets | ---
+++
@@ -26,5 +26,7 @@
define({
// Relative to the samples folder
- "GETTING_STARTED" : "de/Erste Schritte"
+ "GETTING_STARTED" : "de/Erste Schritte",
+ "ADOBE_THIRD_PARTY" : "http://www.adobe.com/go/thirdparty_de/",
+ "WEB_PLATFORM_DOCS_LICENSE" : "http://creativecommons.org/licenses/by/3.0/deed.de"
}); |
7e84c0227dd793591188454e9cc1e3b63d6b8b9f | examples/example.tls.js | examples/example.tls.js | 'use strict';
var spdyPush = require('..')
, spdy = require('spdy')
, express = require('express')
, path = require('path')
, fs = require('fs');
var app = express();
app.use(spdyPush.referrer());
app.use(express.static(path.join(__dirname, '../test/site')));
var options = {
key: fs.readFileSync(path.join(__dirname, '../test/keys/spdy-key.pem')),
cert: fs.readFileSync(path.join(__dirname, '../test/keys/spdy-cert.pem'))
};
options = {
key: fs.readFileSync(process.env.HOME + '/.ssh/localhost.key'),
cert: fs.readFileSync(process.env.HOME + '/.ssh/localhost.crt'),
ca: fs.readFileSync(process.env.HOME + '/.ca/cacert.pem')
};
var port = 8443;
spdy.createServer(options, app).listen(port);
| 'use strict';
var spdyPush = require('..')
, spdy = require('spdy')
, express = require('express')
, path = require('path')
, fs = require('fs');
var app = express();
app.use(spdyPush.referrer());
app.use(express.static(path.join(__dirname, '../test/site')));
var options = {
key: fs.readFileSync(path.join(__dirname, '../test/keys/spdy-key.pem')),
cert: fs.readFileSync(path.join(__dirname, '../test/keys/spdy-cert.pem'))
};
var port = 8443;
spdy.createServer(options, app).listen(port);
| Fix location of SSL key and certificate | Fix location of SSL key and certificate
| JavaScript | mit | halvards/spdy-referrer-push | ---
+++
@@ -13,10 +13,5 @@
key: fs.readFileSync(path.join(__dirname, '../test/keys/spdy-key.pem')),
cert: fs.readFileSync(path.join(__dirname, '../test/keys/spdy-cert.pem'))
};
-options = {
- key: fs.readFileSync(process.env.HOME + '/.ssh/localhost.key'),
- cert: fs.readFileSync(process.env.HOME + '/.ssh/localhost.crt'),
- ca: fs.readFileSync(process.env.HOME + '/.ca/cacert.pem')
-};
var port = 8443;
spdy.createServer(options, app).listen(port); |
54315706195e9280beccdaa7e7cffadef1cecdee | website/static/js/filerenderer.js | website/static/js/filerenderer.js | /*
* Refresh rendered file through mfr
*/
'use strict';
var $ = require('jquery');
var $osf = require('js/osfHelpers');
var FileRenderer = {
start: function(url, selector){
this.url = url;
this.tries = 0;
this.ALLOWED_RETRIES = 10;
this.element = $(selector);
this.getCachedFromServer();
},
getCachedFromServer: function() {
var self = this;
$.ajax({
method: 'GET',
url: self.url,
beforeSend: $osf.setXHRAuthorization
}).done(function(data) {
if (data) {
self.element.html(data.rendered);
} else {
self.handleRetry();
}
}).fail(self.handleRetry);
},
handleRetry: $osf.throttle(function() {
var self = FileRenderer;
self.tries += 1;
if(self.tries > self.ALLOWED_RETRIES){
self.element.html('Timeout occurred while loading, please refresh the page');
} else {
self.getCachedFromServer();
}
}, 1000)
};
module.exports = FileRenderer;
| /*
* Refresh rendered file through mfr
*/
var $ = require('jquery');
var $osf = require('js/osfHelpers');
function FileRenderer(url, selector) {
var self = this;
self.url = url;
self.tries = 0;
self.selector = selector;
self.ALLOWED_RETRIES = 10;
self.element = $(selector);
self.start = function() {
self.getCachedFromServer();
};
self.reload = function() {
self.tries = 0;
self.start();
};
self.getCachedFromServer = function() {
$.ajax({
method: 'GET',
url: self.url,
beforeSend: $osf.setXHRAuthorization
}).done(function(data) {
if (data) {
self.element.html(data);
} else {
self.handleRetry();
}
}).fail(self.handleRetry);
};
self.handleRetry = $osf.throttle(function() {
self.tries += 1;
if(self.tries > self.ALLOWED_RETRIES){
self.element.html('Timeout occurred while loading, please refresh the page');
} else {
self.getCachedFromServer();
}
}, 1000);
}
module.exports = FileRenderer;
| Refactor to OOP ish design | Refactor to OOP ish design
| JavaScript | apache-2.0 | wearpants/osf.io,monikagrabowska/osf.io,KAsante95/osf.io,cosenal/osf.io,doublebits/osf.io,abought/osf.io,mluo613/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,billyhunt/osf.io,KAsante95/osf.io,chennan47/osf.io,ZobairAlijan/osf.io,GageGaskins/osf.io,acshi/osf.io,ticklemepierce/osf.io,ckc6cz/osf.io,mluo613/osf.io,baylee-d/osf.io,arpitar/osf.io,haoyuchen1992/osf.io,Ghalko/osf.io,caseyrollins/osf.io,kwierman/osf.io,jmcarp/osf.io,CenterForOpenScience/osf.io,billyhunt/osf.io,brandonPurvis/osf.io,HarryRybacki/osf.io,reinaH/osf.io,SSJohns/osf.io,doublebits/osf.io,sbt9uc/osf.io,caseyrollins/osf.io,erinspace/osf.io,TomHeatwole/osf.io,cwisecarver/osf.io,kwierman/osf.io,doublebits/osf.io,jinluyuan/osf.io,GageGaskins/osf.io,TomHeatwole/osf.io,abought/osf.io,HarryRybacki/osf.io,samchrisinger/osf.io,chennan47/osf.io,crcresearch/osf.io,lyndsysimon/osf.io,ticklemepierce/osf.io,RomanZWang/osf.io,asanfilippo7/osf.io,GageGaskins/osf.io,jmcarp/osf.io,leb2dg/osf.io,mattclark/osf.io,jolene-esposito/osf.io,acshi/osf.io,HarryRybacki/osf.io,samanehsan/osf.io,billyhunt/osf.io,cslzchen/osf.io,billyhunt/osf.io,billyhunt/osf.io,RomanZWang/osf.io,cosenal/osf.io,pattisdr/osf.io,jnayak1/osf.io,fabianvf/osf.io,monikagrabowska/osf.io,HalcyonChimera/osf.io,jnayak1/osf.io,bdyetton/prettychart,mluo613/osf.io,ZobairAlijan/osf.io,bdyetton/prettychart,amyshi188/osf.io,zamattiac/osf.io,kch8qx/osf.io,KAsante95/osf.io,abought/osf.io,caneruguz/osf.io,danielneis/osf.io,asanfilippo7/osf.io,mluke93/osf.io,TomBaxter/osf.io,ckc6cz/osf.io,MerlinZhang/osf.io,sloria/osf.io,leb2dg/osf.io,ZobairAlijan/osf.io,doublebits/osf.io,kch8qx/osf.io,GageGaskins/osf.io,jnayak1/osf.io,HalcyonChimera/osf.io,lyndsysimon/osf.io,acshi/osf.io,samchrisinger/osf.io,DanielSBrown/osf.io,jeffreyliu3230/osf.io,Johnetordoff/osf.io,monikagrabowska/osf.io,HarryRybacki/osf.io,icereval/osf.io,ckc6cz/osf.io,asanfilippo7/osf.io,samchrisinger/osf.io,Johnetordoff/osf.io,sloria/osf.io,adlius/osf.io,zachjanicki/osf.io,Ghalko/osf.io,sbt9uc/osf.io,amyshi188/osf.io,binoculars/osf.io,erinspace/osf.io,dplorimer/osf,hmoco/osf.io,crcresearch/osf.io,haoyuchen1992/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,felliott/osf.io,chrisseto/osf.io,KAsante95/osf.io,zachjanicki/osf.io,caneruguz/osf.io,chrisseto/osf.io,binoculars/osf.io,zachjanicki/osf.io,bdyetton/prettychart,petermalcolm/osf.io,dplorimer/osf,brianjgeiger/osf.io,icereval/osf.io,barbour-em/osf.io,mfraezz/osf.io,MerlinZhang/osf.io,DanielSBrown/osf.io,ckc6cz/osf.io,Johnetordoff/osf.io,ticklemepierce/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,alexschiller/osf.io,HalcyonChimera/osf.io,mluke93/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,jolene-esposito/osf.io,binoculars/osf.io,lyndsysimon/osf.io,petermalcolm/osf.io,dplorimer/osf,kch8qx/osf.io,asanfilippo7/osf.io,adlius/osf.io,Ghalko/osf.io,haoyuchen1992/osf.io,jinluyuan/osf.io,reinaH/osf.io,cldershem/osf.io,TomHeatwole/osf.io,TomBaxter/osf.io,njantrania/osf.io,cldershem/osf.io,barbour-em/osf.io,jmcarp/osf.io,CenterForOpenScience/osf.io,reinaH/osf.io,brianjgeiger/osf.io,cldershem/osf.io,kch8qx/osf.io,RomanZWang/osf.io,caneruguz/osf.io,kch8qx/osf.io,cslzchen/osf.io,emetsger/osf.io,sloria/osf.io,cldershem/osf.io,danielneis/osf.io,Nesiehr/osf.io,acshi/osf.io,saradbowman/osf.io,jeffreyliu3230/osf.io,baylee-d/osf.io,jinluyuan/osf.io,jeffreyliu3230/osf.io,bdyetton/prettychart,caseyrygt/osf.io,alexschiller/osf.io,njantrania/osf.io,arpitar/osf.io,crcresearch/osf.io,MerlinZhang/osf.io,aaxelb/osf.io,arpitar/osf.io,KAsante95/osf.io,emetsger/osf.io,samchrisinger/osf.io,emetsger/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,caneruguz/osf.io,rdhyee/osf.io,cwisecarver/osf.io,brandonPurvis/osf.io,felliott/osf.io,cosenal/osf.io,monikagrabowska/osf.io,wearpants/osf.io,caseyrygt/osf.io,reinaH/osf.io,amyshi188/osf.io,jolene-esposito/osf.io,petermalcolm/osf.io,danielneis/osf.io,caseyrygt/osf.io,chennan47/osf.io,danielneis/osf.io,jnayak1/osf.io,rdhyee/osf.io,fabianvf/osf.io,cwisecarver/osf.io,rdhyee/osf.io,wearpants/osf.io,alexschiller/osf.io,DanielSBrown/osf.io,felliott/osf.io,chrisseto/osf.io,RomanZWang/osf.io,arpitar/osf.io,brandonPurvis/osf.io,dplorimer/osf,fabianvf/osf.io,barbour-em/osf.io,felliott/osf.io,zamattiac/osf.io,mluke93/osf.io,mfraezz/osf.io,njantrania/osf.io,zachjanicki/osf.io,SSJohns/osf.io,Ghalko/osf.io,erinspace/osf.io,laurenrevere/osf.io,caseyrollins/osf.io,rdhyee/osf.io,cosenal/osf.io,baylee-d/osf.io,hmoco/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,caseyrygt/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,leb2dg/osf.io,njantrania/osf.io,DanielSBrown/osf.io,barbour-em/osf.io,mluo613/osf.io,aaxelb/osf.io,leb2dg/osf.io,samanehsan/osf.io,MerlinZhang/osf.io,jmcarp/osf.io,mfraezz/osf.io,icereval/osf.io,mattclark/osf.io,kwierman/osf.io,sbt9uc/osf.io,wearpants/osf.io,hmoco/osf.io,cslzchen/osf.io,mattclark/osf.io,samanehsan/osf.io,adlius/osf.io,TomHeatwole/osf.io,alexschiller/osf.io,brianjgeiger/osf.io,RomanZWang/osf.io,SSJohns/osf.io,lyndsysimon/osf.io,saradbowman/osf.io,fabianvf/osf.io,kwierman/osf.io,abought/osf.io,adlius/osf.io,pattisdr/osf.io,chrisseto/osf.io,aaxelb/osf.io,Nesiehr/osf.io,SSJohns/osf.io,haoyuchen1992/osf.io,alexschiller/osf.io,ZobairAlijan/osf.io,Nesiehr/osf.io,zamattiac/osf.io,doublebits/osf.io,emetsger/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,pattisdr/osf.io,petermalcolm/osf.io,jolene-esposito/osf.io,jinluyuan/osf.io,sbt9uc/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,mluke93/osf.io,brandonPurvis/osf.io,zamattiac/osf.io,cslzchen/osf.io,samanehsan/osf.io,jeffreyliu3230/osf.io | ---
+++
@@ -2,37 +2,43 @@
* Refresh rendered file through mfr
*/
-'use strict';
-
var $ = require('jquery');
var $osf = require('js/osfHelpers');
-var FileRenderer = {
- start: function(url, selector){
- this.url = url;
- this.tries = 0;
- this.ALLOWED_RETRIES = 10;
- this.element = $(selector);
- this.getCachedFromServer();
- },
+function FileRenderer(url, selector) {
+ var self = this;
- getCachedFromServer: function() {
- var self = this;
+ self.url = url;
+ self.tries = 0;
+ self.selector = selector;
+ self.ALLOWED_RETRIES = 10;
+ self.element = $(selector);
+
+
+ self.start = function() {
+ self.getCachedFromServer();
+ };
+
+ self.reload = function() {
+ self.tries = 0;
+ self.start();
+ };
+
+ self.getCachedFromServer = function() {
$.ajax({
method: 'GET',
url: self.url,
beforeSend: $osf.setXHRAuthorization
}).done(function(data) {
if (data) {
- self.element.html(data.rendered);
+ self.element.html(data);
} else {
self.handleRetry();
}
}).fail(self.handleRetry);
- },
+ };
- handleRetry: $osf.throttle(function() {
- var self = FileRenderer;
+ self.handleRetry = $osf.throttle(function() {
self.tries += 1;
if(self.tries > self.ALLOWED_RETRIES){
@@ -40,7 +46,7 @@
} else {
self.getCachedFromServer();
}
- }, 1000)
-};
+ }, 1000);
+}
module.exports = FileRenderer; |
fb8ff704821e18be2a8aef117f69e32f408cfc5b | models/index.js | models/index.js | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
/* jslint node: true */
const fs = require('fs')
const path = require('path')
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'sqlite',
storage: ':memory:', // replace with 'data/juiceshop.sqlite' for debugging
logging: false
})
sequelizeNoUpdateAttributes(sequelize)
const db = {}
fs.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))
.forEach(file => {
const model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(modelName => {
if ('associate' in db[modelName]) {
db[modelName].associate(db)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
| /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
/* jslint node: true */
const fs = require('fs')
const path = require('path')
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'sqlite',
storage: 'data/juiceshop.sqlite',
logging: false
})
sequelizeNoUpdateAttributes(sequelize)
const db = {}
fs.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))
.forEach(file => {
const model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(modelName => {
if ('associate' in db[modelName]) {
db[modelName].associate(db)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
| Revert SQLite to file-based instead of in-memory | Revert SQLite to file-based instead of in-memory | JavaScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -10,7 +10,7 @@
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'sqlite',
- storage: ':memory:', // replace with 'data/juiceshop.sqlite' for debugging
+ storage: 'data/juiceshop.sqlite',
logging: false
})
sequelizeNoUpdateAttributes(sequelize) |
2b37f7f163fa4eec831e72e1f876ffad3894e1df | pipeline/app/assets/javascripts/app.js | pipeline/app/assets/javascripts/app.js | 'use strict';
var pathwayApp = angular.module('pathwayApp', ['ui.router', 'templates']);
pathwayApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
//Default route
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
$stateProvider
.state('home', {
url: '/',
templateUrl: 'index.html',
// templateUrl: '../app/assets/templates/index.html',
controller: 'HomeController'
})
.state('login', {
url: '/user/login',
templateUrl: 'login.html',
controller: 'UserController'
})
});
| 'use strict';
var pathwayApp = angular.module('pathwayApp', ['ui.router', 'templates']);
pathwayApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
//Default route
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
$stateProvider
.state('home', {
url: '/',
templateUrl: 'index.html',
controller: 'HomeController'
})
.state('logout', {
url: '/',
controller: 'UserController'
})
.state('login', {
url: '/user/login',
templateUrl: 'login.html',
controller: 'UserController'
})
.state('register', {
url: '/user/new',
tempalteUrl: 'register.html',
controller: 'UserController'
})
});
| Add logout and register state, remove incorrect templateUrl | Add logout and register state, remove incorrect templateUrl
| JavaScript | mit | aattsai/Pathway,aattsai/Pathway,aattsai/Pathway | ---
+++
@@ -10,12 +10,20 @@
.state('home', {
url: '/',
templateUrl: 'index.html',
- // templateUrl: '../app/assets/templates/index.html',
controller: 'HomeController'
+ })
+ .state('logout', {
+ url: '/',
+ controller: 'UserController'
})
.state('login', {
url: '/user/login',
templateUrl: 'login.html',
controller: 'UserController'
})
+ .state('register', {
+ url: '/user/new',
+ tempalteUrl: 'register.html',
+ controller: 'UserController'
+ })
}); |
884def1c71c748655bc294e2b3084c627973a848 | test/db-helpers.js | test/db-helpers.js | const fs = require('fs');
const { promisify } = require('util');
const mongodb = require('mongodb');
const request = require('request');
async function readMongoDocuments(file) {
const ISODate = (d) => new Date(d);
const ObjectId = (id) => mongodb.ObjectID.createFromHexString(id);
return eval(await fs.promises.readFile(file, 'utf-8'));
}
async function insertTestData(url, users, posts) {
const mongoClient = await mongodb.MongoClient.connect(url);
const db = mongoClient.db();
await db.collection('user').deleteMany({});
await db.collection('post').deleteMany({});
await db.collection('user').insertMany(users);
await db.collection('post').insertMany(posts);
await mongoClient.close();
}
/* refresh openwhyd's in-memory cache of users, to allow this user to login */
async function refreshOpenwhydCache(urlPrefix = 'http://localhost:8080') {
await promisify(request.post)(urlPrefix + '/testing/refresh');
}
module.exports = {
readMongoDocuments,
insertTestData,
refreshOpenwhydCache,
};
| const fs = require('fs');
const { promisify } = require('util');
const mongodb = require('mongodb');
const request = require('request');
async function readMongoDocuments(file) {
const ISODate = (d) => new Date(d);
const ObjectId = (id) => mongodb.ObjectID.createFromHexString(id);
return eval(await fs.promises.readFile(file, 'utf-8'));
}
async function insertTestData(url, docsPerCollection) {
const mongoClient = await mongodb.MongoClient.connect(url);
const db = mongoClient.db();
await Promise.all(
Object.keys(docsPerCollection).map(async (collection) => {
await db.collection(collection).deleteMany({});
await db.collection(collection).insertMany(docsPerCollection[collection]);
})
);
await mongoClient.close();
}
/* refresh openwhyd's in-memory cache of users, to allow this user to login */
async function refreshOpenwhydCache(urlPrefix = 'http://localhost:8080') {
await promisify(request.post)(urlPrefix + '/testing/refresh');
}
module.exports = {
readMongoDocuments,
insertTestData,
refreshOpenwhydCache,
};
| Allow importing test data for any db collection | fix(tests): Allow importing test data for any db collection
| JavaScript | mit | openwhyd/openwhyd,openwhyd/openwhyd,openwhyd/openwhyd,openwhyd/openwhyd,openwhyd/openwhyd | ---
+++
@@ -9,13 +9,15 @@
return eval(await fs.promises.readFile(file, 'utf-8'));
}
-async function insertTestData(url, users, posts) {
+async function insertTestData(url, docsPerCollection) {
const mongoClient = await mongodb.MongoClient.connect(url);
const db = mongoClient.db();
- await db.collection('user').deleteMany({});
- await db.collection('post').deleteMany({});
- await db.collection('user').insertMany(users);
- await db.collection('post').insertMany(posts);
+ await Promise.all(
+ Object.keys(docsPerCollection).map(async (collection) => {
+ await db.collection(collection).deleteMany({});
+ await db.collection(collection).insertMany(docsPerCollection[collection]);
+ })
+ );
await mongoClient.close();
}
|
4a9a3246f633c3ddb358d3e79a38b39bb2a61bb1 | src/fetch-error.js | src/fetch-error.js |
/**
* fetch-error.js
*
* FetchError interface for operational errors
*/
/**
* Create FetchError instance
*
* @param String message Error message for human
* @param String type Error type for machine
* @param String systemError For Node.js system error
* @return FetchError
*/
export default function FetchError(message, type, systemError) {
// hide custom error implementation details from end-users
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
this.type = type;
// when err.type is `system`, err.code contains system error code
if (systemError) {
this.code = this.errno = systemError.code;
}
}
require('util').inherits(FetchError, Error);
|
/**
* fetch-error.js
*
* FetchError interface for operational errors
*/
/**
* Create FetchError instance
*
* @param String message Error message for human
* @param String type Error type for machine
* @param String systemError For Node.js system error
* @return FetchError
*/
export default function FetchError(message, type, systemError) {
Error.call(this, message);
// hide custom error implementation details from end-users
Error.captureStackTrace(this, this.constructor);
this.message = message;
this.type = type;
// when err.type is `system`, err.code contains system error code
if (systemError) {
this.code = this.errno = systemError.code;
}
}
FetchError.prototype = Object.create(Error.prototype);
FetchError.prototype.name = 'FetchError';
| Remove dependency on Node.js' util module | Remove dependency on Node.js' util module
Closes #194.
| JavaScript | mit | jkantr/node-fetch,bitinn/node-fetch | ---
+++
@@ -14,11 +14,11 @@
* @return FetchError
*/
export default function FetchError(message, type, systemError) {
+ Error.call(this, message);
// hide custom error implementation details from end-users
Error.captureStackTrace(this, this.constructor);
- this.name = this.constructor.name;
this.message = message;
this.type = type;
@@ -29,4 +29,5 @@
}
-require('util').inherits(FetchError, Error);
+FetchError.prototype = Object.create(Error.prototype);
+FetchError.prototype.name = 'FetchError'; |
8114331a8425621e2eb98f39045289ed08bb2e0d | test/e2e/config/delays.js | test/e2e/config/delays.js | /*
* In order to prevent errors caused by e2e tests running too fast you can slow them down by calling the following
* function. Use higher values for slower tests.
*
* utils.delayPromises(30);
*
*/
var promisesDelay = 50;
function delayPromises(milliseconds) {
var executeFunction = browser.driver.controlFlow().execute;
browser.driver.controlFlow().execute = function() {
var args = arguments;
executeFunction.call(browser.driver.controlFlow(), function() {
return protractor.promise.delayed(milliseconds);
});
return executeFunction.apply(browser.driver.controlFlow(), args);
};
}
console.log("Set promises delay to " + promisesDelay + " ms.");
delayPromises(promisesDelay);
var ECWaitTime = 4500;
var shortRest = 200;
module.exports = {
ECWaitTime: ECWaitTime,
shortRest: shortRest
};
| /*
* In order to prevent errors caused by e2e tests running too fast you can slow them down by calling the following
* function. Use higher values for slower tests.
*
* utils.delayPromises(30);
*
*/
var promisesDelay = 0;
function delayPromises(milliseconds) {
var executeFunction = browser.driver.controlFlow().execute;
browser.driver.controlFlow().execute = function() {
var args = arguments;
executeFunction.call(browser.driver.controlFlow(), function() {
return protractor.promise.delayed(milliseconds);
});
return executeFunction.apply(browser.driver.controlFlow(), args);
};
}
console.log("Set promises delay to " + promisesDelay + " ms.");
delayPromises(promisesDelay);
var ECWaitTime = 4500;
var shortRest = 200;
module.exports = {
ECWaitTime: ECWaitTime,
shortRest: shortRest
};
| Set delay to zero for local development. | Set delay to zero for local development.
| JavaScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -5,7 +5,7 @@
* utils.delayPromises(30);
*
*/
-var promisesDelay = 50;
+var promisesDelay = 0;
function delayPromises(milliseconds) { |
d761c33ce8effc9640fccfb4e409bf6a6ee33a91 | util/subtitles.js | util/subtitles.js | const parseTime = (s) => {
const re = /(\d{2}):(\d{2}):(\d{2}),(\d{3})/;
const [, hours, mins, seconds, ms] = re.exec(s);
return 3600*(+hours) + 60*(+mins) + (+seconds) + 0.001*(+ms);
};
export const parseSRT = (text) => {
const normText = text.replace(/\r\n/g, '\n'); // normalize newlines
const re = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n((?:.+\n)+)/g;
const subs = [];
let found;
while (true) {
found = re.exec(normText);
if (!found) {
break;
}
const [full, , beginStr, endStr, lines] = found;
const begin = parseTime(beginStr);
const end = parseTime(endStr);
// TODO: Should verify that end time is >= begin time
// NOTE: We could check that indexes and/or time are in order, but don't really care
subs.push({
begin,
end,
lines,
});
re.lastIndex = found.index + full.length;
}
return subs;
};
| const parseTime = (s) => {
const re = /(\d{2}):(\d{2}):(\d{2}),(\d{3})/;
const [, hours, mins, seconds, ms] = re.exec(s);
return 3600*(+hours) + 60*(+mins) + (+seconds) + 0.001*(+ms);
};
export const parseSRT = (text) => {
const normText = text.replace(/\r\n/g, '\n'); // normalize newlines
const re = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n((?:.+\n)+)/g;
const subs = [];
let found;
while (true) {
found = re.exec(normText);
if (!found) {
break;
}
const [full, , beginStr, endStr, lines] = found;
const begin = parseTime(beginStr);
const end = parseTime(endStr);
// TODO: Should verify that end time is >= begin time
// NOTE: We could check that indexes and/or time are in order, but don't really care
subs.push({
begin,
end,
lines: lines.trim(),
});
re.lastIndex = found.index + full.length;
}
return subs;
};
| Trim whitespace on subtitle import | Trim whitespace on subtitle import
| JavaScript | mit | rsimmons/voracious,rsimmons/immersion-player,rsimmons/immersion-player,rsimmons/voracious,rsimmons/voracious | ---
+++
@@ -24,7 +24,7 @@
subs.push({
begin,
end,
- lines,
+ lines: lines.trim(),
});
re.lastIndex = found.index + full.length;
} |
de74589c0323ad7d0323345fd9e214fb42498e8c | config/env/production.js | config/env/production.js | /**
* Production environment settings
*
* This file can include shared settings for a production environment,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
facebookConfig: {
apiKey: '175967239248590',
callbackUrl: 'https://redrum-js-client.herokuapp.com/user/facebookcb',
secretKey: '319c7ed2f24fc1ac61269a319a19fe11'
},
githubConfig: {
apiKey: '9bab472b1f554514792f',
callbackUrl: 'https://redrum-js-client.herokuapp.com/user/githubcb',
secretKey: '914b62b2aac9c0506e0146f22bab345ffeb2588c'
},
redrumConfig: {
clientId: 'redrum-js-demo',
clientSecret: '847eacd8-d636-4aef-845d-512128dd09a4',
debug: false
}
};
| /**
* Production environment settings
*
* This file can include shared settings for a production environment,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
port: process.env.PORT || 1337,
facebookConfig: {
apiKey: '175967239248590',
callbackUrl: 'https://redrum-js-client.herokuapp.com/user/facebookcb',
secretKey: '319c7ed2f24fc1ac61269a319a19fe11'
},
githubConfig: {
apiKey: '9bab472b1f554514792f',
callbackUrl: 'https://redrum-js-client.herokuapp.com/user/githubcb',
secretKey: '914b62b2aac9c0506e0146f22bab345ffeb2588c'
},
redrumConfig: {
clientId: 'redrum-js-demo',
clientSecret: '847eacd8-d636-4aef-845d-512128dd09a4',
debug: false
}
};
| Set port to environment variable. | Set port to environment variable.
| JavaScript | mit | aug70/redrum-js-client,aug70/redrum-js-client | ---
+++
@@ -11,6 +11,8 @@
*/
module.exports = {
+
+ port: process.env.PORT || 1337,
facebookConfig: {
apiKey: '175967239248590', |
e5c01d6b96b1aec411017bf20069d6706623ff60 | test/markup-frame-test.js | test/markup-frame-test.js | import React from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import MarkupFrame from '../src';
describe( '<MarkupFrame />', () => {
it( 'renders an iframe', () => {
const wrapper = mount( <MarkupFrame markup="" /> );
expect( wrapper.some( 'iframe' ) ).to.equal( true );
} );
it( 'injects props.markup into the iframe' );
it( 'calls props.onLoad with the iframe document' );
} );
| import React from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import MarkupFrame from '../src';
describe( '<MarkupFrame />', function() {
it( 'renders an iframe', function() {
const wrapper = mount( <MarkupFrame markup="" /> );
expect( wrapper.find( 'iframe' ) ).to.have.length( 1 );
} );
it( 'injects props.markup into the iframe', function() {
const wrapper = mount( <MarkupFrame markup="<h1>Hello World</h1>" /> );
expect( wrapper.find( 'iframe' ).get( 0 ).innerHTML ).to.eql( '<h1>Hello World</h1>' )
} );
it( 'calls props.onLoad with the iframe document', function() {
const onLoad = doc => doc.querySelector( 'h1' ).innerHTML = 'greetings';
const wrapper = mount( <MarkupFrame markup="<h1>Hello World</h1>" onLoad={ onLoad } /> );
expect( wrapper.find( 'iframe' ).get( 0 ).innerHTML ).to.eql( '<h1>greetings</h1>' )
} );
} );
| Update tests to cover most common cases | Update tests to cover most common cases
They don't work, of course, because (I think) some mix of React, jsdom, and
iframes don't work correctly together.
| JavaScript | mit | sirbrillig/markup-frame | ---
+++
@@ -3,13 +3,20 @@
import { mount } from 'enzyme';
import MarkupFrame from '../src';
-describe( '<MarkupFrame />', () => {
- it( 'renders an iframe', () => {
+describe( '<MarkupFrame />', function() {
+ it( 'renders an iframe', function() {
const wrapper = mount( <MarkupFrame markup="" /> );
- expect( wrapper.some( 'iframe' ) ).to.equal( true );
+ expect( wrapper.find( 'iframe' ) ).to.have.length( 1 );
} );
- it( 'injects props.markup into the iframe' );
+ it( 'injects props.markup into the iframe', function() {
+ const wrapper = mount( <MarkupFrame markup="<h1>Hello World</h1>" /> );
+ expect( wrapper.find( 'iframe' ).get( 0 ).innerHTML ).to.eql( '<h1>Hello World</h1>' )
+ } );
- it( 'calls props.onLoad with the iframe document' );
+ it( 'calls props.onLoad with the iframe document', function() {
+ const onLoad = doc => doc.querySelector( 'h1' ).innerHTML = 'greetings';
+ const wrapper = mount( <MarkupFrame markup="<h1>Hello World</h1>" onLoad={ onLoad } /> );
+ expect( wrapper.find( 'iframe' ).get( 0 ).innerHTML ).to.eql( '<h1>greetings</h1>' )
+ } );
} ); |
9578954c6b1817ff7a8e8bfa0a4532835c8040e9 | client/js/app.js | client/js/app.js | console.log('Tokimeki Memorial'); | console.log('Tokimeki Memorial');
var host = window.document.location.host.replace(/:.*/, '');
var ws = new WebSocket('ws://' + host + ':8000');
ws.onmessage = function (event) {
//console.log(event);
//console.log(JSON.parse(event.data));
}; | Make WS connection in index page for testing purposes. | Make WS connection in index page for testing purposes.
| JavaScript | apache-2.0 | AI-comp/AILovers,AI-comp/AILovers,AI-comp/AILovers,AI-comp/AILovers,AI-comp/AILovers,AI-comp/AILovers | ---
+++
@@ -1 +1,9 @@
console.log('Tokimeki Memorial');
+
+var host = window.document.location.host.replace(/:.*/, '');
+var ws = new WebSocket('ws://' + host + ':8000');
+
+ws.onmessage = function (event) {
+ //console.log(event);
+ //console.log(JSON.parse(event.data));
+}; |
b8cf678c13325df71135b3e7cc5fc521a3a98b1b | polyfill/fetch.js | polyfill/fetch.js | import "mojave/polyfill/Promise";
import "unfetch/polyfill";
export default window.fetch;
| import "mojave/polyfill/promise";
import "unfetch/polyfill";
export default window.fetch;
| Fix case of promise polyfill | Fix case of promise polyfill
| JavaScript | bsd-3-clause | Becklyn/mojave,Becklyn/mojave,Becklyn/mojave | ---
+++
@@ -1,4 +1,4 @@
-import "mojave/polyfill/Promise";
+import "mojave/polyfill/promise";
import "unfetch/polyfill";
export default window.fetch; |
cc0a3c204f59e1039cad5b592d969fac30c40fbf | src/components/Members/MemberDetail.js | src/components/Members/MemberDetail.js | import React, { Component, PropTypes } from 'react';
class MembersDetail extends Component {
render() {
const {displayName} = this.props;
return (
<div>
<h1>{displayName}</h1>
</div>
);
}
}
MembersDetail.propTypes = {
displayName: PropTypes.string.isRequired,
};
export default MembersDetail;
| import React, { Component, PropTypes } from 'react';
class MembersDetail extends Component {
render() {
const {displayName, image} = this.props;
return (
<div>
<h1>{displayName}</h1>
<img src={image.uri} style={{
display: 'inline-block',
paddingRight: '10px',
}} />
</div>
);
}
}
MembersDetail.propTypes = {
displayName: PropTypes.string.isRequired,
image: PropTypes.shape({
uri: PropTypes.string.isRequired,
height: PropTypes.number,
width: PropTypes.number,
}),
intro: PropTypes.string,
slug: PropTypes.string.isRequired,
usState: PropTypes.string,
};
export default MembersDetail;
| Add image and proptypes for member detail page | Add image and proptypes for member detail page
| JavaScript | cc0-1.0 | cape-io/acf-client,cape-io/acf-client | ---
+++
@@ -3,10 +3,14 @@
class MembersDetail extends Component {
render() {
- const {displayName} = this.props;
+ const {displayName, image} = this.props;
return (
<div>
<h1>{displayName}</h1>
+ <img src={image.uri} style={{
+ display: 'inline-block',
+ paddingRight: '10px',
+ }} />
</div>
);
}
@@ -14,6 +18,14 @@
MembersDetail.propTypes = {
displayName: PropTypes.string.isRequired,
+ image: PropTypes.shape({
+ uri: PropTypes.string.isRequired,
+ height: PropTypes.number,
+ width: PropTypes.number,
+ }),
+ intro: PropTypes.string,
+ slug: PropTypes.string.isRequired,
+ usState: PropTypes.string,
};
export default MembersDetail; |
d794502bfcc0204aa7fdbe6d9f103a1099919718 | kolibri/core/assets/src/state/modules/snackbar.js | kolibri/core/assets/src/state/modules/snackbar.js | export default {
state: {
isVisible: false,
options: {
text: '',
autoDismiss: true,
},
},
getters: {
snackbarIsVisible(state) {
return state.isVisible;
},
snackbarOptions(state) {
return state.options;
},
},
mutations: {
CORE_CREATE_SNACKBAR(state, snackbarOptions = {}) {
// reset
state.isVisible = false;
state.options = {};
// set new options
state.isVisible = true;
state.options = snackbarOptions;
},
CORE_CLEAR_SNACKBAR(state) {
state.isVisible = false;
state.options = {};
},
CORE_SET_SNACKBAR_TEXT(state, text) {
state.options.text = text;
},
},
};
| export default {
state: {
isVisible: false,
options: {
text: '',
autoDismiss: true,
},
},
getters: {
snackbarIsVisible(state) {
return state.isVisible;
},
snackbarOptions(state) {
return state.options;
},
},
mutations: {
CORE_CREATE_SNACKBAR(state, snackbarOptions = {}) {
// reset
state.isVisible = false;
state.options = {};
// set new options
state.isVisible = true;
// options include text, autoDismiss, duration, actionText, actionCallback,
// hideCallback
state.options = snackbarOptions;
},
CORE_CLEAR_SNACKBAR(state) {
state.isVisible = false;
state.options = {};
},
CORE_SET_SNACKBAR_TEXT(state, text) {
state.options.text = text;
},
},
};
| Add comment about autodismiss options | Add comment about autodismiss options
| JavaScript | mit | lyw07/kolibri,indirectlylit/kolibri,mrpau/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,lyw07/kolibri,mrpau/kolibri,lyw07/kolibri,indirectlylit/kolibri,learningequality/kolibri,learningequality/kolibri,lyw07/kolibri | ---
+++
@@ -21,6 +21,8 @@
state.options = {};
// set new options
state.isVisible = true;
+ // options include text, autoDismiss, duration, actionText, actionCallback,
+ // hideCallback
state.options = snackbarOptions;
},
CORE_CLEAR_SNACKBAR(state) { |
23010015c762a1274597e2754d190fabad078cfe | src/components/SearchResultListItem.js | src/components/SearchResultListItem.js | import React from 'react';
import { connect } from 'react-redux';
const DocumentListItem = ({ title, collection, schema }) => (
<tr className={`result result--${schema}`}>
<td>{ title }</td>
<td className="result__collection">{ collection && collection.label }</td>
<td></td>
</tr>
);
const PersonListItem = ({ name, collection, schema }) => (
<tr className={`result result--${schema}`}>
<td className="result__name">{ name }</td>
<td className="result__collection">{ collection && collection.label }</td>
<td></td>
</tr>
);
const ListItems = {
'Document': DocumentListItem,
'Person': PersonListItem,
'LegalEntity': PersonListItem,
'Company': PersonListItem
};
const SearchResultListItem = ({ result, collection }) => {
const ListItem = ListItems[result.schema];
return <ListItem collection={collection} {...result} />;
};
const mapStateToProps = ({ collections }, { result }) => ({
collection: collections[result.collection_id]
});
export default connect(mapStateToProps)(SearchResultListItem);
| import React from 'react';
import { connect } from 'react-redux';
const DocumentListItem = ({ title, collection, schema }) => (
<tr className={`result result--${schema}`}>
<td>{ title }</td>
<td className="result__collection">{ collection && collection.label }</td>
<td></td>
</tr>
);
const PersonListItem = ({ name, collection, schema }) => (
<tr className={`result result--${schema}`}>
<td className="result__name">{ name }</td>
<td className="result__collection">
{ collection ?
collection.label :
<span className="pt-skeleton">Loading collection</span>
}
</td>
<td></td>
</tr>
);
const ListItems = {
'Document': DocumentListItem,
'Person': PersonListItem,
'LegalEntity': PersonListItem,
'Company': PersonListItem
};
const SearchResultListItem = ({ result, collection }) => {
const ListItem = ListItems[result.schema];
return <ListItem collection={collection} {...result} />;
};
const mapStateToProps = ({ collections }, { result }) => ({
collection: collections[result.collection_id]
});
export default connect(mapStateToProps)(SearchResultListItem);
| Add placeholder for loading collection names | Add placeholder for loading collection names
| JavaScript | mit | alephdata/aleph,alephdata/aleph,pudo/aleph,pudo/aleph,pudo/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph | ---
+++
@@ -12,7 +12,12 @@
const PersonListItem = ({ name, collection, schema }) => (
<tr className={`result result--${schema}`}>
<td className="result__name">{ name }</td>
- <td className="result__collection">{ collection && collection.label }</td>
+ <td className="result__collection">
+ { collection ?
+ collection.label :
+ <span className="pt-skeleton">Loading collection</span>
+ }
+ </td>
<td></td>
</tr>
); |
be3331f24e7693c41e012a2eb935d474de224f1f | frontend/web/js/main.js | frontend/web/js/main.js | $(document).ready(function() {
$('#global-modal-container').on('show.bs.modal', function (event) {
sourceUrl = $(event.relatedTarget).attr('href');
getGlobalModalHtml(sourceUrl);
});
});
function getGlobalModalHtml(url) {
$.ajax({
url: url,
type: "post",
success: function(returnData) {
$('#global-modal-container .modal-body').html(returnData);
headerHtml = $('#global-modal-container .modal-body .apc-modal-header')[0].outerHTML;
$('#global-modal-container .modal-body .apc-modal-header').remove();
$('#global-modal-container .modal-header .apc-modal-header').remove();
$('#global-modal-container .modal-header').prepend(headerHtml);
//alert('success');
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error loading Global Modal Container: ' + textStatus + ':' + errorThrown);
}
});
} | $(document).ready(function() {
$('#global-modal-container').on('show.bs.modal', function (event) {
sourceUrl = $(event.relatedTarget).attr('href');
getGlobalModalHtml(sourceUrl);
$('.tooltip').hide();
});
});
function getGlobalModalHtml(url) {
$.ajax({
url: url,
type: "post",
success: function(returnData) {
$('#global-modal-container .modal-body').html(returnData);
headerHtml = $('#global-modal-container .modal-body .apc-modal-header')[0].outerHTML;
$('#global-modal-container .modal-body .apc-modal-header').remove();
$('#global-modal-container .modal-header .apc-modal-header').remove();
$('#global-modal-container .modal-header').prepend(headerHtml);
//alert('success');
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error loading Global Modal Container: ' + textStatus + ':' + errorThrown);
}
});
} | Hide all tooltips when showing a modal window | Hide all tooltips when showing a modal window | JavaScript | bsd-3-clause | gooGooGaJoob/banthecan,gooGooGaJoob/banthecan,gooGooGaJoob/banthecan | ---
+++
@@ -2,6 +2,7 @@
$('#global-modal-container').on('show.bs.modal', function (event) {
sourceUrl = $(event.relatedTarget).attr('href');
getGlobalModalHtml(sourceUrl);
+ $('.tooltip').hide();
});
});
|
1faf99e332f94ab27fcef68f05ef8760c219bf4c | static-routes/stylesheets.js | static-routes/stylesheets.js | const sass = require('node-sass');
const path = require('path');
const config = require('../config');
const fs = require('fs');
const imdino = require('imdi-no');
const development = config.env === 'development';
module.exports = {
"/stylesheets/main.css": function (callback) {
const opts = {
file: path.join(__dirname, "/../stylesheets/main.scss"),
outFile: '/stylesheets/main.css',
includePaths: imdino.includePaths,
sourceMap: development,
sourceMapEmbed: development,
sourceMapContents: development,
sourceComments: development,
outputStyle: development ? 'nested' : 'compressed'
};
sass.render(opts, (err, result)=> {
if (err) {
return callback(err)
}
callback(null, result.css);
});
}
};
fs.readdirSync(imdino.paths.gfx).forEach(file => {
const fullPath = path.join(imdino.paths.gfx, file);
const httpPaths = [
path.join('/imdi-no/_themes/blank/gfx', file),
path.join('/gfx', file)
];
httpPaths.forEach(httpPath => {
module.exports[httpPath] = function() {
return fs.createReadStream(fullPath);
}
});
});
| const sass = require('node-sass');
const path = require('path');
const config = require('../config');
const fs = require('fs');
const imdino = require('imdi-no');
const development = config.env === 'development';
module.exports = {
"/stylesheets/main.css": function (callback) {
const opts = {
file: require.resolve("../stylesheets/main.scss"),
outFile: '/stylesheets/main.css',
includePaths: imdino.includePaths,
sourceMap: development,
sourceMapEmbed: development,
sourceMapContents: development,
sourceComments: development,
outputStyle: development ? 'nested' : 'compressed'
};
sass.render(opts, (err, result)=> {
if (err) {
return callback(err)
}
callback(null, result.css);
});
}
};
fs.readdirSync(imdino.paths.gfx).forEach(file => {
const fullPath = path.join(imdino.paths.gfx, file);
const httpPaths = [
path.join('/imdi-no/_themes/blank/gfx', file),
path.join('/gfx', file)
];
httpPaths.forEach(httpPath => {
module.exports[httpPath] = function() {
return fs.createReadStream(fullPath);
}
});
});
| Use require.resolve to locate main.scss | Use require.resolve to locate main.scss
| JavaScript | mit | bengler/imdikator,bengler/imdikator | ---
+++
@@ -10,7 +10,7 @@
"/stylesheets/main.css": function (callback) {
const opts = {
- file: path.join(__dirname, "/../stylesheets/main.scss"),
+ file: require.resolve("../stylesheets/main.scss"),
outFile: '/stylesheets/main.css',
includePaths: imdino.includePaths,
|
dc50cc1124f8c39b4000eba4d0914191ddd4245a | libs/oada-lib-arangodb/libs/exampledocs/tokens.js | libs/oada-lib-arangodb/libs/exampledocs/tokens.js | module.exports = [
{
"_key": "default:token-123",
"token": "xyz",
"scope": ["oada-rocks:all"],
"createTime": 1413831649937,
"expiresIn": 60,
"user": { "_id": "default:users-frank-123" },
"clientId": "jf93caauf3uzud7f308faesf3@provider.oada-dev.com"
}
];
| module.exports = [
{
"_key": "default:token-123",
"token": "xyz",
"scope": ["oada.rocks:all"],
"createTime": 1413831649937,
"expiresIn": 60,
"user": { "_id": "default:users-frank-123" },
"clientId": "jf93caauf3uzud7f308faesf3@provider.oada-dev.com"
}
];
| Add scope to token xyz. | Add scope to token xyz.
| JavaScript | apache-2.0 | OADA/oada-srvc-docker,OADA/oada-srvc-docker,OADA/oada-srvc-docker,OADA/oada-srvc-docker | ---
+++
@@ -2,7 +2,7 @@
{
"_key": "default:token-123",
"token": "xyz",
- "scope": ["oada-rocks:all"],
+ "scope": ["oada.rocks:all"],
"createTime": 1413831649937,
"expiresIn": 60,
"user": { "_id": "default:users-frank-123" }, |
ccd35fed533ac20783ccf70a09a81c1aaf611341 | templates/javascript/FluxAction.js | templates/javascript/FluxAction.js | 'use strict';
var <%= classedName %> = {
}
<% if (es6) { %> export default <%= classedName %>; <% }
else { %>module.exports = <%= classedName %>; <% } %>
| 'use strict';
var <%= classedName %> = {
};
<% if (es6) { %> export default <%= classedName %>; <% }
else { %>module.exports = <%= classedName %>; <% } %>
| Add missing semicolon to avoid warnings | Add missing semicolon to avoid warnings | JavaScript | mit | mattludwigs/generator-react-redux-kit,mattludwigs/generator-react-redux-kit,react-webpack-generators/generator-react-webpack,newtriks/generator-react-webpack | ---
+++
@@ -2,7 +2,7 @@
var <%= classedName %> = {
-}
+};
<% if (es6) { %> export default <%= classedName %>; <% }
else { %>module.exports = <%= classedName %>; <% } %> |
bd5644d859ccb3639666afe46fda03d3610bb374 | public/modules/slideshows/services/slideshows.client.service.js | public/modules/slideshows/services/slideshows.client.service.js | /*global angular*/
(function () {
'use strict';
//Slideshows service used to communicate Slideshows REST endpoints
angular.module('slideshows').factory('Slideshows', ['$resource',
function ($resource) {
return $resource('slideshows/:slideshowId',
{ slideshowId: '@_id' },
{ update:
{method: 'PUT'}
});
}]);
}());
| /*global angular*/
(function () {
'use strict';
//Slideshows service used to communicate Slideshows REST endpoints
angular.module('slideshows').factory('Slideshows', ['$resource',
function ($resource) {
return $resource('slideshows/:slideshowId', {
slideshowId: '@_id'
}, {
update: {
method: 'PUT'
},
getDevices: {
method: 'GET',
url: 'slideshowDevices/:slideshowId',
isArray: true,
params: {name: '@name'}
},
setDevices: {
method: 'PUT',
url: 'slideshowDevices/:slideshowId'
}
});
}]);
}());
| Add name as parameter when geting devices for a slideshow | Add name as parameter when geting devices for a slideshow
| JavaScript | mit | tmol/iQSlideShow,tmol/iQSlideShow,tmol/iQSlideShow | ---
+++
@@ -5,10 +5,22 @@
//Slideshows service used to communicate Slideshows REST endpoints
angular.module('slideshows').factory('Slideshows', ['$resource',
function ($resource) {
- return $resource('slideshows/:slideshowId',
- { slideshowId: '@_id' },
- { update:
- {method: 'PUT'}
- });
+ return $resource('slideshows/:slideshowId', {
+ slideshowId: '@_id'
+ }, {
+ update: {
+ method: 'PUT'
+ },
+ getDevices: {
+ method: 'GET',
+ url: 'slideshowDevices/:slideshowId',
+ isArray: true,
+ params: {name: '@name'}
+ },
+ setDevices: {
+ method: 'PUT',
+ url: 'slideshowDevices/:slideshowId'
+ }
+ });
}]);
}()); |
dbee31c17ab6f6376683e97cb1904820d37fcd65 | website/src/html.js | website/src/html.js | import React from 'react'
import PropTypes from 'prop-types'
export default function HTML(props) {
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css"
/>
{props.headComponents}
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<noscript key="noscript" id="gatsby-noscript">
This app works best with JavaScript enabled.
</noscript>
<div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: props.body }} />
{props.postBodyComponents}
</body>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js"
/>
</html>
)
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
| import React from 'react'
import PropTypes from 'prop-types'
export default function HTML(props) {
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{props.headComponents}
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css"
/>
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<noscript key="noscript" id="gatsby-noscript">
This app works best with JavaScript enabled.
</noscript>
<div key={`body`} id="___gatsby" dangerouslySetInnerHTML={{ __html: props.body }} />
{props.postBodyComponents}
</body>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js"
/>
</html>
)
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
| Revert "Move DocSearch styles before headComponents" | Revert "Move DocSearch styles before headComponents"
This reverts commit 1232ccbc0ff6c5d9e80de65cefb352c404973e2f.
| JavaScript | mit | spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,honnibal/spaCy | ---
+++
@@ -11,11 +11,11 @@
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
+ {props.headComponents}
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css"
/>
- {props.headComponents}
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents} |
b8f6446ee6a1eb0a149a4f69182f2004b09500ea | app/angular/controllers/games_controller.js | app/angular/controllers/games_controller.js | 'use strict';
module.exports = function(app) {
app.controller('GamesController', ['$scope', 'UserService', 'FriendService', 'GameService', 'SearchService', function($scope, UserService, FriendService, GameService, SearchService) {
let ctrl = this;
$scope.FriendService = FriendService;
$scope.allFriends = FriendService.data.allFriends;
ctrl.user = UserService.data.user;
ctrl.players = [];
ctrl.creating = false;
ctrl.editing = false;
ctrl.createGame = function(gameData) {
gameData.players = ctrl.players;
GameService.createGame(gameData)
.catch((err) => {
console.log('Error creating game.');
});
};
ctrl.addUserToGame = function(user) {
ctrl.players.push(user);
};
ctrl.removePlayer = function(user) {
let playersArray = ctrl.game.players;
let userIndex = playersArray.indexOf(user);
ctrl.friendsList.push(playersArray[userIndex]);
playersArray.splice(userIndex, 1);
};
ctrl.initCreate = function() {
let userData = {
_id: ctrl.user._id,
fullName: ctrl.user.fullName,
email: ctrl.user.email,
};
FriendService.getAllFriends(ctrl.user.email);
ctrl.players.push(userData);
ctrl.creating = true;
};
ctrl.init = function() {
};
// ctrl.init();
}]);
};
| 'use strict';
module.exports = function(app) {
app.controller('GamesController', ['$scope', 'UserService', 'FriendService', 'GameService', 'SearchService', function($scope, UserService, FriendService, GameService, SearchService) {
let ctrl = this;
$scope.FriendService = FriendService;
$scope.allFriends = FriendService.data.allFriends;
ctrl.user = UserService.data.user;
ctrl.players = [];
ctrl.creating = false;
ctrl.editing = false;
ctrl.createGame = function(gameData) {
gameData.players = ctrl.players;
GameService.createGame(gameData);
};
ctrl.addUserToGame = function(user) {
ctrl.players.push(user);
};
ctrl.removePlayer = function(user) {
let playersArray = ctrl.game.players;
let userIndex = playersArray.indexOf(user);
ctrl.friendsList.push(playersArray[userIndex]);
playersArray.splice(userIndex, 1);
};
ctrl.initCreate = function() {
let userData = {
_id: ctrl.user._id,
fullName: ctrl.user.fullName,
email: ctrl.user.email,
};
FriendService.getAllFriends(ctrl.user.email);
ctrl.players.push(userData);
ctrl.creating = true;
};
ctrl.init = function() {
};
// ctrl.init();
}]);
};
| Remove catch from createGame method. Errors are handled by service layer of app. | Remove catch from createGame method. Errors are handled by service layer of app.
| JavaScript | mit | sendjmoon/GolfFourFriends,sendjmoon/GolfFourFriends | ---
+++
@@ -14,10 +14,7 @@
ctrl.createGame = function(gameData) {
gameData.players = ctrl.players;
- GameService.createGame(gameData)
- .catch((err) => {
- console.log('Error creating game.');
- });
+ GameService.createGame(gameData);
};
ctrl.addUserToGame = function(user) { |
2acffe782320c79648816c3a181138b71babb60c | config/webpack.common.js | config/webpack.common.js | const webpack = require('webpack');
const helpers = require('./helpers');
module.exports = {
entry: {
'index': './src/index.js',
// 'test': './src/test.js'
},
output: {
path: helpers.root('dist'),
filename: '[name].js',
chunkFilename: '[id].chunk.js',
libraryTarget: 'umd',
library: 'Servable',
},
performance: {
hints: false
},
resolve: {
extensions: ['*', '.js'],
modules: [helpers.root('node_modules')],
},
resolveLoader: {
modules: [helpers.root('node_modules')]
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: [['es2015', {modules: false, loose: true}], 'stage-0'],
}
},
include: helpers.root('src')
},
]
},
};
| const webpack = require('webpack');
const helpers = require('./helpers');
module.exports = {
entry: {
'index': './src/index.js',
// 'test': './src/test.js'
},
output: {
path: helpers.root('dist'),
filename: '[name].js',
chunkFilename: '[id].chunk.js',
libraryTarget: 'umd',
library: 'Servable',
umdNamedDefine: true,
},
performance: {
hints: false
},
resolve: {
extensions: ['*', '.js'],
modules: [helpers.root('node_modules')],
},
resolveLoader: {
modules: [helpers.root('node_modules')]
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: [['es2015', {modules: false, loose: true}], 'stage-0'],
}
},
include: helpers.root('src')
},
]
},
};
| Update UMD Named define to true | Update UMD Named define to true
| JavaScript | mit | maniator/servable,maniator/servable | ---
+++
@@ -13,6 +13,7 @@
chunkFilename: '[id].chunk.js',
libraryTarget: 'umd',
library: 'Servable',
+ umdNamedDefine: true,
},
performance: { |
fc2c58045d1015187ab6c9cad4532238e6c90736 | next-migrations/src/migrations/20180605215102_users.js | next-migrations/src/migrations/20180605215102_users.js | exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('next_users', table => {
table.bigIncrements()
table.string('email')
table.string('name')
table.string('password')
table.string('origin')
table.string('baseurl')
table.string('phone')
table.boolean('isVerified')
table.string('verifyToken')
table.string('verifyShortToken')
table.bigint('verifyExpires')
table.json('verifyChanges')
table.string('resetToken')
table.string('resetShortToken')
table.bigint('resetExpires')
table.timestamps()
table.unique(['email'])
})
])
}
exports.down = function(knex, Promise) {}
| exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable('next_users', table => {
table.bigIncrements()
table.string('email')
table.string('name')
table.string('password')
table.string('origin')
table.string('baseurl')
table.string('phone')
table.boolean('isVerified')
table.string('verifyToken')
table.string('verifyShortToken')
table.timestamp('verifyExpires')
table.json('verifyChanges')
table.string('resetToken')
table.string('resetShortToken')
table.timestamp('resetExpires')
table.timestamps()
table.unique(['email'])
})
])
}
exports.down = function(knex, Promise) {}
| Revert to using timestamps in database. | TeikeiNext: Revert to using timestamps in database.
| JavaScript | agpl-3.0 | teikei/teikei,teikei/teikei,teikei/teikei | ---
+++
@@ -11,11 +11,11 @@
table.boolean('isVerified')
table.string('verifyToken')
table.string('verifyShortToken')
- table.bigint('verifyExpires')
+ table.timestamp('verifyExpires')
table.json('verifyChanges')
table.string('resetToken')
table.string('resetShortToken')
- table.bigint('resetExpires')
+ table.timestamp('resetExpires')
table.timestamps()
table.unique(['email'])
}) |
aecf231cb6310fba9af5a07ffbcced2e084a799d | config/ember-try.js | config/ember-try.js | module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
| module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember 1.13',
dependencies: {
'ember': '1.13.8'
},
resolutions: {
'ember': '1.13.8'
}
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
| Add 1.13 to the test matrix | Add 1.13 to the test matrix
| JavaScript | mit | cibernox/ember-power-select,chrisgame/ember-power-select,cibernox/ember-power-select,cibernox/ember-power-select,Dremora/ember-power-select,chrisgame/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,esbanarango/ember-power-select,Dremora/ember-power-select,esbanarango/ember-power-select | ---
+++
@@ -3,6 +3,15 @@
{
name: 'default',
dependencies: { }
+ },
+ {
+ name: 'ember 1.13',
+ dependencies: {
+ 'ember': '1.13.8'
+ },
+ resolutions: {
+ 'ember': '1.13.8'
+ }
},
{
name: 'ember-release', |
38aa4dc763e6903cce4ee66c4cbdfdd104b05cd7 | config/processes.js | config/processes.js | 'use strict';
const config = {};
/**
* Heroku makes it available to help calculate correct concurrency
* @see https://devcenter.heroku.com/articles/node-concurrency#tuning-the-concurrency-level
*/
config.memoryAvailable = parseInt(process.env.MEMORY_AVAILABLE, 10);
/**
* Expected MAX memory footprint of a single concurrent process in Megabytes.
*
* NOTE: This value is the basis to calculate the Procfile server flag: --max_old_space_size=<size>
* The value in the Procfile is 90% of the estimated processMemory here.
* Based on a Heroku recommendation. @see https://blog.heroku.com/node-habits-2016#7-avoid-garbage
*/
config.processMemory = 200;
/**
* Calculate total amount of concurrent processes to fork
* based on available memory and estimated process memory footprint
*/
config.total = config.memoryAvailable ?
Math.floor(config.memoryAvailable / config.processMemory) : 1;
module.exports = config;
| 'use strict';
const config = {};
/**
* Heroku makes it available to help calculate correct concurrency
* @see https://devcenter.heroku.com/articles/node-concurrency#tuning-the-concurrency-level
*/
config.memoryAvailable = parseInt(process.env.MEMORY_AVAILABLE, 10);
/**
* Expected MAX memory footprint of a single concurrent process in Megabytes.
*
* NOTE: This value is the basis to calculate the Procfile server flag: --max_old_space_size=<size>
* The value in the Procfile is 90% of the estimated processMemory here.
* Based on a Heroku recommendation. @see https://blog.heroku.com/node-habits-2016#7-avoid-garbage
*/
config.processMemory = 170;
/**
* Calculate total amount of concurrent processes to fork
* based on available memory and estimated process memory footprint
*/
config.total = config.memoryAvailable ?
Math.floor(config.memoryAvailable / config.processMemory) : 1;
module.exports = config;
| Load test 170 per process | Load test 170 per process
| JavaScript | mit | DoSomething/gambit,DoSomething/gambit | ---
+++
@@ -13,7 +13,7 @@
* The value in the Procfile is 90% of the estimated processMemory here.
* Based on a Heroku recommendation. @see https://blog.heroku.com/node-habits-2016#7-avoid-garbage
*/
-config.processMemory = 200;
+config.processMemory = 170;
/**
* Calculate total amount of concurrent processes to fork
* based on available memory and estimated process memory footprint |
405acc213c0861d4aab21a568c5419d4a48a2b57 | test/testHelper.js | test/testHelper.js | require("babel/register")({
stage: 1,
ignore: /node_modules/
});
global.Promise = require('bluebird')
global.Promise.onPossiblyUnhandledRejection((e) => { throw e; });
global.Promise.config({
// Enable warnings.
warnings: false,
// Enable long stack traces.
longStackTraces: true,
// Enable cancellation.
cancellation: true
});
GLOBAL.$redis = require('../config/database')
, GLOBAL.$database = $redis.connect()
, GLOBAL.$should = require('chai').should()
| require("babel/register")({
stage: 1,
ignore: /node_modules/
});
global.Promise = require('bluebird')
global.Promise.onPossiblyUnhandledRejection((e) => { throw e; });
global.Promise.config({
// Enable warnings.
warnings: false,
// Enable long stack traces.
longStackTraces: true,
// Enable cancellation.
cancellation: true
});
GLOBAL.$redis = require('../config/database')
, GLOBAL.$database = $redis.connect()
, GLOBAL.$should = require('chai').should()
, GLOBAL.$postgres = require('../config/postgres')
, GLOBAL.$pg_database = $postgres.connect()
| Add postgres connection and knex to global test variables. | Add postgres connection and knex to global test variables.
| JavaScript | mit | golozubov/freefeed-server,golozubov/freefeed-server,SiTLar/freefeed-server,FreeFeed/freefeed-server,FreeFeed/freefeed-server,SiTLar/freefeed-server | ---
+++
@@ -18,3 +18,5 @@
GLOBAL.$redis = require('../config/database')
, GLOBAL.$database = $redis.connect()
, GLOBAL.$should = require('chai').should()
+ , GLOBAL.$postgres = require('../config/postgres')
+ , GLOBAL.$pg_database = $postgres.connect() |
79865e36fa70a52d04f586b24da14a216b883432 | test/media-test.js | test/media-test.js | /* Global Includes */
var testCase = require('mocha').describe;
var pre = require('mocha').before;
var preEach = require('mocha').beforeEach;
var post = require('mocha').after;
var postEach = require('mocha').afterEach;
var assertions = require('mocha').it;
var assert = require('chai').assert;
var validator = require('validator');
var exec = require('child_process').execSync;
var artik = require('../lib/artik-sdk');
/* Test Specific Includes */
var media = artik.media();
var sound_file = '/usr/share/sounds/alsa/Front_Center.wav';
/* Test Case Module */
testCase('Media', function() {
pre(function() {
});
testCase('#play_sound_file', function() {
assertions('Play the sound file', function() {
media.play_sound_file(sound_file, function(response, status) {
console.log('Finished playing');
});
});
});
post(function() {
});
});
| /* Global Includes */
var testCase = require('mocha').describe;
var pre = require('mocha').before;
var preEach = require('mocha').beforeEach;
var post = require('mocha').after;
var postEach = require('mocha').afterEach;
var assertions = require('mocha').it;
var assert = require('chai').assert;
var validator = require('validator');
var exec = require('child_process').execSync;
var artik = require('../lib/artik-sdk');
/* Test Specific Includes */
var media = artik.media();
var sound_file = '/usr/share/sounds/alsa/Front_Center.wav';
var start, end;
/* Test Case Module */
testCase('Media', function() {
pre(function() {
});
testCase('#play_sound_file', function() {
this.timeout(5000);
start = new Date();
assertions('Play the sound file', function(done) {
media.play_sound_file(sound_file, function(response, status) {
end = new Date();
var timeOfPlay = (end.getTime() - start.getTime())/1000;
console.log('Finished playing. Seconds ' + timeOfPlay);
assert.isAtLeast(timeOfPlay, 1);
done();
});
});
});
post(function() {
});
});
| Use time duration of test to measure the success | Media: Use time duration of test to measure the success
Signed-off-by: Vaibhav Singh <c267fbcdc94c01eb807238c388b92f321583d99b@samsung.com>
| JavaScript | mit | hoondol/artik-sdk,hoondol/artik-sdk | ---
+++
@@ -14,6 +14,7 @@
/* Test Specific Includes */
var media = artik.media();
var sound_file = '/usr/share/sounds/alsa/Front_Center.wav';
+var start, end;
/* Test Case Module */
testCase('Media', function() {
@@ -22,10 +23,17 @@
});
testCase('#play_sound_file', function() {
+ this.timeout(5000);
+ start = new Date();
- assertions('Play the sound file', function() {
+ assertions('Play the sound file', function(done) {
+
media.play_sound_file(sound_file, function(response, status) {
- console.log('Finished playing');
+ end = new Date();
+ var timeOfPlay = (end.getTime() - start.getTime())/1000;
+ console.log('Finished playing. Seconds ' + timeOfPlay);
+ assert.isAtLeast(timeOfPlay, 1);
+ done();
});
});
|
a16b17307bd5658f6ce9eaea4002e7860cea908b | webpack.config.js | webpack.config.js | // Copyright 2018 Google LLC
//
// 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
//
// <https://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.
const fs = require("fs");
const path = require("path");
module.exports = fs
.readdirSync("src")
.filter(filename => filename.endsWith(".js"))
.map(filename => ({
context: path.resolve("src"),
entry: `./${filename}`,
output: {
filename,
path: path.resolve("dist")
},
optimization: {
minimize: false
}
}));
| // Copyright 2018 Google LLC
//
// 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
//
// <https://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.
const fs = require("fs");
const path = require("path");
const webpack = require("webpack");
module.exports = fs
.readdirSync("src")
.filter(filename => filename.endsWith(".js"))
.map(filename => ({
context: path.resolve("src"),
entry: `./${filename}`,
output: {
filename,
path: path.resolve("dist")
},
optimization: {
minimize: false
},
plugins: [
new webpack.BannerPlugin({
banner:
"// Required for JavaScript engine shells.\n" +
"if (typeof console === 'undefined') {\n" +
" console = {log: print};\n" +
"}",
raw: true
})
]
}));
| Support older JavaScript engine shells. | Support older JavaScript engine shells.
| JavaScript | apache-2.0 | v8/promise-performance-tests | ---
+++
@@ -14,6 +14,7 @@
const fs = require("fs");
const path = require("path");
+const webpack = require("webpack");
module.exports = fs
.readdirSync("src")
@@ -27,5 +28,15 @@
},
optimization: {
minimize: false
- }
+ },
+ plugins: [
+ new webpack.BannerPlugin({
+ banner:
+ "// Required for JavaScript engine shells.\n" +
+ "if (typeof console === 'undefined') {\n" +
+ " console = {log: print};\n" +
+ "}",
+ raw: true
+ })
+ ]
})); |
d251916fa362ce6064bbcef28eaa009294e2271a | app/components/summer-note.js | app/components/summer-note.js | /*
This is just a proxy file requiring the component from the /addon folder and
making it available to the dummy application!
*/
import SummerNoteComponent from 'ember-cli-bootstrap3-wysiwyg/components/bs-wysihtml5';
export default SummerNoteComponent; | /*
This is just a proxy file requiring the component from the /addon folder and
making it available to the dummy application!
*/
import SummerNoteComponent from 'ember-cli-summernote/components/summer-note';
export default SummerNoteComponent; | Fix the import path error. | Fix the import path error.
| JavaScript | mit | Flightlogger/ember-cli-summernote,brett-anderson/ember-cli-summernote,vsymguysung/ember-cli-summernote,Flightlogger/ember-cli-summernote,wzowee/ember-cli-summernote,wzowee/ember-cli-summernote,emoryy/ember-cli-summernote,vsymguysung/ember-cli-summernote,emoryy/ember-cli-summernote,brett-anderson/ember-cli-summernote | ---
+++
@@ -2,6 +2,6 @@
This is just a proxy file requiring the component from the /addon folder and
making it available to the dummy application!
*/
-import SummerNoteComponent from 'ember-cli-bootstrap3-wysiwyg/components/bs-wysihtml5';
+import SummerNoteComponent from 'ember-cli-summernote/components/summer-note';
export default SummerNoteComponent; |
9a521faa76fd26b762f7b45096d5dc8ec1608429 | assets/js/vendor/sb-admin-2.js | assets/js/vendor/sb-admin-2.js | $(function() {
$('#side-menu').metisMenu();
});
//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(function() {
$(window).bind("load resize", function() {
topOffset = 50;
width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
if (width < 768) {
$('div.navbar-collapse').addClass('collapse');
topOffset = 100; // 2-row-menu
} else {
$('div.navbar-collapse').removeClass('collapse');
}
height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1;
height = height - topOffset;
if (height < 1) height = 1;
if (height > topOffset) {
$("#page-wrapper").css("min-height", (height) + "px");
}
});
var url = window.location;
var element = $('ul.nav a').filter(function() {
return this.href == url;
}).addClass('active').parent().parent().addClass('in').parent();
if (element.is('li')) {
element.addClass('active');
}
});
| $(function() {
$('#side-menu').metisMenu();
});
//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(function() {
$(window).bind("load resize", function() {
topOffset = 50;
width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
if (width < 768) {
$('div.navbar-collapse').addClass('collapse');
topOffset = 100; // 2-row-menu
} else {
$('div.navbar-collapse').removeClass('collapse');
}
height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1;
height = height - topOffset;
if (height < 1) height = 1;
if (height > topOffset) {
$("#page-wrapper").css("min-height", (height) + "px");
}
});
var url = window.location;
var element = $('ul.nav a').filter(function() {
return this.href == url || url.href.indexOf(this.href) == 0;
}).addClass('active').parent().parent().addClass('in').parent();
if (element.is('li')) {
element.addClass('active');
}
});
| Fix highlighting of menu points for sub-routes. | Fix highlighting of menu points for sub-routes.
| JavaScript | mit | kumpelblase2/modlab,kumpelblase2/modlab | ---
+++
@@ -28,7 +28,7 @@
var url = window.location;
var element = $('ul.nav a').filter(function() {
- return this.href == url;
+ return this.href == url || url.href.indexOf(this.href) == 0;
}).addClass('active').parent().parent().addClass('in').parent();
if (element.is('li')) {
element.addClass('active'); |
3ba0a0fd6bacacb7328fbab9ef335d7697ebb1cb | js/lowlight.js | js/lowlight.js | "use strict";
/*
NOT a general purpose escaper! Only valid when *content* of a tag, not within an attribute.
*/
function escape(code) {
return code
.replace("&", "&", "g")
.replace("<", "<", "g")
.replace(">", ">", "g");
}
function lowlight(lang, lexer, code) {
var ret = "";
var lex = lexer.CeylonLexer(lexer.StringCharacterStream(code));
var cur;
while ((cur = lex.nextToken()) != null) {
if (cur.type.string == "whitespace") {
/*
don’t put whitespace in a span –
this way, styles can use CSS selectors
based on the immediately previous node
without worrying about whitespace
*/
ret += cur.text;
} else {
ret += "<span class=\"";
for (var type in cur.type.__proto__.getT$all()) {
if (type === undefined) break;
ret += type.replace(/.*:/, "");
if (type == "ceylon.lexer.core::TokenType") break;
ret += " ";
}
ret += "\">";
ret += escape(cur.text);
ret += "</span>";
}
}
return ret;
}
| "use strict";
/*
NOT a general purpose escaper! Only valid when *content* of a tag, not within an attribute.
*/
function escape(code) {
return code
.replace("&", "&", "g")
.replace("<", "<", "g")
.replace(">", ">", "g");
}
function lowlight(lang, lexer, code) {
var ret = "";
var lex = lexer.CeylonLexer(lexer.StringCharacterStream(code));
var cur;
while ((cur = lex.nextToken()) != null) {
if (cur.type.string == "whitespace") {
/*
don’t put whitespace in a span –
this way, styles can use CSS selectors
based on the immediately previous node
without worrying about whitespace
*/
ret += cur.text;
} else {
ret += "<span class=\"";
for (var type in cur.type.__proto__.getT$all()) {
if (type === undefined) break;
ret += type.replace(/.*:/, "");
if (type == "ceylon.lexer.core::TokenType") break;
ret += " ";
}
var escaped = escape(cur.text);
ret += "\" content=\"";
ret += escaped;
ret += "\">";
ret += escaped;
ret += "</span>";
}
}
return ret;
}
| Add span content as content attribute | Add span content as content attribute
This allows styles to use it in CSS `.foo[content*=bar]` selectors.
| JavaScript | apache-2.0 | lucaswerkmeister/ColorTrompon,lucaswerkmeister/ColorTrompon | ---
+++
@@ -31,8 +31,11 @@
if (type == "ceylon.lexer.core::TokenType") break;
ret += " ";
}
+ var escaped = escape(cur.text);
+ ret += "\" content=\"";
+ ret += escaped;
ret += "\">";
- ret += escape(cur.text);
+ ret += escaped;
ret += "</span>";
}
} |
707e854d6213dd9580c22a08a7e694f3923c723d | src/url_handler.js | src/url_handler.js | import { flashURLHandler } from './urlhandlers/flash_url_handler';
import { nodeURLHandler } from './urlhandlers/mock_node_url_handler';
import { XHRURLHandler } from './urlhandlers/xhr_url_handler';
function get(url, options, cb) {
// Allow skip of the options param
if (!cb) {
if (typeof options === 'function') {
cb = options;
}
options = {};
}
if (options.urlhandler && options.urlhandler.supported()) {
// explicitly supply your own URLHandler object
return options.urlhandler.get(url, options, cb);
} else if (typeof window === 'undefined' || window === null) {
return nodeURLHandler.get(url, options, cb);
} else if (XHRURLHandler.supported()) {
return XHRURLHandler.get(url, options, cb);
} else if (flashURLHandler.supported()) {
return flashURLHandler.get(url, options, cb);
} else {
return cb(
new Error(
'Current context is not supported by any of the default URLHandlers. Please provide a custom URLHandler'
)
);
}
}
export const urlHandler = {
get
};
| import { flashURLHandler } from './urlhandlers/flash_url_handler';
import { nodeURLHandler } from './urlhandlers/mock_node_url_handler';
import { XHRURLHandler } from './urlhandlers/xhr_url_handler';
function get(url, options, cb) {
// Allow skip of the options param
if (!cb) {
if (typeof options === 'function') {
cb = options;
}
options = {};
}
if (typeof window === 'undefined' || window === null) {
return nodeURLHandler.get(url, options, cb);
} else if (XHRURLHandler.supported()) {
return XHRURLHandler.get(url, options, cb);
} else if (flashURLHandler.supported()) {
return flashURLHandler.get(url, options, cb);
} else {
return cb(
new Error(
'Current context is not supported by any of the default URLHandlers. Please provide a custom URLHandler'
)
);
}
}
export const urlHandler = {
get
};
| Remove useless check from default urlhandler | [util] Remove useless check from default urlhandler
| JavaScript | mit | dailymotion/vast-client-js | ---
+++
@@ -11,10 +11,7 @@
options = {};
}
- if (options.urlhandler && options.urlhandler.supported()) {
- // explicitly supply your own URLHandler object
- return options.urlhandler.get(url, options, cb);
- } else if (typeof window === 'undefined' || window === null) {
+ if (typeof window === 'undefined' || window === null) {
return nodeURLHandler.get(url, options, cb);
} else if (XHRURLHandler.supported()) {
return XHRURLHandler.get(url, options, cb); |
f5078515f9eea811adb79def7748350c37306c0a | packages/react-hot-boilerplate/webpack.config.js | packages/react-hot-boilerplate/webpack.config.js | var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./scripts/index'
],
output: {
path: __dirname + '/scripts/',
filename: 'bundle.js',
publicPath: '/scripts/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{ test: /\.jsx?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }
]
}
};
| var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./scripts/index'
],
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/scripts/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'scripts')
}]
}
};
| Use include over exclude so npm link works | Use include over exclude so npm link works
| JavaScript | mit | gaearon/react-hot-loader,gaearon/react-hot-loader | ---
+++
@@ -1,3 +1,4 @@
+var path = require('path');
var webpack = require('webpack');
module.exports = {
@@ -8,7 +9,7 @@
'./scripts/index'
],
output: {
- path: __dirname + '/scripts/',
+ path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/scripts/'
},
@@ -20,8 +21,10 @@
extensions: ['', '.js', '.jsx']
},
module: {
- loaders: [
- { test: /\.jsx?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }
- ]
+ loaders: [{
+ test: /\.jsx?$/,
+ loaders: ['react-hot', 'babel'],
+ include: path.join(__dirname, 'scripts')
+ }]
}
}; |
fa03a474f29e26078d0a9cd8700eca18c3107e50 | js/stopwatch.js | js/stopwatch.js | (function(stopwatch){
var Game = stopwatch.Game = function(seconds){
this.target = 1000 * seconds; // in milliseconds
};
Game.prototype.current = function(){
return 0;
};
};
var GameView = stopwatch.GameView = function(game, container){
this.game = game;
this.container = container;
this.update();
};
GameView.prototype.update = function(){
var target = this.container.querySelector('#target');
target.innerHTML = this.game.target;
var current = this.container.querySelector('#current');
current.innerHTML = this.game.current();
};
})(window.stopwatch = window.stopwatch || {});
| (function(stopwatch){
var Game = stopwatch.Game = function(seconds){
this.target = 1000 * seconds; // in milliseconds
this.started = false;
this.stopped = false;
};
Game.prototype.current = function(){
if (this.started) {
return (this.stopped ? this.stopTime: this.time) - this.startTime;
}
return 0;
};
Game.prototype.start = function(){
if (!this.started) {
this.started = true;
this.startTime = new Date().getTime();
this.time = this.startTime;
}
};
Game.prototype.stop = function(){
if (!this.stopped) {
this.stopped = true;
this.stopTime = new Date().getTime();
}
};
var GameView = stopwatch.GameView = function(game, container){
this.game = game;
this.container = container;
this.update();
};
GameView.prototype.update = function(){
var target = this.container.querySelector('#target');
target.innerHTML = this.game.target;
var current = this.container.querySelector('#current');
current.innerHTML = this.game.current();
};
})(window.stopwatch = window.stopwatch || {});
| Create a start and stop method | Create a start and stop method
| JavaScript | mit | dvberkel/StopWatch,dvberkel/StopWatch | ---
+++
@@ -1,10 +1,27 @@
(function(stopwatch){
var Game = stopwatch.Game = function(seconds){
this.target = 1000 * seconds; // in milliseconds
+ this.started = false;
+ this.stopped = false;
};
Game.prototype.current = function(){
+ if (this.started) {
+ return (this.stopped ? this.stopTime: this.time) - this.startTime;
+ }
return 0;
};
+ Game.prototype.start = function(){
+ if (!this.started) {
+ this.started = true;
+ this.startTime = new Date().getTime();
+ this.time = this.startTime;
+ }
+ };
+ Game.prototype.stop = function(){
+ if (!this.stopped) {
+ this.stopped = true;
+ this.stopTime = new Date().getTime();
+ }
};
var GameView = stopwatch.GameView = function(game, container){ |
3c9cf063b0578c85362a81d76b5e84bb6faae9b2 | const_and_let.js | const_and_let.js | #!/usr/bin/env node
const constMessage = "Hello, World!";
console.log(constMessage);
let letMessage = "Hello, World!";
console.log(letMessage);
letMessage = "Goodbye, World!";
console.log(letMessage);
| #!/usr/bin/env node
const constMessage = "Hello, World!";
console.log(constMessage);
let letMessage = "Hello, World!";
console.log(letMessage);
letMessage = "Goodbye, World!";
console.log(letMessage);
const é = "Accented";
console.log(é);
const 学习 = "Learn";
console.log(学习);
// const ∃ = "There exists"; CRASH
// const 💹 = "Market"; CRASH
// const 😱 = "Eep!"; CRASH
| Add weird variable names to let and const example | Add weird variable names to let and const example
| JavaScript | apache-2.0 | peopleware/js-training-node-scripting,peopleware/js-training-node-scripting | ---
+++
@@ -7,3 +7,11 @@
console.log(letMessage);
letMessage = "Goodbye, World!";
console.log(letMessage);
+
+const é = "Accented";
+console.log(é);
+const 学习 = "Learn";
+console.log(学习);
+// const ∃ = "There exists"; CRASH
+// const 💹 = "Market"; CRASH
+// const 😱 = "Eep!"; CRASH |
06f6f2ff1dc60897f707e8a482a8ff1084ae8f7a | src/components/user/repo/trashbin.repo.js | src/components/user/repo/trashbin.repo.js | const { model: trashbinModel } = require('./db/trashbin.schema');
const createUserTrashbin = (userId) => {
// access trashbin model
const trashbin = trashbinModel({
userId,
});
return trashbin.save();
};
const updateUserTrashbin = (userId, data = {}) => {
// access trashbin model
return trashbinModel.updateOne({ userId }, data, { upsert: true });
};
module.exports = {
createUserTrashbin,
updateUserTrashbin,
};
| const { model: trashbinModel } = require('./db/trashbin.schema');
const createUserTrashbin = (userId) => {
// access trashbin model
const trashbin = trashbinModel({
userId,
});
return trashbin.save();
};
const updateUserTrashbin = async (id, data = {}) => {
// access trashbin model
const trashbin = await trashbinModel.findById(id).exec();
trashbin.set(data);
return trashbin.save();
};
module.exports = {
createUserTrashbin,
updateUserTrashbin,
};
| Use Mongoose functions for updating | Use Mongoose functions for updating
| JavaScript | agpl-3.0 | schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server | ---
+++
@@ -8,9 +8,11 @@
return trashbin.save();
};
-const updateUserTrashbin = (userId, data = {}) => {
+const updateUserTrashbin = async (id, data = {}) => {
// access trashbin model
- return trashbinModel.updateOne({ userId }, data, { upsert: true });
+ const trashbin = await trashbinModel.findById(id).exec();
+ trashbin.set(data);
+ return trashbin.save();
};
module.exports = { |
2f5b013afcc40bd90ba26aed33c9c5c142237016 | packages/soya-next/src/pages/createBasePage.js | packages/soya-next/src/pages/createBasePage.js | import React from "react";
import { compose } from "react-apollo";
import hoistStatics from "hoist-non-react-statics";
import BaseProvider from "../components/BaseProvider";
import applyRedirect from "../router/applyRedirect";
import withCookies from "../cookies/withCookiesPage";
import withLocale from "../i18n/withLocalePage";
export default Page =>
compose(withLocale, applyRedirect, withCookies)(
hoistStatics(
props => (
<BaseProvider
cookies={props.cookies}
locale={props.locale}
defaultLocale={props.defaultLocale}
siteLocales={props.siteLocales}
>
<Page {...props} />
</BaseProvider>
),
Page
)
);
| import React from "react";
import { compose } from "redux";
import hoistStatics from "hoist-non-react-statics";
import BaseProvider from "../components/BaseProvider";
import applyRedirect from "../router/applyRedirect";
import withCookies from "../cookies/withCookiesPage";
import withLocale from "../i18n/withLocalePage";
export default Page =>
compose(withLocale, applyRedirect, withCookies)(
hoistStatics(
props => (
<BaseProvider
cookies={props.cookies}
locale={props.locale}
defaultLocale={props.defaultLocale}
siteLocales={props.siteLocales}
>
<Page {...props} />
</BaseProvider>
),
Page
)
);
| Replace react-apollo with redux compose | Replace react-apollo with redux compose
| JavaScript | mit | traveloka/soya-next | ---
+++
@@ -1,5 +1,5 @@
import React from "react";
-import { compose } from "react-apollo";
+import { compose } from "redux";
import hoistStatics from "hoist-non-react-statics";
import BaseProvider from "../components/BaseProvider";
import applyRedirect from "../router/applyRedirect"; |
015f85622b33df01971ffc784f0f7594da30c889 | app/controllers/name.controller.js | app/controllers/name.controller.js | 'use strict';
angular.module('houseBand')
.controller('NameCtrl', function($state){
this.roomCheck = function(room){
if(room){
return $state.go('home', {room: room})
}
alert('Please name your band')
return false
}
});
| 'use strict';
angular.module('houseBand')
.controller('NameCtrl', function($state){
this.roomCheck = function(room){
if(room){
return $state.go('home', {room: room.toLowerCase()})
}
alert('Please name your band');
return false
}
});
| Make room name lower case | Make room name lower case
| JavaScript | mit | HouseBand/client,HouseBand/client | ---
+++
@@ -5,9 +5,9 @@
.controller('NameCtrl', function($state){
this.roomCheck = function(room){
if(room){
- return $state.go('home', {room: room})
+ return $state.go('home', {room: room.toLowerCase()})
}
- alert('Please name your band')
+ alert('Please name your band');
return false
}
}); |
55e138a77becada80430cc7795bbb6bd23a66843 | lib/index.js | lib/index.js | 'use strict';
module.exports = (...trackers) => {
const tracker = {};
tracker.createEvent = (eventName, eventData) => {
trackers.forEach((tk) => {
tk.createEvent(eventName, eventData);
});
return tracker;
};
return tracker;
};
| 'use strict';
module.exports = function eventTracker() {
const tracker = {};
const trackers = Array.prototype.slice.call(arguments);
tracker.createEvent = (eventName, eventData) => {
trackers.forEach((tk) => {
tk.createEvent(eventName, eventData);
});
return tracker;
};
return tracker;
};
| Remove destructuring and add arguments | Remove destructuring and add arguments
| JavaScript | mit | ZimpFidelidade/universal-event-tracker | ---
+++
@@ -1,7 +1,8 @@
'use strict';
-module.exports = (...trackers) => {
+module.exports = function eventTracker() {
const tracker = {};
+ const trackers = Array.prototype.slice.call(arguments);
tracker.createEvent = (eventName, eventData) => {
trackers.forEach((tk) => { |
9f8fa2f067e7b91cac796268dbabacdce5a3fc6c | test/boost-field-test.js | test/boost-field-test.js | var mongoose = require('mongoose')
, elastical = require('elastical')
, esClient = new(require('elastical').Client)
, should = require('should')
, config = require('./config')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
, mongoosastic = require('../lib/mongoosastic');
var TweetSchema = new Schema({
user: String
, post_date: {type:Date, es_type:'date'}
, message: {type:String}
, title: {type:String, es_boost:2.0}
});
TweetSchema.plugin(mongoosastic);
var BlogPost = mongoose.model('BlogPost', TweetSchema);
describe('Add Boost Option Per Field', function(){
before(function(done){
mongoose.connect(config.mongoUrl, function(){
BlogPost.remove(function(){
config.deleteIndexIfExists(['blogposts'], done)
});
});
});
it('should create a mapping with boost field added', function(done){
BlogPost.createMapping(function(err, mapping){
esClient.getMapping('blogposts', 'blogpost', function(err, mapping){
var props = mapping.blogposts.mappings.blogpost.properties;
props.title.type.should.eql('string');
props.title.boost.should.eql(2.0);
done();
});
});
});
});
| var mongoose = require('mongoose')
, elastical = require('elastical')
, esClient = new(require('elastical').Client)
, should = require('should')
, config = require('./config')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
, mongoosastic = require('../lib/mongoosastic');
var TweetSchema = new Schema({
user: String
, post_date: {type:Date, es_type:'date'}
, message: {type:String}
, title: {type:String, es_boost:2.0}
});
TweetSchema.plugin(mongoosastic);
var BlogPost = mongoose.model('BlogPost', TweetSchema);
describe('Add Boost Option Per Field', function(){
before(function(done){
mongoose.connect(config.mongoUrl, function(){
BlogPost.remove(function(){
config.deleteIndexIfExists(['blogposts'], done)
});
});
});
it('should create a mapping with boost field added', function(done){
BlogPost.createMapping(function(err, mapping){
esClient.getMapping('blogposts', 'blogpost', function(err, mapping){
/* elasticsearch 1.0 & 0.9 support */
var props =
mapping.blogpost != undefined ?
mapping.blogpost.properties: /* ES 0.9.11 */
mapping.blogposts.mappings.blogpost.properties; /* ES 1.0.0 */
props.title.type.should.eql('string');
props.title.boost.should.eql(2.0);
done();
});
});
});
});
| Correct boost test field (support ES 0.9 and 1.0). | Correct boost test field (support ES 0.9 and 1.0).
In my tests, the mapping format returned by the getMapping function is
not the same between 0.90.11 and 1.0
| JavaScript | mit | mongoosastic/mongoosastic,teambition/mongoosastic,ennosol/mongoosastic,francesconero/mongoosastic,ennosol/mongoosastic,guumaster/mongoosastic,francesconero/mongoosastic,mongoosastic/mongoosastic,avastms/mongoosastic,guumaster/mongoosastic,teambition/mongoosastic,mallzee/mongoosastic,guumaster/mongoosastic,mallzee/mongoosastic,hdngr/mongoosastic,mallzee/mongoosastic,hdngr/mongoosastic,hdngr/mongoosastic,avastms/mongoosastic,mongoosastic/mongoosastic | ---
+++
@@ -30,7 +30,11 @@
it('should create a mapping with boost field added', function(done){
BlogPost.createMapping(function(err, mapping){
esClient.getMapping('blogposts', 'blogpost', function(err, mapping){
- var props = mapping.blogposts.mappings.blogpost.properties;
+ /* elasticsearch 1.0 & 0.9 support */
+ var props =
+ mapping.blogpost != undefined ?
+ mapping.blogpost.properties: /* ES 0.9.11 */
+ mapping.blogposts.mappings.blogpost.properties; /* ES 1.0.0 */
props.title.type.should.eql('string');
props.title.boost.should.eql(2.0);
done(); |
1569457c708195ea017fb047beab7ade7ed918ab | common/components/constants/ProjectConstants.js | common/components/constants/ProjectConstants.js | export const Locations = {
OTHER: "Other",
PRESET_LOCATIONS: [
"Seattle, WA",
"Redmond, WA",
"Kirkland, WA",
"Bellevue, WA",
"Tacoma, WA",
"Olympia, WA",
"Bay Area, CA",
"Baltimore, MD",
"Other"
]
}; | export const Locations = {
OTHER: "Other",
PRESET_LOCATIONS: [
"Seattle, WA",
"Redmond, WA",
"Kirkland, WA",
"Bellevue, WA",
"Tacoma, WA",
"Olympia, WA",
"Portland, OR",
"Bay Area, CA",
"Baltimore, MD",
"Other"
]
}; | Add Portland, OR to location list | Add Portland, OR to location list
| JavaScript | mit | DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange | ---
+++
@@ -7,6 +7,7 @@
"Bellevue, WA",
"Tacoma, WA",
"Olympia, WA",
+ "Portland, OR",
"Bay Area, CA",
"Baltimore, MD",
"Other" |
38eb816b54300fec9ccf2ed3978f0dc66624981a | lib/index.js | lib/index.js | module.exports = {
'Unit': require('./unit'),
'Lexer': require('./lexer'),
};
| module.exports = {
// Objects
'Unit': require('./unit'),
'Lexer': require('./lexer'),
// Methods
'math': require('./math'),
};
| Add math & clean up. | Add math & clean up.
| JavaScript | mit | jamen/craze | ---
+++
@@ -1,4 +1,8 @@
module.exports = {
+ // Objects
'Unit': require('./unit'),
'Lexer': require('./lexer'),
+
+ // Methods
+ 'math': require('./math'),
}; |
51ca67b91d6256ce48171b912e649a08ec7638c1 | cosmoz-bottom-bar-view.js | cosmoz-bottom-bar-view.js | /*global Polymer, Cosmoz*/
(function () {
'use strict';
Polymer({
is: 'cosmoz-bottom-bar-view',
behaviors: [
Cosmoz.ViewInfoBehavior,
Polymer.IronResizableBehavior
],
properties: {
overflowing: {
type: Boolean,
value: false,
reflectToAttribute: true
},
scroller: {
type: Object
}
},
listeners: {
'iron-resize': '_onResize'
},
attached: function () {
this.scroller = this.$.scroller;
},
_onResize: function () {
var scrollerSizer = this.$.scrollerSizer;
// HACK(pasleq): ensure scrollerSizer is sized correctly.
scrollerSizer.style.minHeight = '';
this.async(function () {
if (scrollerSizer.scrollHeight > scrollerSizer.offsetHeight) {
scrollerSizer.style.minHeight = scrollerSizer.scrollHeight + 'px';
}
});
},
_getPadding: function (desktop) {
// if (desktop) {
// return;
// }
return 'padding-bottom: ' + this.$.bar.barHeight + 'px';
},
_getBarHeight: function (desktop) {
return 'min-height: ' + this.$.bar.barHeight + 'px';
}
});
}()); | /*global Polymer, Cosmoz*/
(function () {
'use strict';
Polymer({
is: 'cosmoz-bottom-bar-view',
behaviors: [
Cosmoz.ViewInfoBehavior,
Polymer.IronResizableBehavior
],
properties: {
overflowing: {
type: Boolean,
value: false,
reflectToAttribute: true
},
scroller: {
type: Object
}
},
listeners: {
'iron-resize': '_onResize'
},
attached: function () {
this.scroller = this.$.scroller;
},
_onResize: function () {
var scrollerSizer = this.$.scrollerSizer;
// HACK(pasleq): ensure scrollerSizer is sized correctly.
scrollerSizer.style.minHeight = '';
this.async(function () {
if (scrollerSizer.scrollHeight > scrollerSizer.offsetHeight) {
scrollerSizer.style.minHeight = scrollerSizer.scrollHeight + 'px';
}
});
},
_getPadding: function (desktop) {
// if (desktop) {
// return;
// }
return 'padding-bottom: ' + this.$.bar.barHeight + 'px';
},
_getBarHeight: function (desktop) {
var height = this.$.bar.barHeight;
return [
'max-height: ' + height + 'px',
'min-height: ' + height + 'px'
].join(';');
}
});
}()); | Fix bug where the placeholder would flex out | Fix bug where the placeholder would flex out
Might be related to shady DOM or <slot> hybrid mode.
| JavaScript | apache-2.0 | Neovici/cosmoz-bottom-bar,Neovici/cosmoz-bottom-bar | ---
+++
@@ -55,7 +55,11 @@
},
_getBarHeight: function (desktop) {
- return 'min-height: ' + this.$.bar.barHeight + 'px';
+ var height = this.$.bar.barHeight;
+ return [
+ 'max-height: ' + height + 'px',
+ 'min-height: ' + height + 'px'
+ ].join(';');
}
});
}()); |
aea77bd5b10e00005b0df08bd59ac427e19c4f89 | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/**/*_test.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'PhantomJS', 'Safari', 'Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
| module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/**/*_test.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
| Use Phantom JS alone for speed and ease. | Use Phantom JS alone for speed and ease.
| JavaScript | mit | blinkboxbooks/marvin-frontend.js | ---
+++
@@ -52,7 +52,7 @@
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
- browsers: ['Chrome', 'PhantomJS', 'Safari', 'Firefox'],
+ browsers: ['PhantomJS'],
// Continuous Integration mode |
d1c78416c722a0cf8e1107c8b3a640129f19197a | js/lib/get-absolute-url.js | js/lib/get-absolute-url.js | export function getAbsoluteUrl({ path, getSassFileGlobPattern, glob }, url, includePaths = []) {
const { dir, base } = path.parse(url);
const baseGlobPattern = getSassFileGlobPattern(base);
includePaths.some((includePath) => {
glob.sync(path.resolve(includePath, dir, baseGlobPattern));
return false;
});
}
export default function getAbsoluteUrlFactory() {
return getAbsoluteUrl.bind(null);
}
| import globModule from 'glob';
import pathModule from 'path';
import getSassFileGlobPatternModule from './get-sass-file-glob-pattern';
export function getAbsoluteUrl({ path, getSassFileGlobPattern, glob }, url, includePaths = []) {
const { dir, base } = path.parse(url);
const baseGlobPattern = getSassFileGlobPattern(base);
includePaths.some((includePath) => {
glob.sync(path.resolve(includePath, dir, baseGlobPattern));
return false;
});
}
export default getAbsoluteUrl.bind(null, {
path: pathModule,
getSassFileGlobPattern: getSassFileGlobPatternModule,
glob: globModule,
});
| Implement the simplified testable module pattern. | Implement the simplified testable module pattern.
Read more about the pattern here: https://markus.oberlehner.net/blog/2017/02/the-testable-module-pattern/
| JavaScript | mit | maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer | ---
+++
@@ -1,3 +1,8 @@
+import globModule from 'glob';
+import pathModule from 'path';
+
+import getSassFileGlobPatternModule from './get-sass-file-glob-pattern';
+
export function getAbsoluteUrl({ path, getSassFileGlobPattern, glob }, url, includePaths = []) {
const { dir, base } = path.parse(url);
const baseGlobPattern = getSassFileGlobPattern(base);
@@ -7,6 +12,8 @@
});
}
-export default function getAbsoluteUrlFactory() {
- return getAbsoluteUrl.bind(null);
-}
+export default getAbsoluteUrl.bind(null, {
+ path: pathModule,
+ getSassFileGlobPattern: getSassFileGlobPatternModule,
+ glob: globModule,
+}); |
72b517762e82d421e989f5c30b30c8f7ce18f013 | test/test.js | test/test.js | 'use strict';
var grunt = require('grunt');
/**
* Constructs a test case.
*
* @param {string} file The `package.json` file to be tested.
* @param {boolean} valid Flag indicating whether the test is
* expected to pass.
* @param {Array} [args] Additional arguments to pass to `grunt`.
* @return {function(Object)} Testing function for `nodeunit`.
*/
function test(file, valid, args) {
return function(test) {
test.expect(2);
grunt.util.spawn({
grunt: true,
args: [
'--gruntfile', 'test/Gruntfile.js',
'--pkgFile', file
].concat(args || []).concat('npm-validate')
}, function(error, result, code) {
if (valid) {
test.equal(error, null);
test.equal(code, 0);
} else {
test.notEqual(error, null);
test.notEqual(code, 0);
}
test.done();
});
};
}
module.exports = {
empty: test('fixtures/empty.json', false),
force: test('fixtures/empty.json', true, ['--force', true]),
minimal: test('fixtures/minimal.json', true),
package: test('../package.json', true),
strict: test('fixtures/minimal.json', false, ['--strict', true])
};
| 'use strict';
var grunt = require('grunt');
/**
* Constructs a test case.
*
* @param {string} file The `package.json` file to be tested.
* @param {boolean} valid Flag indicating whether the test is
* expected to pass.
* @param {Array} [args] Additional arguments to pass to `grunt`.
* @return {function(Object)} Testing function for `nodeunit`.
*/
function test(file, valid, args) {
return function(test) {
test.expect(2);
grunt.util.spawn({
grunt: true,
args: [
'--gruntfile', 'test/Gruntfile.js',
'--pkgFile', file
].concat(args || []).concat('npm-validate')
}, function(error, result, code) {
if (valid) {
test.ifError(error);
test.equal(code, 0);
} else {
test.notEqual(error, null);
test.notEqual(code, 0);
}
test.done();
});
};
}
module.exports = {
empty: test('fixtures/empty.json', false),
force: test('fixtures/empty.json', true, ['--force', true]),
minimal: test('fixtures/minimal.json', true),
package: test('../package.json', true),
strict: test('fixtures/minimal.json', false, ['--strict', true])
};
| Use `ifError` assertion instead of `equal`. | Use `ifError` assertion instead of `equal`.
| JavaScript | mit | joshuaspence/grunt-npm-validate | ---
+++
@@ -23,7 +23,7 @@
].concat(args || []).concat('npm-validate')
}, function(error, result, code) {
if (valid) {
- test.equal(error, null);
+ test.ifError(error);
test.equal(code, 0);
} else {
test.notEqual(error, null); |
dda90c0bcf7f32e70d9143327bd8e0d91e5a6f00 | lib/index.js | lib/index.js | /**
* dubdrop compatible task for reading an image file and creating a thumbnail.
*
* @package thumbdrop
* @author drk <drk@diy.org>
*/
// readAsDataURL
/**
* Constructor
*/
function createThumbdrop (_callback) {
return function thumbdrop (file, callback) {
var reader = new FileReader();
reader.onload = function (e) {
var $img = document.createElement('img');
$img.setAttribute('src', e.target.result);
callback(null, file);
_callback(null, $img)
};
reader.readAsDataURL(file);
};
};
/**
* Export
*/
module.exports = createThumbdrop;
| /**
* dubdrop compatible task for reading an image file and creating a thumbnail.
*
* @package thumbdrop
* @author drk <drk@diy.org>
*/
// readAsDataURL
/**
* Constructor
*/
function createThumbdrop (callback) {
return function thumbdrop (file) {
var reader = new FileReader();
reader.onload = function (e) {
var $img = document.createElement('img');
$img.setAttribute('src', e.target.result);
callback(null, $img)
};
reader.readAsDataURL(file);
};
};
/**
* Export
*/
module.exports = createThumbdrop;
| Remove async handling to comply w/ dubdrop 0.0.3 | Remove async handling to comply w/ dubdrop 0.0.3
| JavaScript | mit | derekr/thumbdrop | ---
+++
@@ -10,16 +10,15 @@
/**
* Constructor
*/
-function createThumbdrop (_callback) {
- return function thumbdrop (file, callback) {
+function createThumbdrop (callback) {
+ return function thumbdrop (file) {
var reader = new FileReader();
reader.onload = function (e) {
var $img = document.createElement('img');
$img.setAttribute('src', e.target.result);
- callback(null, file);
- _callback(null, $img)
+ callback(null, $img)
};
reader.readAsDataURL(file); |
eaef0b0012eacbb4994345fd0f45e6e54e58e583 | lib/index.js | lib/index.js | 'use strict'
let consistentEnv
module.exports = function() {
if (!consistentEnv) {
consistentEnv = require('consistent-env')
}
return consistentEnv().PATH || ''
}
module.exports.async = function() {
if (!consistentEnv) {
consistentEnv = require('consistent-env')
}
return consistentEnv.async().then(function(env) {
return env.PATH || ''
})
}
| 'use strict'
let consistentEnv
module.exports = function() {
if (process.platform === 'win32') {
return process.env.PATH || process.env.Path
}
if (!consistentEnv) {
consistentEnv = require('consistent-env')
}
return consistentEnv().PATH || ''
}
module.exports.async = function() {
if (process.platform === 'win32') {
return Promise.resolve(process.env.PATH || process.env.Path)
}
if (!consistentEnv) {
consistentEnv = require('consistent-env')
}
return consistentEnv.async().then(function(env) {
return env.PATH || ''
})
}
| Handle different names of PATH on windows | :bug: Handle different names of PATH on windows
| JavaScript | mit | steelbrain/consistent-path | ---
+++
@@ -3,6 +3,9 @@
let consistentEnv
module.exports = function() {
+ if (process.platform === 'win32') {
+ return process.env.PATH || process.env.Path
+ }
if (!consistentEnv) {
consistentEnv = require('consistent-env')
}
@@ -10,6 +13,9 @@
}
module.exports.async = function() {
+ if (process.platform === 'win32') {
+ return Promise.resolve(process.env.PATH || process.env.Path)
+ }
if (!consistentEnv) {
consistentEnv = require('consistent-env')
} |
51ffd24a0035fe03157ad34e4a0c014e2a4fda04 | lib/index.js | lib/index.js | 'use strict';
var rump = module.exports = require('rump');
var configs = require('./configs');
var originalAddGulpTasks = rump.addGulpTasks;
rump.addGulpTasks = function(options) {
originalAddGulpTasks(options);
require('./gulp');
return rump;
};
rump.on('update:main', function() {
configs.rebuild();
rump.emit('update:less');
});
Object.defineProperty(rump.configs, 'less', {
get: function() {
return configs.less;
}
});
| 'use strict';
var rump = module.exports = require('rump');
var configs = require('./configs');
var originalAddGulpTasks = rump.addGulpTasks;
// TODO remove on next major core update
rump.addGulpTasks = function(options) {
originalAddGulpTasks(options);
require('./gulp');
return rump;
};
rump.on('update:main', function() {
configs.rebuild();
rump.emit('update:less');
});
rump.on('gulp:main', function(options) {
require('./gulp');
rump.emit('gulp:less', options);
});
Object.defineProperty(rump.configs, 'less', {
get: function() {
return configs.less;
}
});
| Handle future event emit for gulp tasks | Handle future event emit for gulp tasks
| JavaScript | mit | rumps/rump-less | ---
+++
@@ -4,6 +4,7 @@
var configs = require('./configs');
var originalAddGulpTasks = rump.addGulpTasks;
+// TODO remove on next major core update
rump.addGulpTasks = function(options) {
originalAddGulpTasks(options);
require('./gulp');
@@ -15,6 +16,11 @@
rump.emit('update:less');
});
+rump.on('gulp:main', function(options) {
+ require('./gulp');
+ rump.emit('gulp:less', options);
+});
+
Object.defineProperty(rump.configs, 'less', {
get: function() {
return configs.less; |
3e96edbd86dc6f233d34edfcf3d57de693a202ac | lib/index.js | lib/index.js | var mongoose = require('mongoose');
var ShortId = require('./shortid');
var defaultSave = mongoose.Model.prototype.save;
mongoose.Model.prototype.save = function(cb) {
for (fieldName in this.schema.tree) {
if (this.isNew && this[fieldName] === undefined) {
var idType = this.schema.tree[fieldName];
if (idType === ShortId || idType.type === ShortId) {
var idInfo = this.schema.path(fieldName);
var retries = idInfo.retries;
var self = this;
function attemptSave() {
idInfo.generator(idInfo.generatorOptions, function(err, id) {
if (err) {
cb(err);
return;
}
self[fieldName] = id;
defaultSave.call(self, function(err, obj) {
if (err &&
err.code == 11000 &&
err.err.indexOf(fieldName) !== -1 &&
retries > 0
) {
--retries;
attemptSave();
} else {
// TODO check these args
cb(err, obj);
}
});
});
}
attemptSave();
return;
}
}
}
defaultSave.call(this, cb);
};
module.exports = exports = ShortId;
| var mongoose = require('mongoose');
var ShortId = require('./shortid');
var defaultSave = mongoose.Model.prototype.save;
mongoose.Model.prototype.save = function(cb) {
for (key in this.schema.tree) {
var fieldName = key
if (this.isNew && this[fieldName] === undefined) {
var idType = this.schema.tree[fieldName];
if (idType === ShortId || idType.type === ShortId) {
var idInfo = this.schema.path(fieldName);
var retries = idInfo.retries;
var self = this;
function attemptSave() {
idInfo.generator(idInfo.generatorOptions, function(err, id) {
if (err) {
cb(err);
return;
}
self[fieldName] = id;
defaultSave.call(self, function(err, obj) {
if (err &&
err.code == 11000 &&
err.err.indexOf(fieldName) !== -1 &&
retries > 0
) {
--retries;
attemptSave();
} else {
// TODO check these args
cb(err, obj);
}
});
});
}
attemptSave();
return;
}
}
}
defaultSave.call(this, cb);
};
module.exports = exports = ShortId;
| Create a variable in scope to avoid being override | Create a variable in scope to avoid being override | JavaScript | mit | jjwchoy/mongoose-shortid,dashersw/mongoose-shortid,jouke/mongoose-shortid,hoist/mongoose-shortid | ---
+++
@@ -3,7 +3,8 @@
var defaultSave = mongoose.Model.prototype.save;
mongoose.Model.prototype.save = function(cb) {
- for (fieldName in this.schema.tree) {
+ for (key in this.schema.tree) {
+ var fieldName = key
if (this.isNew && this[fieldName] === undefined) {
var idType = this.schema.tree[fieldName];
|
43fbb8eddf92a3e6b0fd7125b8e91537f6d21445 | lib/index.js | lib/index.js | var createJob = require('./createJob');
module.exports = function (sails) {
return {
jobs: {},
defaults: {cron: {}},
initialize: function (cb) {
var config = sails.config.cron;
var tasks = Object.keys(config);
tasks.forEach(function (time) {
this.jobs[time] = createJob({
cronTime: time,
onTick: config[time] instanceof Function ? config[time] : config[time].onTick,
onComplete: config[time].onComplete,
start: typeof config[time].start === 'boolean' ? config[time].start : true,
timezone: config[time].timezone,
context: config[time].context
});
}.bind(this));
cb();
}
};
};
| var createJob = require('./createJob');
module.exports = function (sails) {
return {
jobs: {},
defaults: {cron: {}},
initialize: function (cb) {
var config = sails.config.cron;
var tasks = Object.keys(config);
tasks.forEach(function (name) {
this.jobs[name] = createJob({
cronTime: config[name].schedule,
onTick: config[name].onTick,
onComplete: config[name].onComplete,
start: typeof config[name].start === 'boolean' ? config[name].start : true,
timezone: config[name].timezone,
context: config[name].context
});
}.bind(this));
cb();
}
};
};
| Replace schedule as a key with named job | Replace schedule as a key with named job
| JavaScript | mit | ghaiklor/sails-hook-cron | ---
+++
@@ -9,14 +9,14 @@
initialize: function (cb) {
var config = sails.config.cron;
var tasks = Object.keys(config);
- tasks.forEach(function (time) {
- this.jobs[time] = createJob({
- cronTime: time,
- onTick: config[time] instanceof Function ? config[time] : config[time].onTick,
- onComplete: config[time].onComplete,
- start: typeof config[time].start === 'boolean' ? config[time].start : true,
- timezone: config[time].timezone,
- context: config[time].context
+ tasks.forEach(function (name) {
+ this.jobs[name] = createJob({
+ cronTime: config[name].schedule,
+ onTick: config[name].onTick,
+ onComplete: config[name].onComplete,
+ start: typeof config[name].start === 'boolean' ? config[name].start : true,
+ timezone: config[name].timezone,
+ context: config[name].context
});
}.bind(this));
|
5056f8a50db6d6d17d1b29428fdc90f3abe92a1e | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'browserify'],
files: [
'test/**/*.js'
],
preprocessors: {
'test/**/*.js': ['browserify']
},
browsers: ['PhantomJS'],
browserify: {
debug: true
}
});
};
| module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'browserify'],
files: [
'test/**/*.js'
],
preprocessors: {
'test/**/*.js': ['browserify']
},
browsers: ['PhantomJS'],
browserify: {
debug: true
},
singleRun: true
});
};
| Update karma, it will run once with npm test | Update karma, it will run once with npm test
| JavaScript | mit | vudduu/key-enum | ---
+++
@@ -10,6 +10,7 @@
browsers: ['PhantomJS'],
browserify: {
debug: true
- }
+ },
+ singleRun: true
});
}; |
98add101bfda0dd235f2675cfd9ffff04e56b9ba | test/acceptance/global.nightwatch.js | test/acceptance/global.nightwatch.js | module.exports = {
waitForConditionPollInterval: 1000,
waitForConditionTimeout: 6000,
pauseDuration: 5000,
retryAssertionTimeout: 2500,
}
| module.exports = {
waitForConditionPollInterval: 2000,
waitForConditionTimeout: 12000,
pauseDuration: 7500,
retryAssertionTimeout: 5000,
}
| Increase timeouts to improve test runs | Increase timeouts to improve test runs
Attempts to address issue with a high perecentage
of acceptance test runs failing. | JavaScript | mit | uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2 | ---
+++
@@ -1,6 +1,6 @@
module.exports = {
- waitForConditionPollInterval: 1000,
- waitForConditionTimeout: 6000,
- pauseDuration: 5000,
- retryAssertionTimeout: 2500,
+ waitForConditionPollInterval: 2000,
+ waitForConditionTimeout: 12000,
+ pauseDuration: 7500,
+ retryAssertionTimeout: 5000,
} |
ba17d882e72582d5396fa3a3dfb6292656f63b30 | lib/index.js | lib/index.js | 'use strict';
// VARIABLES //
var FLOAT32_VIEW = new Float32Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT32_VIEW.buffer );
// 0 11111111 00000000000000000000000 => 2139095040 => 0x7f800000
var PINF = 0x7f800000;
// Set the ArrayBuffer bit sequence:
UINT32_VIEW[ 0 ] = PINF;
// EXPORTS //
module.exports = FLOAT32_VIEW[ 0 ];
| 'use strict';
// VARIABLES //
var FLOAT32_VIEW = new Float32Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT32_VIEW.buffer );
// 0 11111111 00000000000000000000000 => 2139095040 => 0x7f800000 (see IEEE 754-2008)
var PINF = 0x7f800000;
// Set the ArrayBuffer bit sequence:
UINT32_VIEW[ 0 ] = PINF;
// EXPORTS //
module.exports = FLOAT32_VIEW[ 0 ];
| Add code comment re: IEEE 754-2008 | Add code comment re: IEEE 754-2008
| JavaScript | mit | const-io/pinf-float32 | ---
+++
@@ -5,7 +5,7 @@
var FLOAT32_VIEW = new Float32Array( 1 );
var UINT32_VIEW = new Uint32Array( FLOAT32_VIEW.buffer );
-// 0 11111111 00000000000000000000000 => 2139095040 => 0x7f800000
+// 0 11111111 00000000000000000000000 => 2139095040 => 0x7f800000 (see IEEE 754-2008)
var PINF = 0x7f800000;
// Set the ArrayBuffer bit sequence: |
edca7f5559e256606c7bc4ece9ffcf1f845c8ee7 | src/c/big-input-card.js | src/c/big-input-card.js | import m from 'mithril';
const bigInputCard = {
view(ctrl, args) {
const cardClass = '.w-row.u-marginbottom-30.card.card-terciary.padding-redactor-description.text.optional.project_about_html.field_with_hint';
return m(cardClass, [
m('div', [
m('label.field-label.fontweight-semibold.fontsize-base', args.label),
(args.label_hint ? m('label.hint.fontsize-smallest.fontcolor-secondary', args.label_hint) : '')
]),
m('div', args.children)
]);
}
}
export default bigInputCard;
| import m from 'mithril';
const bigInputCard = {
view(ctrl, args) {
const cardClass = args.cardClass || '.w-row.u-marginbottom-30.card.card-terciary.padding-redactor-description.text.optional.project_about_html.field_with_hint';
return m(cardClass, {style: (args.cardStyle||{})}, [
m('div', [
m('label.field-label.fontweight-semibold.fontsize-base', args.label),
(args.label_hint ? m('label.hint.fontsize-smallest.fontcolor-secondary', args.label_hint) : '')
]),
m('div', args.children)
]);
}
}
export default bigInputCard;
| Adjust bigInputCard to receive a cardStyle and cardClass args | Adjust bigInputCard to receive a cardStyle and cardClass args
| JavaScript | mit | catarse/catarse_admin,vicnicius/catarse_admin,vicnicius/catarse.js,mikesmayer/cs2.js,catarse/catarse.js,sushant12/catarse.js | ---
+++
@@ -2,9 +2,9 @@
const bigInputCard = {
view(ctrl, args) {
- const cardClass = '.w-row.u-marginbottom-30.card.card-terciary.padding-redactor-description.text.optional.project_about_html.field_with_hint';
+ const cardClass = args.cardClass || '.w-row.u-marginbottom-30.card.card-terciary.padding-redactor-description.text.optional.project_about_html.field_with_hint';
- return m(cardClass, [
+ return m(cardClass, {style: (args.cardStyle||{})}, [
m('div', [
m('label.field-label.fontweight-semibold.fontsize-base', args.label),
(args.label_hint ? m('label.hint.fontsize-smallest.fontcolor-secondary', args.label_hint) : '') |
8cdbc23c71c69d628b9f034c11727423c218cf87 | db/migrations/20131216232955-external-transactions.js | db/migrations/20131216232955-external-transactions.js | var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('bank_transactions', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
deposit: { type: 'boolean', notNull: true },
currency: { type: 'string', notNull: true },
cashAmount: { type: 'decimal', notNull: true },
accountId: { type: 'int', notNull: true },
rippleTxId: { type: 'int'},
createdAt: { type: 'datetime', notNull: true },
updatedAt: { type: 'datetime' }
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('bank_transactions', callback);
};
| var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('external_transactions', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
deposit: { type: 'boolean', notNull: true },
currency: { type: 'string', notNull: true },
cashAmount: { type: 'decimal', notNull: true },
externalAccountId: { type: 'int', notNull: true },
rippleTxId: { type: 'int'},
createdAt: { type: 'datetime', notNull: true },
updatedAt: { type: 'datetime' }
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('bank_transactions', callback);
};
| Change accountId to externalAccountId in external transactions migration | [FEATURE] Change accountId to externalAccountId in external transactions migration
| JavaScript | isc | whotooktwarden/gatewayd,zealord/gatewayd,xdv/gatewayd,Parkjeahwan/awegeeks,Parkjeahwan/awegeeks,crazyquark/gatewayd,whotooktwarden/gatewayd,xdv/gatewayd,crazyquark/gatewayd,zealord/gatewayd | ---
+++
@@ -2,12 +2,12 @@
var type = dbm.dataType;
exports.up = function(db, callback) {
- db.createTable('bank_transactions', {
+ db.createTable('external_transactions', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
deposit: { type: 'boolean', notNull: true },
currency: { type: 'string', notNull: true },
cashAmount: { type: 'decimal', notNull: true },
- accountId: { type: 'int', notNull: true },
+ externalAccountId: { type: 'int', notNull: true },
rippleTxId: { type: 'int'},
createdAt: { type: 'datetime', notNull: true },
updatedAt: { type: 'datetime' } |
04182efe223fb18e3678615c024ed3ecd806afb9 | packages/nova-core/lib/containers/withMutation.js | packages/nova-core/lib/containers/withMutation.js | /*
HoC that provides a simple mutation that expects a single JSON object in return
Example usage:
export default withMutation({
name: 'getEmbedlyData',
args: {url: 'String'},
})(EmbedlyURL);
*/
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
export default function withMutation({name, args}) {
const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String
const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url
return graphql(gql`
mutation ${name}(${args1}) {
${name}(${args2})
}
`, {
props: ({ownProps, mutate}) => ({
[name]: (vars) => {
return mutate({
variables: vars,
});
}
}),
});
} | /*
HoC that provides a simple mutation that expects a single JSON object in return
Example usage:
export default withMutation({
name: 'getEmbedlyData',
args: {url: 'String'},
})(EmbedlyURL);
*/
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
export default function withMutation({name, args}) {
let mutation;
if (args) {
const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String
const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url
mutation = `
mutation ${name}(${args1}) {
${name}(${args2})
}
`
} else {
mutation = `
mutation ${name} {
${name}
}
`
}
return graphql(gql`${mutation}`, {
props: ({ownProps, mutate}) => ({
[name]: (vars) => {
return mutate({
variables: vars,
});
}
}),
});
} | Make mutation hoc accept mutations without arguments | Make mutation hoc accept mutations without arguments
| JavaScript | mit | manriquef/Vulcan,SachaG/Zensroom,SachaG/Gamba,bshenk/projectIterate,manriquef/Vulcan,rtluu/immersive,HelloMeets/HelloMakers,dominictracey/Telescope,bshenk/projectIterate,Discordius/Telescope,acidsound/Telescope,dominictracey/Telescope,SachaG/Gamba,VulcanJS/Vulcan,Discordius/Lesswrong2,acidsound/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,JstnEdr/Telescope,JstnEdr/Telescope,TodoTemplates/Telescope,HelloMeets/HelloMakers,VulcanJS/Vulcan,dominictracey/Telescope,TodoTemplates/Telescope,manriquef/Vulcan,SachaG/Gamba,acidsound/Telescope,Discordius/Telescope,rtluu/immersive,rtluu/immersive,SachaG/Zensroom,SachaG/Zensroom,HelloMeets/HelloMakers,TodoTemplates/Telescope,bshenk/projectIterate,bengott/Telescope,Discordius/Lesswrong2,Discordius/Telescope,bengott/Telescope,JstnEdr/Telescope,bengott/Telescope | ---
+++
@@ -16,14 +16,25 @@
export default function withMutation({name, args}) {
- const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String
- const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url
+ let mutation;
- return graphql(gql`
- mutation ${name}(${args1}) {
- ${name}(${args2})
- }
- `, {
+ if (args) {
+ const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String
+ const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url
+ mutation = `
+ mutation ${name}(${args1}) {
+ ${name}(${args2})
+ }
+ `
+ } else {
+ mutation = `
+ mutation ${name} {
+ ${name}
+ }
+ `
+ }
+
+ return graphql(gql`${mutation}`, {
props: ({ownProps, mutate}) => ({
[name]: (vars) => {
return mutate({ |
23737870dcc77538cf7a094d4f5521c8580f965b | lib/models/UserInstance.js | lib/models/UserInstance.js | /* WePay API for Node.js
* (c)2012 Matt Farmer
* Release without warranty under the terms of the
* Apache License. For more details, see the LICENSE
* file at the root of this project.
*/
var UserInstance = function(params) {
//TODO
}
module.exports = UserInstance;
| /* WePay API for Node.js
* (c)2012 Matt Farmer
* Release without warranty under the terms of the
* Apache License. For more details, see the LICENSE
* file at the root of this project.
*/
var UserInstance = function(params) {
// Populate any params passed in.
if (params && ! params instanceof Object)
throw "Parameters passed to an instance constructor must be an object or undefined.";
if (params){
for (key in params) {
this[key] = params[key];
}
}
}
module.exports = UserInstance;
| Implement the User instance constructor. | Implement the User instance constructor.
| JavaScript | apache-2.0 | farmdawgnation/wepay-api-node | ---
+++
@@ -5,7 +5,15 @@
* file at the root of this project.
*/
var UserInstance = function(params) {
- //TODO
+ // Populate any params passed in.
+ if (params && ! params instanceof Object)
+ throw "Parameters passed to an instance constructor must be an object or undefined.";
+
+ if (params){
+ for (key in params) {
+ this[key] = params[key];
+ }
+ }
}
module.exports = UserInstance; |
b27452b32f6be2bb6544833b422b60a9f1d00e0c | generators/app/templates/gulp_tasks/systemjs.js | generators/app/templates/gulp_tasks/systemjs.js | const gulp = require('gulp');
const replace = require('gulp-replace');
const Builder = require('jspm').Builder;
const conf = require('../conf/gulp.conf');
gulp.task('systemjs', systemjs);
gulp.task('systemjs:html', updateIndexHtml);
function systemjs(done) {
const builder = new Builder('./', 'jspm.config.js');
builder.config({
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
packageConfigPaths: [
'npm:@*/*.json',
'npm:*.json',
'github:*/*.json'
]
});
builder.buildStatic(
<%- entry %>,
conf.path.tmp('index.js')
).then(() => done(), done);
}
function updateIndexHtml() {
return gulp.src(conf.path.src('index.html'))
.pipe(replace(
/<script>\n\s*System.import.*\n\s*<\/script>/,
`<script src="index.js"></script>`
))
.pipe(gulp.dest(conf.path.tmp()));
}
| const gulp = require('gulp');
const replace = require('gulp-replace');
const Builder = require('jspm').Builder;
const conf = require('../conf/gulp.conf');
gulp.task('systemjs', systemjs);
gulp.task('systemjs:html', updateIndexHtml);
function systemjs(done) {
const builder = new Builder('./', 'jspm.config.js');
builder.config({
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
packageConfigPaths: [
'npm:@*/*.json',
'npm:*.json',
'github:*/*.json'
]
});
builder.buildStatic(
<%- entry %>,
conf.path.tmp('index.js')
).then(() => done(), done);
}
function updateIndexHtml() {
return gulp.src(conf.path.src('index.html'))
.pipe(replace(
/<script src="jspm_packages\/system.js">[\s\S]*System.import.*\n\s*<\/script>/,
`<script src="index.js"></script>`
))
.pipe(gulp.dest(conf.path.tmp()));
}
| Remove jspm scripts on build | Remove jspm scripts on build
| JavaScript | mit | FountainJS/generator-fountain-systemjs,FountainJS/generator-fountain-systemjs | ---
+++
@@ -30,7 +30,7 @@
function updateIndexHtml() {
return gulp.src(conf.path.src('index.html'))
.pipe(replace(
- /<script>\n\s*System.import.*\n\s*<\/script>/,
+ /<script src="jspm_packages\/system.js">[\s\S]*System.import.*\n\s*<\/script>/,
`<script src="index.js"></script>`
))
.pipe(gulp.dest(conf.path.tmp())); |
827eb5533a6e7f967a40f82871647902dc6b833b | karma.conf.js | karma.conf.js | const base = require('skatejs-build/karma.conf');
module.exports = function (config) {
base(config);
// Remove all explicit IE definitions.
config.browsers = config.browsers.filter(name => !/^internet_explorer/.test(name));
// Only test IE latest.
config.browsers.push('internet_explorer_11');
// Shims for testing.
config.files = [
'node_modules/es6-shim/es6-shim.js'
].concat(config.files);
// Ensure mobile browsers have enough time to run.
config.browserNoActivityTimeout = 60000;
};
| const base = require('skatejs-build/karma.conf');
module.exports = function (config) {
base(config);
// Setup IE if testing in SauceLabs.
if (config.sauceLabs) {
// Remove all explicit IE definitions.
config.browsers = config.browsers.filter(name => !/^internet_explorer/.test(name));
// Only test IE latest.
config.browsers.push('internet_explorer_11');
}
// Shims for testing.
config.files = [
'node_modules/es6-shim/es6-shim.js',
].concat(config.files);
// Ensure mobile browsers have enough time to run.
config.browserNoActivityTimeout = 60000;
};
| Fix tests so that it only tries to run IE11 if running in Sauce Labs. | chore(test): Fix tests so that it only tries to run IE11 if running in Sauce Labs.
For some reason it just started happening that it would try to run IE11 outside of Sauce Labs.
| JavaScript | mit | chrisdarroch/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,skatejs/skatejs | ---
+++
@@ -2,15 +2,18 @@
module.exports = function (config) {
base(config);
- // Remove all explicit IE definitions.
- config.browsers = config.browsers.filter(name => !/^internet_explorer/.test(name));
+ // Setup IE if testing in SauceLabs.
+ if (config.sauceLabs) {
+ // Remove all explicit IE definitions.
+ config.browsers = config.browsers.filter(name => !/^internet_explorer/.test(name));
- // Only test IE latest.
- config.browsers.push('internet_explorer_11');
+ // Only test IE latest.
+ config.browsers.push('internet_explorer_11');
+ }
// Shims for testing.
config.files = [
- 'node_modules/es6-shim/es6-shim.js'
+ 'node_modules/es6-shim/es6-shim.js',
].concat(config.files);
// Ensure mobile browsers have enough time to run. |
665337b8ea125f179f58e9ffd4cee4e1f5272743 | test/svg-test-helper.js | test/svg-test-helper.js | import $ from "cheerio";
const RECTANGULAR_SEQUENCE = ["M", "L", "L", "L", "L"];
const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"];
const SvgTestHelper = {
expectIsRectangular(wrapper) {
expect(exhibitsShapeSequence(wrapper, RECTANGULAR_SEQUENCE)).to.be.true;
},
expectIsCircular(wrapper) {
expect(exhibitsShapeSequence(wrapper, CIRCULAR_SEQUENCE)).to.be.true;
}
};
function exhibitsShapeSequence(wrapper, shapeSequence) {
const commands = getPathCommandsFromWrapper(wrapper);
return commands.every((command, index) => {
return command.name === shapeSequence[index];
});
}
function getPathCommandsFromWrapper(wrapper) {
const commandStr = $(wrapper.html()).attr("d");
return parseSvgPathCommands(commandStr);
}
function parseSvgPathCommands(commandStr) {
const matches = commandStr.match(
/[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g
);
return matches.map(match => {
const name = match.charAt(0);
const args = match.substring(1).split(",").map(arg => parseFloat(arg, 10));
return {
raw: match,
name,
args
}
});
}
export default SvgTestHelper;
| import $ from "cheerio";
const RECTANGULAR_SEQUENCE = ["M", "L", "L", "L", "L"];
const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"];
const expectations = {
expectIsRectangular(wrapper) {
expect(exhibitsShapeSequence(wrapper, RECTANGULAR_SEQUENCE)).to.be.true;
},
expectIsCircular(wrapper) {
expect(exhibitsShapeSequence(wrapper, CIRCULAR_SEQUENCE)).to.be.true;
}
};
const helpers = {
getBarHeight(wrapper) {
expectations.expectIsRectangular(wrapper);
const commands = getPathCommandsFromWrapper(wrapper);
return Math.abs(commands[0].args[1] - commands[1].args[1]);
}
};
const SvgTestHelper = Object.assign({}, expectations, helpers);
function exhibitsShapeSequence(wrapper, shapeSequence) {
const commands = getPathCommandsFromWrapper(wrapper);
return commands.every((command, index) => {
return command.name === shapeSequence[index];
});
}
function getPathCommandsFromWrapper(wrapper) {
const commandStr = $(wrapper.html()).attr("d");
return parseSvgPathCommands(commandStr);
}
function parseSvgPathCommands(commandStr) {
const matches = commandStr.match(
/[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g
);
return matches.map(match => {
const name = match.charAt(0);
const args = match.substring(1).split(",").map(arg => parseFloat(arg, 10));
return {
raw: match,
name,
args
}
});
}
export default SvgTestHelper;
| Split helpers into expectations and helpers | Split helpers into expectations and helpers
| JavaScript | mit | FormidableLabs/victory-chart,FormidableLabs/victory-chart,GreenGremlin/victory-chart,GreenGremlin/victory-chart | ---
+++
@@ -3,7 +3,7 @@
const RECTANGULAR_SEQUENCE = ["M", "L", "L", "L", "L"];
const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"];
-const SvgTestHelper = {
+const expectations = {
expectIsRectangular(wrapper) {
expect(exhibitsShapeSequence(wrapper, RECTANGULAR_SEQUENCE)).to.be.true;
},
@@ -12,6 +12,16 @@
expect(exhibitsShapeSequence(wrapper, CIRCULAR_SEQUENCE)).to.be.true;
}
};
+
+const helpers = {
+ getBarHeight(wrapper) {
+ expectations.expectIsRectangular(wrapper);
+ const commands = getPathCommandsFromWrapper(wrapper);
+ return Math.abs(commands[0].args[1] - commands[1].args[1]);
+ }
+};
+
+const SvgTestHelper = Object.assign({}, expectations, helpers);
function exhibitsShapeSequence(wrapper, shapeSequence) {
const commands = getPathCommandsFromWrapper(wrapper); |
7ac6ead3693b4a26dedfff678d55d11512fe1b76 | tests/integration/components/ember-webcam-test.js | tests/integration/components/ember-webcam-test.js | import { describeComponent, it } from 'ember-mocha';
import { beforeEach, afterEach } from 'mocha';
import { expect } from 'chai';
import hbs from 'htmlbars-inline-precompile';
import page from './page';
describeComponent('ember-webcam', 'Integration: EmberWebcamComponent', {
integration: true
}, () => {
beforeEach(function () {
page.setContext(this);
});
afterEach(() => {
page.removeContext();
});
it('renders', () => {
page.render(hbs`{{ember-webcam}}`);
expect(page.viewer.isVisible).to.be.true;
});
it('takes a snapshot', done => {
let isDone = false;
page.context.setProperties({
didError(errorMessage) {
expect(errorMessage).to.be.ok;
if (!isDone) {
done();
isDone = true;
}
}
});
page.render(hbs`
{{#ember-webcam didError=(action didError) as |camera|}}
<button {{action camera.snap}}>
Take Snapshot!
</button>
{{/ember-webcam}}
`);
page.button.click();
});
});
| import { describeComponent, it } from 'ember-mocha';
import { beforeEach, afterEach } from 'mocha';
import { expect } from 'chai';
import hbs from 'htmlbars-inline-precompile';
import page from './page';
describeComponent('ember-webcam', 'Integration: EmberWebcamComponent', {
integration: true
}, () => {
beforeEach(function () {
page.setContext(this);
});
afterEach(() => {
page.removeContext();
});
it('renders', () => {
page.render(hbs`{{ember-webcam}}`);
expect(page.viewer.isVisible).to.be.true;
});
it('takes a snapshot', done => {
let isDone = false;
page.context.setProperties({
didError(error) {
// Should fail because camera is not available in test environment.
expect(error.name).to.equal('WebcamError');
if (!isDone) {
done();
isDone = true;
}
}
});
page.render(hbs`
{{#ember-webcam didError=(action didError) as |camera|}}
<button {{action camera.snap}}>
Take Snapshot!
</button>
{{/ember-webcam}}
`);
page.button.click();
});
});
| Improve component test when fails to take snapshot | Improve component test when fails to take snapshot
| JavaScript | mit | leizhao4/ember-webcam,forge512/ember-webcam,leizhao4/ember-webcam,forge512/ember-webcam | ---
+++
@@ -23,8 +23,9 @@
it('takes a snapshot', done => {
let isDone = false;
page.context.setProperties({
- didError(errorMessage) {
- expect(errorMessage).to.be.ok;
+ didError(error) {
+ // Should fail because camera is not available in test environment.
+ expect(error.name).to.equal('WebcamError');
if (!isDone) {
done();
isDone = true; |
f8a42180a7b9b1a145ddc76164fd3299468771b4 | lib/index.js | lib/index.js | 'use strict';
module.exports = {};
| 'use strict';
var assert = require('assert');
module.exports = function() {
var privacy = {};
var tags = { in: {}, out: {} };
privacy.wrap = function(asset) {
return {
_unwrap: function(tag) {
assert(tag === tags.in);
return {
tag: tags.out,
asset: asset
};
}
};
};
privacy.unwrap = function(wrappedAsset) {
var unwrapped = wrappedAsset._unwrap(tags.in);
assert(unwrapped.tag === tags.out);
return unwrapped.asset;
};
return privacy;
};
| Add actual code from jellyscript project | Add actual code from jellyscript project
| JavaScript | mit | voltrevo/voltrevo-privacy,leahciMic/voltrevo-privacy | ---
+++
@@ -1,3 +1,31 @@
'use strict';
-module.exports = {};
+var assert = require('assert');
+
+module.exports = function() {
+ var privacy = {};
+
+ var tags = { in: {}, out: {} };
+
+ privacy.wrap = function(asset) {
+ return {
+ _unwrap: function(tag) {
+ assert(tag === tags.in);
+
+ return {
+ tag: tags.out,
+ asset: asset
+ };
+ }
+ };
+ };
+
+ privacy.unwrap = function(wrappedAsset) {
+ var unwrapped = wrappedAsset._unwrap(tags.in);
+ assert(unwrapped.tag === tags.out);
+
+ return unwrapped.asset;
+ };
+
+ return privacy;
+}; |
ad1a69d6bfc62473c322af56aea49da3efa46a75 | karma.conf.js | karma.conf.js | "use strict";
/**
* Karma configuration.
*/
module.exports = function (config) {
config.set({
frameworks: ["mocha", "sinon"],
files: [
"test/**_test.js"
],
preprocessors: {
"test/**_test.js": ["webpack"]
},
reporters: ["progress"],
browsers: ["Chrome"],
webpack: require("./webpack.config"),
plugins: [
"karma-chrome-launcher",
"karma-mocha",
"karma-sinon",
"karma-webpack"
]
});
};
| "use strict";
/**
* Karma configuration.
*/
module.exports = function (config) {
config.set({
frameworks: ["mocha", "sinon"],
files: [
"test/**_test.js"
],
preprocessors: {
"test/**_test.js": ["webpack"]
},
reporters: ["progress"],
browsers: ["Chrome"],
webpack: require("./webpack.config"),
plugins: [
"karma-chrome-launcher",
"karma-firefox-launcher",
"karma-mocha",
"karma-sinon",
"karma-webpack"
]
});
};
| Add Karma Firefox Runner for TravisCI | [Fixed] Add Karma Firefox Runner for TravisCI
| JavaScript | apache-2.0 | mikepb/clerk | ---
+++
@@ -25,6 +25,7 @@
plugins: [
"karma-chrome-launcher",
+ "karma-firefox-launcher",
"karma-mocha",
"karma-sinon",
"karma-webpack" |
f92aa1631ecb7504d21931002dd0dfda01316af7 | lib/client.js | lib/client.js |
var api = require('@request/api')
module.exports = (client, provider, methods, config, transform) => {
return api(methods, {
api: function (options, name) {
options.api = name
return this
},
auth: function (options, arg1, arg2) {
var alias = (options.api || provider.api || '__default')
config.endpoint.auth(alias, options, arg1, arg2)
return this
},
submit: function (options) {
var alias = (options.api || provider.api || '__default')
if (!config.aliases[alias]) {
throw new Error('Purest: non existing alias!')
}
transform.oauth(options)
transform.parse(options)
options = config.endpoint.options(alias, options)
if (!/^http/.test(options.url)) {
options.url = config.url(alias, options)
}
return client(options)
}
})
}
|
var api = require('@request/api')
module.exports = (client, provider, methods, config, transform) => {
return api(methods, {
api: function (name) {
this._options.api = name
return this
},
auth: function (arg1, arg2) {
var alias = (this._options.api || provider.api || '__default')
config.endpoint.auth(alias, this._options, arg1, arg2)
return this
},
submit: function (callback) {
var options = this._options
if (callback) {
options.callback = callback
}
var alias = (options.api || provider.api || '__default')
if (!config.aliases[alias]) {
throw new Error('Purest: non existing alias!')
}
transform.oauth(options)
transform.parse(options)
options = config.endpoint.options(alias, options)
if (!/^http/.test(options.url)) {
options.url = config.url(alias, options)
}
return client(options)
}
})
}
| Fix custom method options + Allow callback to be passed to the submit method | Fix custom method options +
Allow callback to be passed to the submit method
| JavaScript | apache-2.0 | simov/purest | ---
+++
@@ -4,16 +4,22 @@
module.exports = (client, provider, methods, config, transform) => {
return api(methods, {
- api: function (options, name) {
- options.api = name
+ api: function (name) {
+ this._options.api = name
return this
},
- auth: function (options, arg1, arg2) {
- var alias = (options.api || provider.api || '__default')
- config.endpoint.auth(alias, options, arg1, arg2)
+ auth: function (arg1, arg2) {
+ var alias = (this._options.api || provider.api || '__default')
+ config.endpoint.auth(alias, this._options, arg1, arg2)
return this
},
- submit: function (options) {
+ submit: function (callback) {
+ var options = this._options
+
+ if (callback) {
+ options.callback = callback
+ }
+
var alias = (options.api || provider.api || '__default')
if (!config.aliases[alias]) { |
6d22f9733610999ca48d912a125c3bde3e37b285 | lib/utils.js | lib/utils.js | var Person = require('./person');
function incomingMessage(botId, message) {
return message.type === 'message' // check it's a message
&& Boolean(message.text) // check message has some content
&& Boolean(message.user) // check there is a user set
&& message.user !== botId; // check message is not from this bot
}
function directMessage(message) {
// check it's a direct message - direct message channels start with 'D'
return typeof message.channel === 'string' && message.channel[0] === 'D';
}
function channelMessageForMe(botId, message) {
return typeof message.channel === 'string' // check it's a string
&& message.channel[0] === 'C' // channel messages start with 'C'
&& message.text.startsWith('<@' + botId + '>:'); // check it's for me
}
function createResponse(message, callback) {
var response = 'Echo: ' + message.text;
if (message.text.startsWith('person')) {
var person = new Person(message.text.substring(7));
person.getDetails(callback);
}
callback(response);
}
module.exports = {
incomingMessage: incomingMessage,
directMessage: directMessage,
channelMessageForMe: channelMessageForMe,
createResponse: createResponse
};
| var Person = require('./person');
function incomingMessage(botId, message) {
return message.type === 'message' // check it's a message
&& Boolean(message.text) // check message has some content
&& Boolean(message.user) // check there is a user set
&& message.user !== botId; // check message is not from this bot
}
function directMessage(message) {
// check it's a direct message - direct message channels start with 'D'
return typeof message.channel === 'string' && message.channel[0] === 'D';
}
function channelMessageForMe(botId, message) {
return typeof message.channel === 'string' // check it's a string
&& message.channel[0] === 'C' // channel messages start with 'C'
&& message.text.startsWith('<@' + botId + '>:'); // check it's for me
}
function createResponse(message, callback) {
if (message.text.startsWith('person')) {
var person = new Person(message.text.substring(7));
person.getDetails(callback);
} else {
// if nothing else, just echo back the message
callback('Echo: ' + message.text);
}
}
module.exports = {
incomingMessage: incomingMessage,
directMessage: directMessage,
channelMessageForMe: channelMessageForMe,
createResponse: createResponse
};
| Stop double-calling the callback function | Stop double-calling the callback function
| JavaScript | apache-2.0 | tomnatt/tombot | ---
+++
@@ -20,13 +20,13 @@
function createResponse(message, callback) {
- var response = 'Echo: ' + message.text;
if (message.text.startsWith('person')) {
var person = new Person(message.text.substring(7));
person.getDetails(callback);
+ } else {
+ // if nothing else, just echo back the message
+ callback('Echo: ' + message.text);
}
-
- callback(response);
}
|
2f5a1f4bd5754f895efa4f218d1a7dd8712525ee | src/store/modules/fcm.js | src/store/modules/fcm.js | import Vue from 'vue'
import axios from '@/services/axios'
export default {
namespaced: true,
state: {
token: null,
tokens: {},
},
getters: {
token: state => state.token,
tokenExists: state => token => Boolean(state.tokens[token]),
},
actions: {
updateToken ({ commit, rootGetters }, token) {
commit('setToken', token)
},
async fetchTokens ({ commit }) {
commit('receiveTokens', (await axios.get('/api/subscriptions/push/')).data.map(({ token }) => token))
},
},
mutations: {
setToken (state, token) {
state.token = token
},
receiveTokens (state, tokens) {
for (let token of tokens) {
Vue.set(state.tokens, token, true)
}
},
},
}
export const plugin = store => {
store.watch(() => ({
isLoggedIn: store.getters['auth/isLoggedIn'],
token: store.getters['fcm/token'],
}), async ({ isLoggedIn, token }) => {
if (isLoggedIn && token) {
await store.dispatch('fcm/fetchTokens')
if (!store.getters['fcm/tokenExists'](token)) {
await axios.post('/api/subscriptions/push/', { token, platform: 'android' })
await store.dispatch('fcm/fetchTokens')
}
}
})
}
| import Vue from 'vue'
import axios from '@/services/axios'
export default {
namespaced: true,
state: {
token: null,
tokens: {},
},
getters: {
token: state => state.token,
tokenExists: state => token => Boolean(state.tokens[token]),
},
actions: {
updateToken ({ commit, rootGetters }, token) {
commit('setToken', token)
},
async fetchTokens ({ commit }) {
commit('receiveTokens', (await axios.get('/api/subscriptions/push/')).data.map(({ token }) => token))
},
},
mutations: {
setToken (state, token) {
state.token = token
},
receiveTokens (state, tokens) {
state.tokens = {}
for (let token of tokens) {
Vue.set(state.tokens, token, true)
}
},
},
}
export const plugin = store => {
store.watch(() => ({
isLoggedIn: store.getters['auth/isLoggedIn'],
token: store.getters['fcm/token'],
}), async ({ isLoggedIn, token }) => {
if (isLoggedIn && token) {
await store.dispatch('fcm/fetchTokens')
if (!store.getters['fcm/tokenExists'](token)) {
await axios.post('/api/subscriptions/push/', { token, platform: 'android' })
await store.dispatch('fcm/fetchTokens')
}
}
})
}
| Clear subscription tokens before updating | Clear subscription tokens before updating
| JavaScript | mit | yunity/foodsaving-frontend,yunity/foodsaving-frontend,yunity/karrot-frontend,yunity/karrot-frontend,yunity/karrot-frontend,yunity/karrot-frontend,yunity/foodsaving-frontend,yunity/foodsaving-frontend | ---
+++
@@ -24,6 +24,7 @@
state.token = token
},
receiveTokens (state, tokens) {
+ state.tokens = {}
for (let token of tokens) {
Vue.set(state.tokens, token, true)
} |
5e9118abc8aeb801bc51e4f3230b12ae116fed5e | lib/crouch.js | lib/crouch.js | "use strict";
;(function ( root, name, definition ) {
/*
* Exports
*/
if ( typeof define === 'function' && define.amd ) {
define( [], definition );
}
else if ( typeof module === 'object' && module.exports ) {
module.exports = definition();
}
else {
root[ name ] = definition();
}
})( this, 'crouch', function () {
/**
* RegExp to find placeholders in the template
*
* http://regexr.com/3e1o7
* @type {RegExp}
*/
var _re = /{([0-9a-zA-Z]+?)}/g;
/**
* Micro template compiler
*
* @param {string} template
* @param {array|object} values
* @returns {string}
*/
var crouch = function ( template, values ) {
/*
* Default arguments
*/
var
template = template || "",
values = values || {};
var match;
/*
* Loop through all the placeholders that matched with regex
*/
while ( match = _re.exec( template ) ) {
/*
* Get value from given values and
* if it doesn't exist use empty string
*/
var _value = values[ match[ 1 ] ];
if ( !_value ) _value = "";
/*
* Replace the placeholder with a real value.
*/
template = template.replace( match[ 0 ], _value )
}
/*
* Return the template with filled in values
*/
return template;
};
/**
* 😎
*/
return crouch;
} );
| "use strict";
;(function ( root, name, definition ) {
/*
* Exports
*/
if ( typeof define === 'function' && define.amd ) {
define( [], definition );
}
else if ( typeof module === 'object' && module.exports ) {
module.exports = definition();
}
else {
root[ name ] = definition();
}
})( this, 'crouch', function () {
/**
* RegExp to find placeholders in the template
*
* http://regexr.com/3eveu
* @type {RegExp}
*/
var _re = /{([0-9a-z_]+?)}/ig;
/**
* Micro template compiler
*
* @param {string} template
* @param {array|object} values
* @returns {string}
*/
var crouch = function ( template, values ) {
/*
* Default arguments
*/
var
template = template || "",
values = values || {};
var match;
/*
* Loop through all the placeholders that matched with regex
*/
while ( match = _re.exec( template ) ) {
/*
* Get value from given values and
* if it doesn't exist use empty string
*/
var _value = values[ match[ 1 ] ];
if ( !_value ) _value = "";
/*
* Replace the placeholder with a real value.
*/
template = template.replace( match[ 0 ], _value )
}
/*
* Return the template with filled in values
*/
return template;
};
/**
* 😎
*/
return crouch;
} );
| Update regex to match underscore and be case insensitive; | Update regex to match underscore and be case insensitive;
| JavaScript | mit | hendrysadrak/crouch | ---
+++
@@ -18,10 +18,10 @@
/**
* RegExp to find placeholders in the template
*
- * http://regexr.com/3e1o7
+ * http://regexr.com/3eveu
* @type {RegExp}
*/
- var _re = /{([0-9a-zA-Z]+?)}/g;
+ var _re = /{([0-9a-z_]+?)}/ig;
/** |
5a3e8af0505b8777358db1984b5020fd5a4dfb48 | lib/util/generalRequest.js | lib/util/generalRequest.js | // Includes
var http = require('./http.js').func;
var getVerification = require('./getVerification.js').func;
var promise = require('./promise.js');
// Args
exports.required = ['url', 'events'];
exports.optional = ['customOpt', 'getBody', 'jar'];
function general (jar, url, inputs, events, customOpt, body) {
return function (resolve, reject) {
for (var input in events) {
inputs[input] = events[input];
}
var httpOpt = {
url: url,
options: {
resolveWithFullResponse: true,
method: 'POST',
form: inputs,
jar: jar
}
};
if (customOpt) {
Object.assign(httpOpt.options, customOpt);
}
http(httpOpt).then(function (res) {
resolve({
res: res,
body: body
});
});
};
}
exports.func = function (args) {
var jar = args.jar;
var url = args.url;
return getVerification({url: url, jar: jar, getBody: args.getBody})
.then(function (response) {
return promise(general(jar, url, response.inputs, args.events, args.http, response.body));
});
};
| // Includes
var http = require('./http.js').func;
var getVerification = require('./getVerification.js').func;
var promise = require('./promise.js');
// Args
exports.required = ['url', 'events'];
exports.optional = ['http', 'ignoreCache', 'getBody', 'jar'];
function general (jar, url, inputs, events, customOpt, body) {
return function (resolve, reject) {
for (var input in events) {
inputs[input] = events[input];
}
var httpOpt = {
url: url,
options: {
resolveWithFullResponse: true,
method: 'POST',
form: inputs,
jar: jar
}
};
if (customOpt) {
if (customOpt.url) {
delete customOpt.url;
}
Object.assign(httpOpt.options, customOpt);
}
http(httpOpt).then(function (res) {
resolve({
res: res,
body: body
});
});
};
}
exports.func = function (args) {
var jar = args.jar;
var url = args.url;
var custom = args.http;
return getVerification({url: custom ? (custom.url || url) : url, jar: jar, ignoreCache: args.ignoreCache, getBody: args.getBody})
.then(function (response) {
return promise(general(jar, url, response.inputs, args.events, args.http, response.body));
});
};
| Add ignoreCache option and http option | Add ignoreCache option and http option
| JavaScript | mit | FroastJ/roblox-js,OnlyTwentyCharacters/roblox-js,sentanos/roblox-js | ---
+++
@@ -5,7 +5,7 @@
// Args
exports.required = ['url', 'events'];
-exports.optional = ['customOpt', 'getBody', 'jar'];
+exports.optional = ['http', 'ignoreCache', 'getBody', 'jar'];
function general (jar, url, inputs, events, customOpt, body) {
return function (resolve, reject) {
@@ -22,6 +22,9 @@
}
};
if (customOpt) {
+ if (customOpt.url) {
+ delete customOpt.url;
+ }
Object.assign(httpOpt.options, customOpt);
}
http(httpOpt).then(function (res) {
@@ -36,7 +39,8 @@
exports.func = function (args) {
var jar = args.jar;
var url = args.url;
- return getVerification({url: url, jar: jar, getBody: args.getBody})
+ var custom = args.http;
+ return getVerification({url: custom ? (custom.url || url) : url, jar: jar, ignoreCache: args.ignoreCache, getBody: args.getBody})
.then(function (response) {
return promise(general(jar, url, response.inputs, args.events, args.http, response.body));
}); |
9af35bf97daa2a3b81d3984f7047a0c893b7b983 | lib/helper.js | lib/helper.js | 'use babel'
import {BufferedProcess} from 'atom'
export function exec(command, args = [], options = {}) {
if (!arguments.length) throw new Error('Nothing to execute')
return new Promise(function(resolve, reject) {
const data = {stdout: [], stderr: []}
const spawnedProcess = new BufferedProcess({
command: command,
args: args,
options: options,
stdout: function(contents) {
data.stdout.push(contents)
},
stderr: function(contents) {
data.stderr.push(contents)
},
exit: function() {
if (data.stderr.length) {
reject(new Error(data.stderr.join('')))
} else {
resolve(data.stdout.join(''))
}
}
})
spawnedProcess.onWillThrowError(function({error, handle}) {
reject(error)
handle()
})
})
}
| 'use babel'
import {BufferedProcess} from 'atom'
export function installPackages(packageNames, callback) {
const APMPath = atom.packages.getApmPath()
const Promises = []
return Promise.all(Promise)
}
export function exec(command, args = [], options = {}) {
if (!arguments.length) throw new Error('Nothing to execute')
return new Promise(function(resolve, reject) {
const data = {stdout: [], stderr: []}
const spawnedProcess = new BufferedProcess({
command: command,
args: args,
options: options,
stdout: function(contents) {
data.stdout.push(contents)
},
stderr: function(contents) {
data.stderr.push(contents)
},
exit: function() {
if (data.stderr.length) {
reject(new Error(data.stderr.join('')))
} else {
resolve(data.stdout.join(''))
}
}
})
spawnedProcess.onWillThrowError(function({error, handle}) {
reject(error)
handle()
})
})
}
| Create a dummy installPackages function | :art: Create a dummy installPackages function
| JavaScript | mit | steelbrain/package-deps,openlawlibrary/package-deps,steelbrain/package-deps | ---
+++
@@ -2,6 +2,12 @@
import {BufferedProcess} from 'atom'
+export function installPackages(packageNames, callback) {
+ const APMPath = atom.packages.getApmPath()
+ const Promises = []
+
+ return Promise.all(Promise)
+}
export function exec(command, args = [], options = {}) {
if (!arguments.length) throw new Error('Nothing to execute')
|
6c1222bfbd64be37e64e4b5142c7c92555664e81 | polymerjs/gulpfile.js | polymerjs/gulpfile.js | var gulp = require('gulp');
var browserSync = require('browser-sync');
var vulcanize = require('gulp-vulcanize');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
gulp.task('copy', function () {
return gulp.src('./app/index.html', {base: './app/'})
.pipe(gulp.dest('./dist/'));
});
gulp.task('compress', function () {
return gulp.src('./app/bower_components/webcomponentsjs/webcomponents-lite.min.js')
.pipe(uglify({mangle: true}))
.pipe(concat('_polymer.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('vulcanize', function () {
return gulp.src('app/elements/my-app.html')
.pipe(vulcanize({
stripComments: true,
inlineCss: true,
inlineScripts: true
}))
.pipe(concat('_polymer.html'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('build', ['copy', 'compress', 'vulcanize']);
gulp.task('serve', ['build'], function () {
browserSync.init({
server: './dist'
});
gulp.watch('app/elements/**/*.html', ['vulcanize']);
gulp.watch('app/index.html', ['copy']);
gulp.watch('dist/*.html').on('change', browserSync.reload);
});
| var gulp = require('gulp');
var browserSync = require('browser-sync');
var vulcanize = require('gulp-vulcanize');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
gulp.task('copy', function () {
return gulp.src('./app/index.html', {base: './app/'})
.pipe(gulp.dest('./dist/'));
});
gulp.task('compress', function () {
return gulp.src('./app/bower_components/webcomponentsjs/webcomponents-lite.min.js')
.pipe(uglify({mangle: true}))
.pipe(concat('_polymer.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('vulcanize', function () {
return gulp.src('app/elements/my-app.html')
.pipe(vulcanize({
stripComments: true,
inlineCss: true,
inlineScripts: true
}))
.pipe(concat('_polymer.html'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('build', ['copy', 'compress', 'vulcanize']);
gulp.task('serve', ['build'], function () {
browserSync.init({
server: './dist',
port: 4200
});
gulp.watch('app/elements/**/*.html', ['vulcanize']);
gulp.watch('app/index.html', ['copy']);
gulp.watch('dist/*.html').on('change', browserSync.reload);
});
| Change browserSync to use port 4200 | [Polymer] Change browserSync to use port 4200
| JavaScript | mit | hawkup/github-stars,hawkup/github-stars | ---
+++
@@ -31,7 +31,8 @@
gulp.task('serve', ['build'], function () {
browserSync.init({
- server: './dist'
+ server: './dist',
+ port: 4200
});
gulp.watch('app/elements/**/*.html', ['vulcanize']); |
1888b71a627455c051ad26932eabb8ca36cd578d | messenger.js | messenger.js | /*jshint strict: true, esnext: true, node: true*/
"use strict";
const Wreck = require("wreck");
const qs = require("querystring");
class FBMessenger {
constructor(token) {
this._fbBase = "https://graph.facebook.com/v2.6/me/";
this._token = token;
this._q = qs.stringify({access_token: token});
this._wreck = Wreck.defaults({
baseUrl: this._fbBase
});
}
sendMessage(userid, msg) {
let payload = "";
payload = JSON.stringify({
recipient: { id: userid },
message: msg
});
return new Promise(function(resolve, reject) {
this._wreck.request(
"POST",
`/messages?${this._q}`,
{
payload: payload
},
(err, response) => {
if(err) {
return reject(err);
}
if(response.body.error) {
return reject(response.body.error);
}
return resolve(response.body);
}
);
});
}
}
module.exports = FBMessenger;
| /*jshint strict: true, esnext: true, node: true*/
"use strict";
const Wreck = require("wreck");
const qs = require("querystring");
class FBMessenger {
constructor(token) {
this._fbBase = "https://graph.facebook.com/v2.6/";
this._token = token;
this._q = qs.stringify({access_token: token});
this._wreck = Wreck.defaults({
baseUrl: this._fbBase
});
}
sendMessage(userid, msg) {
let payload = "";
payload = JSON.stringify({
recipient: { id: userid },
message: msg
});
return this._makeRequest(`/me/messages?${this._q}`,payload);
}
getUserProfile(userid, fields) {
let params = {
access_token: this._token
};
let q = "";
fields = (Array.isArray(fields)) ? fields.join(",") : fields;
if(fields) {
params.fields = fields;
}
q = qs.stringify(params);
return this._makeRequest(`/${userid}?${q}`);
}
_makeRequest(url, payload) {
let method = "GET";
let opts = {};
if(payload) {
method = "POST";
opts.payload = payload;
}
return new Promise((resolve, reject) => {
this._wreck.request(
method,
url,
opts,
(err, response) => {
if(err) {
return reject(err);
}
if(response.body.error) {
return reject(response.body.error);
}
return resolve(response.body);
}
);
});
}
}
module.exports = FBMessenger;
| Add function to get profile. Refactor. | Add function to get profile. Refactor.
| JavaScript | mit | dapuck/fbmsgr-game | ---
+++
@@ -5,7 +5,7 @@
class FBMessenger {
constructor(token) {
- this._fbBase = "https://graph.facebook.com/v2.6/me/";
+ this._fbBase = "https://graph.facebook.com/v2.6/";
this._token = token;
this._q = qs.stringify({access_token: token});
this._wreck = Wreck.defaults({
@@ -19,13 +19,34 @@
recipient: { id: userid },
message: msg
});
- return new Promise(function(resolve, reject) {
+ return this._makeRequest(`/me/messages?${this._q}`,payload);
+ }
+
+ getUserProfile(userid, fields) {
+ let params = {
+ access_token: this._token
+ };
+ let q = "";
+ fields = (Array.isArray(fields)) ? fields.join(",") : fields;
+ if(fields) {
+ params.fields = fields;
+ }
+ q = qs.stringify(params);
+ return this._makeRequest(`/${userid}?${q}`);
+ }
+
+ _makeRequest(url, payload) {
+ let method = "GET";
+ let opts = {};
+ if(payload) {
+ method = "POST";
+ opts.payload = payload;
+ }
+ return new Promise((resolve, reject) => {
this._wreck.request(
- "POST",
- `/messages?${this._q}`,
- {
- payload: payload
- },
+ method,
+ url,
+ opts,
(err, response) => {
if(err) {
return reject(err); |
48052b56b145a4fc7b1370db7e1764b3397c15b5 | js/mobiscroll.treelist.js | js/mobiscroll.treelist.js | (function ($) {
var ms = $.mobiscroll,
presets = ms.presets.scroller;
presets.treelist = presets.list;
ms.presetShort('treelist');
})(jQuery); | (function ($) {
var ms = $.mobiscroll,
presets = ms.presets.scroller;
presets.treelist = presets.list;
ms.presetShort('list');
ms.presetShort('treelist');
})(jQuery); | Add missing list shorthand init | Add missing list shorthand init
| JavaScript | mit | jeancroy/mobiscroll,xuyansong1991/mobiscroll,loki315zx/mobiscroll,mrzzcn/mobiscroll,mrzzcn/mobiscroll,Julienedies/mobiscroll,xuyansong1991/mobiscroll,Julienedies/mobiscroll,loki315zx/mobiscroll,jeancroy/mobiscroll | ---
+++
@@ -3,6 +3,8 @@
presets = ms.presets.scroller;
presets.treelist = presets.list;
+
+ ms.presetShort('list');
ms.presetShort('treelist');
})(jQuery); |
c732b7edc490137446df41d7d85cb58fc8d8fc7a | lib/white-space.js | lib/white-space.js | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-white-space/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-white-space/tachyons-white-space.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8')
var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/typography/white-space/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-white-space/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-white-space/tachyons-white-space.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/white-space/index.html', html)
| Update with reference to global nav partial | Update with reference to global nav partial
| JavaScript | mit | topherauyeung/portfolio,fenderdigital/css-utilities,topherauyeung/portfolio,pietgeursen/pietgeursen.github.io,topherauyeung/portfolio,cwonrails/tachyons,matyikriszta/moonlit-landing-page,fenderdigital/css-utilities,tachyons-css/tachyons,getfrank/tachyons | ---
+++
@@ -10,6 +10,8 @@
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8')
+var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
+
var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8')
var tpl = _.template(template)
@@ -17,7 +19,8 @@
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
- srcCSS: srcCSS
+ srcCSS: srcCSS,
+ navDocs: navDocs
})
fs.writeFileSync('./docs/typography/white-space/index.html', html) |
2f1b73dd12c57e8b64f34d7218c07ecd1f05996e | src/middleware/command/system_defaults/handler.js | src/middleware/command/system_defaults/handler.js | 'use strict';
const { mapValues, omitBy } = require('../../../utilities');
const { defaults } = require('./defaults');
// Apply system-defined defaults to input, including input arguments
const systemDefaults = async function (nextFunc, input) {
const { serverOpts } = input;
const argsA = getDefaultArgs({ serverOpts, input });
const inputA = Object.assign({}, input, { args: argsA });
const response = await nextFunc(inputA);
return response;
};
// Retrieve default arguments
const getDefaultArgs = function ({
serverOpts,
input,
input: { command, args },
}) {
const filteredDefaults = omitBy(
defaults,
({ commands, test: testFunc }, attrName) =>
// Whitelist by command.name
(commands && !commands.includes(command.name)) ||
// Whitelist by tests
(testFunc && !testFunc({ serverOpts, input })) ||
// Only if user has not specified that argument
args[attrName] !== undefined
);
// Reduce to a single object
const defaultArgs = mapValues(filteredDefaults, ({ value }) =>
(typeof value === 'function' ? value({ serverOpts, input }) : value)
);
return defaultArgs;
};
module.exports = {
systemDefaults,
};
| 'use strict';
const { mapValues, omitBy } = require('../../../utilities');
const { defaults } = require('./defaults');
// Apply system-defined defaults to input, including input arguments
const systemDefaults = async function (nextFunc, input) {
const { serverOpts } = input;
const argsA = getDefaultArgs({ serverOpts, input });
const inputA = Object.assign({}, input, { args: argsA });
const response = await nextFunc(inputA);
return response;
};
// Retrieve default arguments
const getDefaultArgs = function ({
serverOpts,
input,
input: { command, args },
}) {
const filteredDefaults = omitBy(
defaults,
({ commands, test: testFunc }, attrName) =>
// Whitelist by command.name
(commands && !commands.includes(command.name)) ||
// Whitelist by tests
(testFunc && !testFunc({ serverOpts, input })) ||
// Only if user has not specified that argument
args[attrName] !== undefined
);
// Reduce to a single object
const defaultArgs = mapValues(filteredDefaults, ({ value }) =>
(typeof value === 'function' ? value({ serverOpts, input }) : value)
);
return Object.assign({}, args, defaultArgs);
};
module.exports = {
systemDefaults,
};
| Fix system defaults overriding all args | Fix system defaults overriding all args
| JavaScript | apache-2.0 | autoserver-org/autoserver,autoserver-org/autoserver | ---
+++
@@ -37,7 +37,7 @@
(typeof value === 'function' ? value({ serverOpts, input }) : value)
);
- return defaultArgs;
+ return Object.assign({}, args, defaultArgs);
};
module.exports = { |
cea5f4bf13f5b3359aea957b35cf52965fa40c37 | app/places/places-service.js | app/places/places-service.js | 'use strict';
angular
.module('webClient.places')
.factory('PlacesService', PlacesService);
function PlacesService($resource, envService) {
console.log('Hello :)');
return $resource(
envService.read('baseBackendUrl') + '/places',
{},
{query: {method:'GET', isArray:true}}
);
}
| 'use strict';
angular
.module('webClient.places')
.factory('PlacesService', PlacesService);
function PlacesService($resource, envService) {
return $resource(
envService.read('baseBackendUrl') + '/places',
{},
{query: {method:'GET', isArray:true}}
);
}
| Revert "Story-52 [Marcela, Felipe] Just testing if the new versions are being correctly deployed to Heroku from Snap - this commit will be reverted in the next push" | Revert "Story-52 [Marcela, Felipe] Just testing if the new versions are being correctly deployed to Heroku from Snap - this commit will be reverted in the next push"
This reverts commit 926c0f09dc56c1fa9ffb91c548d644c771b08046.
| JavaScript | mit | simpatize/webclient,simpatize/webclient,simpatize/webclient | ---
+++
@@ -5,7 +5,6 @@
.factory('PlacesService', PlacesService);
function PlacesService($resource, envService) {
- console.log('Hello :)');
return $resource(
envService.read('baseBackendUrl') + '/places',
{}, |
9d73d1e23c2bce43ee87d150905ec2623277185f | src/js/dom-utils.js | src/js/dom-utils.js | // DOM Library Utilites
$.parseUrlQuery = function (url) {
var query = {}, i, params, param;
if (url.indexOf('?') >= 0) url = url.split('?')[1];
params = url.split('&');
for (i = 0; i < params.length; i++) {
param = params[i].split('=');
query[param[0]] = param[1];
}
return query;
};
$.isArray = function (arr) {
if (Object.prototype.toString.apply(arr) === '[object Array]') return true;
else return false;
};
$.unique = function (arr) {
var unique = [];
for (var i = 0; i < arr.length; i++) {
if (unique.indexOf(arr[i]) === -1) unique.push(arr[i]);
}
return unique;
};
$.trim = function (str) {
return str.trim();
};
$.supportTouch = (function () {
return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
})();
$.fn = Dom7.prototype;
| // DOM Library Utilites
$.parseUrlQuery = function (url) {
var query = {}, i, params, param;
if (url.indexOf('?') >= 0) url = url.split('?')[1];
params = url.split('&');
for (i = 0; i < params.length; i++) {
param = params[i].split('=');
query[param[0]] = param[1];
}
return query;
};
$.isArray = function (arr) {
if (Object.prototype.toString.apply(arr) === '[object Array]') return true;
else return false;
};
$.unique = function (arr) {
var unique = [];
for (var i = 0; i < arr.length; i++) {
if (unique.indexOf(arr[i]) === -1) unique.push(arr[i]);
}
return unique;
};
$.trim = function (str) {
return str.trim();
};
$.serializeObject = function (obj) {
if (typeof obj === 'string') return obj;
var resultArray = [];
var separator = '&';
for (var prop in obj) {
if ($.isArray(obj[prop])) {
var toPush = [];
for (var i = 0; i < obj[prop].length; i ++) {
toPush.push(prop + '=' + obj[prop][i]);
}
resultArray.push(toPush.join(separator));
}
else {
// Should be string
resultArray.push(prop + '=' + obj[prop]);
}
}
return resultArray.join(separator);
};
$.fn = Dom7.prototype;
| Remove supportTouch, add new serializeObject util | Remove supportTouch, add new serializeObject util
| JavaScript | mit | thdoan/Framework7,akio46/Framework7,luistapajos/Lista7,Iamlars/Framework7,Janusorz/Framework7,JustAMisterE/Framework7,Dr1ks/Framework7,Liu-Young/Framework7,dingxin/Framework7,yangfeiloveG/Framework7,pandoraui/Framework7,lilien1010/Framework7,youprofit/Framework7,framework7io/Framework7,quannt/Framework7,xuyuanxiang/Framework7,hanziwang/Framework7,megaplan/Framework7,yucopowo/Framework7,DmitryNek/Framework7,zd9027/Framework7-Plus,luistapajos/Lista7,jvrunion/mercury-seed,ks3dev/Framework7,pratikbutani/Framework7,xuyuanxiang/Framework7,Janusorz/Framework7,ks3dev/Framework7,nolimits4web/Framework7,Dr1ks/Framework7,LeoHuiyi/Framework7,pingjiang/Framework7,quietdog/Framework7,stonegithubs/Framework7,iamxiaoma/Framework7,NichenLg/Framework7,StudyForFun/Framework7-Plus,Iamlars/Framework7,zhangzuoqiang/Framework7-Plus,Logicify/Framework7,Liu-Young/Framework7,gank0326/HTMLINIOS,DmitryNek/Framework7,tiptronic/Framework7,megaplan/Framework7,EhteshamMehmood/Framework7,Miantang/FrameWrork7-Demo,ina9er/bein,Iamlars/Framework7,pleshevskiy/Framework7,tranc99/Framework7,iamxiaoma/Framework7,121595113/Framework7,121595113/Framework7,romanticcup/Framework7,ChineseDron/Framework7,stonegithubs/Framework7-Plus,shuai959980629/Framework7,Logicify/Framework7,NichenLg/Framework7,DrGo/Framework7,LeoHuiyi/Framework7,itstar4tech/Framework7,makelivedotnet/Framework7,Carrotzpc/Framework7,johnjamesjacoby/Framework7,vulcan/Framework7-Plus,pandoraui/Framework7,zhangzuoqiang/Framework7-Plus,thdoan/Framework7,dgilliam/Ref7,elma-cao/Framework7,crazyurus/Framework7,lihongxun945/Framework7,ks3dev/Framework7,crazyurus/Framework7,iamxiaoma/Framework7,RubenDjOn/Framework7,trunk-studio/demo20151024,dingxin/Framework7,quannt/Framework7,domhnallohanlon/Framework7,tiptronic/Framework7,xpyctum/Framework7,RubenDjOn/Framework7,luistapajos/Lista7,johnjamesjacoby/Framework7,Carrotzpc/Framework7,trunk-studio/demo20151024,gagustavo/Framework7,akio46/Framework7,nolimits4web/Framework7,DmitryNek/Framework7,pingjiang/Framework7,StudyForFun/Framework7-Plus,ChineseDron/Framework7,NichenLg/Framework7,chenbk85/Framework7-Plus,gagustavo/Framework7,pandoraui/Framework7,Logicify/Framework7,makelivedotnet/Framework7,gank0326/HTMLINIOS,JustAMisterE/Framework7,thdoan/Framework7,wicky-info/Framework7,RubenDjOn/Framework7,Miantang/FrameWrork7-Demo,DrGo/Framework7,Dr1ks/Framework7,wicky-info/Framework7,trunk-studio/demo20151024,megaplan/Framework7,xpyctum/Framework7,faustinoloeza/Framework7,microlv/Framework7,tiptronic/Framework7,jeremykenedy/Framework7,AdrianV/Framework7,lihongxun945/Framework7,yangfeiloveG/Framework7,ina9er/bein,framework7io/Framework7,chenbk85/Framework7-Plus,quietdog/Framework7,trunk-studio/demo20151024,elma-cao/Framework7,AdrianV/Framework7,etsb5z/Framework7,StudyForFun/Framework7-Plus,ina9er/bein,crazyurus/Framework7,itstar4tech/Framework7,lihongxun945/Framework7,trunk-studio/demo20151024,insionng/Framework7,makelivedotnet/Framework7,Miantang/FrameWrork7-Demo,quannt/Framework7,pratikbutani/Framework7,yucopowo/Framework7,etsb5z/Framework7,stonegithubs/Framework7,romanticcup/Framework7,pleshevskiy/Framework7,shuai959980629/Framework7,mgesmundo/Framework7,prashen/Framework7,microlv/Framework7,chenbk85/Framework7-Plus,mgesmundo/Framework7,faustinoloeza/Framework7,iamxiaoma/Framework7,nolimits4web/Framework7,JustAMisterE/Framework7,shuai959980629/Framework7,zhangzuoqiang/Framework7-Plus,hanziwang/Framework7,etsb5z/Framework7,lilien1010/Framework7,wicky-info/Framework7,yucopowo/Framework7,gagustavo/Framework7,xpyctum/Framework7,lilien1010/Framework7,dgilliam/Ref7,jvrunion/mercury-seed,yangfeiloveG/Framework7,jvrunion/mercury-seed,itstar4tech/Framework7,romanticcup/Framework7,pleshevskiy/Framework7,dgilliam/Ref7,wjb12/Framework7,ChineseDron/Framework7,Carrotzpc/Framework7,EhteshamMehmood/Framework7,elma-cao/Framework7,stonegithubs/Framework7-Plus,hanziwang/Framework7,DrGo/Framework7,johnjamesjacoby/Framework7,EhteshamMehmood/Framework7,zd9027/Framework7-Plus,tranc99/Framework7,zd9027/Framework7-Plus,microlv/Framework7,jeremykenedy/Framework7,vulcan/Framework7-Plus,prashen/Framework7,akio46/Framework7,AdrianV/Framework7,youprofit/Framework7,prashen/Framework7,domhnallohanlon/Framework7,LeoHuiyi/Framework7,quietdog/Framework7,xuyuanxiang/Framework7,pratikbutani/Framework7,insionng/Framework7,Liu-Young/Framework7,insionng/Framework7,stonegithubs/Framework7,mgesmundo/Framework7,Janusorz/Framework7,vulcan/Framework7-Plus,wjb12/Framework7,tranc99/Framework7,wjb12/Framework7,pingjiang/Framework7,faustinoloeza/Framework7,youprofit/Framework7,jeremykenedy/Framework7,stonegithubs/Framework7-Plus | ---
+++
@@ -23,7 +23,24 @@
$.trim = function (str) {
return str.trim();
};
-$.supportTouch = (function () {
- return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
-})();
+$.serializeObject = function (obj) {
+ if (typeof obj === 'string') return obj;
+ var resultArray = [];
+ var separator = '&';
+ for (var prop in obj) {
+ if ($.isArray(obj[prop])) {
+ var toPush = [];
+ for (var i = 0; i < obj[prop].length; i ++) {
+ toPush.push(prop + '=' + obj[prop][i]);
+ }
+ resultArray.push(toPush.join(separator));
+ }
+ else {
+ // Should be string
+ resultArray.push(prop + '=' + obj[prop]);
+ }
+ }
+
+ return resultArray.join(separator);
+};
$.fn = Dom7.prototype; |
a667210d417520082ea946342a64f16f18d1a2e3 | src/js/notifications.js | src/js/notifications.js | const push = require('push.js');
angular.module('opentok-meet').factory('Push', () => push);
angular.module('opentok-meet').factory('NotificationService', ['$window', 'OTSession', 'Push',
function NotificationService($window, OTSession, Push) {
let focused = true;
$window.addEventListener('blur', () => {
focused = false;
});
$window.addEventListener('focus', () => {
focused = true;
});
const notifyOnConnectionCreated = () => {
if (!OTSession.session) {
OTSession.on('init', notifyOnConnectionCreated);
} else {
OTSession.session.on('connectionCreated', (event) => {
if (!focused &&
event.connection.connectionId !== OTSession.session.connection.connectionId) {
Push.create('New Participant', {
body: 'Someone joined your meeting',
icon: '/icon.png',
tag: 'new-participant',
timeout: 5000,
onClick() {
$window.focus();
this.close();
},
});
}
});
}
};
return {
init() {
if (Push.Permission.has()) {
notifyOnConnectionCreated();
} else {
try {
Push.Permission.request(() => {
notifyOnConnectionCreated();
}, (err) => {
console.warn(err);
});
} catch (err) {
console.warn(err);
}
}
},
};
},
]);
| const push = require('push.js');
angular.module('opentok-meet').factory('Push', () => push);
angular.module('opentok-meet').factory('NotificationService', ['$window', 'OTSession', 'Push',
function NotificationService($window, OTSession, Push) {
let focused = true;
$window.addEventListener('blur', () => {
focused = false;
});
$window.addEventListener('focus', () => {
focused = true;
});
const notifyOnConnectionCreated = () => {
if (!OTSession.session) {
OTSession.on('init', notifyOnConnectionCreated);
} else {
OTSession.session.on('connectionCreated', (event) => {
const visible = $window.document.visibilityState === 'visible';
if ((!focused || !visible) &&
event.connection.connectionId !== OTSession.session.connection.connectionId) {
Push.create('New Participant', {
body: 'Someone joined your meeting',
icon: '/icon.png',
tag: 'new-participant',
timeout: 5000,
onClick() {
$window.focus();
this.close();
},
});
}
});
}
};
return {
init() {
if (Push.Permission.has()) {
notifyOnConnectionCreated();
} else {
try {
Push.Permission.request(() => {
notifyOnConnectionCreated();
}, (err) => {
console.warn(err);
});
} catch (err) {
console.warn(err);
}
}
},
};
},
]);
| Add extra condition to show "user joined" notification | Add extra condition to show "user joined" notification
If you open the page and without clicking anything you go to other app, then you won't get the notification => I don't know how to solve this.
If you open the page and without clicking anything you go to other tab, then you won't get the notification => It should be fixed with this change because in that case visibilityState === 'hidden'.
(Disclaimer: Didn't test it inside opentok-meet but in my own app) | JavaScript | mit | opentok/opentok-meet,aullman/opentok-meet,opentok/opentok-meet,opentok/opentok-meet,aullman/opentok-meet | ---
+++
@@ -19,7 +19,8 @@
OTSession.on('init', notifyOnConnectionCreated);
} else {
OTSession.session.on('connectionCreated', (event) => {
- if (!focused &&
+ const visible = $window.document.visibilityState === 'visible';
+ if ((!focused || !visible) &&
event.connection.connectionId !== OTSession.session.connection.connectionId) {
Push.create('New Participant', {
body: 'Someone joined your meeting', |
7bf21890f9b24b6afde0d5ff83ffa70ecf7163e2 | src/database/json-file-manager.js | src/database/json-file-manager.js | import fileSystem from 'fs';
const JsonFileManager = {
load(fileName) {
console.log(`[INFO] Loading data from ${__dirname}/${fileName} file`);
return JSON.parse(fileSystem.readFileSync(`${__dirname}/${fileName}`));
},
save(fileName, json) {
console.log(`[INFO] Saving data in ${__dirname}/${fileName} file`);
fileSystem.writeFileSync(`${__dirname}/${fileName}`, JSON.stringify(json));
}
};
export default JsonFileManager;
| import fileSystem from 'fs';
const JsonFileManager = {
load(path) {
console.log(`[INFO] Loading data from ${path} file`);
return JSON.parse(fileSystem.readFileSync(`${path}`));
},
save(path, json) {
console.log(`[INFO] Saving data in ${path} file`);
fileSystem.writeFileSync(`${path}`, JSON.stringify(json));
}
};
export default JsonFileManager;
| Add some changes in path settings for JsonFIleManager | Add some changes in path settings for JsonFIleManager
| JavaScript | mit | adrianobrito/vaporwave | ---
+++
@@ -1,13 +1,13 @@
import fileSystem from 'fs';
const JsonFileManager = {
- load(fileName) {
- console.log(`[INFO] Loading data from ${__dirname}/${fileName} file`);
- return JSON.parse(fileSystem.readFileSync(`${__dirname}/${fileName}`));
+ load(path) {
+ console.log(`[INFO] Loading data from ${path} file`);
+ return JSON.parse(fileSystem.readFileSync(`${path}`));
},
- save(fileName, json) {
- console.log(`[INFO] Saving data in ${__dirname}/${fileName} file`);
- fileSystem.writeFileSync(`${__dirname}/${fileName}`, JSON.stringify(json));
+ save(path, json) {
+ console.log(`[INFO] Saving data in ${path} file`);
+ fileSystem.writeFileSync(`${path}`, JSON.stringify(json));
}
};
|
914b86f5c0351599a9a168c5f0dc65b9bfa942d5 | src/runner/typecheck.js | src/runner/typecheck.js | import { execFile } from 'child_process'
import flow from 'flow-bin'
import { logError, log } from '../util/log'
const errorCodes = {
TYPECHECK_ERROR: 2
}
export default (saguiOptions) => new Promise((resolve, reject) => {
const commandArgs = ['check', '--color=always']
if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) {
commandArgs.push('--all')
}
execFile(flow, commandArgs, (err, stdout, stderr) => {
if (err) {
logError('Type check failed:\n')
switch (err.code) {
case errorCodes.TYPECHECK_ERROR:
console.log(stdout)
break
default:
console.log(err)
}
reject()
} else {
log('Type check completed without errors')
resolve()
}
})
})
| import { execFile } from 'child_process'
import flow from 'flow-bin'
import { logError, logWarning, log } from '../util/log'
const errorCodes = {
TYPECHECK_ERROR: 2
}
export default (saguiOptions) => new Promise((resolve, reject) => {
// Currently Facebook does not provide Windows builds.
// https://github.com/flowtype/flow-bin#flow-bin-
//
// Instead of using `flow`, we show a warning and ignore this task
// For further discussion, you can go to:
// https://github.com/saguijs/sagui/issues/179
if (process.platform === 'win32') {
logWarning('Type checking in Windows is not currently supported')
log('Official flow builds for Windows are not currently provided.')
log('We are exploring options in https://github.com/saguijs/sagui/issues/179')
return resolve()
}
const commandArgs = ['check', '--color=always']
if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) {
commandArgs.push('--all')
}
execFile(flow, commandArgs, (err, stdout, stderr) => {
if (err) {
logError('Type check failed:\n')
switch (err.code) {
case errorCodes.TYPECHECK_ERROR:
console.log(stdout)
break
default:
console.log(err)
}
reject()
} else {
log('Type check completed without errors')
resolve()
}
})
})
| Disable type checking in Windows 😞 | Disable type checking in Windows 😞
| JavaScript | mit | saguijs/sagui,saguijs/sagui | ---
+++
@@ -1,12 +1,26 @@
import { execFile } from 'child_process'
import flow from 'flow-bin'
-import { logError, log } from '../util/log'
+import { logError, logWarning, log } from '../util/log'
const errorCodes = {
TYPECHECK_ERROR: 2
}
export default (saguiOptions) => new Promise((resolve, reject) => {
+ // Currently Facebook does not provide Windows builds.
+ // https://github.com/flowtype/flow-bin#flow-bin-
+ //
+ // Instead of using `flow`, we show a warning and ignore this task
+ // For further discussion, you can go to:
+ // https://github.com/saguijs/sagui/issues/179
+ if (process.platform === 'win32') {
+ logWarning('Type checking in Windows is not currently supported')
+ log('Official flow builds for Windows are not currently provided.')
+ log('We are exploring options in https://github.com/saguijs/sagui/issues/179')
+
+ return resolve()
+ }
+
const commandArgs = ['check', '--color=always']
if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) { |
b6c7749859a6bba20301d5b0ad01754624964829 | coeus-webapp/src/main/webapp/scripts/common/global.js | coeus-webapp/src/main/webapp/scripts/common/global.js | var Kc = Kc || {};
Kc.Global = Kc.Global || {};
(function (namespace, $) {
// set all modals to static behavior (clicking out does not close)
$.fn.modal.Constructor.DEFAULTS.backdrop = "static";
})(Kc.Global, jQuery); | var Kc = Kc || {};
Kc.Global = Kc.Global || {};
(function (namespace, $) {
// set all modals to static behavior (clicking out does not close)
$.fn.modal.Constructor.DEFAULTS.backdrop = "static";
$(document).on("ready", function(){
// date conversion for date fields to full leading 0 - for days and months and to full year dates
$(document).on("blur", ".uif-dateControl", function(){
var dateFormat = $.datepicker._defaults.dateFormat;
var date = $(this).val();
if (!date) {
return;
}
date = date.replace(/-/g, "/");
if (date && (date.match(/\//g) || []).length === 2) {
// find the expected position and value of year in the string based on date format
var year;
if (dateFormat.indexOf("y") === 0) {
year = date.substr(0, date.indexOf("/"));
}
else {
year = date.substr(date.lastIndexOf("/") + 1, date.length - 1);
}
// when year is length of 2 append the first 2 numbers of the current full year (ie 14 -> 2014)
if (year.length === 2) {
var currentDate = new Date();
year = currentDate.getFullYear().toString().substr(0,2) + year;
}
var dateObj = new Date(date);
if (isNaN(dateObj.valueOf())) {
// not valid abandon conversion
return;
}
dateObj.setFullYear(year);
var formattedDate = $.datepicker.formatDate(dateFormat, dateObj);
$(this).val(formattedDate);
}
});
});
})(Kc.Global, jQuery); | Convert non-full date to full date on loss of focus in js | [KRACOEUS-8479] Convert non-full date to full date on loss of focus in js
| JavaScript | agpl-3.0 | geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit | ---
+++
@@ -3,4 +3,46 @@
(function (namespace, $) {
// set all modals to static behavior (clicking out does not close)
$.fn.modal.Constructor.DEFAULTS.backdrop = "static";
+
+ $(document).on("ready", function(){
+ // date conversion for date fields to full leading 0 - for days and months and to full year dates
+ $(document).on("blur", ".uif-dateControl", function(){
+ var dateFormat = $.datepicker._defaults.dateFormat;
+ var date = $(this).val();
+ if (!date) {
+ return;
+ }
+
+ date = date.replace(/-/g, "/");
+
+ if (date && (date.match(/\//g) || []).length === 2) {
+
+ // find the expected position and value of year in the string based on date format
+ var year;
+ if (dateFormat.indexOf("y") === 0) {
+ year = date.substr(0, date.indexOf("/"));
+ }
+ else {
+ year = date.substr(date.lastIndexOf("/") + 1, date.length - 1);
+ }
+
+ // when year is length of 2 append the first 2 numbers of the current full year (ie 14 -> 2014)
+ if (year.length === 2) {
+ var currentDate = new Date();
+ year = currentDate.getFullYear().toString().substr(0,2) + year;
+ }
+
+ var dateObj = new Date(date);
+ if (isNaN(dateObj.valueOf())) {
+ // not valid abandon conversion
+ return;
+ }
+
+ dateObj.setFullYear(year);
+
+ var formattedDate = $.datepicker.formatDate(dateFormat, dateObj);
+ $(this).val(formattedDate);
+ }
+ });
+ });
})(Kc.Global, jQuery); |
e041a79fdfa455939b44436677b6ee40d3534e24 | app/scripts/pipelineDirectives/droprowsfunction.js | app/scripts/pipelineDirectives/droprowsfunction.js | 'use strict';
/**
* @ngdoc directive
* @name grafterizerApp.directive:dropRowsFunction
* @description
* # dropRowsFunction
*/
angular.module('grafterizerApp')
.directive('dropRowsFunction', function(transformationDataModel) {
return {
templateUrl: 'views/pipelineFunctions/dropRowsFunction.html',
restrict: 'E',
link: function postLink(scope, element, attrs) {
if (!scope.function) {
scope.function = {
numberOfRows: 1,
take: true,
docstring: null
};
}
scope.$parent.generateCurrFunction = function() {
return new transformationDataModel.DropRowsFunction(parseInt(
scope.function.numberOfRows), scope.function.take, scope.function.docstring);
};
scope.doGrep = function() {
scope.$parent.selectefunctionName = 'grep';
};
scope.showUsage = false;
scope.switchShowUsage = function() {
scope.showUsage = !scope.showUsage;
};
}
};
});
| 'use strict';
/**
* @ngdoc directive
* @name grafterizerApp.directive:dropRowsFunction
* @description
* # dropRowsFunction
*/
angular.module('grafterizerApp')
.directive('dropRowsFunction', function(transformationDataModel) {
return {
templateUrl: 'views/pipelineFunctions/dropRowsFunction.html',
restrict: 'E',
link: function postLink(scope, element, attrs) {
if (!scope.function) {
scope.function = {
numberOfRows: 1,
take: false,
docstring: null
};
}
scope.$parent.generateCurrFunction = function() {
return new transformationDataModel.DropRowsFunction(parseInt(
scope.function.numberOfRows), scope.function.take, scope.function.docstring);
};
scope.doGrep = function() {
scope.$parent.selectefunctionName = 'grep';
};
scope.showUsage = false;
scope.switchShowUsage = function() {
scope.showUsage = !scope.showUsage;
};
}
};
});
| Use drop row by default | Use drop row by default
| JavaScript | epl-1.0 | dapaas/grafterizer,dapaas/grafterizer,datagraft/grafterizer,datagraft/grafterizer | ---
+++
@@ -15,7 +15,7 @@
if (!scope.function) {
scope.function = {
numberOfRows: 1,
- take: true,
+ take: false,
docstring: null
};
} |
387fe28bf03d894ea37483455067c43edb7ef947 | public/app/scripts/controllers/users.js | public/app/scripts/controllers/users.js | 'use strict';
angular.module('publicApp')
.controller('UsersCtrl', ['$scope', '$http', '$location', '$routeParams', 'UserService', function ($scope, $http, $location, $user, $routeParams) {
console.log('user id', $routeParams.id);
if ($user) {
console.log('user is logged in');
if (($user.id == $routeParams.id) || $user.admin) {
console.log('user is allowed to access this resource');
} else {
$location.path = '/users/'+$user.id;
}
} else {
$location.path = '/login';
}
}]);
| 'use strict';
angular.module('publicApp')
.controller('UsersCtrl', ['$scope', '$http', '$location', '$route', '$routeParams', 'UserService', function ($scope, $http, $location, $route, $routeParams, $user) {
$scope.user = $user;
if ($user.isLogged) {
if (($user.id == $routeParams.id) || $user.admin) {
// do ALL THE THINGS!
setupDashboard();
console.log($scope.user);
} else {
$location.path('/users/'+$user.id);
}
} else {
$location.path('/login');
}
function setupDashboard() {
$scope.user.balances = [{ currency: 'USD', amount: 1510 }, { currency: 'XAG', amount: 75 }];
$scope.user.ripple_transactions = [];
$scope.user.external_transaction = [];
$scope.user.external_accounts = [];
$scope.user.ripple_addresses = [];
}
}]);
| Add user data variables to scope | [FEATURE] Add user data variables to scope
| JavaScript | isc | Parkjeahwan/awegeeks,Parkjeahwan/awegeeks,crazyquark/gatewayd,xdv/gatewayd,whotooktwarden/gatewayd,zealord/gatewayd,zealord/gatewayd,crazyquark/gatewayd,xdv/gatewayd,whotooktwarden/gatewayd | ---
+++
@@ -1,17 +1,26 @@
'use strict';
angular.module('publicApp')
- .controller('UsersCtrl', ['$scope', '$http', '$location', '$routeParams', 'UserService', function ($scope, $http, $location, $user, $routeParams) {
- console.log('user id', $routeParams.id);
- if ($user) {
- console.log('user is logged in');
+ .controller('UsersCtrl', ['$scope', '$http', '$location', '$route', '$routeParams', 'UserService', function ($scope, $http, $location, $route, $routeParams, $user) {
+ $scope.user = $user;
+ if ($user.isLogged) {
if (($user.id == $routeParams.id) || $user.admin) {
- console.log('user is allowed to access this resource');
+ // do ALL THE THINGS!
+ setupDashboard();
+ console.log($scope.user);
} else {
- $location.path = '/users/'+$user.id;
+ $location.path('/users/'+$user.id);
}
} else {
- $location.path = '/login';
+ $location.path('/login');
+ }
+
+ function setupDashboard() {
+ $scope.user.balances = [{ currency: 'USD', amount: 1510 }, { currency: 'XAG', amount: 75 }];
+ $scope.user.ripple_transactions = [];
+ $scope.user.external_transaction = [];
+ $scope.user.external_accounts = [];
+ $scope.user.ripple_addresses = [];
}
}]); |
a005ed629f02f7f61ac2719ad7286693935fbfab | tut5/script.js | tut5/script.js | $(document).ready(function () {
})
| $(document).ready(function main() {
$("#add").click(function addRow() {
var name = $("<td></td>").text($("#name").val());
var up = $("<button></button>").text("Move up").click(moveUp);
var down = $("<button></button>").text("Move down").click(moveDown);
var operations = $("<td></td>").append(up, down);
var row = $("<tr></tr>").append(name, operations);
$("#nameList").append(row);
$("#name").val("");
})
})
function moveUp() {
}
function moveDown() {
}
| Implement adding rows to the table | Implement adding rows to the table
| JavaScript | mit | benediktg/DDS-tutorial,benediktg/DDS-tutorial,benediktg/DDS-tutorial | ---
+++
@@ -1,3 +1,20 @@
-$(document).ready(function () {
+$(document).ready(function main() {
+ $("#add").click(function addRow() {
+ var name = $("<td></td>").text($("#name").val());
+ var up = $("<button></button>").text("Move up").click(moveUp);
+ var down = $("<button></button>").text("Move down").click(moveDown);
+ var operations = $("<td></td>").append(up, down);
+ var row = $("<tr></tr>").append(name, operations);
+ $("#nameList").append(row);
+ $("#name").val("");
+ })
})
+
+function moveUp() {
+
+}
+
+function moveDown() {
+
+} |
66297d71ac6675625201c20ef3a24c0156839469 | src/javascripts/frigging_bootstrap/components/text.js | src/javascripts/frigging_bootstrap/components/text.js | let React = require("react")
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, textarea} = React.DOM
let cx = require("classnames")
export default class extends React.Component {
static displayName = "Frig.friggingBootstrap.Text"
static defaultProps = Object.assign(require("../default_props.js"))
_inputHtml() {
return Object.assign({}, this.props.inputHtml, {
className: `${this.props.className || ""} form-control`.trim(),
valueLink: this.props.valueLink,
})
}
_cx() {
return cx({
"form-group": true,
"has-error": this.props.errors != null,
"has-success": this.state.edited && this.props.errors == null,
})
}
_label() {
if (this.props.label == null) return ""
return label(this.props.labelHtml, this.props.label)
}
render() {
return div({className: cx(sizeClassNames(this.props))},
div({className: this._cx()},
this._label(),
div({className: "controls"},
textarea(this._inputHtml()),
),
this._errorList(this.props.errors),
),
)
}
}
| let React = require("react")
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, textarea} = React.DOM
let cx = require("classnames")
export default class extends React.Component {
static displayName = "Frig.friggingBootstrap.Text"
static defaultProps = Object.assign(require("../default_props.js"))
_inputHtml() {
return Object.assign({}, this.props.inputHtml, {
className: `${this.props.className || ""} form-control`.trim(),
valueLink: this.props.valueLink,
})
}
_cx() {
return cx({
"form-group": true,
"has-error": this.props.errors != null,
"has-success": this.state.edited && this.props.errors == null,
})
}
render() {
return div({className: cx(sizeClassNames(this.props))},
div({className: this._cx()},
label(this.props),
div({className: "controls"},
textarea(this._inputHtml()),
),
errorList(this.props.errors),
),
)
}
}
| Remove Textarea Label, Use Frig Version Instead | Remove Textarea Label, Use Frig Version Instead
| JavaScript | mit | TouchBistro/frig,frig-js/frig,frig-js/frig,TouchBistro/frig | ---
+++
@@ -24,19 +24,14 @@
})
}
- _label() {
- if (this.props.label == null) return ""
- return label(this.props.labelHtml, this.props.label)
- }
-
render() {
return div({className: cx(sizeClassNames(this.props))},
div({className: this._cx()},
- this._label(),
+ label(this.props),
div({className: "controls"},
textarea(this._inputHtml()),
),
- this._errorList(this.props.errors),
+ errorList(this.props.errors),
),
)
} |
9e5ab890d8ca61ee5d86b2bc4ae29a5ddada60f7 | website/app/application/core/projects/project/home/home.js | website/app/application/core/projects/project/home/home.js | (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];
function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.chooseExistingProcess = chooseExistingProcess;
ctrl.templates = templates;
ctrl.hasFavorites = _.partial(_.any, ctrl.templates, _.matchesProperty('favorite', true));
/////////////////////////
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
});
}
function chooseExistingProcess() {
Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
var processName = existingProcess.process_name ? existingProcess.process_name : 'TEM';
$state.go('projects.project.processes.create', {process: processName, process_id: existingProcess.id});
});
});
}
}
}(angular.module('materialscommons')));
| (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];
function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.chooseExistingProcess = chooseExistingProcess;
ctrl.templates = templates;
ctrl.hasFavorites = _.partial(_.any, ctrl.templates, _.matchesProperty('favorite', true));
/////////////////////////
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
});
}
function chooseExistingProcess() {
Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
$state.go('projects.project.processes.create',
{process: existingProcess.process_name, process_id: existingProcess.id});
});
});
}
}
}(angular.module('materialscommons')));
| Remove the hard coded process name now that the process name has been set. | Remove the hard coded process name now that the process name has been set.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -22,8 +22,8 @@
function chooseExistingProcess() {
Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
- var processName = existingProcess.process_name ? existingProcess.process_name : 'TEM';
- $state.go('projects.project.processes.create', {process: processName, process_id: existingProcess.id});
+ $state.go('projects.project.processes.create',
+ {process: existingProcess.process_name, process_id: existingProcess.id});
});
});
} |
aff1582fbd5163dcf299897751bff0c21f99a408 | app/services/report-results.js | app/services/report-results.js | import Ember from 'ember';
const { inject } = Ember;
const { service } = inject;
export default Ember.Service.extend({
store: service(),
getResults(subject, object, objectId){
return this.get('store').query(
this.getModel(subject),
this.getQuery(object, objectId)
).then(results => {
return results.map(result => {
return this.mapResult(result, object);
});
});
},
getModel(subject){
let model = subject.dasherize();
if(model === 'instructor'){
model = 'user';
}
if(model === 'mesh-term'){
model = 'mesh-descriptor';
}
return model;
},
getQuery(object, objectId){
let query = {
limit: 1000
};
if(object && objectId){
query.filter = {};
query.filter[object] = objectId;
}
return query;
},
mapResult(result, object){
let titleParam = 'title';
if(object === 'instructor'){
titleParam = 'fullName';
}
if(object === 'mesh-term'){
titleParam = 'name';
}
return {
value: result.get(titleParam)
};
}
});
| import Ember from 'ember';
const { inject } = Ember;
const { service } = inject;
export default Ember.Service.extend({
store: service(),
getResults(subject, object, objectId){
return this.get('store').query(
this.getModel(subject),
this.getQuery(object, objectId)
).then(results => {
return results.map(result => {
return this.mapResult(result, object);
});
});
},
getModel(subject){
let model = subject.dasherize();
if(model === 'instructor'){
model = 'user';
}
if(model === 'mesh-term'){
model = 'mesh-descriptor';
}
return model;
},
getQuery(object, objectId){
let query = {
limit: 1000
};
if(object && objectId){
query.filters = {};
query.filters[object] = objectId;
}
return query;
},
mapResult(result, object){
let titleParam = 'title';
if(object === 'instructor'){
titleParam = 'fullName';
}
if(object === 'mesh-term'){
titleParam = 'name';
}
return {
value: result.get(titleParam)
};
}
});
| Fix report query to actually query | Fix report query to actually query
| JavaScript | mit | dartajax/frontend,jrjohnson/frontend,gboushey/frontend,thecoolestguy/frontend,dartajax/frontend,gabycampagna/frontend,thecoolestguy/frontend,stopfstedt/frontend,jrjohnson/frontend,stopfstedt/frontend,ilios/frontend,gboushey/frontend,gabycampagna/frontend,ilios/frontend,djvoa12/frontend,djvoa12/frontend | ---
+++
@@ -31,8 +31,8 @@
limit: 1000
};
if(object && objectId){
- query.filter = {};
- query.filter[object] = objectId;
+ query.filters = {};
+ query.filters[object] = objectId;
}
return query; |
8d20035df56fcc1d40c6d28ad8e7a4ff30900636 | script.js | script.js | var ctx = document.getElementById("chart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, {
tooltipTemplate = function(valuesObject){
var label = valuesObject.label;
var idx = data.labels.indexOf(label);
var result = data.datasets[0].time[idx];
if (data.datasets[0].languages[idx] !== 0)
result += '[' + data.datasets[0].languages[idx].join(", ") + "]"
return result;
}
});
document.getElementById("summary").innerHTML = "I have written code for " + totalTime + " in the the last week in mostly " + languages.join(", ") + ".";
| var data = {"labels": ["12 December", "13 December", "14 December", "15 December", "16 December", "17 December", "18 December"], "datasets": [{"languages": [[], [], [], [], [], ["Python", "Other"], ["Python", "JavaScript", "Bash"]], "pointHighlightFill": "#fff", "fillColor": "rgba(151,187,205,0.2)", "pointHighlightStroke": "rgba(151,187,205,1)", "time": [" 0 secs", " 0 secs", " 0 secs", " 0 secs", " 0 secs", "53 mins", "2 hrs 17 mins"], "pointColor": "rgba(151,187,205,1)", "strokeColor": "rgba(151,187,205,1)", "pointStrokeColor": "#fff", "data": [0.0, 0.0, 0.0, 0.0, 0.0, 0.8852777777777778, 2.2880555555555557], "label": "Dataset"}]};
var totalTime = "3 hours 10 minutes";
var languages = ["Python", "JavaScript", "Bash"];
var ctx = document.getElementById("chart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, {
tooltipTemplate = function(valuesObject){
var label = valuesObject.label;
var idx = data.labels.indexOf(label);
var result = data.datasets[0].time[idx];
if (data.datasets[0].languages[idx] !== 0)
result += '[' + data.datasets[0].languages[idx].join(", ") + "]"
return result;
}
});
document.getElementById("summary").innerHTML = "I have written code for " + totalTime + " in the the last week in mostly " + languages.join(", ") + ".";
| Update dashboard at Fri Dec 18 02:17:47 NPT 2015 | Update dashboard at Fri Dec 18 02:17:47 NPT 2015
| JavaScript | mit | switchkiller/HaloTracker,switchkiller/HaloTracker,switchkiller/HaloTracker | ---
+++
@@ -1,3 +1,6 @@
+var data = {"labels": ["12 December", "13 December", "14 December", "15 December", "16 December", "17 December", "18 December"], "datasets": [{"languages": [[], [], [], [], [], ["Python", "Other"], ["Python", "JavaScript", "Bash"]], "pointHighlightFill": "#fff", "fillColor": "rgba(151,187,205,0.2)", "pointHighlightStroke": "rgba(151,187,205,1)", "time": [" 0 secs", " 0 secs", " 0 secs", " 0 secs", " 0 secs", "53 mins", "2 hrs 17 mins"], "pointColor": "rgba(151,187,205,1)", "strokeColor": "rgba(151,187,205,1)", "pointStrokeColor": "#fff", "data": [0.0, 0.0, 0.0, 0.0, 0.0, 0.8852777777777778, 2.2880555555555557], "label": "Dataset"}]};
+var totalTime = "3 hours 10 minutes";
+var languages = ["Python", "JavaScript", "Bash"];
var ctx = document.getElementById("chart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, {
tooltipTemplate = function(valuesObject){ |
6af74e45b203a159b1401c7815c68b476b8835e0 | src/test/helper/database/index.js | src/test/helper/database/index.js | import mongoose from "mongoose"
async function createConnection() {
mongoose.Promise = Promise
// Don't forget to add a user for this connection
const connection = await mongoose.connect("mongodb://localhost/twi-test", {
useMongoClient: true,
promiseLibrary: Promise
})
return connection
}
async function closeConnection() {
return await mongoose.disconnect()
}
export {
createConnection,
closeConnection
}
| import mongoose from "mongoose"
async function createConnection() {
mongoose.Promise = Promise
// Don't forget to add a user for this connection
const connection = await mongoose.connect("mongodb://localhost/twi-test", {
promiseLibrary: Promise
})
return connection
}
async function closeConnection() {
return await mongoose.disconnect()
}
export {
createConnection,
closeConnection
}
| Fix db connection in tests helper | Fix db connection in tests helper
| JavaScript | mit | octet-stream/ponyfiction-js,octet-stream/twi,octet-stream/ponyfiction-js,twi-project/twi-server | ---
+++
@@ -5,7 +5,6 @@
// Don't forget to add a user for this connection
const connection = await mongoose.connect("mongodb://localhost/twi-test", {
- useMongoClient: true,
promiseLibrary: Promise
})
|
45d8406eea3afee7049c26d5449e5b86e46eef61 | migrations/20170310124040_add_event_id_for_actions.js | migrations/20170310124040_add_event_id_for_actions.js |
exports.up = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.string('event_id').index();
table.foreign('event_id')
.references('id')
.inTable('events')
.onDelete('RESTRICT')
.onUpdate('CASCADE');
})
.raw(`
CREATE UNIQUE INDEX
only_one_check_in_per_event
ON
actions(user_id, event_id)
WHERE action_type_id = 9;
`);
};
// ALTER TABLE actions ADD CONSTRAINT actions_user_event_uniq UNIQUE (user_id, event_id)
exports.down = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.dropColumn('event_id');
});
}
|
exports.up = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.string('event_id').index();
table.foreign('event_id')
.references('id')
.inTable('events')
.onDelete('RESTRICT')
.onUpdate('CASCADE');
})
.raw(`
CREATE UNIQUE INDEX
only_one_check_in_per_event
ON
actions(user_id, event_id)
-- Magic number 9 is CHECK_IN_EVENT action type ID.
WHERE action_type_id = 9;
`);
};
exports.down = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.dropColumn('event_id');
});
}
| Comment to explain the magic number | Comment to explain the magic number
| JavaScript | mit | futurice/wappuapp-backend,futurice/wappuapp-backend,kaupunki-apina/prahapp-backend,kaupunki-apina/prahapp-backend | ---
+++
@@ -13,10 +13,11 @@
only_one_check_in_per_event
ON
actions(user_id, event_id)
+ -- Magic number 9 is CHECK_IN_EVENT action type ID.
WHERE action_type_id = 9;
`);
};
-// ALTER TABLE actions ADD CONSTRAINT actions_user_event_uniq UNIQUE (user_id, event_id)
+
exports.down = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.dropColumn('event_id'); |
9e0376684a68efedbfa5a4c43dedb1de966ec15f | lib/lookup-reopen/main.js | lib/lookup-reopen/main.js | Ember.ComponentLookup.reopen({
lookupFactory: function(name) {
var Component = this._super.apply(this, arguments);
if (!Component) { return; }
name = name.replace(".","/");
if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){
return Component;
}
return Component.reopen({
classNames: [Ember.COMPONENT_CSS_LOOKUP[name]]
});
},
componentFor: function(name) {
var Component = this._super.apply(this, arguments);
if (!Component) { return; }
name = name.replace(".","/");
if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){
return Component;
}
return Component.reopen({
classNames: [Ember.COMPONENT_CSS_LOOKUP[name]]
});
}
});
| (function() {
function componentHasBeenReopened(Component, className) {
return Component.prototype.classNames.indexOf(className) > -1;
}
function reopenComponent(_Component, className) {
var Component = _Component.reopen({
classNames: [className]
});
return Component;
}
function ensureComponentCSSClassIncluded(_Component, _name) {
var Component = _Component;
var name = name.replace(".","/");
var className = Ember.COMPONENT_CSS_LOOKUP[name];
if (!componentHasBeenReopened(Component)) {
Component = reopenComponent(Component, className);
}
return Component;
}
Ember.ComponentLookup.reopen({
lookupFactory: function(name) {
var Component = this._super.apply(this, arguments);
if (!Component) { return; }
return ensureComponentCSSClassIncluded(Component, name);
},
componentFor: function(name) {
var Component = this._super.apply(this, arguments);
if (!Component) { return; }
return ensureComponentCSSClassIncluded(Component, name);
}
});
})()
| Refactor monkey-patch to include less duplication. | Refactor monkey-patch to include less duplication.
| JavaScript | mit | samselikoff/ember-component-css,samselikoff/ember-component-css,webark/ember-component-css,ebryn/ember-component-css,ebryn/ember-component-css,webark/ember-component-css | ---
+++
@@ -1,32 +1,43 @@
-Ember.ComponentLookup.reopen({
- lookupFactory: function(name) {
- var Component = this._super.apply(this, arguments);
+(function() {
+ function componentHasBeenReopened(Component, className) {
+ return Component.prototype.classNames.indexOf(className) > -1;
+ }
- if (!Component) { return; }
+ function reopenComponent(_Component, className) {
+ var Component = _Component.reopen({
+ classNames: [className]
+ });
- name = name.replace(".","/");
- if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){
- return Component;
+ return Component;
+ }
+
+ function ensureComponentCSSClassIncluded(_Component, _name) {
+ var Component = _Component;
+ var name = name.replace(".","/");
+ var className = Ember.COMPONENT_CSS_LOOKUP[name];
+
+ if (!componentHasBeenReopened(Component)) {
+ Component = reopenComponent(Component, className);
}
- return Component.reopen({
- classNames: [Ember.COMPONENT_CSS_LOOKUP[name]]
- });
- },
+ return Component;
+ }
- componentFor: function(name) {
- var Component = this._super.apply(this, arguments);
+ Ember.ComponentLookup.reopen({
+ lookupFactory: function(name) {
+ var Component = this._super.apply(this, arguments);
- if (!Component) { return; }
+ if (!Component) { return; }
- name = name.replace(".","/");
+ return ensureComponentCSSClassIncluded(Component, name);
+ },
- if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){
- return Component;
+ componentFor: function(name) {
+ var Component = this._super.apply(this, arguments);
+
+ if (!Component) { return; }
+
+ return ensureComponentCSSClassIncluded(Component, name);
}
-
- return Component.reopen({
- classNames: [Ember.COMPONENT_CSS_LOOKUP[name]]
- });
- }
-});
+ });
+})() |
a7bf2991eb9c5d093cc2f90ca5491bf0d7ee3433 | frontend/src/karma.conf.js | frontend/src/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) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('karma-mocha-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['kjhtml', 'mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
customLaunchers: {
ChromeHeadlessForDocker: {
base: 'ChromeHeadless',
flags: [
'--disable-web-security',
'--disable-gpu',
'--no-sandbox'
],
displayName: 'Chrome Headless for docker'
}
},
browsers: ['Chrome']
});
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('karma-mocha-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['kjhtml', 'mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
customLaunchers: {
ChromeHeadlessForDocker: {
base: 'ChromeHeadless',
flags: [
'--disable-web-security',
'--disable-gpu',
'--no-sandbox'
],
displayName: 'Chrome Headless for docker'
}
},
browsers: ['ChromeHeadlessForDocker']
});
};
| Use headless Chrome for Angular tests again. | Fix: Use headless Chrome for Angular tests again.
| JavaScript | apache-2.0 | iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,IteraSpeed/OpenSpeedMonitor,IteraSpeed/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,iteratec/OpenSpeedMonitor,IteraSpeed/OpenSpeedMonitor | ---
+++
@@ -38,6 +38,6 @@
displayName: 'Chrome Headless for docker'
}
},
- browsers: ['Chrome']
+ browsers: ['ChromeHeadlessForDocker']
});
}; |
4393047a5ca961d06eedb3501b8d1e0b0a68b279 | player.js | player.js | var game = require('socket.io-client')('http://192.168.0.24:3000'),
lobby = require('socket.io-client')('http://192.168.0.24:3030'),
Chess = require('chess.js').Chess,
name = 'RndJesus_' + Math.floor(Math.random() * 100);;
lobby.on('connect', function () {
console.log('Player ' + name + ' is connected to lobby');
});
lobby.on('join', function (gameId) {
console.log('Player is joining game: ' + gameId);
game.emit('join', gameId);
});
game.on('connect', function () {
console.log('Player ' + name + ' is connected to game');
//game.emit('join', 'test_game');
});
game.on('move', function (gameState) {
var chess = new Chess();
chess.load(gameState.board);
var moves = chess.moves(),
move = moves[Math.floor(Math.random() * moves.length)];
console.log(move);
gameState.move = move;
game.emit('move', gameState);
});
| var game = require('socket.io-client')('http://localhost:3000'),
lobby = require('socket.io-client')('http://localhost:3030'),
Chess = require('chess.js').Chess,
name = 'RndJesus_' + Math.floor(Math.random() * 100);;
lobby.on('connect', function () {
console.log('Player ' + name + ' is connected to lobby');
});
lobby.on('join', function (gameId) {
console.log('Player is joining game: ' + gameId);
game.emit('join', gameId);
});
game.on('connect', function () {
console.log('Player ' + name + ' is connected to game');
//game.emit('join', 'test_game');
});
game.on('move', function (gameState) {
var chess = new Chess();
chess.load(gameState.board);
var moves = chess.moves(),
move = moves[Math.floor(Math.random() * moves.length)];
console.log(move);
gameState.move = move;
game.emit('move', gameState);
});
| Use localhost when running locally | Use localhost when running locally
| JavaScript | mit | cheslie-team/cheslie-player,cheslie-team/cheslie-player | ---
+++
@@ -1,5 +1,5 @@
-var game = require('socket.io-client')('http://192.168.0.24:3000'),
- lobby = require('socket.io-client')('http://192.168.0.24:3030'),
+var game = require('socket.io-client')('http://localhost:3000'),
+ lobby = require('socket.io-client')('http://localhost:3030'),
Chess = require('chess.js').Chess,
name = 'RndJesus_' + Math.floor(Math.random() * 100);; |
542a5dc9cb71b9bcb402620b82d4c5c8c8c98109 | lib/node_modules/@stdlib/utils/timeit/lib/min_time.js | lib/node_modules/@stdlib/utils/timeit/lib/min_time.js | 'use strict';
// MAIN //
/**
* Computes the minimum time.
*
* @private
* @param {ArrayArray} times - times
* @returns {NonNegativeIntegerArray} minimum time
*/
function min( times ) {
var out;
var t;
var i;
out = times[ 0 ];
for ( i = 1; i < times.length; i++ ) {
t = times[ i ];
if (
t[ 0 ] <= out[ 0 ] &&
t[ 1 ] < out[ 1 ]
) {
out = t;
}
}
return out;
} // end FUNCTION min()
// EXPORTS //
module.exports = min;
| 'use strict';
// MAIN //
/**
* Computes the minimum time.
*
* @private
* @param {ArrayArray} times - times
* @returns {NonNegativeIntegerArray} minimum time
*/
function min( times ) {
var out;
var t;
var i;
out = times[ 0 ];
for ( i = 1; i < times.length; i++ ) {
t = times[ i ];
if (
t[ 0 ] < out[ 0 ] ||
(
t[ 0 ] === out[ 0 ] &&
t[ 1 ] < out[ 1 ]
)
) {
out = t;
}
}
return out;
} // end FUNCTION min()
// EXPORTS //
module.exports = min;
| Fix bug when calculating minimum time | Fix bug when calculating minimum time
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -18,8 +18,11 @@
for ( i = 1; i < times.length; i++ ) {
t = times[ i ];
if (
- t[ 0 ] <= out[ 0 ] &&
- t[ 1 ] < out[ 1 ]
+ t[ 0 ] < out[ 0 ] ||
+ (
+ t[ 0 ] === out[ 0 ] &&
+ t[ 1 ] < out[ 1 ]
+ )
) {
out = t;
} |
a48d5a1ae957db81aa464d463a4aab0b15ff29a2 | lib/server.js | lib/server.js | var st = require('st')
, http = require('http')
, js = require('atomify-js')
, css = require('atomify-css')
, open = require('open')
module.exports = function (args) {
var mount = st(args.server.st || process.cwd())
, port = args.server.port || 1337
, launch = args.server.open
, path = args.server.path || ''
, url = args.server.url || 'http://localhost:' + port + path
http.createServer(function(req, res) {
switch (req.url) {
case args.js.alias || args.js.entry:
js(args.js, responder('javascript', res))
break
case args.css.alias || args.css.entry:
css(args.css, responder('css', res))
break
default:
mount(req, res)
break
}
}).listen(port)
if (launch) open(url)
}
function responder (type, res) {
return function (err, src) {
if (!res.headersSent) res.setHeader('Content-Type', 'text/' + type)
res.end(src)
}
}
| var st = require('st')
, http = require('http')
, js = require('atomify-js')
, css = require('atomify-css')
, open = require('open')
module.exports = function (args) {
var mount = st(args.server.st || process.cwd())
, port = args.server.port || 1337
, launch = args.server.open
, path = args.server.path || '/'
, url
if (path.charAt(0) !== '/') path = '/' + path
url = args.server.url || 'http://localhost:' + port + path
http.createServer(function (req, res) {
switch (req.url) {
case args.js.alias || args.js.entry:
js(args.js, responder('javascript', res))
break
case args.css.alias || args.css.entry:
css(args.css, responder('css', res))
break
default:
mount(req, res)
break
}
}).listen(port)
if (launch) open(url)
}
function responder (type, res) {
return function (err, src) {
if (!res.headersSent) res.setHeader('Content-Type', 'text/' + type)
res.end(src)
}
}
| Add leading slash to path if not provided | Add leading slash to path if not provided | JavaScript | mit | atomify/atomify | ---
+++
@@ -9,10 +9,14 @@
var mount = st(args.server.st || process.cwd())
, port = args.server.port || 1337
, launch = args.server.open
- , path = args.server.path || ''
- , url = args.server.url || 'http://localhost:' + port + path
+ , path = args.server.path || '/'
+ , url
- http.createServer(function(req, res) {
+ if (path.charAt(0) !== '/') path = '/' + path
+
+ url = args.server.url || 'http://localhost:' + port + path
+
+ http.createServer(function (req, res) {
switch (req.url) {
case args.js.alias || args.js.entry: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.