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
cb92521b4c237e8a6d7b26f0fe02c26b10187c3a
modifyurl@2ch.user.js
modifyurl@2ch.user.js
// ==UserScript== // @id Modify URL @2ch // @name Modify URL @2ch // @version 0.0.5 // @namespace curipha // @author curipha // @description Modify "ttp://" text to anchor and redirect URIs to direct link. // @include http://*.2ch.net/* // @include http://*.bbspink.com/* // @run-at document-end // @grant none // ==/UserScript== (function(){ var anchor = document.getElementsByTagName('a'); var pattern = /^http:\/\/([^\/]+\.)?(ime\.(nu|st)\/|pinktower\.com\/|jump\.2ch\.net\/\?)/i; for (var a of anchor) { if (a.href.indexOf('http') !== 0) continue; uri = a.href.replace(pattern, 'http://'); a.href = decodeURIComponent(uri); } var dd = document.getElementsByTagName('dd'); var ttp = /([^h])(ttps?:\/\/[\x21-\x7E]+)/ig; for (var d of dd) { d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>'); } })();
// ==UserScript== // @id Modify URL @2ch // @name Modify URL @2ch // @version 0.0.6 // @namespace curipha // @author curipha // @description Modify "ttp://" text to anchor and redirect URIs to direct link. // @include http://*.2ch.net/* // @include http://*.bbspink.com/* // @run-at document-end // @grant none // ==/UserScript== (function(){ var anchor = document.getElementsByTagName('a'); var pattern = /^http:\/\/([^\/]+\.)?(ime\.(nu|st)\/|pinktower\.com\/|jump\.2ch\.net\/\?)/i; for (var a of anchor) { if (a.href.indexOf('http') !== 0) continue; uri = a.href.replace(pattern, 'http://'); a.href = decodeURIComponent(uri); } var dd = document.getElementsByTagName('dd'); var ttp = /([^h])(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig; for (var d of dd) { d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>'); } })();
Fix the potential XSS in URI-like strings with <, > and "
Fix the potential XSS in URI-like strings with <, > and "
JavaScript
unlicense
curipha/userscripts,curipha/userscripts
--- +++ @@ -1,7 +1,7 @@ // ==UserScript== // @id Modify URL @2ch // @name Modify URL @2ch -// @version 0.0.5 +// @version 0.0.6 // @namespace curipha // @author curipha // @description Modify "ttp://" text to anchor and redirect URIs to direct link. @@ -23,7 +23,7 @@ } var dd = document.getElementsByTagName('dd'); - var ttp = /([^h])(ttps?:\/\/[\x21-\x7E]+)/ig; + var ttp = /([^h])(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig; for (var d of dd) { d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>');
c515c365778b609c1e54a24bc670f23d3ef2fac4
lib/message.js
lib/message.js
/** * Creates an instance of `Message`. * * This class is used as a mock when testing Crane handlers, substituted in * place of a `Message` from the underlying message queue adapter. * * @constructor * @api protected */ function Message(cb) { this.queue = '/'; this.headers = {}; this.__cb = cb; } Message.prototype.ack = function() { if (this.__cb) { this.__cb(); } }; /** * Expose `Response`. */ module.exports = Response;
/** * Creates an instance of `Message`. * * This class is used as a mock when testing Crane handlers, substituted in * place of a `Message` from the underlying message queue adapter. * * @constructor * @api protected */ function Message(cb) { this.topic = '/'; this.headers = {}; this.__cb = cb; } Message.prototype.ack = function() { if (this.__cb) { this.__cb(); } }; /** * Expose `Message`. */ module.exports = Message;
Set topic rather than queue.
Set topic rather than queue.
JavaScript
mit
jaredhanson/chai-crane-handler
--- +++ @@ -8,7 +8,7 @@ * @api protected */ function Message(cb) { - this.queue = '/'; + this.topic = '/'; this.headers = {}; this.__cb = cb; } @@ -19,6 +19,6 @@ /** - * Expose `Response`. + * Expose `Message`. */ -module.exports = Response; +module.exports = Message;
1dabed199a7087054b64896d523983f1539802af
prepublish.js
prepublish.js
'use strict'; var fs = require('fs'); var visitors = require('react-tools/vendor/fbtransform/visitors'); var jstransform = require('jstransform'); var visitorList = visitors.getAllVisitors(); var getJsName = function(filename) { var dot = filename.lastIndexOf("."); var baseName = filename.substring(0, dot); return baseName + ".js"; } // perform es6 / jsx tranforms on all files and simultaneously copy them to the // top level. var files = fs.readdirSync('js'); for (var i = 0; i < files.length; i++) { var src = 'js/' + files[i]; var dest = getJsName(files[i]); var js = fs.readFileSync(src, {encoding: 'utf8'}); var transformed = jstransform.transform(visitorList, js).code; fs.writeFileSync(dest, transformed); }
'use strict'; var fs = require('fs'); var visitors = require('react-tools/vendor/fbtransform/visitors'); var jstransform = require('jstransform'); var visitorList = visitors.getAllVisitors(); var getJsName = function(filename) { var dot = filename.lastIndexOf("."); var baseName = filename.substring(0, dot); return baseName + ".js"; } // perform es6 / jsx tranforms on all files and simultaneously copy them to the // top level. var files = fs.readdirSync('js'); for (var i = 0; i < files.length; i++) { var src = 'js/' + files[i]; var dest = getJsName(files[i]); var js = fs.readFileSync(src, {encoding: 'utf8'}); var transformed = jstransform.transform(visitorList, js).code; transformed = transformed.replace('.jsx', '.js'); fs.writeFileSync(dest, transformed); }
Replace .jsx requires in .js to be able to require e.g. timeago
Replace .jsx requires in .js to be able to require e.g. timeago
JavaScript
mit
sloria/react-components,quicktoolbox/react-components,sloria/react-components,redsunsoft/react-components,jepezi/react-components,jepezi/react-components,Khan/react-components,redsunsoft/react-components,jepezi/react-components,vasanthk/react-components,sloria/react-components,vasanthk/react-components,quicktoolbox/react-components,redsunsoft/react-components,vasanthk/react-components,Khan/react-components,Khan/react-components,quicktoolbox/react-components
--- +++ @@ -21,6 +21,7 @@ var js = fs.readFileSync(src, {encoding: 'utf8'}); var transformed = jstransform.transform(visitorList, js).code; + transformed = transformed.replace('.jsx', '.js'); fs.writeFileSync(dest, transformed); }
3e1f0ab719845969ae82f73713374cd15342d51d
src/Node/Encoding.js
src/Node/Encoding.js
/* global exports */ /* global Buffer */ "use strict"; // module Node.Encoding exports.byteLength = function (str) { return function (enc) { return Buffer.byteLength(str, enc); }; };
/* global exports */ /* global Buffer */ "use strict"; // module Node.Encoding exports.byteLengthImpl = function (str) { return function (enc) { return Buffer.byteLength(str, enc); }; };
Fix foreign import declaration for byteLength
Fix foreign import declaration for byteLength
JavaScript
mit
purescript-node/purescript-node-buffer
--- +++ @@ -4,8 +4,8 @@ // module Node.Encoding -exports.byteLength = function (str) { - return function (enc) { - return Buffer.byteLength(str, enc); +exports.byteLengthImpl = function (str) { + return function (enc) { + return Buffer.byteLength(str, enc); }; };
5d03539ad1fb34c246b3d7f729256c4370f1ad6d
javascript/mailblock.js
javascript/mailblock.js
(function($) { $(document).ready(function(){ showHideButton(); $('.cms-tabset-nav-primary li').on('click', showHideButton); function showHideButton() { if ($('#Root_Mailblock_set').is(':visible')) { $('#Form_EditForm_action_mailblockTestEmail').show(); } else { $('#Form_EditForm_action_mailblockTestEmail').hide(); } } }) })(jQuery);
(function($) { $(document).ready(function(){ showHideButton(); $('.cms-tabset-nav-primary li').on('click', showHideButton); function showHideButton() { if ($('#Root_Mailblock_set').is(':visible')) { $('#Form_EditForm_action_mailblockTestEmail').show(); } else { $('#Form_EditForm_action_mailblockTestEmail').hide(); } } }) })(jQuery);
Replace all tabs with spaces.
Replace all tabs with spaces.
JavaScript
bsd-3-clause
signify-nz/silverstripe-mailblock,signify-nz/silverstripe-mailblock
--- +++ @@ -1,16 +1,15 @@ (function($) { - $(document).ready(function(){ - - showHideButton(); - $('.cms-tabset-nav-primary li').on('click', showHideButton); - - function showHideButton() { - if ($('#Root_Mailblock_set').is(':visible')) { - $('#Form_EditForm_action_mailblockTestEmail').show(); - } - else { - $('#Form_EditForm_action_mailblockTestEmail').hide(); - } - } - }) + $(document).ready(function(){ + showHideButton(); + $('.cms-tabset-nav-primary li').on('click', showHideButton); + + function showHideButton() { + if ($('#Root_Mailblock_set').is(':visible')) { + $('#Form_EditForm_action_mailblockTestEmail').show(); + } + else { + $('#Form_EditForm_action_mailblockTestEmail').hide(); + } + } + }) })(jQuery);
fed9ff29a9a2390146666ec19119836fa91cd96a
examples/starters/list/js/controllers.js
examples/starters/list/js/controllers.js
angular.module('listExample.controllers', []) // Controller that fetches a list of data .controller('MovieIndexCtrl', function($scope, MovieService) { // "MovieService" is a service returning mock data (services.js) // the returned data from the service is placed into this // controller's scope so the template can render the data $scope.movies = MovieService.all(); $scope.title = "Completely Random Collection Of Movies"; }) // Controller that shows more detailed info about a movie .controller('MovieDetailCtrl', function($scope, $routeParams, MovieService) { // "MovieService" is a service returning mock data (services.js) $scope.movie = MovieService.get($routeParams.movieId); $scope.title = "Movie Info"; });
angular.module('listExample.controllers', []) // Controller that fetches a list of data .controller('MovieIndexCtrl', function($scope, MovieService,$timeout) { // "MovieService" is a service returning mock data (services.js) // the returned data from the service is placed into this // controller's scope so the template can render the data $scope.movies = MovieService.all(); $scope.title = "Completely Random Collection Of Movies"; // Method called on infinite scroll // Receives a "done" callback to inform the infinite scroll that we are done $scope.loadMore = function(done) { $timeout(function() { $scope.movies.push({ id: 'tt0114814', title: 'Usual Suspects', released: '1995', description: 'A boat has been destroyed, criminals are dead, and the key to this mystery lies with the only survivor and his twisted, convoluted story beginning with five career crooks in a seemingly random police lineup.', director: 'Bryan Singer', rating: 8.3 }); $scope.movies.push({ id: 'tt0357413', title: 'Anchorman: The Legend of Ron Burgundy', released: '2004', description: "Ron Burgundy is San Diego's top rated newsman in the male-dominated broadcasting of the 70's, but that's all about to change for Ron and his cronies when an ambitious woman is hired as a new anchor.", director: 'Adam McKay', rating: 7.2 }); $scope.movies.push({ id: 'tt0058331', title: 'Mary Poppins', released: '1964', description: "A magic nanny comes to work for a cold banker's unhappy family.", director: 'Robert Stevenson', rating: 7.7 }); done(); }, 1000); } }) // Controller that shows more detailed info about a movie .controller('MovieDetailCtrl', function($scope, $routeParams, MovieService) { // "MovieService" is a service returning mock data (services.js) $scope.movie = MovieService.get($routeParams.movieId); $scope.title = "Movie Info"; });
Add 3 movies in example, looks better
Add 3 movies in example, looks better
JavaScript
mit
Jeremy017/ionic,Jeremy017/ionic,lutrosis81/manup-app,gyx8899/ionic,Gregcop1/ionic,blueElix/ionic,Kryz/ionic,ddddm/ionic,yalishizhude/ionic,nelsonsozinho/ionic,cnbin/ionic,chrisbautista/ionic,thebigbrain/ionic,Jandersolutions/ionic,chinakids/ionic,abcd-ca/ionic,brant-hwang/ionic,Urigo/meteor-ionic,Xeeshan94/ionic,janij/ionic,ptarjan/ionic,ngonzalvez/ionic,cleor41/meteor-ionic,asfandiyark7/ionic,openbizgit/ionic,r14r-work/fork_ionic,caiiiycuk/ionic,leobetosouza/ionic,shazhumao/ionic,javascriptit/ionic,celsoyh/ionic,willshen/ionic,5amfung/ionic,qzapaia/ionic,yurtaev/ionic,r14r/fork_ionic_master,SobolevLexa/ionic,NandoKstroNet/ionic,oabc124/ionic,beauby/ionic,rreinold/FitnessDashboard_IonicApp,ahmadawais/ionic,rreinold/FitnessDashboard_IonicApp,buiphu/ionic,Jeremy017/ionic,celsoyh/ionic,treejames/ionic,cbmeeks/ionic,lewisl9029/ionic,thiagofelix/ionic,mingming1986/ionic,954053260/ionic,chrisbautista/ionic,treejames/ionic,zittix/ionic,kylezhang/ionic,staney7/ionic,jayvi/ionic,oabc124/ionic,buiphu/ionic,jvkops/ionic,cesarmarinhorj/ionic,ViniciusAugusto/ionic,SobolevLexa/ionic,Testoni/ionic,emonidi/ionic,anongtech/ionic,open-anesthesia/ionic,blueElix/ionic,yurtaev/ionic,huangsen0912/ionic,fangjing828/ionic,pod4g/ionic,puurinternet/ionic,youprofit/ionic,yalishizhude/ionic,MarcBT/ionic,eaglesjava/ionic,leerduo/ionic,sitacote/ionic-across,uus169/ionic,baiyanghese/ionic,javascriptit/ionic,ezc/ionic,blueElix/ionic,hanmichael/ionic,timtimUp/ionic,jeremyrussell/ionic,JoeyAndres/meteoric-sass,100goals/ionic,MartinMa/ionic,zhonggaoyong/ionic,hotarzhang/ionic,DiZyStudio/ionic,trevorgrayson/ionic,thompsonemerson/ionic,pargatsingh-webklabs/ionic,LawrenceHan/ionic,taraszerebecki/ionic,jgw96/ionic,sitexa/ionic,javascriptit/ionic,xuyuanxiang/ionic,jgw96/ionic,huangsen0912/ionic,Baskmart/ionic,jango2015/ionic,zittix/ionic,thebigbrain/ionic,jianganglu/ionic,willshen/ionic,contigo/ionic,GhostGroup/ionic,promactkaran/ionic,hotarzhang/ionic,bewebltd/ionic,caiiiycuk/ionic,thebigbrain/ionic,VinceOPS/ionic,awhedbee22/ionic,n0b0dy897/ionic,open-anesthesia/ionic,treejames/ionic,leerduo/ionic,thompsonemerson/ionic,r14r/fork_ionic_master,EricCheung3/ionic,agyrafa/ionic,angrilove/ionic,PaperMonster/ionic,fangjing828/ionic,possan/ionic,taraszerebecki/ionic,htc550605125/ionic,yanzhihong23/ionic-nono,oabc124/ionic,Xeeshan94/ionic,possan/ionic,yalishizhude/ionic,RodrigoIbarraSanchez/ionic,Xeeshan94/ionic,open-anesthesia/ionic,RodrigoIbarraSanchez/ionic,trevorgrayson/ionic,yanzhihong23/ionic-nono,urish/ionic,jvkops/ionic,michaellourenco/ionic,jgw96/ionic,PressReader/ionic,n0b0dy897/ionic,nelsonsozinho/ionic,puurinternet/ionic,JackieLin/ionic,chinakids/ionic,Drok1015/ionic,jamesdixon/ionic,Niades/ionic,yanzhihong23/ionic-nono,x303597316/ionic,ezc/ionic,mhartington/ionic,thiagofelix/ionic,pargatsingh-webklabs/ionic,AndyShiTw/ionic,anongtech/ionic,felipealbuquerq/ionic,VinceOPS/ionic,asfandiyark7/ionic,zittix/ionic,edwardchor/ionic,VinceOPS/ionic,freedomdebug/ionic,Sourazou/login,csbz17027/ionic,RodrigoIbarraSanchez/ionic,agyrafa/ionic,angrilove/ionic,fanhaich/ionic,100goals/ionic,janij/ionic,TakayukiSakai/ionic,jayvi/ionic,puurinternet/ionic,daew823/ionic,xuyuanxiang/ionic,lazamar/ionic,zhiqiangli520210/ionic,microlv/ionic,open-anesthesia/ionic,promactkaran/ionic,pargatsingh-webklabs/ionic,hanmichael/ionic,hectoruch/ionic,Xeeshan94/ionic,hotarzhang/ionic,ViniciusAugusto/ionic,JsonChiu/ionic,fjzdjd/ionic,leejeap/ionic,asfandiyark7/ionic,shazhumao/ionic,sloops77/ionic,MarcBT/ionic,oneillsp96/ionic,edwardchor/ionic,eric-stanley/ionic,kylezhang/ionic,cbmeeks/ionic,bankonme/ionic,daew823/ionic,possan/ionic,jtomaszewski/ionic,q310550690/ionic,studio666/ionic,felipealbuquerq/ionic,jvkops/ionic,felipealbuquerq/ionic,oneillsp96/ionic,hectoruch/ionic,PaperMonster/ionic,freedomdebug/ionic,xuyuanxiang/ionic,AndyShiTw/ionic,zhengqiangzi/ionic,baiwyc119/ionic,bewebltd/ionic,r14r-work/fork_ionic_master,edparsons/ionic,chrisbautista/ionic,eric-stanley/ionic,lutrosis81/manup-app,jee1mr/meteor-ionic,femotizo/ionic,DiZyStudio/ionic,GhostGroup/ionic,AmberWhiteSky/ionic,sthashree/ionic,lewisl9029/ionic,leejeap/ionic,Jeremy017/ionic,jeremyrussell/ionic,edparsons/ionic,uidoyen/ionic,angrilove/ionic,sloops77/ionic,edwardchor/ionic,nraboy/ionic,chrisbautista/ionic,jasdeepkhalsa/ionic,hanmichael/ionic,pod4g/ionic,vjrantal/ionic,x303597316/ionic,fjzdjd/ionic,LawrenceHan/ionic,Flllexa/ionic,eyalish/ionic,MrChen2015/ionic,urish/ionic,shazhumao/ionic,r14r-work/fork_ionic,ctetreault/ionic,PaperMonster/ionic,laispace/ionic,kylezhang/ionic,lewisl9029/ionic,lutrosis81/manup-app,NandoKstroNet/ionic,sitexa/ionic,WingGao/ionic,zhengqiangzi/ionic,cleor41/meteor-ionic,jayvi/ionic,johnli388/ionic,felipealbuquerq/ionic,bankonme/ionic,jomaf1010/ionic,fanhaich/ionic,felquis/ionic,AlphaStaxLLC/ionic,Testoni/ionic,cnbin/ionic,LawrenceHan/ionic,zhengqiangzi/ionic,SaadBinShahid/ionic,malixsys/ionic,eaglesjava/ionic,csbz17027/ionic,abcd-ca/ionic,r14r-work/fork_ionic,jtomaszewski/ionic,n0b0dy897/ionic,jianganglu/ionic,thebigbrain/ionic,studio666/ionic,tkh44/ionic,ralic/ionic,zhonggaoyong/ionic,Kryz/ionic,vladipus/ionic,uidoyen/ionic,baiwyc119/ionic,sitexa/ionic,deer-hope/ionic,jomaf1010/ionic,timtimUp/ionic,AppGyver/ionic,AndyShiTw/ionic,sloops77/ionic,Niades/ionic,uus169/ionic,leobetosouza/ionic,DiZyStudio/ionic,bankonme/ionic,eyalish/ionic,amitparrikar/ionic,TakayukiSakai/ionic,staney7/ionic,ralic/ionic,femotizo/ionic,leobetosouza/ionic,VinceOPS/ionic,timtimUp/ionic,leejeap/ionic,jamesdixon/ionic,eyalish/ionic,leeric92/ionic,ptarjan/ionic,jtomaszewski/ionic,tkh44/ionic,angrilove/ionic,edparsons/ionic,xuyuanxiang/ionic,jee1mr/meteor-ionic,pod4g/ionic,Flllexa/ionic,nelsonsozinho/ionic,zhonggaoyong/ionic,microlv/ionic,youprofit/ionic,tkh44/ionic,contigo/ionic,eyalish/ionic,ihongcn/ionic,taraszerebecki/ionic,KholofeloMoyaba/atajo-ui,GeorgeMe/ionic,r14r/fork_ionic_master,zittix/ionic,astagi/ionic,MartinMa/ionic,yurtaev/ionic,lazamar/ionic,csbz17027/ionic,asfandiyark7/ionic,brant-hwang/ionic,xzyfer/ionic,wkrueger/ionic,EricCheung3/ionic,janglednerves/ionic,qzapaia/ionic,RodrigoIbarraSanchez/ionic,freedomdebug/ionic,amitparrikar/ionic,freedomdebug/ionic,SobolevLexa/ionic,astagi/ionic,GeorgeMe/ionic,ddddm/ionic,SaadBinShahid/ionic,100goals/ionic,sitacote/ionic-across,AppGyver/ionic,MartinMa/ionic,lewisl9029/ionic,contigo/ionic,GhostGroup/ionic,ahmadawais/ionic,100goals/ionic,buiphu/ionic,tkh44/ionic,MeteorPackaging/ionic,astagi/ionic,eaglesjava/ionic,urish/ionic,mallzee/ionic,ddddm/ionic,Baskmart/ionic,youprofit/ionic,kylezhang/ionic,rreinold/FitnessDashboard_IonicApp,Drok1015/ionic,lazamar/ionic,q310550690/ionic,csbz17027/ionic,mallzee/ionic,ViniciusAugusto/ionic,awhedbee22/ionic,staney7/ionic,zhiqiangli520210/ionic,felquis/ionic,x303597316/ionic,amitparrikar/ionic,fjzdjd/ionic,cbmeeks/ionic,rreinold/FitnessDashboard_IonicApp,jianganglu/ionic,mingming1986/ionic,agyrafa/ionic,sitexa/ionic,Niades/ionic,baiyanghese/ionic,celsoyh/ionic,ralic/ionic,felquis/ionic,jango2015/ionic,MrChen2015/ionic,TakayukiSakai/ionic,glustful/ionic,sahat/ionic,Gregcop1/ionic,anongtech/ionic,jeremyrussell/ionic,anongtech/ionic,Nalinc/ionic,CNVCrew/ionic,MeteorPackaging/ionic,michaellourenco/ionic,buiphu/ionic,sahat/ionic,javascriptit/ionic,jomaf1010/ionic,AndyShiTw/ionic,q310550690/ionic,MartinMa/ionic,promactkaran/ionic,AlphaStaxLLC/ionic,bewebltd/ionic,Kryz/ionic,glustful/ionic,willshen/ionic,thiagofelix/ionic,ngonzalvez/ionic,q310550690/ionic,ngonzalvez/ionic,CNVCrew/ionic,SobolevLexa/ionic,cnbin/ionic,WingGao/ionic,cleor41/meteor-ionic,PressReader/ionic,Drok1015/ionic,ctetreault/ionic,vjrantal/ionic,mingming1986/ionic,staney7/ionic,ViniciusAugusto/ionic,5amfung/ionic,jamesdixon/ionic,954053260/ionic,treejames/ionic,johnli388/ionic,cnbin/ionic,CNVCrew/ionic,janglednerves/ionic,yurtaev/ionic,johnli388/ionic,johnli388/ionic,Testoni/ionic,envistaInteractive/ionic,ctetreault/ionic,nelsonsozinho/ionic,ihongcn/ionic,guaerguagua/ionic,jamesdixon/ionic,EricCheung3/ionic,jasdeepkhalsa/ionic,gyx8899/ionic,cesarmarinhorj/ionic,contigo/ionic,thompsonemerson/ionic,jianganglu/ionic,MJefferson/ionic,sthashree/ionic,openbizgit/ionic,awhedbee22/ionic,AlphaStaxLLC/ionic,leeric92/ionic,r14r-work/fork_ionic_master,5amfung/ionic,thiagofelix/ionic,JackieLin/ionic,janglednerves/ionic,cleor41/meteor-ionic,ngonzalvez/ionic,ezc/ionic,puurinternet/ionic,agyrafa/ionic,GeorgeMe/ionic,Nalinc/ionic,htc550605125/ionic,janij/ionic,Testoni/ionic,cbmeeks/ionic,jango2015/ionic,leerduo/ionic,KholofeloMoyaba/atajo-ui,gyx8899/ionic,PaperMonster/ionic,Gregcop1/ionic,SaadBinShahid/ionic,astagi/ionic,AmberWhiteSky/ionic,ahmadawais/ionic,yanzhihong23/ionic-nono,zyaboutblank/ionic,jee1mr/meteor-ionic,brant-hwang/ionic,michaellourenco/ionic,MrChen2015/ionic,Sourazou/login,KholofeloMoyaba/atajo-ui,NandoKstroNet/ionic,Drok1015/ionic,5amfung/ionic,brant-hwang/ionic,TakayukiSakai/ionic,r14r/fork_ionic_master,ihongcn/ionic,954053260/ionic,shazhumao/ionic,qzapaia/ionic,bewebltd/ionic,954053260/ionic,MarcBT/ionic,r14r-work/fork_ionic,AlphaStaxLLC/ionic,r14r-work/fork_ionic_master,ptarjan/ionic,SaadBinShahid/ionic,femotizo/ionic,LawrenceHan/ionic,zhengqiangzi/ionic,uidoyen/ionic,trevorgrayson/ionic,timtimUp/ionic,huangsen0912/ionic,emonidi/ionic,fangjing828/ionic,Baskmart/ionic,zyaboutblank/ionic,ezc/ionic,emonidi/ionic,Kryz/ionic,AmberWhiteSky/ionic,uus169/ionic,zhiqiangli520210/ionic,guaerguagua/ionic,taraszerebecki/ionic,GhostGroup/ionic,cesarmarinhorj/ionic,jeremyrussell/ionic,Flllexa/ionic,huangsen0912/ionic,studio666/ionic,hectoruch/ionic,thompsonemerson/ionic,MJefferson/ionic,lutrosis81/manup-app,deer-hope/ionic,KholofeloMoyaba/atajo-ui,caiiiycuk/ionic,openbizgit/ionic,emonidi/ionic,xzyfer/ionic,JsonChiu/ionic,mingming1986/ionic,microlv/ionic,yalishizhude/ionic,NandoKstroNet/ionic,xzyfer/ionic,hanmichael/ionic,AmberWhiteSky/ionic,caiiiycuk/ionic,mhartington/ionic,baiwyc119/ionic,oneillsp96/ionic,ralic/ionic,abcd-ca/ionic,n0b0dy897/ionic,mhartington/ionic,zhiqiangli520210/ionic,CNVCrew/ionic,promactkaran/ionic,ahmadawais/ionic,Niades/ionic,jgw96/ionic,wkrueger/ionic,youprofit/ionic,ctetreault/ionic,blueElix/ionic,edwardchor/ionic,Sourazou/login,nraboy/ionic,envistaInteractive/ionic,Nalinc/ionic,leeric92/ionic,sloops77/ionic,ihongcn/ionic,xzyfer/ionic,vladipus/ionic,ptarjan/ionic,DurgaprasadPati/ionic,awhedbee22/ionic,MeteorPackaging/ionic,sthashree/ionic,jayvi/ionic,janglednerves/ionic,leobetosouza/ionic,pargatsingh-webklabs/ionic,Tetpay/ionic,zyaboutblank/ionic,amitparrikar/ionic,r14r-work/fork_ionic_master,fangjing828/ionic,studio666/ionic,Gregcop1/ionic,willshen/ionic,ddddm/ionic,JsonChiu/ionic,DurgaprasadPati/ionic,MeteorPackaging/ionic,openbizgit/ionic,fanhaich/ionic,JackieLin/ionic,htc550605125/ionic,Baskmart/ionic,beauby/ionic,leejeap/ionic,deer-hope/ionic,trevorgrayson/ionic,EricCheung3/ionic,MJefferson/ionic,baiwyc119/ionic,vjrantal/ionic,PressReader/ionic,janglednerves/ionic,deer-hope/ionic,jvkops/ionic,Jandersolutions/ionic,MrChen2015/ionic,DurgaprasadPati/ionic,glustful/ionic,cesarmarinhorj/ionic,jasdeepkhalsa/ionic,envistaInteractive/ionic,fanhaich/ionic,Tetpay/ionic,janij/ionic,microlv/ionic,sthashree/ionic,zhonggaoyong/ionic,lazamar/ionic,bankonme/ionic,hotarzhang/ionic,qzapaia/ionic,JsonChiu/ionic,leerduo/ionic,michaellourenco/ionic,DiZyStudio/ionic,GeorgeMe/ionic,sitacote/ionic-across,x303597316/ionic,possan/ionic,JackieLin/ionic,guaerguagua/ionic,wkrueger/ionic,Nalinc/ionic,leeric92/ionic,envistaInteractive/ionic,femotizo/ionic,jomaf1010/ionic,jgw96/ionic,hectoruch/ionic,glustful/ionic,oneillsp96/ionic,guaerguagua/ionic,uidoyen/ionic,jango2015/ionic,MJefferson/ionic,zyaboutblank/ionic,gyx8899/ionic,pod4g/ionic,chinakids/ionic,daew823/ionic,jee1mr/meteor-ionic,AppGyver/ionic,daew823/ionic,jasdeepkhalsa/ionic,DurgaprasadPati/ionic,uus169/ionic,MarcBT/ionic,laispace/ionic
--- +++ @@ -2,7 +2,7 @@ // Controller that fetches a list of data -.controller('MovieIndexCtrl', function($scope, MovieService) { +.controller('MovieIndexCtrl', function($scope, MovieService,$timeout) { // "MovieService" is a service returning mock data (services.js) // the returned data from the service is placed into this @@ -10,6 +10,38 @@ $scope.movies = MovieService.all(); $scope.title = "Completely Random Collection Of Movies"; + + // Method called on infinite scroll + // Receives a "done" callback to inform the infinite scroll that we are done + $scope.loadMore = function(done) { + $timeout(function() { + $scope.movies.push({ + id: 'tt0114814', + title: 'Usual Suspects', + released: '1995', + description: 'A boat has been destroyed, criminals are dead, and the key to this mystery lies with the only survivor and his twisted, convoluted story beginning with five career crooks in a seemingly random police lineup.', + director: 'Bryan Singer', + rating: 8.3 + }); + $scope.movies.push({ + id: 'tt0357413', + title: 'Anchorman: The Legend of Ron Burgundy', + released: '2004', + description: "Ron Burgundy is San Diego's top rated newsman in the male-dominated broadcasting of the 70's, but that's all about to change for Ron and his cronies when an ambitious woman is hired as a new anchor.", + director: 'Adam McKay', + rating: 7.2 + }); + $scope.movies.push({ + id: 'tt0058331', + title: 'Mary Poppins', + released: '1964', + description: "A magic nanny comes to work for a cold banker's unhappy family.", + director: 'Robert Stevenson', + rating: 7.7 + }); + done(); + }, 1000); + } }) // Controller that shows more detailed info about a movie
af892e2365daa6b213c89b3bacdfaf4da777d1d6
src/js/Enemy.js
src/js/Enemy.js
'use strict'; /** * @description Enemy class => objects the player should avoid * @constructor * @param {number} x position of the enemy on the 'x' axis * @param {number} y position of the enemy on the 'y' axis * @param {number} speed speed factor of the enemy */ var Enemy = function (x, y, speed) { this.x = x; this.y = y; // TODO: update y = (y * rowHeight) + (0.5 * rowHeight) + 73 this.speed = speed; // TODO: update speed = * speedRatio this.sprite = 'images/goomba.png'; //TODO: remove hard coded sprite }; /** * @description Move the enemy accross the gameBord * @param {number} dt Time delta between the previous and actual frame * @param {object} bounds Gameboard bounds */ Enemy.prototype.update = function (dt, bounds) { // Restrict the enemy back and forth mouvement to the bound of the screen this.speed = this.x < bounds.right && this.x > bounds.left ? this.speed : -this.speed; // Move the enemy accross the screen back and forth this.x += this.speed * dt; }; /** * @descritpion Render the enemy object */ Enemy.prototype.render = function (context) { context.drawImage(Resources.get(this.sprite), this.x, this.y); };
'use strict'; /** * @description Enemy class => objects the player should avoid * @constructor * @param {number} x position of the enemy on the 'x' axis * @param {number} y position of the enemy on the 'y' axis * @param {number} speed speed factor of the enemy */ var Enemy = function (x, y, speed) { this.x = x; this.y = y; // TODO: update y = (y * rowHeight) + (0.5 * rowHeight) + 73 this.speed = speed; // TODO: update speed = * speedRatio this.sprite = 'images/goomba.png'; //TODO: remove hard coded sprite }; /** * @description Move the enemy accross the gameBord * @param {number} dt Time delta between the previous and actual frame * @param {object} bounds Gameboard bounds */ Enemy.prototype.update = function (dt, bounds) { // Restrict the enemy back and forth mouvement to the bound of the screen this.speed = this.x < bounds.right - 10 && this.x > bounds.left + 10 ? this.speed : -this.speed; // Move the enemy accross the screen back and forth this.x += this.speed * dt; }; /** * @descritpion Render the enemy object */ Enemy.prototype.render = function (context) { context.drawImage(Resources.get(this.sprite), this.x, this.y); };
Update the enemy bounds in the enemy class
Update the enemy bounds in the enemy class
JavaScript
mit
zakhttp/super-mario-frogger,zakhttp/super-mario-frogger
--- +++ @@ -24,7 +24,7 @@ Enemy.prototype.update = function (dt, bounds) { // Restrict the enemy back and forth mouvement to the bound of the screen - this.speed = this.x < bounds.right && this.x > bounds.left ? this.speed : -this.speed; + this.speed = this.x < bounds.right - 10 && this.x > bounds.left + 10 ? this.speed : -this.speed; // Move the enemy accross the screen back and forth this.x += this.speed * dt;
d7991bc3af6d3bce7ae1fec107e8497c4b1e25f1
js/components/player.js
js/components/player.js
import React from 'react'; module.exports = React.createClass({ getInitialState: function getInitialState() { return { isPlayingStream: typeof window.orientation === 'undefined', // Should return true if not mobile nowPlayingLabel: 'Offline', }; }, setPlayerState: function setPlayerState() { const stream = document.getElementById('stream-player'); if (!this.state.isPlayingStream) { stream.pause(); } else { stream.play(); } }, componentDidMount: function componentDidMount() { this.setPlayerState(); }, componentDidUpdate: function componentDidUpdate() { this.setPlayerState(); }, render: function render() { const audioButtonClass = this.state.isPlayingStream ? 'icon-play3' : 'icon-pause2'; return ( <div className="c-player"> <audio id="stream-player" src="http://airtime.frequency.asia:8000/airtime_128"></audio> <button id="play-stream" className="c-player__button"> <span className={ audioButtonClass }></span> </button> <p className="c-player__text">{ this.state.nowPlayingLabel }</p> <div className="c-player__volume"> <input type="range" value="8" data-steps="10" id="volume-slider" /> </div> </div> ); }, });
import React from 'react'; module.exports = React.createClass({ getInitialState: function getInitialState() { return { isPlayingStream: typeof window.orientation === 'undefined', // Should return true if not mobile nowPlayingLabel: 'Offline', }; }, onPlayClicked: function onPlayClicked() { this.setState({ isPlayingStream: !this.state.isPlayingStream }); }, setPlayerState: function setPlayerState() { const stream = document.getElementById('stream-player'); if (!this.state.isPlayingStream) { stream.pause(); } else { stream.play(); } }, componentDidMount: function componentDidMount() { this.setPlayerState(); }, componentDidUpdate: function componentDidUpdate() { this.setPlayerState(); }, render: function render() { const audioButtonClass = this.state.isPlayingStream ? 'icon-pause2' : 'icon-play3'; return ( <div className="c-player"> <audio id="stream-player" src="http://airtime.frequency.asia:8000/airtime_128"></audio> <button id="play-stream" className="c-player__button" onClick={ this.onPlayClicked }> <span className={ audioButtonClass }></span> </button> <p className="c-player__text">{ this.state.nowPlayingLabel }</p> <div className="c-player__volume"> <input type="range" value="8" data-steps="10" id="volume-slider" /> </div> </div> ); }, });
Add click listener to play buttotn.
Add click listener to play buttotn.
JavaScript
mit
frequencyasia/website,frequencyasia/website
--- +++ @@ -6,6 +6,10 @@ isPlayingStream: typeof window.orientation === 'undefined', // Should return true if not mobile nowPlayingLabel: 'Offline', }; + }, + + onPlayClicked: function onPlayClicked() { + this.setState({ isPlayingStream: !this.state.isPlayingStream }); }, setPlayerState: function setPlayerState() { @@ -26,11 +30,11 @@ }, render: function render() { - const audioButtonClass = this.state.isPlayingStream ? 'icon-play3' : 'icon-pause2'; + const audioButtonClass = this.state.isPlayingStream ? 'icon-pause2' : 'icon-play3'; return ( <div className="c-player"> <audio id="stream-player" src="http://airtime.frequency.asia:8000/airtime_128"></audio> - <button id="play-stream" className="c-player__button"> + <button id="play-stream" className="c-player__button" onClick={ this.onPlayClicked }> <span className={ audioButtonClass }></span> </button> <p className="c-player__text">{ this.state.nowPlayingLabel }</p>
768f4bf499d00c6a801b018b6a1c656c5800076c
nodejs/lib/hoptoad.js
nodejs/lib/hoptoad.js
var Hoptoad = require('hoptoad-notifier').Hoptoad , env = require('../environment') , shouldReport = env.hoptoad && env.hoptoad.reportErrors; if(shouldReport) Hoptoad.key = env.hoptoad.apiKey; process.addListener('uncaughtException', function(err) { if(shouldReport) Hoptoad.notify(err, function(){}); }); Hoptoad.expressErrorNotifier = function(err,req,res,next){ if(shouldReport) Hoptoad.notify(err, function(){}); next(err); } Hoptoad.notifyCallback = function(err){ if(shouldReport && err) Hoptoad.notify(err, function(){}); } module.exports = Hoptoad;
var Hoptoad = require('hoptoad-notifier').Hoptoad , env = require('../environment') , shouldReport = env.hoptoad && env.hoptoad.reportErrors; if(shouldReport) Hoptoad.key = env.hoptoad.apiKey; process.addListener('uncaughtException', function(err) { if(shouldReport) Hoptoad.notify(err, function(){}); console.error("~~~ Error ~~~ " + Date()) console.error(err.stack); }); Hoptoad.expressErrorNotifier = function(err,req,res,next){ if(shouldReport) Hoptoad.notify(err, function(){}); next(err); } Hoptoad.notifyCallback = function(err){ if(shouldReport && err) Hoptoad.notify(err, function(){}); } module.exports = Hoptoad;
Print out uncaught exceptions. Node stops doing this when you add an uncaught exception handler.
Print out uncaught exceptions. Node stops doing this when you add an uncaught exception handler.
JavaScript
mit
iFixit/wompt.com,iFixit/wompt.com,Wompt/wompt.com,iFixit/wompt.com,Wompt/wompt.com,Wompt/wompt.com,iFixit/wompt.com
--- +++ @@ -9,6 +9,8 @@ process.addListener('uncaughtException', function(err) { if(shouldReport) Hoptoad.notify(err, function(){}); + console.error("~~~ Error ~~~ " + Date()) + console.error(err.stack); }); Hoptoad.expressErrorNotifier = function(err,req,res,next){
e0860e4491a2519493426cb1cfdbcca8071467e9
validators/json/load.js
validators/json/load.js
const utils = require('../../utils') const load = (files, jsonFiles, jsonContentsDict, annexed, dir) => { let issues = [] // Read JSON file contents and parse for issues const readJsonFile = (file, annexed, dir) => utils.files .readFile(file, annexed, dir) .then(contents => utils.json.parse(file, contents)) .then(({ issues: parseIssues, parsed }) => { // Append any parse issues to returned issues Array.prototype.push.apply(issues, parseIssues) // Abort further tests if an error is found if ( parseIssues && !parseIssues.some(issue => issue.severity === 'error') ) { jsonContentsDict[file.relativePath] = parsed jsonFiles.push(file) } }) // Start concurrent read/parses const fileReads = files.map(file => utils.limit(() => readJsonFile(file, annexed, dir)), ) // After all reads/parses complete, return any found issues return Promise.all(fileReads).then(() => issues) } module.exports = load
const utils = require('../../utils') class JSONParseError extends Error { constructor(message) { super(message) this.name = 'JSONParseError' } } const load = (files, jsonFiles, jsonContentsDict, annexed, dir) => { let issues = [] // Read JSON file contents and parse for issues const readJsonFile = (file, annexed, dir) => utils.files .readFile(file, annexed, dir) .then(contents => utils.json.parse(file, contents)) .then(({ issues: parseIssues, parsed }) => { // Append any parse issues to returned issues Array.prototype.push.apply(issues, parseIssues) // Abort further tests if an error is found if ( parseIssues && parseIssues.some(issue => issue.severity === 'error') ) { throw new JSONParseError('Aborted due to parse error') } jsonContentsDict[file.relativePath] = parsed jsonFiles.push(file) }) // Start concurrent read/parses const fileReads = files.map(file => utils.limit(() => readJsonFile(file, annexed, dir)), ) // After all reads/parses complete, return any found issues return Promise.all(fileReads) .then(() => issues) .catch(err => { // Handle early exit if (err instanceof JSONParseError) { return issues } else { throw err } }) } module.exports = load
Reimplement early exit for JSON parse errors.
Reimplement early exit for JSON parse errors.
JavaScript
mit
nellh/bids-validator,Squishymedia/bids-validator,Squishymedia/BIDS-Validator,nellh/bids-validator,nellh/bids-validator
--- +++ @@ -1,4 +1,11 @@ const utils = require('../../utils') + +class JSONParseError extends Error { + constructor(message) { + super(message) + this.name = 'JSONParseError' + } +} const load = (files, jsonFiles, jsonContentsDict, annexed, dir) => { let issues = [] @@ -15,11 +22,13 @@ // Abort further tests if an error is found if ( parseIssues && - !parseIssues.some(issue => issue.severity === 'error') + parseIssues.some(issue => issue.severity === 'error') ) { - jsonContentsDict[file.relativePath] = parsed - jsonFiles.push(file) + throw new JSONParseError('Aborted due to parse error') } + + jsonContentsDict[file.relativePath] = parsed + jsonFiles.push(file) }) // Start concurrent read/parses @@ -28,7 +37,16 @@ ) // After all reads/parses complete, return any found issues - return Promise.all(fileReads).then(() => issues) + return Promise.all(fileReads) + .then(() => issues) + .catch(err => { + // Handle early exit + if (err instanceof JSONParseError) { + return issues + } else { + throw err + } + }) } module.exports = load
754bd76e3f18246b4b3cf161755fb9919571cc19
app/util.js
app/util.js
function randomFrom(array) { return array[Math.floor(Math.random()*array.length)] } function filter_available(item) { return !item.unreleased } var language_map = { "en_US": "en", "fr_FR": "fr", "ja_JP": "ja", "fr_CA": "fr-ca", "es_ES": "es", "es_MX": "es-mx" } String.prototype.format = function(scope) { eval(Object.keys(scope).map( function(x) { return "var " + x + "=scope." + x }).join(";")); return this.replace(/{(.+?)}/g, function($0, $1) { return eval($1); }) }; angular.module('splatApp').util = function($scope, $sce) { // this only works when each language is moved to a directory setup like above (ie in distribution on loadout.ink) $scope.redirect = function(lang) { var dir = language_map[lang] var URL = window.location.protocol + "//"+ window.location.hostname + "/" + dir + "/" if(window.location.hash) URL += window.location.hash; if (typeof(Storage) !== "undefined") { localStorage.selectedLang = lang; } window.location = URL; } $scope.renderHtml = function(html_code) { return $sce.trustAsHtml(html_code); }; }
function randomFrom(array) { return array[Math.floor(Math.random()*array.length)] } function filter_available(item) { return !item.unreleased } var language_map = { "en_US": "en-us", "fr_FR": "fr", "ja_JP": "ja", "fr_CA": "fr-ca", "es_ES": "es", "es_MX": "es-mx" } String.prototype.format = function(scope) { eval(Object.keys(scope).map( function(x) { return "var " + x + "=scope." + x }).join(";")); return this.replace(/{(.+?)}/g, function($0, $1) { return eval($1); }) }; angular.module('splatApp').util = function($scope, $sce) { // this only works when each language is moved to a directory setup like above (ie in distribution on loadout.ink) $scope.redirect = function(lang) { var dir = language_map[lang] var URL = window.location.protocol + "//"+ window.location.hostname + "/" + dir + "/" if(window.location.hash) URL += window.location.hash; if (typeof(Storage) !== "undefined") { localStorage.selectedLang = lang; } window.location = URL; } $scope.renderHtml = function(html_code) { return $sce.trustAsHtml(html_code); }; }
Change en_US code from "en" to "en-us" for consistency
Change en_US code from "en" to "en-us" for consistency
JavaScript
mit
DeviPotato/splat2-calc,DeviPotato/splat2-calc
--- +++ @@ -7,7 +7,7 @@ } var language_map = { - "en_US": "en", + "en_US": "en-us", "fr_FR": "fr", "ja_JP": "ja", "fr_CA": "fr-ca",
fea368f1da1c6c3a58ad7bbcf6193d56c5592e68
app/Resources/appify.js
app/Resources/appify.js
/* * This is a template used when TiShadow "appifying" a titanium project. * See the README. */ var TiShadow = require("/api/TiShadow"); var Compression = require('ti.compression'); // Need to unpack the bundle on a first load; var path_name = "{{app_name}}".replace(/ /g,"_"); var target = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name); if (!target.exists()) { target.createDirectory(); Compression.unzip(Ti.Filesystem.applicationDataDirectory + "/" + path_name, Ti.Filesystem.resourcesDirectory + "/" + path_name + '.zip',true); } //Call home TiShadow.connect({ proto: "{{proto}}", host : "{{host}}", port : "{{port}}", room : "{{room}}", name : Ti.Platform.osname + ", " + Ti.Platform.version + ", " + Ti.Platform.address }); //Launch the app TiShadow.launchApp(path_name);
/* * This is a template used when TiShadow "appifying" a titanium project. * See the README. */ Titanium.App.idleTimerDisabled = true; var TiShadow = require("/api/TiShadow"); var Compression = require('ti.compression'); // Need to unpack the bundle on a first load; var path_name = "{{app_name}}".replace(/ /g,"_"); var target = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name); if (!target.exists()) { target.createDirectory(); Compression.unzip(Ti.Filesystem.applicationDataDirectory + "/" + path_name, Ti.Filesystem.resourcesDirectory + "/" + path_name + '.zip',true); } //Call home TiShadow.connect({ proto: "{{proto}}", host : "{{host}}", port : "{{port}}", room : "{{room}}", name : Ti.Platform.osname + ", " + Ti.Platform.version + ", " + Ti.Platform.address }); //Launch the app TiShadow.launchApp(path_name);
Disable idleTimer on iOS for appified apps
Disable idleTimer on iOS for appified apps
JavaScript
apache-2.0
titanium-forks/dbankier.TiShadow,r8o8s1e0/TiShadow,HazemKhaled/TiShadow,FokkeZB/TiShadow,emilyvon/TiShadow,HazemKhaled/TiShadow,r8o8s1e0/TiShadow,Biotelligent/TiShadow,r8o8s1e0/TiShadow,Biotelligent/TiShadow,HazemKhaled/TiShadow,FokkeZB/TiShadow,emilyvon/TiShadow,emilyvon/TiShadow,titanium-forks/dbankier.TiShadow,titanium-forks/dbankier.TiShadow,FokkeZB/TiShadow,Biotelligent/TiShadow
--- +++ @@ -2,6 +2,8 @@ * This is a template used when TiShadow "appifying" a titanium project. * See the README. */ + +Titanium.App.idleTimerDisabled = true; var TiShadow = require("/api/TiShadow"); var Compression = require('ti.compression');
c140b8c985cfc05ce8ae1326e470d9f4e1231a54
lib/metalsmith-metafiles.js
lib/metalsmith-metafiles.js
"use strict"; var MetafileMatcher = require('./metafile-matcher'); // Not needed in Node 4.0+ if (!Object.assign) Object.assign = require('object-assign'); class MetalsmithMetafiles { constructor(options) { options = options || {}; this._initMatcherOptions(options); this._initMatchers(); } _initMatcherOptions(options) { this._matcherOptions = []; var parserOptions = Object.assign({'.json': true}, options.parsers); for (var extension in parserOptions) { var enabled = parserOptions[extension]; if (enabled) { this._matcherOptions.push( Object.assign({}, options, {"extension": extension}) ); } } } _initMatchers() { this._matchers = this._matcherOptions.map((options) => new MetafileMatcher(options)); } // Main interface parseMetafiles(files) { filesLoop: for (var path in files) { for (var matcher of this._matchers) { var metafile = matcher.metafile(path, files[path]); if (!metafile.isMetafile) continue; if (!files[metafile.mainFile]) continue; Object.assign(files[metafile.mainFile], metafile.metadata); if (matcher.deleteMetaFiles) delete files[metafile.path]; continue filesLoop; } } } } module.exports = MetalsmithMetafiles;
"use strict"; var MetafileMatcher = require('./metafile-matcher'); // Not needed in Node 4.0+ if (!Object.assign) Object.assign = require('object-assign'); class MetalsmithMetafiles { constructor(options) { options = options || {}; this._initMatcherOptions(options); this._initMatchers(); } _initMatcherOptions(options) { this._matcherOptions = []; var parserOptions = Object.assign({'.json': true}, options.parsers); for (var extension in parserOptions) { var enabled = parserOptions[extension]; if (enabled) { this._matcherOptions.push( Object.assign({}, options, {"extension": extension}) ); } } } _initMatchers() { this._matchers = this._matcherOptions.map(function(options) { return new MetafileMatcher(options); }); } // Main interface parseMetafiles(files) { filesLoop: for (var path in files) { for (var matcher of this._matchers) { var metafile = matcher.metafile(path, files[path]); if (!metafile.isMetafile) continue; if (!files[metafile.mainFile]) continue; Object.assign(files[metafile.mainFile], metafile.metadata); if (matcher.deleteMetaFiles) delete files[metafile.path]; continue filesLoop; } } } } module.exports = MetalsmithMetafiles;
Remove arrow function to remain compatible with older Node versions
Remove arrow function to remain compatible with older Node versions
JavaScript
mit
Ajedi32/metalsmith-metafiles
--- +++ @@ -27,7 +27,9 @@ } _initMatchers() { - this._matchers = this._matcherOptions.map((options) => new MetafileMatcher(options)); + this._matchers = this._matcherOptions.map(function(options) { + return new MetafileMatcher(options); + }); } // Main interface
14b04b085f0688c37580b7622ef36b062e4d0bcf
app/routes/ember-cli.js
app/routes/ember-cli.js
import Route from '@ember/routing/route'; export default Route.extend({ titleToken() { return 'Ember CLI'; } });
import Route from '@ember/routing/route'; export default Route.extend({ title() { return 'Ember CLI - Ember API Documentation'; } });
Update to return the title Function
Update to return the title Function
JavaScript
mit
ember-learn/ember-api-docs,ember-learn/ember-api-docs
--- +++ @@ -1,7 +1,7 @@ import Route from '@ember/routing/route'; export default Route.extend({ - titleToken() { - return 'Ember CLI'; + title() { + return 'Ember CLI - Ember API Documentation'; } });
1623ae966b9823088e65870104d9e37d714b23c0
src/reactize.js
src/reactize.js
var Turbolinks = require("exports?this.Turbolinks!turbolinks"); /* Disable the Turbolinks page cache to prevent Tlinks from storing versions of * pages with `react-id` attributes in them. When popping off the history, the * `react-id` attributes cause React to treat the old page like a pre-rendered * page and breaks diffing. */ Turbolinks.pagesCached(0); var HTMLtoJSX = require("htmltojsx"); var JSXTransformer = require("react-tools"); var React = require("react"); var Reactize = { version: REACTIZE_VERSION }; var converter = new HTMLtoJSX({createClass: false}); Reactize.reactize = function(element) { var code = JSXTransformer.transform(converter.convert(element.innerHTML)); return eval(code); }; Reactize.applyDiff = function(replacementElement, targetElement) { var bod = Reactize.reactize(replacementElement); React.render(bod, targetElement); }; function applyBodyDiff() { Reactize.applyDiff(document.body, document.body); global.removeEventListener("load", applyBodyDiff); } global.addEventListener("load", applyBodyDiff); // Turbolinks calls `replaceChild` on the document element when an update should // occur. Monkeypatch the method so Turbolinks can be used without modification. global.document.documentElement.replaceChild = Reactize.applyDiff; module.exports = global.Reactize = Reactize;
var Turbolinks = require("exports?this.Turbolinks!turbolinks"); // Disable the Turbolinks page cache to prevent Tlinks from storing versions of // pages with `react-id` attributes in them. When popping off the history, the // `react-id` attributes cause React to treat the old page like a pre-rendered // page and breaks diffing. Turbolinks.pagesCached(0); var HTMLtoJSX = require("htmltojsx"); var JSXTransformer = require("react-tools"); var React = require("react"); var Reactize = { version: REACTIZE_VERSION }; var converter = new HTMLtoJSX({createClass: false}); Reactize.reactize = function(element) { var code = JSXTransformer.transform(converter.convert(element.innerHTML)); return eval(code); }; Reactize.applyDiff = function(replacementElement, targetElement) { var bod = Reactize.reactize(replacementElement); React.render(bod, targetElement); }; function applyBodyDiff() { Reactize.applyDiff(document.body, document.body); global.removeEventListener("load", applyBodyDiff); } global.addEventListener("load", applyBodyDiff); // Turbolinks calls `replaceChild` on the document element when an update should // occur. Monkeypatch the method so Turbolinks can be used without modification. global.document.documentElement.replaceChild = Reactize.applyDiff; module.exports = global.Reactize = Reactize;
Standardize on “//“ for all JS comments
Standardize on “//“ for all JS comments
JavaScript
apache-2.0
ssorallen/turbo-react,ssorallen/turbo-react,ssorallen/turbo-react
--- +++ @@ -1,10 +1,9 @@ var Turbolinks = require("exports?this.Turbolinks!turbolinks"); -/* Disable the Turbolinks page cache to prevent Tlinks from storing versions of - * pages with `react-id` attributes in them. When popping off the history, the - * `react-id` attributes cause React to treat the old page like a pre-rendered - * page and breaks diffing. - */ +// Disable the Turbolinks page cache to prevent Tlinks from storing versions of +// pages with `react-id` attributes in them. When popping off the history, the +// `react-id` attributes cause React to treat the old page like a pre-rendered +// page and breaks diffing. Turbolinks.pagesCached(0); var HTMLtoJSX = require("htmltojsx");
fd20009fcf17de391b398cbb7ce746144fc610c6
js/Search.spec.js
js/Search.spec.js
import React from 'react' import { shallow } from 'enzyme' import { shallowToJson } from 'enzyme-to-json' import Search from './Search' import ShowCard from './ShowCard' import preload from '../public/data.json' test('Search snapshot test', () => { const component = shallow(<Search />) const tree = shallowToJson(component) expect(tree).toMatchSnapshot() }) test('Search should render a ShowCard for each show', () => { const component = shallow(<Search />) expect(component.find(ShowCard).length).toEqual(preload.shows.length) })
import React from 'react' import { shallow } from 'enzyme' import { shallowToJson } from 'enzyme-to-json' import Search from './Search' import ShowCard from './ShowCard' import preload from '../public/data.json' test('Search snapshot test', () => { const component = shallow(<Search />) const tree = shallowToJson(component) expect(tree).toMatchSnapshot() }) test('Search should render a ShowCard for each show', () => { const component = shallow(<Search />) expect(component.find(ShowCard).length).toEqual(preload.shows.length) }) test('Search should render correct amount of shows based on the search', () => { const searchWord = 'house' const component = shallow(<Search />) component.find('input').simulate('change', {target:{value:searchWord}}) const showCount = preload.shows.filter((show) => { return `${show.title} ${show.description}` .toUpperCase().indexOf(searchWord .toUpperCase()) >= 0 }).length expect(component.find(ShowCard).length).toEqual(showCount) })
Add test for the search field.
Add test for the search field.
JavaScript
mit
dianafisher/FEM-complete-intro-to-react,dianafisher/FEM-complete-intro-to-react
--- +++ @@ -12,6 +12,18 @@ }) test('Search should render a ShowCard for each show', () => { - const component = shallow(<Search />) + const component = shallow(<Search />) expect(component.find(ShowCard).length).toEqual(preload.shows.length) }) + +test('Search should render correct amount of shows based on the search', () => { + const searchWord = 'house' + const component = shallow(<Search />) + component.find('input').simulate('change', {target:{value:searchWord}}) + const showCount = preload.shows.filter((show) => { + return `${show.title} ${show.description}` + .toUpperCase().indexOf(searchWord + .toUpperCase()) >= 0 + }).length + expect(component.find(ShowCard).length).toEqual(showCount) +})
fdcfa64c627f9522db5f176cc103171df839cad1
ember-cli-build.js
ember-cli-build.js
/* eslint-env node */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { var app = new EmberAddon(defaults, { // Add options here }); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
/* eslint-env node */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function (defaults) { var app = new EmberAddon(defaults, { 'ember-cli-babel': { includePolyfill: true } }); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
Fix broken test by including babel polyfill on dummy app
Fix broken test by including babel polyfill on dummy app
JavaScript
mit
scottwernervt/ember-cli-group-by,scottwernervt/ember-cli-group-by
--- +++ @@ -1,17 +1,19 @@ /* eslint-env node */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); -module.exports = function(defaults) { +module.exports = function (defaults) { var app = new EmberAddon(defaults, { - // Add options here + 'ember-cli-babel': { + includePolyfill: true + } }); /* - This build file specifies the options for the dummy test app of this - addon, located in `/tests/dummy` - This build file does *not* influence how the addon or the app using it - behave. You most likely want to be modifying `./index.js` or app's build file - */ + This build file specifies the options for the dummy test app of this + addon, located in `/tests/dummy` + This build file does *not* influence how the addon or the app using it + behave. You most likely want to be modifying `./index.js` or app's build file + */ return app.toTree(); };
0d7cfde7c85bf6c8275b7db45cc2f2faf911fb41
js/application.js
js/application.js
;(function(){ var G = dijkstra.hexGrid(2); var view = new dijkstra.GraphView(G, document.getElementById('graph'), { placement: function(position){ return { 'x': 100 * position.x, 'y': 100 * position.y }}, radius: 20, between: 0.3, vertex: { events : { mouseenter: function(event){ var id = this.getAttribute('data-vertex'); var v = G.findVertex(id); algorithm.setPathFrom(v); } } } }); var algorithm = new dijkstra.ShortestPath(G); algorithm.setSource(G.vertices[0]); algorithm.setTarget(G.vertices[G.vertices.length - 1]); algorithm.setPathFrom(G.vertices[G.vertices.length - 1]); view.visualize(algorithm); function loop(){ view.update(); requestAnimationFrame(loop); }; loop(); document.body.addEventListener('keypress', function(event){ if (event.keyCode == 32) { algorithm.step(); } }); window.G = G; })();
;(function(){ var G = dijkstra.hexGrid(2); var view = new dijkstra.GraphView(G, document.getElementById('graph'), { placement: function(position){ return { 'x': 100 * position.x, 'y': 100 * position.y }}, radius: 20, between: 0.3, vertex: { events : { mouseenter: function(event){ var id = this.getAttribute('data-vertex'); var v = G.findVertex(id); algorithm.setPathFrom(v); } } } }); var algorithm = new dijkstra.ShortestPath(G); algorithm.setSource(G.vertices[0]); algorithm.setTarget(G.vertices[G.vertices.length - 1]); algorithm.setPathFrom(G.vertices[G.vertices.length - 1]); view.visualize(algorithm); function loop(){ view.update(); requestAnimationFrame(loop); }; loop(); document.body.addEventListener('keypress', function(event){ if (event.charCode == 32) { algorithm.step(); } }); window.G = G; })();
Use charCode instead of keyCode
Use charCode instead of keyCode
JavaScript
mit
dvberkel/Dijkstra,dvberkel/Dijkstra
--- +++ @@ -33,7 +33,7 @@ loop(); document.body.addEventListener('keypress', function(event){ - if (event.keyCode == 32) { + if (event.charCode == 32) { algorithm.step(); } });
62bc1ec26ad607e42a2495257b3e0156830b42dd
app/templates/src/main/webapp/scripts/app/account/settings/_settings.controller.js
app/templates/src/main/webapp/scripts/app/account/settings/_settings.controller.js
'use strict'; angular.module('<%=angularAppName%>') .controller('SettingsController', function ($scope, Principal, Auth) { $scope.success = null; $scope.error = null; Principal.identity().then(function(account) { $scope.settingsAccount = account; }); $scope.save = function () { Auth.updateAccount($scope.settingsAccount).then(function() { $scope.error = null; $scope.success = 'OK'; Principal.identity().then(function(account) { $scope.settingsAccount = account; }); }).catch(function() { $scope.success = null; $scope.error = 'ERROR'; }); }; });
'use strict'; angular.module('<%=angularAppName%>') .controller('SettingsController', function ($scope, Principal, Auth) { $scope.success = null; $scope.error = null; Principal.identity(true).then(function(account) { $scope.settingsAccount = account; }); $scope.save = function () { Auth.updateAccount($scope.settingsAccount).then(function() { $scope.error = null; $scope.success = 'OK'; Principal.identity().then(function(account) { $scope.settingsAccount = account; }); }).catch(function() { $scope.success = null; $scope.error = 'ERROR'; }); }; });
Refresh data for the user settings page when it is being accessed
Refresh data for the user settings page when it is being accessed Fix #1281
JavaScript
apache-2.0
vivekmore/generator-jhipster,deepu105/generator-jhipster,dynamicguy/generator-jhipster,mosoft521/generator-jhipster,pascalgrimaud/generator-jhipster,ziogiugno/generator-jhipster,atomfrede/generator-jhipster,siliconharborlabs/generator-jhipster,wmarques/generator-jhipster,duderoot/generator-jhipster,maniacneron/generator-jhipster,dynamicguy/generator-jhipster,PierreBesson/generator-jhipster,dimeros/generator-jhipster,hdurix/generator-jhipster,maniacneron/generator-jhipster,dimeros/generator-jhipster,gzsombor/generator-jhipster,lrkwz/generator-jhipster,maniacneron/generator-jhipster,rkohel/generator-jhipster,baskeboler/generator-jhipster,baskeboler/generator-jhipster,rkohel/generator-jhipster,JulienMrgrd/generator-jhipster,duderoot/generator-jhipster,erikkemperman/generator-jhipster,gzsombor/generator-jhipster,wmarques/generator-jhipster,jhipster/generator-jhipster,sohibegit/generator-jhipster,ctamisier/generator-jhipster,cbornet/generator-jhipster,rkohel/generator-jhipster,vivekmore/generator-jhipster,mraible/generator-jhipster,eosimosu/generator-jhipster,eosimosu/generator-jhipster,jhipster/generator-jhipster,cbornet/generator-jhipster,hdurix/generator-jhipster,mraible/generator-jhipster,gzsombor/generator-jhipster,Tcharl/generator-jhipster,mosoft521/generator-jhipster,nkolosnjaji/generator-jhipster,stevehouel/generator-jhipster,yongli82/generator-jhipster,yongli82/generator-jhipster,Tcharl/generator-jhipster,liseri/generator-jhipster,wmarques/generator-jhipster,jhipster/generator-jhipster,ramzimaalej/generator-jhipster,Tcharl/generator-jhipster,lrkwz/generator-jhipster,mosoft521/generator-jhipster,danielpetisme/generator-jhipster,hdurix/generator-jhipster,robertmilowski/generator-jhipster,ramzimaalej/generator-jhipster,dalbelap/generator-jhipster,gmarziou/generator-jhipster,xetys/generator-jhipster,sendilkumarn/generator-jhipster,gmarziou/generator-jhipster,baskeboler/generator-jhipster,yongli82/generator-jhipster,Tcharl/generator-jhipster,rifatdover/generator-jhipster,JulienMrgrd/generator-jhipster,duderoot/generator-jhipster,stevehouel/generator-jhipster,vivekmore/generator-jhipster,mosoft521/generator-jhipster,robertmilowski/generator-jhipster,jkutner/generator-jhipster,mraible/generator-jhipster,danielpetisme/generator-jhipster,sendilkumarn/generator-jhipster,sohibegit/generator-jhipster,eosimosu/generator-jhipster,liseri/generator-jhipster,eosimosu/generator-jhipster,erikkemperman/generator-jhipster,sohibegit/generator-jhipster,yongli82/generator-jhipster,atomfrede/generator-jhipster,PierreBesson/generator-jhipster,pascalgrimaud/generator-jhipster,ruddell/generator-jhipster,maniacneron/generator-jhipster,atomfrede/generator-jhipster,liseri/generator-jhipster,sendilkumarn/generator-jhipster,siliconharborlabs/generator-jhipster,stevehouel/generator-jhipster,xetys/generator-jhipster,robertmilowski/generator-jhipster,lrkwz/generator-jhipster,hdurix/generator-jhipster,dynamicguy/generator-jhipster,hdurix/generator-jhipster,ctamisier/generator-jhipster,stevehouel/generator-jhipster,wmarques/generator-jhipster,sohibegit/generator-jhipster,erikkemperman/generator-jhipster,rifatdover/generator-jhipster,wmarques/generator-jhipster,nkolosnjaji/generator-jhipster,mraible/generator-jhipster,duderoot/generator-jhipster,cbornet/generator-jhipster,eosimosu/generator-jhipster,deepu105/generator-jhipster,cbornet/generator-jhipster,xetys/generator-jhipster,PierreBesson/generator-jhipster,baskeboler/generator-jhipster,gzsombor/generator-jhipster,Tcharl/generator-jhipster,pascalgrimaud/generator-jhipster,vivekmore/generator-jhipster,cbornet/generator-jhipster,sohibegit/generator-jhipster,deepu105/generator-jhipster,ruddell/generator-jhipster,siliconharborlabs/generator-jhipster,PierreBesson/generator-jhipster,ctamisier/generator-jhipster,rifatdover/generator-jhipster,ramzimaalej/generator-jhipster,liseri/generator-jhipster,dimeros/generator-jhipster,sendilkumarn/generator-jhipster,jkutner/generator-jhipster,dalbelap/generator-jhipster,ruddell/generator-jhipster,jkutner/generator-jhipster,nkolosnjaji/generator-jhipster,jkutner/generator-jhipster,jkutner/generator-jhipster,erikkemperman/generator-jhipster,dalbelap/generator-jhipster,ziogiugno/generator-jhipster,siliconharborlabs/generator-jhipster,atomfrede/generator-jhipster,siliconharborlabs/generator-jhipster,xetys/generator-jhipster,ruddell/generator-jhipster,danielpetisme/generator-jhipster,dalbelap/generator-jhipster,gmarziou/generator-jhipster,pascalgrimaud/generator-jhipster,ctamisier/generator-jhipster,nkolosnjaji/generator-jhipster,deepu105/generator-jhipster,gmarziou/generator-jhipster,JulienMrgrd/generator-jhipster,ziogiugno/generator-jhipster,mraible/generator-jhipster,dynamicguy/generator-jhipster,ziogiugno/generator-jhipster,deepu105/generator-jhipster,baskeboler/generator-jhipster,rkohel/generator-jhipster,rkohel/generator-jhipster,dimeros/generator-jhipster,dimeros/generator-jhipster,danielpetisme/generator-jhipster,liseri/generator-jhipster,lrkwz/generator-jhipster,jhipster/generator-jhipster,gmarziou/generator-jhipster,atomfrede/generator-jhipster,yongli82/generator-jhipster,pascalgrimaud/generator-jhipster,sendilkumarn/generator-jhipster,ziogiugno/generator-jhipster,robertmilowski/generator-jhipster,vivekmore/generator-jhipster,maniacneron/generator-jhipster,jhipster/generator-jhipster,erikkemperman/generator-jhipster,nkolosnjaji/generator-jhipster,ruddell/generator-jhipster,duderoot/generator-jhipster,lrkwz/generator-jhipster,dalbelap/generator-jhipster,danielpetisme/generator-jhipster,robertmilowski/generator-jhipster,ctamisier/generator-jhipster,JulienMrgrd/generator-jhipster,stevehouel/generator-jhipster,PierreBesson/generator-jhipster,mosoft521/generator-jhipster,JulienMrgrd/generator-jhipster,gzsombor/generator-jhipster
--- +++ @@ -4,7 +4,7 @@ .controller('SettingsController', function ($scope, Principal, Auth) { $scope.success = null; $scope.error = null; - Principal.identity().then(function(account) { + Principal.identity(true).then(function(account) { $scope.settingsAccount = account; });
6ce99ce4acbed8c57b672706c4b26dfc063bb04b
extensionloader.js
extensionloader.js
/* Load a block from github.io. Accepts a url as a parameter which can include url parameters e.g. https://megjlow.github.io/extension2.js?name=SUN&ip=10.0.0.1 */ new (function() { var ext = this; var descriptor = { blocks: [ [' ', 'Load extension block %s', 'loadBlock', 'url', 'url'], ], url: 'http://www.warwick.ac.uk/tilesfortales' }; ext._shutdown = function() {}; ext._getStatus = function() { return {status: 2, msg: 'Device connected'} }; ext.loadBlock = function(url) { ScratchExtensions.loadExternalJS(url); }; ScratchExtensions.register("extensionloader", descriptor, ext); });
/* Load a block from github.io. Accepts a url as a parameter which can include url parameters e.g. https://megjlow.github.io/extension2.js?name=SUN&ip=10.0.0.1 */ new (function() { var ext = this; var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = decodeURIComponent(document.currentScript.src.split("?")[1]), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; ext.url = getUrlParameter("extUrl"); var descriptor = { blocks: [ [' ', 'Load extension block %s', 'loadBlock', 'url', 'url'], ], url: 'http://www.warwick.ac.uk/tilesfortales' }; ext._shutdown = function() {}; ext._getStatus = function() { return {status: 2, msg: 'Device connected'} }; ext.loadBlock = function(url) { ScratchExtensions.loadExternalJS(url); }; ScratchExtensions.register("extensionloader", descriptor, ext); if(ext.url != undefined) { ext.loadBlock(ext.url); } });
Allow a block to be specified for loading
Allow a block to be specified for loading
JavaScript
mit
megjlow/megjlow.github.io
--- +++ @@ -5,6 +5,23 @@ new (function() { var ext = this; + + var getUrlParameter = function getUrlParameter(sParam) { + var sPageURL = decodeURIComponent(document.currentScript.src.split("?")[1]), + sURLVariables = sPageURL.split('&'), + sParameterName, + i; + + for (i = 0; i < sURLVariables.length; i++) { + sParameterName = sURLVariables[i].split('='); + + if (sParameterName[0] === sParam) { + return sParameterName[1] === undefined ? true : sParameterName[1]; + } + } + }; + + ext.url = getUrlParameter("extUrl"); var descriptor = { blocks: [ @@ -24,5 +41,9 @@ }; ScratchExtensions.register("extensionloader", descriptor, ext); + + if(ext.url != undefined) { + ext.loadBlock(ext.url); + } });
997ef4147d96618cd4f1c57289e98004b7b7eb7d
extra/_buildAll.js
extra/_buildAll.js
const childProcess = require("child_process"); const fs = require("fs"); if (process.argv.length !== 3) { throw new Error("Requires the base path as argument."); } const basePath = process.argv[2]; if (!basePath.match(/[\\\/]$/)) { throw new Error("Path must end with a slash - any slash will do."); } else if (!fs.existsSync(basePath)) { throw new Error(`Invalid path, '${basePath}' does not exist or is not readable.`); } fs.readdirSync(basePath) .filter(directory => { if (directory.indexOf('.') !== 0 && fs.statSync(basePath + directory).isDirectory()) { // filter by known repository name patterns if (directory === "WCF" || directory.indexOf("com.woltlab.") === 0) { return true; } } return false; }) .forEach(directory => { console.log(`##### Building ${directory} #####\n`); let path = basePath + directory; if (directory === "WCF") { childProcess.execSync(`node _buildCore.js`, { stdio: [0, 1, 2] }); } else { childProcess.execSync(`node _buildExternal.js ${path}`, { stdio: [0, 1, 2] }); } childProcess.execSync(`ts-node syncTemplates.ts ${path}`, { stdio: [0, 1, 2] }); console.log("\n"); });
const childProcess = require("child_process"); const fs = require("fs"); if (process.argv.length !== 3) { throw new Error("Requires the base path as argument."); } const basePath = process.argv[2]; if (!basePath.match(/[\\\/]$/)) { throw new Error("Path must end with a slash - any slash will do."); } else if (!fs.existsSync(basePath)) { throw new Error(`Invalid path, '${basePath}' does not exist or is not readable.`); } fs.readdirSync(basePath) .filter(directory => { if (directory.indexOf('.') !== 0 && fs.statSync(basePath + directory).isDirectory()) { // filter by known repository name patterns if (directory === "WCF" || directory.indexOf("com.woltlab.") === 0) { return true; } } return false; }) .forEach(directory => { console.log(`##### Building ${directory} #####\n`); let path = basePath + directory; if (directory === "WCF") { childProcess.execSync(`node _buildCore.js`, { stdio: [0, 1, 2] }); } else { childProcess.execSync(`node _buildExternal.js ${path}`, { stdio: [0, 1, 2] }); } childProcess.execSync(`npx ts-node syncTemplates.ts ${path}`, { stdio: [0, 1, 2] }); console.log("\n"); });
Stop relying on `ts-node` from the global scope
Stop relying on `ts-node` from the global scope
JavaScript
lgpl-2.1
WoltLab/WCF,WoltLab/WCF,SoftCreatR/WCF,WoltLab/WCF,SoftCreatR/WCF,SoftCreatR/WCF,SoftCreatR/WCF,WoltLab/WCF
--- +++ @@ -39,7 +39,7 @@ }); } - childProcess.execSync(`ts-node syncTemplates.ts ${path}`, { + childProcess.execSync(`npx ts-node syncTemplates.ts ${path}`, { stdio: [0, 1, 2] });
275dc5b09b27d5441814aa423cddaa7472344dbf
src/hooks/usePopover.js
src/hooks/usePopover.js
import React, { useState, useCallback, useRef } from 'react'; /** * Hook which manages popover position over a DOM element. * Pass a ref created by React.createRef. Receive callbacks, */ export const usePopover = () => { const [visibilityState, setVisibilityState] = useState(false); const ref = useRef(React.createRef()); const showPopover = useCallback(() => setVisibilityState(true), []); const closePopover = useCallback(() => setVisibilityState(false), []); return [ref, visibilityState, showPopover, closePopover]; };
import React, { useState, useCallback, useRef } from 'react'; import { useNavigationFocus } from './useNavigationFocus'; /** * Hook which manages popover position over a DOM element. * Pass a ref created by React.createRef. Receive callbacks, */ export const usePopover = navigation => { const [visibilityState, setVisibilityState] = useState(false); const ref = useRef(React.createRef()); const showPopover = useCallback(() => setVisibilityState(true), []); const closePopover = useCallback(() => setVisibilityState(false), []); useNavigationFocus(navigation, null, closePopover); return [ref, visibilityState, showPopover, closePopover]; };
Add use of navigation focus custom hook in usePopOver hook
Add use of navigation focus custom hook in usePopOver hook
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
--- +++ @@ -1,15 +1,18 @@ import React, { useState, useCallback, useRef } from 'react'; +import { useNavigationFocus } from './useNavigationFocus'; /** * Hook which manages popover position over a DOM element. * Pass a ref created by React.createRef. Receive callbacks, */ -export const usePopover = () => { +export const usePopover = navigation => { const [visibilityState, setVisibilityState] = useState(false); const ref = useRef(React.createRef()); const showPopover = useCallback(() => setVisibilityState(true), []); const closePopover = useCallback(() => setVisibilityState(false), []); + useNavigationFocus(navigation, null, closePopover); + return [ref, visibilityState, showPopover, closePopover]; };
0087fa9db21bf615d3c57480c89a706c8d8e75bf
lib/jsdom/level2/languages/javascript.js
lib/jsdom/level2/languages/javascript.js
var Context = process.binding('evals').Context, // TODO: Remove .Script when bumping req'd node version to >= 5.0 Script = process.binding('evals').NodeScript || process.binding('evals').Script; exports.javascript = function(element, code, filename) { var document = element.ownerDocument, window = document.parentWindow; if (window) { var ctx = window.__scriptContext; if (!ctx) { window.__scriptContext = ctx = new Context(); ctx.__proto__ = window; } var tracelimitbak = Error.stackTraceLimit; Error.stackTraceLimit = 100; try { Script.runInContext(code, ctx, filename); } catch(e) { document.trigger( 'error', 'Running ' + filename + ' failed.', {error: e, filename: filename} ); } Error.stackTraceLimit = tracelimitbak; } };
var vm = require('vm'); exports.javascript = function(element, code, filename) { var document = element.ownerDocument, window = document.parentWindow; if (window) { var ctx = window.__scriptContext; if (!ctx) { window.__scriptContext = ctx = vm.createContext({}); ctx.__proto__ = window; } var tracelimitbak = Error.stackTraceLimit; Error.stackTraceLimit = 100; try { vm.Script.runInContext(code, ctx, filename); } catch(e) { document.trigger( 'error', 'Running ' + filename + ' failed.', {error: e, filename: filename} ); } Error.stackTraceLimit = tracelimitbak; } };
Use vm instead of evals binding
Use vm instead of evals binding
JavaScript
mit
iizukanao/jsdom,aduyng/jsdom,jeffcarp/jsdom,jeffcarp/jsdom,tmpvar/jsdom,Zirro/jsdom,evdevgit/jsdom,susaing/jsdom,sebmck/jsdom,Zirro/jsdom,Ye-Yong-Chi/jsdom,mbostock/jsdom,zaucy/jsdom,beni55/jsdom,kesla/jsdom,darobin/jsdom,cpojer/jsdom,mbostock/jsdom,Sebmaster/jsdom,snuggs/jsdom,AshCoolman/jsdom,szarouski/jsdom,janusnic/jsdom,cpojer/jsdom,szarouski/jsdom,Joris-van-der-Wel/jsdom,susaing/jsdom,kangax/jsdom,evdevgit/jsdom,evdevgit/jsdom,robertknight/jsdom,isaacs/jsdom,brianmcd/cloudbrowser-jsdom,mzgol/jsdom,Sebmaster/jsdom,kevinold/jsdom,fiftin/jsdom,brianmcd/cloudbrowser-jsdom,substack/jsdom,kevinold/jsdom,sirbrillig/jsdom,sebmck/jsdom,janusnic/jsdom,kesla/jsdom,evanlucas/jsdom,danieljoppi/jsdom,vestineo/jsdom,godmar/jsdom,lcstore/jsdom,evanlucas/jsdom,AshCoolman/jsdom,aduyng/jsdom,selam/jsdom,mzgol/jsdom,dexteryy/jsdom-nogyp,papandreou/jsdom,darobin/jsdom,kevinold/jsdom,robertknight/jsdom,AVGP/jsdom,cpojer/jsdom,danieljoppi/jsdom,sirbrillig/jsdom,kesla/jsdom,Ye-Yong-Chi/jsdom,crealogix/jsdom,Joris-van-der-Wel/jsdom,selam/jsdom,Sebmaster/jsdom,lcstore/jsdom,zaucy/jsdom,lcstore/jsdom,fiftin/jsdom,mbostock/jsdom,dexteryy/jsdom-nogyp,medikoo/jsdom,nicolashenry/jsdom,susaing/jsdom,kangax/jsdom,vestineo/jsdom,darobin/jsdom,danieljoppi/jsdom,selam/jsdom,jeffcarp/jsdom,nicolashenry/jsdom,beni55/jsdom,Ye-Yong-Chi/jsdom,Joris-van-der-Wel/jsdom,crealogix/jsdom,isaacs/jsdom,godmar/jsdom,mzgol/jsdom,medikoo/jsdom,substack/jsdom,fiftin/jsdom,iizukanao/jsdom,kittens/jsdom,aduyng/jsdom,robertknight/jsdom,medikoo/jsdom,concord-consortium/jsdom,kittens/jsdom,tmpvar/jsdom,AshCoolman/jsdom,beni55/jsdom,singlebrook/linkck,nicolashenry/jsdom,janusnic/jsdom,szarouski/jsdom,zaucy/jsdom,sirbrillig/jsdom,evanlucas/jsdom,snuggs/jsdom,papandreou/jsdom,AVGP/jsdom,vestineo/jsdom,concord-consortium/jsdom,sebmck/jsdom,kittens/jsdom
--- +++ @@ -1,6 +1,4 @@ -var Context = process.binding('evals').Context, - // TODO: Remove .Script when bumping req'd node version to >= 5.0 - Script = process.binding('evals').NodeScript || process.binding('evals').Script; +var vm = require('vm'); exports.javascript = function(element, code, filename) { var document = element.ownerDocument, @@ -9,13 +7,13 @@ if (window) { var ctx = window.__scriptContext; if (!ctx) { - window.__scriptContext = ctx = new Context(); + window.__scriptContext = ctx = vm.createContext({}); ctx.__proto__ = window; } var tracelimitbak = Error.stackTraceLimit; Error.stackTraceLimit = 100; try { - Script.runInContext(code, ctx, filename); + vm.Script.runInContext(code, ctx, filename); } catch(e) { document.trigger(
dcbba806e6d933f714fec77c1b37c485a43a9e00
tests/unit/controllers/submit-test.js
tests/unit/controllers/submit-test.js
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:submit', 'Unit | Controller | submit', { // Specify the other units that are required for this test. // needs: ['controller:foo'] needs: [ 'validator:presence', 'validator:length', 'validator:format', 'service:metrics' ], }); // Replace this with your real tests. test('it exists', function(assert) { let controller = this.subject(); assert.ok(controller); });
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:submit', 'Unit | Controller | submit', { // Specify the other units that are required for this test. // needs: ['controller:foo'] needs: [ 'validator:presence', 'validator:length', 'validator:format', 'service:metrics' ], test('editLicense sets basicsLicense and licenseValid', function(assert) { const ctrl = this.subject(); assert.equal(ctrl.get('basicsLicense.copyrightHolders'), null); assert.equal(ctrl.get('basicsLicense.licenseType'), null); assert.equal(ctrl.get('basicsLicense.year'), null); assert.equal(ctrl.get('licenseValid'), false); // Trigger controller action ctrl.send('editLicense', 'license', true); assert.equal(ctrl.get('basicsLicense'), 'license'); assert.equal(ctrl.get('licenseValid'), true); }); test('applyLicenseToggle toggles applyLicense', function(assert) { const ctrl = this.subject(); assert.equal(ctrl.get('applyLicense'), false); ctrl.send('applyLicenseToggle', true); assert.equal(ctrl.get('applyLicense'), true); }); // Replace this with your real tests. test('it exists', function(assert) { let controller = this.subject(); assert.ok(controller); });
Add tests for some submit controller actions.
Add tests for some submit controller actions.
JavaScript
apache-2.0
baylee-d/ember-preprints,caneruguz/ember-preprints,baylee-d/ember-preprints,CenterForOpenScience/ember-preprints,CenterForOpenScience/ember-preprints,laurenrevere/ember-preprints,laurenrevere/ember-preprints,caneruguz/ember-preprints
--- +++ @@ -9,6 +9,24 @@ 'validator:format', 'service:metrics' ], +test('editLicense sets basicsLicense and licenseValid', function(assert) { + const ctrl = this.subject(); + assert.equal(ctrl.get('basicsLicense.copyrightHolders'), null); + assert.equal(ctrl.get('basicsLicense.licenseType'), null); + assert.equal(ctrl.get('basicsLicense.year'), null); + assert.equal(ctrl.get('licenseValid'), false); + // Trigger controller action + ctrl.send('editLicense', 'license', true); + + assert.equal(ctrl.get('basicsLicense'), 'license'); + assert.equal(ctrl.get('licenseValid'), true); +}); + +test('applyLicenseToggle toggles applyLicense', function(assert) { + const ctrl = this.subject(); + assert.equal(ctrl.get('applyLicense'), false); + ctrl.send('applyLicenseToggle', true); + assert.equal(ctrl.get('applyLicense'), true); }); // Replace this with your real tests.
c8e2d1ac9ed72967aa8f8210f8c05f2af8044cab
tests/dummy/app/components/froala-editor.js
tests/dummy/app/components/froala-editor.js
import FroalaEditorComponent from 'ember-froala-editor/components/froala-editor'; export default FroalaEditorComponent.extend({ // eslint-disable-next-line ember/avoid-leaking-state-in-ember-objects options: { key: 'Tvywseoh1irkdyzdhvlvC8ehe==' } });
import FroalaEditorComponent from 'ember-froala-editor/components/froala-editor'; export default FroalaEditorComponent.extend({ // eslint-disable-next-line ember/avoid-leaking-state-in-ember-objects options: { key: '3C3B6eF5B4A3E3E2C2C6D6A3D3xg1kemB-22B-16rF-11dyvwtvze1zdA1H-8vw==' } });
Update editor key for docs site
Update editor key for docs site
JavaScript
mit
froala/ember-froala-editor,froala/ember-froala-editor,Panman8201/ember-froala-editor,Panman8201/ember-froala-editor
--- +++ @@ -3,6 +3,6 @@ export default FroalaEditorComponent.extend({ // eslint-disable-next-line ember/avoid-leaking-state-in-ember-objects options: { - key: 'Tvywseoh1irkdyzdhvlvC8ehe==' + key: '3C3B6eF5B4A3E3E2C2C6D6A3D3xg1kemB-22B-16rF-11dyvwtvze1zdA1H-8vw==' } });
8ddadad76536c0445c1da4cd203646509dc30cfd
contribs/gmf/src/proj/epsg21781projection.js
contribs/gmf/src/proj/epsg21781projection.js
goog.provide('gmf.proj.EPSG21781'); goog.require('ol.proj'); if (typeof proj4 == 'function') { proj4.defs('EPSG:21781', '+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 ' + '+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel' + '+towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs'); ol.proj.get('EPSG:21781').setExtent([420000, 30000, 900000, 350000]); }
goog.provide('gmf.proj.EPSG21781'); goog.require('ol.proj'); if (typeof proj4 == 'function') { proj4.defs('EPSG:21781', '+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 ' + '+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel ' + '+towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs'); ol.proj.get('EPSG:21781').setExtent([420000, 30000, 900000, 350000]); }
Add missing space in proj definition
Add missing space in proj definition
JavaScript
mit
Jenselme/ngeo,kalbermattenm/ngeo,ger-benjamin/ngeo,pgiraud/ngeo,camptocamp/ngeo,ger-benjamin/ngeo,pgiraud/ngeo,Jenselme/ngeo,ger-benjamin/ngeo,Jenselme/ngeo,camptocamp/ngeo,adube/ngeo,camptocamp/ngeo,adube/ngeo,camptocamp/ngeo,adube/ngeo,kalbermattenm/ngeo,kalbermattenm/ngeo,adube/ngeo,camptocamp/ngeo,Jenselme/ngeo,pgiraud/ngeo
--- +++ @@ -5,7 +5,7 @@ if (typeof proj4 == 'function') { proj4.defs('EPSG:21781', '+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 ' + - '+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel' + + '+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel ' + '+towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs'); ol.proj.get('EPSG:21781').setExtent([420000, 30000, 900000, 350000]); }
5b0082d9aaa6ae25e2ed7a0049b1829b3a9aa242
src/patch_dns_lookup.js
src/patch_dns_lookup.js
// Patch DNS.lookup to resolve all hosts added via Replay.localhost as 127.0.0.1 const DNS = require('dns'); const Replay = require('./'); const originalLookup = DNS.lookup; DNS.lookup = function(domain, options, callback) { if (typeof domain === 'string' && typeof options === 'object' && typeof callback === 'function' && Replay.isLocalhost(domain)) { const family = options.family || 4; const ip = (family === 6) ? '::1' : '127.0.0.1'; callback(null, ip, family); } else originalLookup(domain, options, callback); };
// Patch DNS.lookup to resolve all hosts added via Replay.localhost as 127.0.0.1 const DNS = require('dns'); const Replay = require('./'); const originalLookup = DNS.lookup; DNS.lookup = function(domain, options, callback) { if (typeof domain === 'string' && typeof options === 'object' && typeof callback === 'function' && Replay.isLocalhost(domain)) { const family = options.family || 4; const ip = (family === 6) ? '::1' : '127.0.0.1'; if (options.all) callback(null, [ip], family); else callback(null, ip, family); } else originalLookup(domain, options, callback); };
Support |all| option when shimming DNS.lookup
Support |all| option when shimming DNS.lookup Before, clients attempting an "all" style address lookup, such as the SQL Server database module tedious does in its connector.js when provided a hostname, were liable to error out due to treating the argument as an array when Replay was supplying a string. This might have looked like: TypeError: this.addresses.shift is not a function Now, when the |all| option is detected, the string is wrapped in an array to match client expectations.
JavaScript
mit
assaf/node-replay
--- +++ @@ -10,7 +10,10 @@ typeof callback === 'function' && Replay.isLocalhost(domain)) { const family = options.family || 4; const ip = (family === 6) ? '::1' : '127.0.0.1'; - callback(null, ip, family); + if (options.all) + callback(null, [ip], family); + else + callback(null, ip, family); } else originalLookup(domain, options, callback); };
cf06f9680d8494204db1b70fab4f859f91ca684e
graphql/database/charities/__tests__/CharityModel.test.js
graphql/database/charities/__tests__/CharityModel.test.js
/* eslint-env jest */ import tableNames from '../../tables' import Charity from '../CharityModel' jest.mock('../../database') describe('CharityModel', () => { it('implements the name property', () => { expect(Charity.name).toBeDefined() }) it('implements the hashKey property', () => { expect(Charity.hashKey).toBeDefined() }) it('implements the tableName property', () => { expect(Charity.tableName).toBe(tableNames['charities']) }) it('auto creates an id', async () => { const charity = await Charity.create({ name: 'something' }) expect(charity.id).toBeDefined() expect(charity.name).toEqual('something') }) // TODO: test getting charities })
/* eslint-env jest */ import uuid from 'uuid/v4' import tableNames from '../../tables' import Charity from '../CharityModel' jest.mock('../../database') describe('CharityModel', () => { it('implements the name property', () => { expect(Charity.name).toBeDefined() }) it('implements the hashKey property', () => { expect(Charity.hashKey).toBeDefined() }) it('implements the tableName property', () => { expect(Charity.tableName).toBe(tableNames['charities']) }) it('auto creates an id', async () => { const charity = await Charity.create({ name: 'something' }) expect(charity.id).toBeDefined() expect(charity.name).toEqual('something') }) it('create with existing id', async () => { const someId = uuid() const charity = await Charity.create({ id: someId, name: 'something' }) expect(charity.id).toBe(someId) }) // TODO: test getting charities })
Test using an existing ID.
Test using an existing ID.
JavaScript
mpl-2.0
gladly-team/tab,gladly-team/tab,gladly-team/tab
--- +++ @@ -1,4 +1,6 @@ /* eslint-env jest */ + +import uuid from 'uuid/v4' import tableNames from '../../tables' import Charity from '../CharityModel' @@ -24,5 +26,14 @@ expect(charity.name).toEqual('something') }) + it('create with existing id', async () => { + const someId = uuid() + const charity = await Charity.create({ + id: someId, + name: 'something' + }) + expect(charity.id).toBe(someId) + }) + // TODO: test getting charities })
6e853e6d2eba890ddff29b71a21130e145c747fb
html/directives/validateBitcoinAddress.js
html/directives/validateBitcoinAddress.js
angular.module('app').directive("validateBitcoinAddress", function() { return { require: 'ngModel', link: function(scope, ele, attrs, ctrl) { ctrl.$parsers.unshift(function(value) { // test and set the validity after update. var valid = window.bitcoinAddress.validate(value); ctrl.$setValidity('validateBitcoinAddress', valid); // if it's valid, return the value to the model, // otherwise return undefined. return valid ? value : undefined; }); ctrl.$formatters.unshift(function(value) { // validate. ctrl.$setValidity('validateBitcoinAddress', window.bitcoinAddress.validate(value)); // return the value or nothing will be written to the DOM. return value; }); } }; });
angular.module('app').directive("validateBitcoinAddress", function() { return { require: 'ngModel', link: function(scope, ele, attrs, ctrl) { ctrl.$parsers.unshift(function(value) { var valid = window.bitcoinAddress.validate(value); ctrl.$setValidity('validateBitcoinAddress', valid); return valid ? value : undefined; }); ctrl.$formatters.unshift(function(value) { var valid = window.bitcoinAddress.validate(value); ctrl.$setValidity('validateBitcoinAddress', valid); return value; }); } }; });
Clean up comments and validity check
Clean up comments and validity check
JavaScript
mit
atsuyim/OpenBazaar,must-/OpenBazaar,must-/OpenBazaar,saltduck/OpenBazaar,NolanZhao/OpenBazaar,NolanZhao/OpenBazaar,tortxof/OpenBazaar,tortxof/OpenBazaar,must-/OpenBazaar,blakejakopovic/OpenBazaar,habibmasuro/OpenBazaar,bankonme/OpenBazaar,blakejakopovic/OpenBazaar,rllola/OpenBazaar,rllola/OpenBazaar,mirrax/OpenBazaar,blakejakopovic/OpenBazaar,saltduck/OpenBazaar,Renelvon/OpenBazaar,saltduck/OpenBazaar,bglassy/OpenBazaar,must-/OpenBazaar,atsuyim/OpenBazaar,NolanZhao/OpenBazaar,mirrax/OpenBazaar,Renelvon/OpenBazaar,mirrax/OpenBazaar,rllola/OpenBazaar,bankonme/OpenBazaar,blakejakopovic/OpenBazaar,saltduck/OpenBazaar,bankonme/OpenBazaar,mirrax/OpenBazaar,tortxof/OpenBazaar,matiasbastos/OpenBazaar,bglassy/OpenBazaar,Renelvon/OpenBazaar,bglassy/OpenBazaar,habibmasuro/OpenBazaar,habibmasuro/OpenBazaar,matiasbastos/OpenBazaar,rllola/OpenBazaar,Renelvon/OpenBazaar,bankonme/OpenBazaar,matiasbastos/OpenBazaar,NolanZhao/OpenBazaar,atsuyim/OpenBazaar,matiasbastos/OpenBazaar,atsuyim/OpenBazaar,tortxof/OpenBazaar,habibmasuro/OpenBazaar,bglassy/OpenBazaar
--- +++ @@ -4,21 +4,14 @@ link: function(scope, ele, attrs, ctrl) { ctrl.$parsers.unshift(function(value) { - - // test and set the validity after update. var valid = window.bitcoinAddress.validate(value); ctrl.$setValidity('validateBitcoinAddress', valid); - - // if it's valid, return the value to the model, - // otherwise return undefined. return valid ? value : undefined; }); ctrl.$formatters.unshift(function(value) { - // validate. - ctrl.$setValidity('validateBitcoinAddress', window.bitcoinAddress.validate(value)); - - // return the value or nothing will be written to the DOM. + var valid = window.bitcoinAddress.validate(value); + ctrl.$setValidity('validateBitcoinAddress', valid); return value; });
246825583b1c778e56bad458f3e4283c9b1c5df6
es2015/total-replies.js
es2015/total-replies.js
"use strict"; let replyCount = 21; let message = `This topic has a total of replies`;
"use strict"; let replyCount = 21; let message = `This topic has a total of ${replyCount} replies`;
Complete the code to use the variable replyCount from inside the template string
Complete the code to use the variable replyCount from inside the template string
JavaScript
mit
var-bin/reactjs-training,var-bin/reactjs-training,var-bin/reactjs-training
--- +++ @@ -1,4 +1,4 @@ "use strict"; let replyCount = 21; -let message = `This topic has a total of replies`; +let message = `This topic has a total of ${replyCount} replies`;
5a14bf458e67d893cefe99e7515fdb3b904ab556
src/interfaces/i-tracker-manager.js
src/interfaces/i-tracker-manager.js
'use strict'; const EventEmitter = require('events'); /** * Tracker Manager * @interface */ class ITrackerManager extends EventEmitter { constructor() { super(); if (this.constructor === ITrackerManager) { throw new TypeError('Can not create new instance of interface'); } } /** * Include tracker in search * @param {ITracker} tracker * @return {number|undefined} Index of tracker in array */ include(tracker) { throw new TypeError('Method "include" is not implemented.'); } /** * Exclude tracker from search * @param {number} index * @return {ITracker|undefined} Excluded Tracker instance */ exclude(index) { throw new TypeError('Method "exclude" is not implemented.'); } /** * Search in all included trackers * @param {SearchParams} searchParams */ search(searchParams) { throw new TypeError('Method "search" is not implemented.'); } } module.exports = ITrackerManager;
'use strict'; const EventEmitter = require('events'); /** * Tracker Manager * @interface */ class ITrackerManager extends EventEmitter { constructor() { super(); if (this.constructor === ITrackerManager) { throw new TypeError('Can not create new instance of interface'); } } /** * Include tracker in search * @param {ITracker} tracker * @return {string|undefined} UID of tracker in list */ include(tracker) { throw new TypeError('Method "include" is not implemented.'); } /** * Exclude tracker from search * @param {string} uid * @return {ITracker|undefined} Excluded Tracker instance */ exclude(uid) { throw new TypeError('Method "exclude" is not implemented.'); } /** * Search in all included trackers * @param {SearchParams} searchParams */ search(searchParams) { throw new TypeError('Method "search" is not implemented.'); } } module.exports = ITrackerManager;
Change interface for make change in implementation
Change interface for make change in implementation
JavaScript
mit
reeFridge/tracker-proxy
--- +++ @@ -18,7 +18,7 @@ /** * Include tracker in search * @param {ITracker} tracker - * @return {number|undefined} Index of tracker in array + * @return {string|undefined} UID of tracker in list */ include(tracker) { throw new TypeError('Method "include" is not implemented.'); @@ -26,10 +26,10 @@ /** * Exclude tracker from search - * @param {number} index + * @param {string} uid * @return {ITracker|undefined} Excluded Tracker instance */ - exclude(index) { + exclude(uid) { throw new TypeError('Method "exclude" is not implemented.'); }
733b66e5733800e4abc8dbcf358b3af20e424313
app/components/popover-confirm.js
app/components/popover-confirm.js
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['popover-confirm'], iconClass: function () { var filename = this.get('filename'), regex, extension; if (filename) { regex = /\.([0-9a-z]+)$/i; extension = filename.match(/\.([0-9a-z]+)$/i)[1]; if (extension) { return 'glyphicon-' + extension.toLowerCase(); } } }.property('filename'), isShowingDidChange: function () { if (!!this.get('isShowing')) { this.show(); } else { this.hide(); } }.observes('isShowing'), didInsertElement: function () { this._super(); this.$().hide(); }, // Uber hacky way to make Bootstrap 'popover' plugin work with Ember metamorph show: function () { // Delay until related properties are computed Ember.run.next(this, function () { var html = this.$().html(); // Content needs to be visible, // so that popover position is calculated properly. this.$().show(); this.$().popover({ html: true, content: html, placement: 'top' }); this.$().popover('show'); this.$().hide(); }); }, hide: function () { this.$().popover('destroy'); }, actions: { confirm: function () { this.hide(); this.sendAction('confirm'); }, cancel: function() { this.hide(); this.sendAction('cancel'); } } });
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['popover-confirm'], iconClass: function () { var filename = this.get('filename'), regex, match, extension; if (filename) { regex = /\.([0-9a-z]+)$/i; match = filename.match(/\.([0-9a-z]+)$/i); extension = match && match[1]; if (extension) { return 'glyphicon-' + extension.toLowerCase(); } } }.property('filename'), isShowingDidChange: function () { if (!!this.get('isShowing')) { this.show(); } else { this.hide(); } }.observes('isShowing'), didInsertElement: function () { this._super(); this.$().hide(); }, // Uber hacky way to make Bootstrap 'popover' plugin work with Ember metamorph show: function () { // Delay until related properties are computed Ember.run.next(this, function () { var html = this.$().html(); // Content needs to be visible, // so that popover position is calculated properly. this.$().show(); this.$().popover({ html: true, content: html, placement: 'top' }); this.$().popover('show'); this.$().hide(); }); }, hide: function () { this.$().popover('destroy'); }, actions: { confirm: function () { this.hide(); this.sendAction('confirm'); }, cancel: function() { this.hide(); this.sendAction('cancel'); } } });
Fix generating icon name for files without extension
Fix generating icon name for files without extension
JavaScript
mit
cowbell/sharedrop,umeshjakhar/sharedrop,cowbell/sharedrop,rogervaas/sharedrop,umeshjakhar/sharedrop,rogervaas/sharedrop
--- +++ @@ -5,12 +5,16 @@ iconClass: function () { var filename = this.get('filename'), - regex, extension; + regex, match, extension; if (filename) { regex = /\.([0-9a-z]+)$/i; - extension = filename.match(/\.([0-9a-z]+)$/i)[1]; - if (extension) { return 'glyphicon-' + extension.toLowerCase(); } + match = filename.match(/\.([0-9a-z]+)$/i); + extension = match && match[1]; + + if (extension) { + return 'glyphicon-' + extension.toLowerCase(); + } } }.property('filename'),
c118153f2f48a271cb8d4859e5c65e22cd59ee5f
app/components/repos-list-item.js
app/components/repos-list-item.js
import Ember from 'ember'; import Polling from 'travis/mixins/polling'; import { colorForState } from 'travis/utils/helpers'; export default Ember.Component.extend(Polling, { routing: Ember.inject.service('-routing'), tagName: 'li', pollModels: 'repo', classNames: ['repo'], classNameBindings: ['selected'], selected: function() { return this.get('repo') === this.get('selectedRepo'); }.property('selectedRepo'), color: function() { return colorForState(this.get('repo.lastBuildState')); }.property('repo.lastBuildState'), scrollTop: function() { if (window.scrollY > 0) { return $('html, body').animate({ scrollTop: 0 }, 200); } }, click() { this.scrollTop(); return this.get('routing').transitionTo('repo', this.get('repo.slug').split('/')); } });
import Ember from 'ember'; import Polling from 'travis/mixins/polling'; import { colorForState } from 'travis/utils/helpers'; export default Ember.Component.extend(Polling, { routing: Ember.inject.service('-routing'), tagName: 'li', pollModels: 'repo', classNames: ['repo'], classNameBindings: ['selected'], selected: function() { return this.get('repo') === this.get('selectedRepo'); }.property('selectedRepo'), color: function() { return colorForState(this.get('repo.lastBuildState')); }.property('repo.lastBuildState'), scrollTop: function() { if (window.scrollY > 0) { return $('html, body').animate({ scrollTop: 0 }, 200); } } });
Remove click handler overriding default link behavior
Remove click handler overriding default link behavior An [issue](https://github.com/travis-ci/travis-ci/issues/5181) was reported in which the repository sidebar links were not functioning properly. I've tracked it down to the fact that a click handler was registered and automatically performing a redirect to the repo route. This breaks CMD+Click behavior (as the click handler was still called and navigating when the user did not expect it, as well as navigated to a link that the user did not intend to visit. This commit simply removes that click handler. I checked the previous coffee version of the file to gain more context on why it was initially added, but unfortunately, it was simply added when the original component was created, so I'm not sure what its use was.
JavaScript
mit
fauxton/travis-web,fotinakis/travis-web,travis-ci/travis-web,travis-ci/travis-web,travis-ci/travis-web,travis-ci/travis-web,fotinakis/travis-web,fauxton/travis-web,fauxton/travis-web,fauxton/travis-web,fotinakis/travis-web,fotinakis/travis-web
--- +++ @@ -23,10 +23,5 @@ scrollTop: 0 }, 200); } - }, - - click() { - this.scrollTop(); - return this.get('routing').transitionTo('repo', this.get('repo.slug').split('/')); } });
8aa9ed0a01065affb26bd069fc4afbdcfd9a7cf3
tasks/appium.js
tasks/appium.js
/* * grunt-appium * https://github.com/hungrydavid/grunt-appium * * Copyright (c) 2015 David Adams * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('appium', 'Grunt plugin for running appium', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({}); var appiumPath = require.resolve('appium'); var spawn = require('child_process').spawn; var child = spawn('node', [appiumPath], function (err) { console.log(err); }); process.on('exit', function(data) { console.log('exit'); child.kill("SIGTERM"); }); }); };
/* * grunt-appium * https://github.com/hungrydavid/grunt-appium * * Copyright (c) 2015 David Adams * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('appium', 'Grunt plugin for running appium', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({}); var appiumPath = require.resolve('appium'); var spawn = require('child_process').spawn; var done = this.async(); var child = spawn('node', [appiumPath], function (err) { console.log(err); }); process.on('exit', function(data) { done(); child.kill("SIGTERM"); }); }); };
Make task async and only quit once process exits
Make task async and only quit once process exits
JavaScript
mit
hungrydavid/grunt-appium
--- +++ @@ -18,13 +18,14 @@ var options = this.options({}); var appiumPath = require.resolve('appium'); var spawn = require('child_process').spawn; + var done = this.async(); var child = spawn('node', [appiumPath], function (err) { console.log(err); }); process.on('exit', function(data) { - console.log('exit'); + done(); child.kill("SIGTERM"); }); });
8920390d8a84fdaf0d887a7fccd023ce0855e4bb
components/app/common/Browser.js
components/app/common/Browser.js
import React from 'react'; function Browser() { return ( <div className="c-browser"> <h3>Browser not supported</h3> <p>The browser you are using is out-of-date and not supported by our site.</p> <h4>For the most secure and best experience, we recommend these browsers.</h4> <ul> <li><a href="https://www.google.com/chrome/" rel="noreferrer" target="__BLANK">Latest chrome</a></li> <li><a href="https://www.mozilla.org/en-US/firefox/new/" rel="noreferrer" target="__BLANK">Latest firefox</a></li> </ul> </div> ); } export default Browser;
import React from 'react'; function Browser() { return ( <div className="c-browser"> <h3>Browser not supported</h3> <p>The browser you are using is out-of-date and not is supported by our site.</p> <h4>For the most secure and best experience, we recommend these browsers.</h4> <ul> <li><a href="https://www.google.com/chrome/" rel="noreferrer" target="__BLANK">Latest chrome</a></li> <li><a href="https://www.mozilla.org/en-US/firefox/new/" rel="noreferrer" target="__BLANK">Latest firefox</a></li> </ul> </div> ); } export default Browser;
Fix spelling error in browser change modal
Fix spelling error in browser change modal
JavaScript
mit
resource-watch/resource-watch,resource-watch/resource-watch,resource-watch/resource-watch,resource-watch/resource-watch
--- +++ @@ -4,7 +4,7 @@ return ( <div className="c-browser"> <h3>Browser not supported</h3> - <p>The browser you are using is out-of-date and not supported by our site.</p> + <p>The browser you are using is out-of-date and not is supported by our site.</p> <h4>For the most secure and best experience, we recommend these browsers.</h4>
308f844589596950fc43b2699bdd33d79f67bcb4
postinstall.js
postinstall.js
'use strict'; var fs = require('fs'); var cp = require('child_process'); var assert = require('assert'); var partialDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2" }; var fullDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2", "try-thread-sleep": "^1.0.0" }; var REQUIRES_UPDATE = false; var pkg = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')); if (cp.spawnSync || __dirname.indexOf('node_modules') === -1) { try { assert.deepEqual(pkg.dependencies, partialDependencies); } catch (ex) { pkg.dependencies = partialDependencies; REQUIRES_UPDATE = true; } } else { try { assert.deepEqual(pkg.dependencies, fullDependencies); } catch (ex) { pkg.dependencies = fullDependencies; REQUIRES_UPDATE = true; } } if (REQUIRES_UPDATE && __dirname.indexOf('node_modules') !== -1) { fs.writeFileSync(__dirname + '/package.json', JSON.stringify(pkg, null, ' ')); cp.exec((process.env.npm_execpath || 'npm') + ' install --production', { cwd: __dirname }, function (err) { if (err) { throw err; } }); }
'use strict'; var fs = require('fs'); var cp = require('child_process'); var assert = require('assert'); var partialDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2" }; var fullDependencies = { "concat-stream": "^1.4.7", "os-shim": "^0.1.2", "try-thread-sleep": "^1.0.0" }; var REQUIRES_UPDATE = false; var pkg = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')); if (cp.spawnSync || __dirname.indexOf('node_modules') === -1) { try { assert.deepEqual(pkg.dependencies, partialDependencies); } catch (ex) { pkg.dependencies = partialDependencies; REQUIRES_UPDATE = true; } } else { try { assert.deepEqual(pkg.dependencies, fullDependencies); } catch (ex) { pkg.dependencies = fullDependencies; REQUIRES_UPDATE = true; } } if (REQUIRES_UPDATE && __dirname.indexOf('node_modules') !== -1) { fs.writeFileSync(__dirname + '/package.json', JSON.stringify(pkg, null, ' ')); cp.exec((('"' + process.env.npm_execpath + '"') || 'npm') + ' install --production', { cwd: __dirname }, function (err) { if (err) { throw err; } }); }
Add quotes around the npm_execpath
Add quotes around the npm_execpath [fixes #19]
JavaScript
mit
ForbesLindesay/spawn-sync,terabyte/spawn-sync,bcoe/spawn-sync,tmagiera/spawn-sync
--- +++ @@ -33,7 +33,7 @@ } if (REQUIRES_UPDATE && __dirname.indexOf('node_modules') !== -1) { fs.writeFileSync(__dirname + '/package.json', JSON.stringify(pkg, null, ' ')); - cp.exec((process.env.npm_execpath || 'npm') + ' install --production', { + cp.exec((('"' + process.env.npm_execpath + '"') || 'npm') + ' install --production', { cwd: __dirname }, function (err) { if (err) {
48e5053047d6b48c40a55a69b9f945658b4ef438
lib/Middleware.js
lib/Middleware.js
export default class Middleware { /** * Constructor */ constructor(key, value) { key = key.toLowerCase(); // In case of simple middleware if (key == "middleware") { return this.simpleMiddleware(value); } if (OPTIONS[key]) { return OPTIONS[key].init(value); } } /** * Get middleware from middleware options * @param {array} middlewares [an array of middleware location in api/middleware] * @return {array} middleware function */ simpleMiddleware(middlewares) { return middlewares .map( middle => middle.split('.') ) .map( middle => { if (middle.length == 2) return require("../api/middleware/" + middle[0])[middle[1]]; return require("../api/middleware/index")[middle[0]]; }); } }
export default class Middleware { /** * Constructor */ constructor(key, value) { key = key.toLowerCase(); // In case of simple middleware if (key == "middleware") { return this.simpleMiddleware(value); } if (OPTIONS[key]) { return { key: key, value: OPTIONS[key].init(value) }; } } /** * Get middleware from middleware options * @param {array} middlewares [an array of middleware location in api/middleware] * @return {array} middleware function */ simpleMiddleware(middlewares) { return middlewares .map( middle => middle.split('.') ) .map( middle => { if (middle.length == 2) return require("../api/middleware/" + middle[0])[middle[1]]; return require("../api/middleware/index")[middle[0]]; }); } }
Add the key and value in option
Add the key and value in option
JavaScript
mit
ArthurMialon/StarterApiNodejs
--- +++ @@ -12,7 +12,10 @@ } if (OPTIONS[key]) { - return OPTIONS[key].init(value); + return { + key: key, + value: OPTIONS[key].init(value) + }; } }
46f8795db8215e2a470b54cfe1e94ebb1888460e
closure/testing/test/arithmetic_es6module_test.js
closure/testing/test/arithmetic_es6module_test.js
// Copyright 2016 The Closure Rules Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'goog:goog.testing.asserts'; import 'goog:goog.testing.jsunit'; import { add } from '/closure/testing/test/arithmetic_es6module.js'; function testAdd() { assertEquals(4, add(2, 2)); }
// Copyright 2016 The Closure Rules Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.require('goog.testing.asserts'); goog.require('goog.testing.jsunit'); import { add } from '/closure/testing/test/arithmetic_es6module.js'; function testAdd() { assertEquals(4, add(2, 2)); }
Remove use of the import 'goog:...' pattern
Remove use of the import 'goog:...' pattern Support for this is soon to be removed. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=177366930
JavaScript
apache-2.0
jart/rules_closure,jart/rules_closure,jart/rules_closure,gramic/rules_closure,gramic/rules_closure,bazelbuild/rules_closure,gramic/rules_closure,gramic/rules_closure,jart/rules_closure,jart/rules_closure,bazelbuild/rules_closure,bazelbuild/rules_closure,bazelbuild/rules_closure
--- +++ @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -import 'goog:goog.testing.asserts'; -import 'goog:goog.testing.jsunit'; +goog.require('goog.testing.asserts'); +goog.require('goog.testing.jsunit'); import { add } from '/closure/testing/test/arithmetic_es6module.js';
ab7e76c25376e82ca3559b6a088ea213ae227a6e
src/resources/basefield.js
src/resources/basefield.js
export class Basefield { id = ''; label = ''; columns = 8; index = undefined; parent = undefined; init(id = '', {label = '', columns = 8, parent, index} = {}) { this.id = id; this.label = label; this.columns = columns; this.index = index; this.parent = parent; return this; } bind() { if (this.label.length === 0) { this.label = this.id.substr(0, 1).toUpperCase() + this.id.substr(1); } } delete() { if (this.parent && this.index) { this.parent.deleteChild(this.index); } } getValue() { return undefined; } }
export class Basefield { id = ''; label = ''; columns = 8; index = undefined; parent = undefined; init(id = '', {label = '', columns = 8, parent, index} = {}) { this.id = id; this.label = label; this.columns = columns; this.index = index; this.parent = parent; return this; } bind() { if (this.label.length === 0) { this.label = this.id.substr(0, 1).toUpperCase() + this.id.substr(1); } } delete() { if (this.parent && typeof this.index === 'number') { this.parent.deleteChild(this.index); } } getValue() { return undefined; } }
Fix not being able to delete first item of list
Fix not being able to delete first item of list
JavaScript
mit
apinf/openapi-designer,apinf/open-api-designer,apinf/open-api-designer,apinf/openapi-designer
--- +++ @@ -21,7 +21,7 @@ } delete() { - if (this.parent && this.index) { + if (this.parent && typeof this.index === 'number') { this.parent.deleteChild(this.index); } }
204c213882920d4666fb962d8c3bb39ce2fcf988
lib/apply-data.js
lib/apply-data.js
import { handleSuccess, handleFailure } from './assert-promise'; function applyData(object, data) { return new Ember.RSVP.Promise(function(resolve, reject) { if (typeof data === 'function') { var newObject = data.call(object, object); if (!newObject.then) { return resolve(newObject); } else { return newObject .catch(handleFailure('Failed to assemble data for model')) .then(resolve); } } var key, val, promiseList = []; for (key in data) { if (data.hasOwnProperty(key)) { val = data[key]; if (typeof val === 'function') { val = val.call(object, object.get(key)); if (val.then) { val = val.catch(handleFailure('Failed to apply attribute: ' + key)); promiseList.push(val); continue; } } if (typeof val !== 'undefined') { object.set(key, val); } } } Ember.RSVP.Promise.all(promiseList).then(function() { resolve(object); }); }); } export default applyData; export { applyData };
import { handleSuccess, handleFailure } from './assert-promise'; function applyData(object, data) { return new Ember.RSVP.Promise(function(resolve, reject) { if (typeof data === 'function') { var newObject = data.call(object, object); if (!newObject.then) { return resolve(newObject); } else { return newObject .catch(handleFailure('Failed to assemble data for model')) .then(resolve); } } var key, val, related, promiseList = []; for (key in data) { if (data.hasOwnProperty(key)) { val = data[key]; if (typeof val === 'function') { val = val.call(object, object.get(key)); if (val && val.then) { val = val.catch(handleFailure('Failed to apply attribute: ' + key)); promiseList.push(val); continue; } } else { related = (object.constructor || {}).typeForRelationship && object.constructor.typeForRelationship(key); if (related && val.id && (val.fake || val.local)) { val = object.store.createRecord(related.typeKey, {id: val.id}); } } if (typeof val !== 'undefined') { object.set(key, val); } } } Ember.RSVP.Promise.all(promiseList).then(function() { resolve(object); }); }); } export default applyData; export { applyData };
Allow `{local: true, id: 123}` specification for relationships (inside `data` hash)
Allow `{local: true, id: 123}` specification for relationships (inside `data` hash)
JavaScript
mit
runtrizapps/ember-testing-grate
--- +++ @@ -14,7 +14,7 @@ } } - var key, val, promiseList = []; + var key, val, related, promiseList = []; for (key in data) { if (data.hasOwnProperty(key)) { @@ -23,10 +23,15 @@ if (typeof val === 'function') { val = val.call(object, object.get(key)); - if (val.then) { + if (val && val.then) { val = val.catch(handleFailure('Failed to apply attribute: ' + key)); promiseList.push(val); continue; + } + } else { + related = (object.constructor || {}).typeForRelationship && object.constructor.typeForRelationship(key); + if (related && val.id && (val.fake || val.local)) { + val = object.store.createRecord(related.typeKey, {id: val.id}); } }
8dcb43a4272563971cd22f32106731519451f83a
desktop/app/components/tasks/directive.js
desktop/app/components/tasks/directive.js
angular.module('MainApp') .directive('uaf', () => { // uaf = Update after find return (scope, el, attrs) => { scope.$watch('tasks', (newVal) => { el[0].children[0].children[0].innerHTML = newVal[attrs.uaf]; }, true); }; });
angular.module('MainApp') .directive('uaf', () => // uaf = Update after find (scope, el, attrs) => { scope.$watch('tasks', (newVal) => { el[0].children[0].children[0].innerHTML = newVal[attrs.uaf]; }, true); } );
Fix eslint errors - 6
Fix eslint errors - 6
JavaScript
mit
mkermani144/wanna,mkermani144/wanna
--- +++ @@ -1,8 +1,8 @@ angular.module('MainApp') - .directive('uaf', () => { // uaf = Update after find - return (scope, el, attrs) => { + .directive('uaf', () => // uaf = Update after find + (scope, el, attrs) => { scope.$watch('tasks', (newVal) => { el[0].children[0].children[0].innerHTML = newVal[attrs.uaf]; }, true); - }; - }); + } + );
d90c82cea8abeace95e5b97cc0e51debe0b63225
packages/lesswrong/lib/collections/tagRels/views.js
packages/lesswrong/lib/collections/tagRels/views.js
import { TagRels } from './collection.js'; import { ensureIndex } from '../../collectionUtils'; TagRels.addView('postsWithTag', terms => { return { selector: { tagId: terms.tagId, baseScore: {$gt: 0}, }, } }); TagRels.addView('tagsOnPost', terms => { return { selector: { postId: terms.postId, baseScore: {$gt: 0}, }, } }); ensureIndex(TagRels, {postId:1}); ensureIndex(TagRels, {tagId:1});
import { TagRels } from './collection.js'; import { ensureIndex } from '../../collectionUtils'; TagRels.addView('postsWithTag', terms => { return { selector: { tagId: terms.tagId, baseScore: {$gt: 0}, }, sort: {baseScore: -1}, } }); TagRels.addView('tagsOnPost', terms => { return { selector: { postId: terms.postId, baseScore: {$gt: 0}, }, sort: {baseScore: -1}, } }); ensureIndex(TagRels, {postId:1}); ensureIndex(TagRels, {tagId:1});
Sort tags by descending relevance
Sort tags by descending relevance
JavaScript
mit
Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2
--- +++ @@ -7,6 +7,7 @@ tagId: terms.tagId, baseScore: {$gt: 0}, }, + sort: {baseScore: -1}, } }); @@ -16,6 +17,7 @@ postId: terms.postId, baseScore: {$gt: 0}, }, + sort: {baseScore: -1}, } });
df3fd41acf43fe5b0401ecb60ae090541c575d59
lib/mainWindow.js
lib/mainWindow.js
import { screen } from 'electron'; /** * Create main window's settings. * @param {Object} rawopts - Configuration options for main window. * @return {Object} The main window configuration. */ function mainWindow(rawopts) { const { width, height } = screen.getPrimaryDisplay().workAreaSize; const opts = Object.assign({ width: width - 200, height: height - 200, }, mainWindow._default, rawopts); return opts; } mainWindow._default = { center: true, autoHideMenuBar: true, }; export default mainWindow;
import { screen } from 'electron'; /** * Create main window's settings. * @param {Object} rawopts - Configuration options for main window. * @return {Object} The main window configuration. */ function mainWindow(rawopts) { const { width, height } = screen.getPrimaryDisplay().workAreaSize; const opts = Object.assign({ width: width - 200, height: height - 200, }, mainWindow._default, rawopts); return opts; } mainWindow._default = { center: true, autoHideMenuBar: true, show: false, }; export default mainWindow;
Hide main window until ready
Hide main window until ready
JavaScript
mit
JamenMarz/cluster,JamenMarz/vint
--- +++ @@ -17,6 +17,7 @@ mainWindow._default = { center: true, autoHideMenuBar: true, + show: false, };
c32995e50fc10e50e6808d5f5df51dd203c8a613
src/utils/getUsers.js
src/utils/getUsers.js
import axios from 'axios'; function getUsers() { return axios({ url: '/api/users', timeout: 20000, method: 'get', responseType: 'json' }) .then(function (res) { return res.data; }) } export default getUsers;
import axios from 'axios'; function getUsers() { return axios({ url: '/api/users', timeout: 20000, method: 'get', responseType: 'json' }) .then(function (res) { return res.data; }) } export default getUsers;
Set up getUser axios to get all users
Set up getUser axios to get all users
JavaScript
mit
Keitarokido/tiles,Keitarokido/tiles
8941d15ae95988becf61ba2d05a4eca140dd2486
test/of_test.js
test/of_test.js
import check from './support/check'; describe('of operator', () => { it('turns into an `in` operator', () => { check(` a of b `, ` a in b; `); }); it('works in an expression context', () => { check(` a(b, c.d of e) `, ` a(b, c.d in e); `); }); it('works with negated `of`', () => { check(` a not of b `, ` !(a in b); `); }); });
import check from './support/check'; describe('of operator', () => { it('turns into an `in` operator', () => { check(` a of b `, ` a in b; `); }); it('works in an expression context', () => { check(` a(b, c.d of e) `, ` a(b, c.d in e); `); }); it('works with negated `of`', () => { check(` a not of b `, ` !(a in b); `); }); it('can be double negated', () => { check(` unless a not of b c `, ` if (a in b) { c; } `); }); });
Add another test for double negation of `of`.
Add another test for double negation of `of`.
JavaScript
mit
eventualbuddha/decaffeinate,alangpierce/decaffeinate,decaffeinate/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate,decaffeinate/decaffeinate,alangpierce/decaffeinate
--- +++ @@ -24,4 +24,15 @@ !(a in b); `); }); + + it('can be double negated', () => { + check(` + unless a not of b + c + `, ` + if (a in b) { + c; + } + `); + }); });
ebf95a31b0ba193817a28ec16468ef7809ec6953
cronjobs.js
cronjobs.js
var fs = require('fs'); var cronJob = require('cron').CronJob; var config = require('./config'); var data = require('./data'); function init() { writeJSON(); } module.exports = init; function writeJSON() { write(); new cronJob('*/5 * * * *', write, null, true); function write() { data.checks(config.pingdom, 5, function(err, data) { fs.writeFile('./public/data.json', JSON.stringify(data), function(err) { if(err) return console.error(err); console.log('Wrote data.json'); }); }); } }
var fs = require('fs'); var cronJob = require('cron').CronJob; var config = require('./config'); var data = require('./data'); function init() { writeJSON(); } module.exports = init; function writeJSON() { write(); new cronJob('*/5 * * * *', write, null, true); function write() { data.checks(config.pingdom, 50, function(err, data) { fs.writeFile('./public/data.json', JSON.stringify(data), function(err) { if(err) return console.error(err); console.log('Wrote data.json'); }); }); } }
Increase the amount of data points
Increase the amount of data points
JavaScript
mit
cdnperf/cdnperf,bebraw/cdnperf,bebraw/cdnperf,cdnperf/cdnperf
--- +++ @@ -17,7 +17,7 @@ new cronJob('*/5 * * * *', write, null, true); function write() { - data.checks(config.pingdom, 5, function(err, data) { + data.checks(config.pingdom, 50, function(err, data) { fs.writeFile('./public/data.json', JSON.stringify(data), function(err) { if(err) return console.error(err);
5016ab3b206d1a53fce943d07b0402df7a145aed
server/db/controllers/getMatchesGivenSelfAndOffset.js
server/db/controllers/getMatchesGivenSelfAndOffset.js
const db = require('../db.js'); module.exports = (self, offSet) => { const queryStr = `SELECT teach.teach_id FROM ( ( SELECT users_languages_levels.user AS teach_id FROM users_languages_levels INNER JOIN languages_levels ON users_languages_levels.languages_levels = languages_levels.id INNER JOIN languages ON languages_levels.language = languages.id INNER JOIN levels ON languages_levels.level = levels.id WHERE languages.name IN (${self.willLearn.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') ) AS teach INNER JOIN ( SELECT users_languages_levels.user AS learn_id FROM users_languages_levels INNER JOIN languages_levels ON users_languages_levels.languages_levels = languages_levels.id INNER JOIN languages ON languages_levels.language = languages.id INNER JOIN levels ON languages_levels.level = levels.id WHERE languages.name IN (${self.canTeach.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') ) AS learn ON teach.teach_id = learn.learn_id ) `; // db.query(); };
const db = require('../db.js'); module.exports = (self, offSet) => { const queryStr = `SELECT teach.teach_id FROM ( ( SELECT users_languages_levels.user AS teach_id FROM users_languages_levels INNER JOIN languages_levels ON users_languages_levels.languages_levels = languages_levels.id INNER JOIN languages ON languages_levels.language = languages.id INNER JOIN levels ON languages_levels.level = levels.id WHERE languages.name IN (${self.willLearn.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') ) AS teach INNER JOIN ( SELECT users_languages_levels.user AS learn_id FROM users_languages_levels INNER JOIN languages_levels ON users_languages_levels.languages_levels = languages_levels.id INNER JOIN languages ON languages_levels.language = languages.id INNER JOIN levels ON languages_levels.level = levels.id WHERE languages.name IN (${self.canTeach.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') ) AS learn ON teach.teach_id = learn.learn_id ) LIMIT 20 OFFSET ${offSet} `; // db.query(); };
Add limit and offset in query string
Add limit and offset in query string
JavaScript
mit
VictoriousResistance/iDioma,VictoriousResistance/iDioma
--- +++ @@ -4,27 +4,29 @@ const queryStr = `SELECT teach.teach_id FROM ( ( SELECT users_languages_levels.user AS teach_id FROM users_languages_levels - INNER JOIN languages_levels - ON users_languages_levels.languages_levels = languages_levels.id - INNER JOIN languages - ON languages_levels.language = languages.id - INNER JOIN levels - ON languages_levels.level = levels.id - WHERE languages.name IN (${self.willLearn.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') - ) AS teach - INNER JOIN - ( + INNER JOIN languages_levels + ON users_languages_levels.languages_levels = languages_levels.id + INNER JOIN languages + ON languages_levels.language = languages.id + INNER JOIN levels + ON languages_levels.level = levels.id + WHERE languages.name IN (${self.willLearn.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') + ) AS teach + INNER JOIN + ( SELECT users_languages_levels.user AS learn_id FROM users_languages_levels - INNER JOIN languages_levels - ON users_languages_levels.languages_levels = languages_levels.id - INNER JOIN languages - ON languages_levels.language = languages.id - INNER JOIN levels - ON languages_levels.level = levels.id - WHERE languages.name IN (${self.canTeach.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') - ) AS learn - ON teach.teach_id = learn.learn_id - ) + INNER JOIN languages_levels + ON users_languages_levels.languages_levels = languages_levels.id + INNER JOIN languages + ON languages_levels.language = languages.id + INNER JOIN levels + ON languages_levels.level = levels.id + WHERE languages.name IN (${self.canTeach.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native') + ) AS learn + ON teach.teach_id = learn.learn_id + ) + LIMIT 20 + OFFSET ${offSet} `; // db.query(); };
217c40ac2ca61f4a14f41a1a5b3d4f7983910b46
harmless-ransom-note.js
harmless-ransom-note.js
// Harmless Ransom Note /* Rules: Takes two parameters First will be the note we want to write as a string. The second will be the magazine text we have available to make the note out of as a string The purpose of the algorithm is to see if we have enough words in the magazine text to write our note If yes, return true If no, return false NOTE: If one word is used 2 (or more) times in the note, but only seen once (or less) in magazine text then it fails. */
// Harmless Ransom Note /* Rules: Takes two parameters First will be the note we want to write as a string. The second will be the magazine text we have available to make the note out of as a string The purpose of the algorithm is to see if we have enough words in the magazine text to write our note If yes, return true If no, return false NOTE: If one word is used 2 (or more) times in the note, but only seen once (or less) in magazine text then it fails. */ /* PSEUDOCODE 1) Turn the note into an array of words 2) Turn the mag into an array of words 3) Organize each new array alphabetically 4) Look at the first letter of each word in note array, and insert that letter into a reference array 5) compare the reference array with each first letter of each word in mag array. IF word starts with any letter inside note array, keep the word ELSE remove the word 6) Compare the actual words! IF there is a match, cool. Make note of that and move on to the next word ELSE IF there isn't a match, then that's enough already for you to return FALSE */ function harmlessNote(note, mag){ }
Add pseudocode in notes, begin skeleton of function
Add pseudocode in notes, begin skeleton of function
JavaScript
mit
benjaminhyw/javascript_algorithms
--- +++ @@ -10,3 +10,21 @@ NOTE: If one word is used 2 (or more) times in the note, but only seen once (or less) in magazine text then it fails. */ + +/* PSEUDOCODE + + 1) Turn the note into an array of words + 2) Turn the mag into an array of words + 3) Organize each new array alphabetically + 4) Look at the first letter of each word in note array, and insert that letter into a reference array + 5) compare the reference array with each first letter of each word in mag array. + IF word starts with any letter inside note array, keep the word + ELSE remove the word + 6) Compare the actual words! + IF there is a match, cool. Make note of that and move on to the next word + ELSE IF there isn't a match, then that's enough already for you to return FALSE +*/ + +function harmlessNote(note, mag){ + +}
3a4bba37b5f2e46fc8484a9ad1a5142bf9adc183
src/templates/blog-post.js
src/templates/blog-post.js
import React from "react"; import { graphql, Link } from "gatsby"; import Layout from "../app/layout"; import "./blog-post.scss"; export const BLOG_POST_QUERY = graphql` query BlogPostTemplate($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { id excerpt html fields { slug } frontmatter { title date(formatString: "MMMM DD, YYYY") } } } `; function BlogPostTemplate(props) { const post = props.data.markdownRemark; return ( <Layout> <main> <article className="BlogPost"> <div className="l-wide"> <div className="BlogPost-metadata"> <h1 className="BlogPost-title"> <Link to={post.fields.slug}>{post.frontmatter.title}</Link> </h1> <time className="BlogPost-date">{post.frontmatter.date}</time> </div> </div> <div className="l-narrow"> <div className="BlogPost-content" dangerouslySetInnerHTML={{ __html: post.html }} /> </div> </article> </main> </Layout> ); } export default BlogPostTemplate;
import React from "react"; import { graphql, Link } from "gatsby"; import Layout from "../app/layout"; import "prismjs/themes/prism-solarizedlight.css"; import "./blog-post.scss"; export const BLOG_POST_QUERY = graphql` query BlogPostTemplate($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { id excerpt html fields { slug } frontmatter { title date(formatString: "MMMM DD, YYYY") } } } `; function BlogPostTemplate(props) { const post = props.data.markdownRemark; return ( <Layout> <main> <article className="BlogPost"> <div className="l-wide"> <div className="BlogPost-metadata"> <h1 className="BlogPost-title"> <Link to={post.fields.slug}>{post.frontmatter.title}</Link> </h1> <time className="BlogPost-date">{post.frontmatter.date}</time> </div> </div> <div className="l-narrow"> <div className="BlogPost-content" dangerouslySetInnerHTML={{ __html: post.html }} /> </div> </article> </main> </Layout> ); } export default BlogPostTemplate;
Add styles for code blocks
Add styles for code blocks
JavaScript
mit
yanglinz/personal-site,yanglinz/personal-site
--- +++ @@ -3,6 +3,7 @@ import Layout from "../app/layout"; +import "prismjs/themes/prism-solarizedlight.css"; import "./blog-post.scss"; export const BLOG_POST_QUERY = graphql`
422c9f3f7f937e06179c9aedabda1bedb61a1e2c
js/views/Value.js
js/views/Value.js
jsio('from shared.javascript import Class, bind') jsio('import ui.Component') exports = Class(ui.Component, function(supr){ this._domTag = 'span' this._className = 'Value' this.init = function(jsArgs, viewArgs) { supr(this, 'init') this._itemIds = jsArgs[0] this._property = viewArgs[0] } this._createContent = function() { this.setDependant(this._itemIds, this._property) } this.setDependant = function(itemIds, property) { if (this._item) { logger.warn("TODO unsubscribe from old item") } this._propertyChain = property.split('.') var itemId = (typeof itemIds == 'string' ? itemIds : itemIds.getId ? itemIds.getId() : itemIds[this._propertyChain.shift()]) this._item = fin.getItem(itemId) this._item.addDependant(this._propertyChain, bind(this, '_onItemMutation')) } this._onItemMutation = function(mutation, newValue) { this.setValue(newValue) } this.setValue = function(value) { if (typeof value == 'undefined') { return } value = value.replace(/\n/g, '<br />') value = value.replace(/ $/, '&nbsp;') this._element.innerHTML = value } })
jsio('from shared.javascript import Class, bind') jsio('import ui.Component') exports = Class(ui.Component, function(supr){ this._domTag = 'span' this._className = 'Value' this.init = function(jsArgs, viewArgs) { supr(this, 'init') this._itemIds = jsArgs[0] this._property = viewArgs[0] } this._createContent = function() { this.setDependant(this._itemIds, this._property) } this.setDependant = function(itemIds, property) { if (this._item) { logger.warn("TODO unsubscribe from old item") } this._propertyChain = property.split('.') var itemId = (typeof itemIds == 'string' ? itemIds : itemIds.getId ? itemIds.getId() : itemIds[this._propertyChain.shift()]) this._item = fin.getItem(itemId) this._item.addDependant(this._propertyChain, bind(this, '_onItemMutation')) } this._onItemMutation = function(mutation, newValue) { this.setValue(newValue) } this.setValue = function(value) { if (typeof value == 'undefined') { return } if (typeof value == 'string') { value = value.replace(/\n/g, '<br />') value = value.replace(/ $/, '&nbsp;') } this._element.innerHTML = value } })
Fix linebreaks only for string values
Fix linebreaks only for string values
JavaScript
mit
marcuswestin/Focus
--- +++ @@ -33,8 +33,10 @@ this.setValue = function(value) { if (typeof value == 'undefined') { return } - value = value.replace(/\n/g, '<br />') - value = value.replace(/ $/, '&nbsp;') + if (typeof value == 'string') { + value = value.replace(/\n/g, '<br />') + value = value.replace(/ $/, '&nbsp;') + } this._element.innerHTML = value } })
0e34b6069f2f4e70620eeb40fa44f19e1a93f5e0
datasets.js
datasets.js
/** * Different datasets the tool can use * * The first-level keys are country names, in English, * as they will appear in the app * * The second level names are database identifiers. * These ids are used in the url, so should be as short as possible * * The name of a database will be visible in the app, and may be localised * The url can be a relative url, or an absolute one (starting with http:) * Relative URLs make testing on a local server easier. */ var datasets = { "Belgium": { "BE_dl": { "url": "datasets/belgium-haltes-de-lijn/", "name": "Haltes De Lijn", }, }, "Italy": { "IT_fuel": { "url": "datasets/Italia-stazioni-di-servizo/", "name": "Stazioni di servizo", } }, /* "Norway" : { "NO_kg": { "url": "http://obtitus.github.io/barnehagefakta_osm_data/POI-Importer-data/dataset.json", "name": "Barnehagefakta fra Utdanningsdirektoratet", } }*/ };
/** * Different datasets the tool can use * * The first-level keys are country names, in English, * as they will appear in the app * * The second level names are database identifiers. * These ids are used in the url, so should be as short as possible * * The name of a database will be visible in the app, and may be localised * The url can be a relative url, or an absolute one (starting with http:) * Relative URLs make testing on a local server easier. */ var datasets = { "Belgium": { "BE_dl": { "url": "datasets/belgium-haltes-de-lijn/", "name": "Haltes De Lijn", }, }, "Italy": { "IT_fuel": { "url": "datasets/Italia-stazioni-di-servizo/", "name": "Stazioni di servizo", } }, "Norway" : { "NO_kg": { "url": "datasets/norge-barnehagefakta/", "name": "Barnehagefakta", } } };
Enable the Norwegian kindergartens again (not yet visible due to lack of data in the right repo)
Enable the Norwegian kindergartens again (not yet visible due to lack of data in the right repo)
JavaScript
bsd-3-clause
POI-Importer/POI-Importer.github.io,POI-Importer/POI-Importer.github.io
--- +++ @@ -27,12 +27,12 @@ "name": "Stazioni di servizo", } }, -/* "Norway" : + "Norway" : { "NO_kg": { - "url": "http://obtitus.github.io/barnehagefakta_osm_data/POI-Importer-data/dataset.json", - "name": "Barnehagefakta fra Utdanningsdirektoratet", + "url": "datasets/norge-barnehagefakta/", + "name": "Barnehagefakta", } - }*/ + } };
050a474b6f5e000584bf5a1a8f41e3d9750faf3d
tasks/load-options.js
tasks/load-options.js
/* * grunt-load-options * https://github.com/chriszarate/grunt-load-options * * Copyright (c) 2013 Chris Zarate * Licensed under the MIT license. */ 'use strict'; var requireDirectory = require('require-directory'); module.exports = function(grunt) { grunt.initConfig(requireDirectory(module, './grunt/options')); grunt.loadTasks('./grunt/tasks'); };
/* * grunt-load-options * https://github.com/chriszarate/grunt-load-options * * Copyright (c) 2013 Chris Zarate * Licensed under the MIT license. */ 'use strict'; var requireDirectory = require('require-directory'); module.exports = function(grunt) { // Load config options. var options = requireDirectory(module, './grunt/options'); // Resolve options expressed as functions. Object.keys(options).forEach(function(name) { if(typeof options[name] === 'function') { options[name] = options[name](grunt); } }); grunt.initConfig(options); grunt.loadTasks('./grunt/tasks'); };
Resolve options expressed as functions.
Resolve options expressed as functions.
JavaScript
mit
chriszarate/grunt-load-options
--- +++ @@ -11,7 +11,18 @@ var requireDirectory = require('require-directory'); module.exports = function(grunt) { - grunt.initConfig(requireDirectory(module, './grunt/options')); + + // Load config options. + var options = requireDirectory(module, './grunt/options'); + + // Resolve options expressed as functions. + Object.keys(options).forEach(function(name) { + if(typeof options[name] === 'function') { + options[name] = options[name](grunt); + } + }); + + grunt.initConfig(options); grunt.loadTasks('./grunt/tasks'); + }; -
3fc6e2976b46dfaa6dc6768884f8c7a959c12996
client/shared/services/metaDataService.js
client/shared/services/metaDataService.js
'use strict'; export default class metaDataService { constructor() { this.pageTitle = ''; } getPageTitle() { return this.pageTitle; } setPageTitle(newTitle) { this.pageTitle = newTitle; } }
'use strict'; export default class metaDataService { constructor($location) { this.pageTitle = ''; this.address = `http://${$location.host()}/`; } getPageTitle() { return this.pageTitle; } setPageTitle(newTitle) { this.pageTitle = newTitle; } } metaDataService.$inject = ['$location'];
Add site address to metadata service
Add site address to metadata service
JavaScript
mit
flareair/board_of_shame,flareair/board_of_shame,flareair/board_of_shame
--- +++ @@ -1,8 +1,9 @@ 'use strict'; export default class metaDataService { - constructor() { + constructor($location) { this.pageTitle = ''; + this.address = `http://${$location.host()}/`; } getPageTitle() { @@ -13,3 +14,5 @@ this.pageTitle = newTitle; } } + +metaDataService.$inject = ['$location'];
4c869f1077036ededd6c755a600b9200997f56bb
src/widgets/index.js
src/widgets/index.js
// Lazy-loaded modules are assumed on the hosting domain, // so we override the constant at runtime. // __webpack_public_path__ = process.env.NODE_ENV === "production" // ? "https://example.com" // : "http://localhost:3000"; import { camelCase } from "lodash"; (async () => { // For minority of browers, bring in heavier polyfills. if (!Object.assign || !Array.from || !window.location.origin) { await import("../polyfills"); } // Iterable list of widget scripts const containers = [...document.querySelectorAll("[data-my-widget]")]; for (const container of containers) { const options = [...container.attributes] .filter(({ name }) => /^data-/.test(name)) .reduce((acc, attribute) => { const { name, value } = attribute; const prop = camelCase(name.replace(/^data-(.+$)/, "$1")); return { ...acc, [prop]: value }; }, {}); const { myWidget, ...props } = options; // Attempt to import widget init script, or throw exception const render = await (async () => { try { const imported = await import(`./${myWidget}.js`); // `import`ed code-split modules contain all exports return imported.default; } catch (e) { // Friendly error message for invalid widget names if (e.message.match("Cannot find module")) { throw new Error(`Unknown data-my-widget: ${myWidget}`); } else { throw e; } } })(); render(props, container); } })();
import { camelCase } from "lodash"; (async () => { // For minority of browers, bring in heavier polyfills. if (!Object.assign || !Array.from || !window.location.origin) { await import("../polyfills"); } // Iterable list of widget scripts const containers = [...document.querySelectorAll("[data-my-widget]")]; for (const container of containers) { const options = [...container.attributes] .filter(({ name }) => /^data-/.test(name)) .reduce((acc, attribute) => { const { name, value } = attribute; const prop = camelCase(name.replace(/^data-(.+$)/, "$1")); return { ...acc, [prop]: value }; }, {}); const { myWidget, ...props } = options; // Attempt to import widget init script, or throw exception const render = await (async () => { try { const imported = await import(`./${myWidget}.js`); // `import`ed code-split modules contain all exports return imported.default; } catch (e) { // Friendly error message for invalid widget names if (e.message.match("Cannot find module")) { throw new Error(`Unknown data-my-widget: ${myWidget}`); } else { throw e; } } })(); render(props, container); } })();
Remove __webpack_public_path__ for a "gotcha"
Remove __webpack_public_path__ for a "gotcha"
JavaScript
mit
ericclemmons/performant-3rd-party-widgets,ericclemmons/performant-3rd-party-widgets
--- +++ @@ -1,9 +1,3 @@ -// Lazy-loaded modules are assumed on the hosting domain, -// so we override the constant at runtime. -// __webpack_public_path__ = process.env.NODE_ENV === "production" -// ? "https://example.com" -// : "http://localhost:3000"; - import { camelCase } from "lodash"; (async () => {
765578bfcb878b4fc7668b08ce2fe6fb12721592
helpers/unixToDate.js
helpers/unixToDate.js
module.exports = (function(){ return function unixToDate(unixTime) { console.log(unixTime) var date = new Date(Number(unixTime)); var year = date.getFullYear(); var month; var day; if (date.getMonth().toString().length === 1) { month = "0" + (date.getMonth() + 1).toString(); } else { month = (date.getMonth() + 1).toString(); } if (date.getDate().toString().length === 1) { day = "0" + date.getDay().toString(); } else { day = date.getDate().toString(); } return year + '-' + month + '-' + day; } })();
module.exports = function(unixTime) { var date = new Date(Number(unixTime)) var year = date.getFullYear() var month = constructMonth(date) var day = constructDay(date) return year + '-' + month + '-' + day } function constructMonth(date) { var month = (date.getMonth() + 1).toString() return padFormatting(month) } function constructDay(date) { var day = date.getDate().toString() return padFormatting(day) } function padFormatting(value) { return (value.length === 1) ? '0' + value : value }
Refactor date conversion into smaller, more modular methods
Refactor date conversion into smaller, more modular methods
JavaScript
mit
capsul/capsul-api
--- +++ @@ -1,23 +1,22 @@ -module.exports = (function(){ - return function unixToDate(unixTime) { - console.log(unixTime) - var date = new Date(Number(unixTime)); - var year = date.getFullYear(); - var month; - var day; +module.exports = function(unixTime) { + var date = new Date(Number(unixTime)) + var year = date.getFullYear() + var month = constructMonth(date) + var day = constructDay(date) - if (date.getMonth().toString().length === 1) { - month = "0" + (date.getMonth() + 1).toString(); - } else { - month = (date.getMonth() + 1).toString(); - } - - if (date.getDate().toString().length === 1) { - day = "0" + date.getDay().toString(); - } else { - day = date.getDate().toString(); - } + return year + '-' + month + '-' + day +} - return year + '-' + month + '-' + day; - } -})(); +function constructMonth(date) { + var month = (date.getMonth() + 1).toString() + return padFormatting(month) +} + +function constructDay(date) { + var day = date.getDate().toString() + return padFormatting(day) +} + +function padFormatting(value) { + return (value.length === 1) ? '0' + value : value +}
277eeede63ec0ec591eaa934c2ace2df13592e77
test/special/index.js
test/special/index.js
'use strict'; var _ = require('lodash'); var fs = require('fs'); var hljs = require('../../build'); var jsdom = require('jsdom').jsdom; var utility = require('../utility'); describe('special cases tests', function() { before(function(done) { var filename = utility.buildPath('fixtures', 'index.html'); fs.readFile(filename, 'utf-8', function(err, page) { var blocks; // Allows hljs to use document global.document = jsdom(page); // Setup hljs environment hljs.configure({ tabReplace: ' ' }); hljs.initHighlighting(); // Setup hljs for non-`<pre><code>` tests hljs.configure({ useBR: true }); blocks = document.querySelectorAll('.code'); _.each(blocks, hljs.highlightBlock); done(err); }); }); require('./explicitLanguage'); require('./customMarkup'); require('./languageAlias'); require('./noHighlight'); require('./subLanguages'); require('./buildClassName'); require('./useBr'); });
'use strict'; var _ = require('lodash'); var bluebird = require('bluebird'); var hljs = require('../../build'); var jsdomEnv = bluebird.promisify(require('jsdom').env); var readFile = bluebird.promisify(require('fs').readFile); var utility = require('../utility'); describe('special cases tests', function() { before(function() { var filename = utility.buildPath('fixtures', 'index.html'); return readFile(filename, 'utf-8') .then(page => jsdomEnv(page)) .then(window => { var blocks; // Allows hljs to use document global.document = window.document; // Setup hljs environment hljs.configure({ tabReplace: ' ' }); hljs.initHighlighting(); // Setup hljs for non-`<pre><code>` tests hljs.configure({ useBR: true }); blocks = document.querySelectorAll('.code'); _.each(blocks, hljs.highlightBlock); }); }); require('./explicitLanguage'); require('./customMarkup'); require('./languageAlias'); require('./noHighlight'); require('./subLanguages'); require('./buildClassName'); require('./useBr'); });
Use promises for special case tests
Use promises for special case tests I'm not too sure what is causing tests to fail because locally they pass and on travis `class` is turning into `undefined`.
JavaScript
bsd-3-clause
aurusov/highlight.js,teambition/highlight.js,Sannis/highlight.js,MakeNowJust/highlight.js,carlokok/highlight.js,bluepichu/highlight.js,StanislawSwierc/highlight.js,carlokok/highlight.js,palmin/highlight.js,teambition/highlight.js,carlokok/highlight.js,isagalaev/highlight.js,dbkaplun/highlight.js,tenbits/highlight.js,highlightjs/highlight.js,highlightjs/highlight.js,tenbits/highlight.js,highlightjs/highlight.js,carlokok/highlight.js,aurusov/highlight.js,dbkaplun/highlight.js,sourrust/highlight.js,isagalaev/highlight.js,dbkaplun/highlight.js,MakeNowJust/highlight.js,MakeNowJust/highlight.js,Sannis/highlight.js,Sannis/highlight.js,sourrust/highlight.js,tenbits/highlight.js,palmin/highlight.js,highlightjs/highlight.js,bluepichu/highlight.js,bluepichu/highlight.js,sourrust/highlight.js,aurusov/highlight.js,lead-auth/highlight.js,StanislawSwierc/highlight.js,palmin/highlight.js,teambition/highlight.js
--- +++ @@ -1,33 +1,34 @@ 'use strict'; -var _ = require('lodash'); -var fs = require('fs'); -var hljs = require('../../build'); -var jsdom = require('jsdom').jsdom; -var utility = require('../utility'); +var _ = require('lodash'); +var bluebird = require('bluebird'); +var hljs = require('../../build'); +var jsdomEnv = bluebird.promisify(require('jsdom').env); +var readFile = bluebird.promisify(require('fs').readFile); +var utility = require('../utility'); describe('special cases tests', function() { - before(function(done) { + before(function() { var filename = utility.buildPath('fixtures', 'index.html'); - fs.readFile(filename, 'utf-8', function(err, page) { - var blocks; + return readFile(filename, 'utf-8') + .then(page => jsdomEnv(page)) + .then(window => { + var blocks; - // Allows hljs to use document - global.document = jsdom(page); + // Allows hljs to use document + global.document = window.document; - // Setup hljs environment - hljs.configure({ tabReplace: ' ' }); - hljs.initHighlighting(); + // Setup hljs environment + hljs.configure({ tabReplace: ' ' }); + hljs.initHighlighting(); - // Setup hljs for non-`<pre><code>` tests - hljs.configure({ useBR: true }); + // Setup hljs for non-`<pre><code>` tests + hljs.configure({ useBR: true }); - blocks = document.querySelectorAll('.code'); - _.each(blocks, hljs.highlightBlock); - - done(err); - }); + blocks = document.querySelectorAll('.code'); + _.each(blocks, hljs.highlightBlock); + }); }); require('./explicitLanguage');
97f6eb7ce14fe5baa6533216fa04717e69e7f44b
test/support/index.js
test/support/index.js
var root = null; if (typeof window === 'undefined') { root = global; root.tryc = require('../../'); } else { root = window; root.tryc = require('tryc'); root.__karma__.start = function() { root.__karma__.info({ total: 1 }); root.__karma__.result({ success: true }); root.__karma__.complete(); }; } root.assert = function(expr, msg) { if (expr) return; throw Error(msg || 'Assertion failed'); }; root.test = function(str, fn) { var timeout = setTimeout(function() { throw new Error(str + ' timeout'); }, 1000); fn(function() { clearTimeout(timeout); }); };
var root = null; var completed = null; var tests = []; if (typeof window === 'undefined') { root = global; root.tryc = require('../../'); completed = function(){}; } else { root = window; root.tryc = require('tryc'); root.__karma__.start = function() {}; completed = function() { root.__karma__.info({ total: 1 }); root.__karma__.result({ success: true }); root.__karma__.complete(); }; } root.assert = function(expr, msg) { if (expr) return; throw Error(msg || 'Assertion failed'); }; root.test = function(str, fn) { tests.push({ title: str, fn: fn }); }; setTimeout(function runNextTest() { var test = tests.shift(); if (!test) return completed(); var timeout = setTimeout(function() { throw new Error(test.title + ' timeout'); }, 1000); test.fn(function() { clearTimeout(timeout); runNextTest(); }); }, 1);
Fix issues with the custom test runner
Fix issues with the custom test runner
JavaScript
mit
vesln/tryc
--- +++ @@ -1,12 +1,17 @@ var root = null; +var completed = null; +var tests = []; if (typeof window === 'undefined') { root = global; root.tryc = require('../../'); + completed = function(){}; } else { root = window; root.tryc = require('tryc'); - root.__karma__.start = function() { + root.__karma__.start = function() {}; + + completed = function() { root.__karma__.info({ total: 1 }); root.__karma__.result({ success: true }); root.__karma__.complete(); @@ -19,11 +24,19 @@ }; root.test = function(str, fn) { + tests.push({ title: str, fn: fn }); +}; + +setTimeout(function runNextTest() { + var test = tests.shift(); + if (!test) return completed(); + var timeout = setTimeout(function() { - throw new Error(str + ' timeout'); + throw new Error(test.title + ' timeout'); }, 1000); - fn(function() { + test.fn(function() { clearTimeout(timeout); + runNextTest(); }); -}; +}, 1);
7326ec30d95f8a80b6011aca31f3d57f589309fe
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var minify = require('gulp-minify-css'); var del = require('del'); var lint = require('gulp-jshint'); gulp.task('lint', function() { return gulp.src('private/scripts/**/*.js') .pipe(lint()) .pipe(lint.reporter('default')) .pipe(lint.reporter('fail')); }); gulp.task('clean', function () { return del(['public/**/*']); }); gulp.task('styles', function() { return gulp.src('private/styles/*.css') .pipe(sass()) .pipe(minify()) .pipe(concat("style.css")) .pipe(gulp.dest('public/styles')); }); gulp.task('scripts', function() { return gulp.src('private/scripts/**/*.js') //.pipe(uglify()) // TODO: uncomment .pipe(concat("ang.min.js")) .pipe(gulp.dest('public/scripts')); }); gulp.task('images', function() { return gulp.src('private/images/*.*') .pipe(gulp.dest('public/images')); }); gulp.task('default', gulp.series('lint', 'clean', gulp.parallel('styles', 'scripts', 'images')));
var gulp = require('gulp'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var minify = require('gulp-minify-css'); var del = require('del'); var lint = require('gulp-jshint'); gulp.task('lint', function() { return gulp.src('private/scripts/**/*.js') .pipe(lint()) .pipe(lint.reporter('default')) .pipe(lint.reporter('fail')); }); gulp.task('clean', function () { return del(['public/**/*']); }); gulp.task('styles', function() { return gulp.src('private/styles/*.css') .pipe(sass()) .pipe(minify()) .pipe(concat("style.css")) .pipe(gulp.dest('public/styles')); }); gulp.task('scripts', function() { return gulp.src('private/scripts/**/*.js') //.pipe(uglify()) // TODO: uncomment .pipe(concat("ang.min.js")) .pipe(gulp.dest('public/scripts')); }); gulp.task('images', function() { return gulp.src('private/images/*.*') .pipe(gulp.dest('public/images')); }); gulp.task('default', gulp.series(//'lint', // fail early 'clean', gulp.parallel('styles', 'scripts', 'images', function(done) { gulp.watch('private/images/*.*', gulp.parallel('images')); gulp.watch('private/styles/*.css', gulp.parallel('styles')); gulp.watch('private/scripts/**/*.js', gulp.series('lint', 'scripts')); done(); })));
Use gulp as a listener
Use gulp as a listener
JavaScript
agpl-3.0
blagae/webcomicvault
--- +++ @@ -37,4 +37,13 @@ .pipe(gulp.dest('public/images')); }); -gulp.task('default', gulp.series('lint', 'clean', gulp.parallel('styles', 'scripts', 'images'))); +gulp.task('default', gulp.series(//'lint', // fail early + 'clean', + gulp.parallel('styles', 'scripts', 'images', + function(done) { + gulp.watch('private/images/*.*', gulp.parallel('images')); + gulp.watch('private/styles/*.css', gulp.parallel('styles')); + gulp.watch('private/scripts/**/*.js', gulp.series('lint', 'scripts')); + + done(); + })));
f506d6f9e71821fe808d2b77d2b5c886591383ed
lib/plugin/theme/renderable/collection.js
lib/plugin/theme/renderable/collection.js
"use strict"; const Renderable = require('./renderable'); class Collection extends Renderable {} Collection.Instance = require('./collectionInstance'); /* const Registry = require('../../../util/registry'); class Collection extends Renderable { addElement(data, element) { if (!data.elementRegistry) { data.elementRegistry = new Registry({useId: 'name'}); } data.elementRegistry.set(element); element.parent = data; return this; } async init(context, data={}) { const FormApi = this.engine.pluginRegistry.get('FormApi'); data = await super.init(context, data); let replacementRegistry = new Registry({useId: 'name'}); if (data.elementRegistry) { for (let element of data.elementRegistry.getOrderedElements()) { const Element = context.theme.getRenderable(element.type) || FormApi.getElement(element.type); replacementRegistry.set(await Element.init(context, element)); } data.elementRegistry = replacementRegistry; } return data; } async commit(data) { const FormApi = this.engine.pluginRegistry.get('FormApi'); return data.elementRegistry ? (await Promise.all(data.elementRegistry.getOrderedElements() .map(async (item) => { const Element = data.context.theme.getRenderable(item.type) || FormApi.getElement(item.type); return await Element.commit(item) }))) .join('') : ''; } *getAllElementsRecursive(data) { // NOTE: Intentionally leaving this as a generator. if (data && data.elementRegistry) { for (let element of data.elementRegistry.getOrderedElements()) { yield element; yield* this.getAllElementsRecursive(element.data); } } } } */ module.exports = Collection;
"use strict"; const Renderable = require('./renderable'); class Collection extends Renderable {} Collection.Instance = require('./collectionInstance'); module.exports = Collection;
Remove accidental inclusion of commented-out code
Remove accidental inclusion of commented-out code
JavaScript
mit
coreyp1/defiant,coreyp1/defiant
--- +++ @@ -5,57 +5,5 @@ class Collection extends Renderable {} Collection.Instance = require('./collectionInstance'); -/* -const Registry = require('../../../util/registry'); - -class Collection extends Renderable { - addElement(data, element) { - if (!data.elementRegistry) { - data.elementRegistry = new Registry({useId: 'name'}); - } - data.elementRegistry.set(element); - element.parent = data; - return this; - } - - async init(context, data={}) { - const FormApi = this.engine.pluginRegistry.get('FormApi'); - data = await super.init(context, data); - let replacementRegistry = new Registry({useId: 'name'}); - if (data.elementRegistry) { - for (let element of data.elementRegistry.getOrderedElements()) { - const Element = context.theme.getRenderable(element.type) - || FormApi.getElement(element.type); - replacementRegistry.set(await Element.init(context, element)); - } - data.elementRegistry = replacementRegistry; - } - return data; - } - - async commit(data) { - const FormApi = this.engine.pluginRegistry.get('FormApi'); - return data.elementRegistry - ? (await Promise.all(data.elementRegistry.getOrderedElements() - .map(async (item) => { - const Element = data.context.theme.getRenderable(item.type) - || FormApi.getElement(item.type); - return await Element.commit(item) - }))) - .join('') - : ''; - } - - *getAllElementsRecursive(data) { - // NOTE: Intentionally leaving this as a generator. - if (data && data.elementRegistry) { - for (let element of data.elementRegistry.getOrderedElements()) { - yield element; - yield* this.getAllElementsRecursive(element.data); - } - } - } -} -*/ module.exports = Collection;
ff4845f9cd7591fafffe0316b4c80948fbe80008
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const sweetjs = require("gulp-sweetjs"); const sourcemaps = require('gulp-sourcemaps'); const concat = require('gulp-concat-util'); // Macro packages. const match = "sparkler/macros"; const lambda = "lambda-chop/macros"; const bdd = "sweet-bdd"; gulp.task('default', function() { console.log("Use either the 'build' or 'test' tasks"); }); gulp.task("build", function () { function pipeline (from, to, macros) { gulp.src("src/" + from + "/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: macros, readableNames: true })) .pipe(sourcemaps.write("../sourcemaps/" + from)) .pipe(gulp.dest(to)) } pipeline("lib", "lib", [match, lambda]); pipeline("plugin", "tennu_plugins", [match]); pipeline("test", "test", [bdd]); gulp.src("src/bin/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: [], readableNames: true })) .pipe(concat.header("#! /usr/bin/env node\n\n")) .pipe(sourcemaps.write("../sourcemaps/bin")) .pipe(gulp.dest("bin")) });
const gulp = require('gulp'); const sweetjs = require("gulp-sweetjs"); const sourcemaps = require('gulp-sourcemaps'); const concat = require('gulp-concat-util'); // Macro packages. const match = "sparkler/macros"; const lambda = "lambda-chop/macros"; const bdd = "sweet-bdd"; gulp.task('default', function() { console.log("Use either the 'build' or 'test' tasks"); }); gulp.task("build", function () { function pipeline (from, to, macros) { gulp.src("src/" + from + "/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: macros, readableNames: true })) .pipe(sourcemaps.write("../sourcemaps/" + from)) .pipe(gulp.dest(to)) } pipeline("lib", "lib", [match, lambda]); pipeline("plugin", "tennu_plugins", [match, lambda]); pipeline("test", "test", [bdd]); gulp.src("src/bin/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: [], readableNames: true })) .pipe(concat.header("#! /usr/bin/env node\n\n")) .pipe(sourcemaps.write("../sourcemaps/bin")) .pipe(gulp.dest("bin")) });
Add lambda-match to plugins macros.
Internal: Add lambda-match to plugins macros.
JavaScript
isc
hagb4rd/tennu,LordWingZero/tennu,Tennu/tennu
--- +++ @@ -25,7 +25,7 @@ } pipeline("lib", "lib", [match, lambda]); - pipeline("plugin", "tennu_plugins", [match]); + pipeline("plugin", "tennu_plugins", [match, lambda]); pipeline("test", "test", [bdd]); gulp.src("src/bin/**/*.sjs")
eba98196b93eaba09ba8d64a6a7e70ab832ded1c
lib/git-manager.js
lib/git-manager.js
var GithubApi = require('github'), config = require('../config'), Promise = require('promise'), github = new GithubApi({ debug: config.debug, version: '3.0.0' }); github.authenticate({ type: 'oauth', token: config.github.token }); module.exports = { github: github, getAllPulls: function() { var p = Promise.denodeify(github.pullRequests.getAll); return p({ user: config.repo.owner, repo: config.repo.name }); } };
var GithubApi = require('github'), config = require('../config'), Promise = require('promise'), github = new GithubApi({ debug: config.debug, version: '3.0.0' }); github.authenticate({ type: 'oauth', token: config.github.token }); module.exports = { github: github, getAllPulls: function() { var getAllPulls = Promise.denodeify(github.pullRequests.getAll); return getAllPulls({ user: config.repo.owner, repo: config.repo.name }); } };
Change a variable name for clarity
Change a variable name for clarity
JavaScript
mit
iFixit/pulldasher,iFixit/pulldasher,iFixit/pulldasher,iFixit/pulldasher
--- +++ @@ -14,7 +14,7 @@ module.exports = { github: github, getAllPulls: function() { - var p = Promise.denodeify(github.pullRequests.getAll); - return p({ user: config.repo.owner, repo: config.repo.name }); + var getAllPulls = Promise.denodeify(github.pullRequests.getAll); + return getAllPulls({ user: config.repo.owner, repo: config.repo.name }); } };
3f1d2eec28ec703569637e1d148fb7b668ee1e41
lib/git-wrapper.js
lib/git-wrapper.js
var Q = require('q'); var _ = require('lodash'); var spawn = require('child_process').spawn; module.exports = function(args, options) { var deferred = Q.defer(); options = options || {}; var defaults = { cwd: process.cwd(), verbose: false }; options = _.extend({}, defaults, options); var child = spawn('git', args, _.omit(options, 'verbose')); child.on('exit', function(code) { if (code === 128) { deferred.reject("git did not exit cleanly"); } else { deferred.resolve(code); } }); child.stdout.on('data', function(data) { deferred.notify(data.toString()); }); child.stderr.on('data', function(data) { deferred.reject(data.toString()); }); return deferred.promise; };
var Q = require('q'); var _ = require('lodash'); var spawn = require('child_process').spawn; module.exports = function(args, options) { var deferred = Q.defer(); options = options || {}; var defaults = { cwd: process.cwd(), verbose: false }; options = _.extend({}, defaults, options); var child = spawn('git', args, _.omit(options, 'verbose')); child.on('exit', function(code) { if (code === 128) { deferred.reject("git did not exit cleanly"); } else { deferred.resolve(code); } }); child.stdout.on('data', function(data) { deferred.notify(data.toString()); }); // TODO: Why does this return non-error output? // i.e. Cloning into... child.stderr.on('data', function(data) { deferred.notify(data.toString()); }); return deferred.promise; };
Fix early cache resolve bug
Fix early cache resolve bug
JavaScript
mit
crowdtap/parachute
--- +++ @@ -28,8 +28,10 @@ deferred.notify(data.toString()); }); + // TODO: Why does this return non-error output? + // i.e. Cloning into... child.stderr.on('data', function(data) { - deferred.reject(data.toString()); + deferred.notify(data.toString()); }); return deferred.promise;
eeb287f6029c7116b81ac81af76e055b2e3efa85
commands/misc.js
commands/misc.js
/* Miscellaneous commands */ Settings.addPermissions(['pick', 'randomanswer']); exports.commands = { choose: 'pick', pick: function (arg, by, room, cmd) { var choices = arg.split(","); choices = choices.filter(function (i) {return (toId(i) !== '');}); if (choices.length < 2) return this.pmReply(this.trad('err')); var choice = choices[Math.floor(Math.random() * choices.length)]; if (!this.can('pick') || this.roomType === 'pm') { this.pmReply(Tools.stripCommands(choice)); } else { this.reply(Tools.stripCommands(choice)); } }, '8ball': 'randomanswer', helix: 'randomanswer', randomanswer: function (arg, user, room) { if (room === user) return false; var text = ''; var rand = ~~(20 * Math.random()); var answers = this.trad('answers'); text += (answers[rand] || answers[0]); this.restrictReply(text, 'randomanswer'); } };
/* Miscellaneous commands */ Settings.addPermissions(['pick', 'randomanswer', 'usage', 'help']); exports.commands = { choose: 'pick', pick: function (arg, by, room, cmd) { var choices = arg.split(","); choices = choices.filter(function (i) {return (toId(i) !== '');}); if (choices.length < 2) return this.pmReply(this.trad('err')); var choice = choices[Math.floor(Math.random() * choices.length)]; if (!this.can('pick') || this.roomType === 'pm') { this.pmReply(Tools.stripCommands(choice)); } else { this.reply(Tools.stripCommands(choice)); } }, '8ball': 'randomanswer', helix: 'randomanswer', randomanswer: function (arg, user, room) { if (room === user) return false; var text = ''; var rand = ~~(20 * Math.random()); var answers = this.trad('answers'); text += (answers[rand] || answers[0]); this.restrictReply(text, 'randomanswer'); }, usagestats: 'usage', usage: function (arg, user, room) { this.restrictReply('http://www.smogon.com/stats/', 'usage'); }, guide: 'help', botguide: 'help', help: function (arg, user, room) { this.restrictReply('https://github.com/Ecuacion/Pokemon-Showdown-Node-Bot/blob/master/commands/README.md', 'help'); } };
Add usage and help commands
Add usage and help commands
JavaScript
mit
ateck5/le_spatula,sama2/Pokemon-Showdown-Node-Bot,awolffromspace/PC-Battle-Server-Bot,TheFenderStory/Mambot,Ecuacion/Espaol-Bot,abulechu/Pokemon-Showdown-Node-Bot,Robophill/Pokemon-Showdown-Node-Bot,Flareninja/Pokemon-Showdown-Node-Bot,Ecuacion/Pokemon-Showdown-Node-Bot,TheFenderStory/Pokemon-Showdown-Node-Bot,Freigeist/Pokemon-Showdown-Node-Bot,megaslowbro1/test-bot,psnsVGC/Le-Spatula,megaslowbro1/heatah-fajita-bot-test-2
--- +++ @@ -2,7 +2,7 @@ Miscellaneous commands */ -Settings.addPermissions(['pick', 'randomanswer']); +Settings.addPermissions(['pick', 'randomanswer', 'usage', 'help']); exports.commands = { choose: 'pick', @@ -27,5 +27,16 @@ var answers = this.trad('answers'); text += (answers[rand] || answers[0]); this.restrictReply(text, 'randomanswer'); + }, + + usagestats: 'usage', + usage: function (arg, user, room) { + this.restrictReply('http://www.smogon.com/stats/', 'usage'); + }, + + guide: 'help', + botguide: 'help', + help: function (arg, user, room) { + this.restrictReply('https://github.com/Ecuacion/Pokemon-Showdown-Node-Bot/blob/master/commands/README.md', 'help'); } };
28aed7e4779ad302b0b25b2d321a975179a24602
test/validation_test.js
test/validation_test.js
'use strict'; const assert = require('assert'); const Event = require('../db/models/Event'); describe('Validation of User records', () => { it('should require a name for every event', () => { const validationEvt = new Event({ name: undefined }), validationResult = validationEvt.validateSync(), { message } = validationResult.errors.name; assert(message === 'This event requires a name.'); }); it ('should require an event\'s name to be at least 3 characters long', () => { const validationEvt = new Event({ name: 'ab' }), validationResult = validationEvt.validateSync(), { message } = validationResult.errors.name; assert(message === 'Your event name must be at least 3 characters long.'); }); it('should disallow invalid records from being saved to the database', (done) => { const invalidEvt = new Event({ name: 'ab', }); invalidEvt .save() .catch((validationResult) => { const { message } = validationResult.errors.name; assert(message === 'Your event name must be at least 3 characters long.'); done(); }); }); });
'use strict'; const assert = require('assert'); const Event = require('../db/models/Event'); describe('Validation of User records', () => { // Tests that records for which no `name` property is defined are marked invalid // and return a validation fallback message: it('should require a name for every event', () => { const validationEvt = new Event({ name: undefined }), validationResult = validationEvt.validateSync(), { message } = validationResult.errors.name; assert(message === 'This event requires a name.'); }); // Tests that records for which the `name` property is less than three (3) characters // in length are marked invalid and return a validation fallback message: it ('should require an event\'s name to be at least 3 characters long', () => { const validationEvt = new Event({ name: 'ab' }), validationResult = validationEvt.validateSync(), { message } = validationResult.errors.name; assert(message === 'Your event name must be at least 3 characters long.'); }); // Tests that attempts to `save()` records marked as invalid to the database are caught // as errors and are not added to the database: it('should disallow invalid records from being saved to the database', (done) => { const invalidEvt = new Event({ name: 'ab', }); invalidEvt .save() .catch((validationResult) => { const { message } = validationResult.errors.name; assert(message === 'Your event name must be at least 3 characters long.'); done(); }); }); });
Write test to catch invalid inserts
test: Write test to catch invalid inserts
JavaScript
mit
IsenrichO/react-timeline,IsenrichO/react-timeline
--- +++ @@ -5,6 +5,8 @@ describe('Validation of User records', () => { + // Tests that records for which no `name` property is defined are marked invalid + // and return a validation fallback message: it('should require a name for every event', () => { const validationEvt = new Event({ name: undefined }), validationResult = validationEvt.validateSync(), @@ -13,6 +15,8 @@ assert(message === 'This event requires a name.'); }); + // Tests that records for which the `name` property is less than three (3) characters + // in length are marked invalid and return a validation fallback message: it ('should require an event\'s name to be at least 3 characters long', () => { const validationEvt = new Event({ name: 'ab' }), validationResult = validationEvt.validateSync(), @@ -21,6 +25,8 @@ assert(message === 'Your event name must be at least 3 characters long.'); }); + // Tests that attempts to `save()` records marked as invalid to the database are caught + // as errors and are not added to the database: it('should disallow invalid records from being saved to the database', (done) => { const invalidEvt = new Event({ name: 'ab', }); invalidEvt
5f32e2d1ee4cb89dc50b4bcd5126258cbe6f2107
test/common/cycle.js
test/common/cycle.js
'use strict'; /* global describe, it */ let assert = require('assert'); let Cycle = require('../../src/cycle'); describe('Cycle', function () { describe('API', function () { it('should have `applyToDOM`', function () { assert.strictEqual(typeof Cycle.applyToDOM, 'function'); }); it('should have `renderAsHTML`', function () { assert.strictEqual(typeof Cycle.renderAsHTML, 'function'); }); it('should have `registerCustomElement`', function () { assert.strictEqual(typeof Cycle.registerCustomElement, 'function'); }); it('should have a shortcut to Rx', function () { assert.strictEqual(typeof Cycle.Rx, 'object'); }); it('should have a shortcut to virtual-hyperscript', function () { assert.strictEqual(typeof Cycle.h, 'function'); }); }); });
'use strict'; /* global describe, it */ let assert = require('assert'); let Cycle = require('../../src/cycle'); describe('Cycle', function () { describe('API', function () { it('should have `applyToDOM`', function () { assert.strictEqual(typeof Cycle.applyToDOM, 'function'); }); it('should have `renderAsHTML`', function () { assert.strictEqual(typeof Cycle.renderAsHTML, 'function'); }); it('should have `registerCustomElement`', function () { assert.strictEqual(typeof Cycle.registerCustomElement, 'function'); }); it('should have a shortcut to Rx', function () { assert.strictEqual(typeof Cycle.Rx, 'object'); }); it('should have a shortcut to virtual-hyperscript', function () { assert.strictEqual(typeof Cycle.h, 'function'); }); it('should have a shortcut to virtual-dom\'s svg', function () { assert.strictEqual(typeof Cycle.svg, 'function'); }); }); });
Add test case for svg() (like h() is)
Add test case for svg() (like h() is)
JavaScript
mit
bzalasky/cycle-core,Widdershin/cycle-core,secobarbital/cycle-core,beni55/cycle-core,gdseller/cycle-core,Amirus/cycle-core,secobarbital/cycle-core,richardTowers/cycle-core,beni55/cycle-core,ccapndave/cycle-core,Iced-Tea/cycle-core,Widdershin/cycle-core,Iced-Tea/cycle-core,Amirus/cycle-core
--- +++ @@ -24,5 +24,9 @@ it('should have a shortcut to virtual-hyperscript', function () { assert.strictEqual(typeof Cycle.h, 'function'); }); + + it('should have a shortcut to virtual-dom\'s svg', function () { + assert.strictEqual(typeof Cycle.svg, 'function'); + }); }); });
5116c1dd1c7a9e993d0c4b86a67d58520386fb56
test/detect/index.js
test/detect/index.js
'use strict'; var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var hljs = require('../../build'); var path = require('path'); var utility = require('../utility'); function testAutoDetection(language) { var languagePath = utility.buildPath('detect', language); it(`should have test for ${language}`, function() { return fs.statAsync(languagePath) .then(path => path.isDirectory().should.be.true); }); it(`should be detected as ${language}`, function() { return fs.readdirAsync(languagePath) .map(function(example) { var filename = path.join(languagePath, example); return fs.readFileAsync(filename, 'utf-8'); }) .each(function(content) { var expected = language, actual = hljs.highlightAuto(content).language; actual.should.equal(expected); }); }); } describe('hljs.highlightAuto()', function() { var languages = hljs.listLanguages(); languages.forEach(testAutoDetection); });
'use strict'; let bluebird = require('bluebird'); let fs = bluebird.promisifyAll(require('fs')); let hljs = require('../../build'); let path = require('path'); let utility = require('../utility'); function testAutoDetection(language) { let languagePath = utility.buildPath('detect', language); it(`should have test for ${language}`, function() { return fs.statAsync(languagePath) .then(path => path.isDirectory().should.be.true); }); it(`should be detected as ${language}`, function() { return fs.readdirAsync(languagePath) .map(function(example) { let filename = path.join(languagePath, example); return fs.readFileAsync(filename, 'utf-8'); }) .each(function(content) { let expected = language, actual = hljs.highlightAuto(content).language; actual.should.equal(expected); }); }); } describe('hljs.highlightAuto()', function() { let languages = hljs.listLanguages(); languages.forEach(testAutoDetection); });
Use let in the detect test suite
Use let in the detect test suite
JavaScript
bsd-3-clause
bluepichu/highlight.js,bluepichu/highlight.js,MakeNowJust/highlight.js,isagalaev/highlight.js,highlightjs/highlight.js,highlightjs/highlight.js,teambition/highlight.js,Sannis/highlight.js,carlokok/highlight.js,MakeNowJust/highlight.js,palmin/highlight.js,sourrust/highlight.js,bluepichu/highlight.js,StanislawSwierc/highlight.js,Sannis/highlight.js,sourrust/highlight.js,lead-auth/highlight.js,isagalaev/highlight.js,teambition/highlight.js,StanislawSwierc/highlight.js,aurusov/highlight.js,carlokok/highlight.js,Sannis/highlight.js,aurusov/highlight.js,highlightjs/highlight.js,palmin/highlight.js,palmin/highlight.js,MakeNowJust/highlight.js,carlokok/highlight.js,sourrust/highlight.js,highlightjs/highlight.js,teambition/highlight.js,carlokok/highlight.js,aurusov/highlight.js
--- +++ @@ -1,13 +1,13 @@ 'use strict'; -var bluebird = require('bluebird'); -var fs = bluebird.promisifyAll(require('fs')); -var hljs = require('../../build'); -var path = require('path'); -var utility = require('../utility'); +let bluebird = require('bluebird'); +let fs = bluebird.promisifyAll(require('fs')); +let hljs = require('../../build'); +let path = require('path'); +let utility = require('../utility'); function testAutoDetection(language) { - var languagePath = utility.buildPath('detect', language); + let languagePath = utility.buildPath('detect', language); it(`should have test for ${language}`, function() { return fs.statAsync(languagePath) @@ -17,12 +17,12 @@ it(`should be detected as ${language}`, function() { return fs.readdirAsync(languagePath) .map(function(example) { - var filename = path.join(languagePath, example); + let filename = path.join(languagePath, example); return fs.readFileAsync(filename, 'utf-8'); }) .each(function(content) { - var expected = language, + let expected = language, actual = hljs.highlightAuto(content).language; actual.should.equal(expected); @@ -31,7 +31,7 @@ } describe('hljs.highlightAuto()', function() { - var languages = hljs.listLanguages(); + let languages = hljs.listLanguages(); languages.forEach(testAutoDetection); });
78f8be18c8042305c401f1ac47e4ba5a3c2105f8
ui/protractor.conf.js
ui/protractor.conf.js
const protractor = require('protractor') const phantomjs = require('phantomjs-prebuilt') exports.config = { framework: 'mocha', plugins: [{ package: 'aurelia-protractor-plugin' }, { package: 'protractor-console', logLevels: ['debug', 'info', 'warning', 'severe'] }], capabilities: { 'browserName': 'phantomjs', 'phantomjs.binary.path': phantomjs.path }, seleniumServerJar: './node_modules/selenium-jar/bin/selenium-server-standalone-2.52.0.jar', localSeleniumStandaloneOpts: { args: ['-Djna.nosys=true'] }, baseUrl: 'http://localhost:3000', specs: ['test/e2e*.spec.js'], onPrepare: () => { protractor.ignoreSynchronization = true }, mochaOpts: { reporter: 'spec', timeout: 6000 } }
const phantomjs = require('phantomjs-prebuilt') exports.config = { framework: 'mocha', plugins: [{ package: 'aurelia-protractor-plugin' }, { package: 'protractor-console', logLevels: ['debug', 'info', 'warning', 'severe'] }], capabilities: { 'browserName': 'phantomjs', 'phantomjs.binary.path': phantomjs.path }, seleniumServerJar: './node_modules/selenium-jar/bin/selenium-server-standalone-2.52.0.jar', localSeleniumStandaloneOpts: { args: ['-Djna.nosys=true'] }, baseUrl: 'http://localhost:3000', specs: ['test/e2e*.spec.js'], mochaOpts: { reporter: 'spec', timeout: 6000 } }
Remove not-needed option. The aurelia plugin already takes care of this.
Remove not-needed option. The aurelia plugin already takes care of this.
JavaScript
mit
jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr
--- +++ @@ -1,4 +1,3 @@ -const protractor = require('protractor') const phantomjs = require('phantomjs-prebuilt') exports.config = { @@ -22,10 +21,6 @@ baseUrl: 'http://localhost:3000', specs: ['test/e2e*.spec.js'], - onPrepare: () => { - protractor.ignoreSynchronization = true - }, - mochaOpts: { reporter: 'spec', timeout: 6000
880c178a446d61d77ba512e027e2cd076d412df8
api/lib/log/logger.js
api/lib/log/logger.js
// TODO: To decide and adopt to some logging utility like winston var util = require('util'); module.exports = { info: function(message,context) { if(context) { console.log(message, util.format('%j', context)); } else { console.log(message); } }, error: function(message, error) { console.error(message, util.format('%j', error)); } };
// TODO: To decide and adopt to some logging utility like winston var util = require('util'); module.exports = { info: function(message,context) { var logItem = { timestamp: new Date(), source: 'autoscaler:apiserver', text: message, log_level: 'info', data: context === null ? {} : context }; console.log (util.format('%j', logItem)); }, error: function(message, error) { var logItem = { timestamp: new Date(), source: 'autoscaler:apiserver', text: message, log_level: 'error', data: error }; console.error (util.format('%j', logItem)); } };
Prepare log output as parseable JSON data
Prepare log output as parseable JSON data
JavaScript
apache-2.0
cloudfoundry-incubator/app-autoscaler,pradyutsarma/app-autoscaler,qibobo/app-autoscaler,pradyutsarma/app-autoscaler,qibobo/app-autoscaler,pradyutsarma/app-autoscaler,cloudfoundry-incubator/app-autoscaler,cloudfoundry-incubator/app-autoscaler,qibobo/app-autoscaler,qibobo/app-autoscaler,cloudfoundry-incubator/app-autoscaler,pradyutsarma/app-autoscaler
--- +++ @@ -2,16 +2,24 @@ var util = require('util'); module.exports = { - info: function(message,context) { - if(context) { - console.log(message, util.format('%j', context)); - } - else { - console.log(message); - } - + info: function(message,context) { + var logItem = { + timestamp: new Date(), + source: 'autoscaler:apiserver', + text: message, + log_level: 'info', + data: context === null ? {} : context + }; + console.log (util.format('%j', logItem)); }, error: function(message, error) { - console.error(message, util.format('%j', error)); + var logItem = { + timestamp: new Date(), + source: 'autoscaler:apiserver', + text: message, + log_level: 'error', + data: error + }; + console.error (util.format('%j', logItem)); } };
cb192f3b98bcfc5d8363924c5be1f2be37a2dbb5
admin/scripts/default.js
admin/scripts/default.js
$(document).ready(function () { /*Navigation initialization*/ var navigation = $('#navigation'); var navShown = false; $('#nav-controller').on('click', function () { if (navShown) { navigation.removeClass('show-nav'); navigation.addClass('hide-nav'); navShown = false; } else { navigation.removeClass('hide-nav'); navigation.addClass('show-nav'); navShown = true; } }); /*Bootstrap Popover initialization*/ $(function () { $('[data-toggle="popover"]').popover() }); /*Verical scorlling*/ $(function () { function scrollHorizontally(e) { e = window.event || e; var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); document.getElementById('horizontal-scrolling').scrollLeft -= (delta * 40); // Multiplied by 40 e.preventDefault(); } if (document.getElementById('horizontal-scrolling').addEventListener) { // IE9, Chrome, Safari, Opera document.getElementById('horizontal-scrolling').addEventListener("mousewheel", scrollHorizontally, false); // Firefox document.getElementById('horizontal-scrolling').addEventListener("DOMMouseScroll", scrollHorizontally, false); } else { // IE 6/7/8 document.getElementById('horizontal-scrolling').attachEvent("onmousewheel", scrollHorizontally); } }); /*File uplad button*/ document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; });
$(document).ready(function () { /*Navigation initialization*/ var navigation = $('#navigation'); var navShown = false; var navController = $('#nav-controller'); if (navController) { navController.on('click', function () { if (navShown) { navigation.removeClass('show-nav'); navigation.addClass('hide-nav'); navShown = false; } else { navigation.removeClass('hide-nav'); navigation.addClass('show-nav'); navShown = true; } }); } /*Bootstrap Popover initialization*/ $(function () { $('[data-toggle="popover"]').popover() }); /*Verical scorlling*/ $(function () { function scrollHorizontally(e) { e = window.event || e; var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); document.getElementById('horizontal-scrolling').scrollLeft -= (delta * 40); // Multiplied by 40 e.preventDefault(); } var horizontalScrolling = document.getElementById('horizontal-scrolling'); if (horizontalScrolling) { if (horizontalScrolling.addEventListener) { // IE9, Chrome, Safari, Opera horizontalScrolling.addEventListener("mousewheel", scrollHorizontally, false); // Firefox horizontalScrolling.addEventListener("DOMMouseScroll", scrollHorizontally, false); } else { // IE 6/7/8 horizontalScrolling.attachEvent("onmousewheel", scrollHorizontally); } } }); /*File uplad button*/ document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; }; });
Resolve all the JS errors
Resolve all the JS errors
JavaScript
mit
UoG-Libraries/Adshow,UoG-Libraries/Adshow,UoG-Libraries/Adshow
--- +++ @@ -3,17 +3,20 @@ /*Navigation initialization*/ var navigation = $('#navigation'); var navShown = false; - $('#nav-controller').on('click', function () { - if (navShown) { - navigation.removeClass('show-nav'); - navigation.addClass('hide-nav'); - navShown = false; - } else { - navigation.removeClass('hide-nav'); - navigation.addClass('show-nav'); - navShown = true; - } - }); + var navController = $('#nav-controller'); + if (navController) { + navController.on('click', function () { + if (navShown) { + navigation.removeClass('show-nav'); + navigation.addClass('hide-nav'); + navShown = false; + } else { + navigation.removeClass('hide-nav'); + navigation.addClass('show-nav'); + navShown = true; + } + }); + } /*Bootstrap Popover initialization*/ $(function () { @@ -29,14 +32,17 @@ e.preventDefault(); } - if (document.getElementById('horizontal-scrolling').addEventListener) { - // IE9, Chrome, Safari, Opera - document.getElementById('horizontal-scrolling').addEventListener("mousewheel", scrollHorizontally, false); - // Firefox - document.getElementById('horizontal-scrolling').addEventListener("DOMMouseScroll", scrollHorizontally, false); - } else { - // IE 6/7/8 - document.getElementById('horizontal-scrolling').attachEvent("onmousewheel", scrollHorizontally); + var horizontalScrolling = document.getElementById('horizontal-scrolling'); + if (horizontalScrolling) { + if (horizontalScrolling.addEventListener) { + // IE9, Chrome, Safari, Opera + horizontalScrolling.addEventListener("mousewheel", scrollHorizontally, false); + // Firefox + horizontalScrolling.addEventListener("DOMMouseScroll", scrollHorizontally, false); + } else { + // IE 6/7/8 + horizontalScrolling.attachEvent("onmousewheel", scrollHorizontally); + } } });
10be5cde2d00aee7a8aaf248f978476d92f73581
app/js/service/router.js
app/js/service/router.js
define([ 'flight/lib/component', 'director' ], function(defineComponent, Router) { 'use strict'; function RouterService() { this.gotoPost = function(id) { this.trigger(document, 'service.fetchPost', { "id": id }); }; this.gotoPosts = function(id) { this.trigger(document, 'service.fetchPosts'); }; this.after('initialize', function() { this.routers = { '/post/:id': this.gotoPost.bind(this), '/posts': this.gotoPosts.bind(this), '(.*)': this.gotoPosts.bind(this) }; this.router = Router(this.routers); this.router.init(); }); } return defineComponent(RouterService); });
define([ 'flight/lib/component', 'director' ], function(defineComponent, Router) { 'use strict'; function RouterService() { this.gotoPost = function(id) { this.trigger(document, 'service.fetchPost', { "id": id }); }; this.gotoPosts = function(id) { this.trigger(document, 'service.fetchPosts'); }; this.after('initialize', function() { this.routers = { '/post/:id': this.gotoPost.bind(this), '/posts': this.gotoPosts.bind(this), '/': this.gotoPosts.bind(this) }; this.router = Router(this.routers); this.router.init(); if (location.pathname == '/') { this.router.setRoute('/posts'); } }); } return defineComponent(RouterService); });
Set post page as the default page
Set post page as the default page
JavaScript
mit
unitedstackfront/ued,unitedstackfront/ued
--- +++ @@ -19,12 +19,15 @@ this.routers = { '/post/:id': this.gotoPost.bind(this), '/posts': this.gotoPosts.bind(this), - '(.*)': this.gotoPosts.bind(this) + '/': this.gotoPosts.bind(this) }; this.router = Router(this.routers); this.router.init(); + if (location.pathname == '/') { + this.router.setRoute('/posts'); + } }); }
d76797c3ac220189e303670312bb6571ef096b22
packages/create-graphql/src/utils.js
packages/create-graphql/src/utils.js
import shell from 'shelljs'; import chalk from 'chalk'; import ora from 'ora'; import spawn from 'cross-spawn-promise'; const tic = chalk.green('✓'); const tac = chalk.red('✗'); const installYeoman = async () => { const spinner = ora('Installing Yeoman...'); spinner.start(); let command = 'yarn'; let args = ['global', 'add', 'yo']; if (!shell.which('npm')) { command = 'npm'; args = ['install', '-g', 'yo']; } const options = { shell: true, stdio: false, }; try { await spawn(command, args, options); spinner.stop(); console.log(`${tic} Yeoman installed!`); } catch (error) { spinner.stop(); console.error(`${tac} There was an error while trying to install Yeoman:`, error); } }; export const verifyYeoman = async () => { // eslint-disable-line import/prefer-default-export if (!shell.which('yo')) { console.error(`${tac} GraphQL CLI requires Yeoman to be installed.`); await installYeoman(); } return true; };
import shell from 'shelljs'; import chalk from 'chalk'; import ora from 'ora'; import spawn from 'cross-spawn-promise'; const tic = chalk.green('✓'); const tac = chalk.red('✗'); const installYeoman = async () => { const spinner = ora('Installing Yeoman...'); spinner.start(); const command = 'npm'; const args = ['install', '-g', 'yo']; const options = { shell: true, stdio: false, }; try { await spawn(command, args, options); spinner.stop(); console.log(`${tic} Yeoman installed!`); } catch (error) { spinner.stop(); console.error(`${tac} There was an error while trying to install Yeoman:`, error); } }; export const verifyYeoman = async () => { // eslint-disable-line import/prefer-default-export if (!shell.which('yo')) { console.error(`${tac} GraphQL CLI requires Yeoman to be installed.`); await installYeoman(); } return true; };
Remove the yarn checking, as yarn itself is not stable yet and a lot of people are using old versions.
Remove the yarn checking, as yarn itself is not stable yet and a lot of people are using old versions.
JavaScript
mit
graphql-community/create-graphql,lucasbento/create-graphql
--- +++ @@ -11,14 +11,8 @@ spinner.start(); - let command = 'yarn'; - let args = ['global', 'add', 'yo']; - - if (!shell.which('npm')) { - command = 'npm'; - args = ['install', '-g', 'yo']; - } - + const command = 'npm'; + const args = ['install', '-g', 'yo']; const options = { shell: true, stdio: false,
cd0c283d607b5ac4af377d9a05a99218c5ae7091
assets/js/modules/idea-hub/datastore/base.js
assets/js/modules/idea-hub/datastore/base.js
/** * `modules/idea-hub` base data store * * Site Kit by Google, Copyright 2021 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. */ /** * Internal dependencies */ import Modules from 'googlesitekit-modules'; import { MODULES_IDEA_HUB } from './constants'; const baseModuleStore = Modules.createModuleStore( 'idea-hub', { storeName: MODULES_IDEA_HUB, settingSlugs: [ 'tosAccepted' ], } ); export default baseModuleStore;
/** * `modules/idea-hub` base data store * * Site Kit by Google, Copyright 2021 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. */ /** * Internal dependencies */ import Modules from 'googlesitekit-modules'; import { MODULES_IDEA_HUB } from './constants'; const baseModuleStore = Modules.createModuleStore( 'idea-hub', { storeName: MODULES_IDEA_HUB, settingSlugs: [ 'tosAccepted', 'ownerID' ], } ); export default baseModuleStore;
Add ownerID in settingSlugs for idea hub.
Add ownerID in settingSlugs for idea hub.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -24,7 +24,7 @@ const baseModuleStore = Modules.createModuleStore( 'idea-hub', { storeName: MODULES_IDEA_HUB, - settingSlugs: [ 'tosAccepted' ], + settingSlugs: [ 'tosAccepted', 'ownerID' ], } ); export default baseModuleStore;
eb530d7da6d372703d54f6648cdf5000949d71a9
Ship/CommandSource.js
Ship/CommandSource.js
class CommandSource { constructor(messageSource,botUsername){ this.botUsername = botUsername; this.bindings = {}; messageSource.on("text",this.handle.bind(this)); } addCommand(name,command){ if(name in this.bindings){ throw `Error: A command is already bound to ${name}`; } this.bindings[name] = command; } handle(message){ let text = message.text; if(text.substr(0,1) !== "/"){ return; } text = text.substr(1); let tokens = text.split(" "); let commandName = tokens.shift(); let atAt = commandName.indexOf("@"); if(atAt !== -1){ let commandName = commandName.substr(0,atAt); if (commanName.substr(atAt+1) !== this.botUsername){ return; } } commandName = commandName.toLowerCase(); if(!(commandName in this.bindings)){ throw `Error: ${commandName} is not a known command`; } this.bindings[commandName].execute(tokens,message); } } module.exports = CommandSource;
class CommandSource { constructor(messageSource,botUsername){ this.botUsername = botUsername; this.bindings = {}; messageSource.on("text",this.handle.bind(this)); } addCommand(name,command){ if(name in this.bindings){ throw `Error: A command is already bound to ${name}`; } this.bindings[name] = command; } handle(message){ let text = message.text; if(text.substr(0,1) !== "/"){ return; } text = text.substr(1); let tokens = text.split(" "); let commandName = tokens.shift(); let atAt = commandName.indexOf("@"); if(atAt !== -1){ if (commandName.substr(atAt+1) !== this.botUsername){ return; } commandName = commandName.substr(0,atAt); } commandName = commandName.toLowerCase(); if(!(commandName in this.bindings)){ throw `Error: ${commandName} is not a known command`; } this.bindings[commandName].execute(tokens,message); } } module.exports = CommandSource;
Fix bot failing to respond to command with it's username
Fix bot failing to respond to command with it's username Fix #5
JavaScript
mit
severnbronies/Sail
--- +++ @@ -22,10 +22,10 @@ let commandName = tokens.shift(); let atAt = commandName.indexOf("@"); if(atAt !== -1){ - let commandName = commandName.substr(0,atAt); - if (commanName.substr(atAt+1) !== this.botUsername){ + if (commandName.substr(atAt+1) !== this.botUsername){ return; } + commandName = commandName.substr(0,atAt); } commandName = commandName.toLowerCase(); if(!(commandName in this.bindings)){
7c014584f848d9f7df9470ee796aaa32317a82de
db/users.js
db/users.js
var records = [ { id: 1, username: 'jack', password: 'secret', displayName: 'Jack', emails: [ { value: 'jack@example.com' } ] } , { id: 2, username: 'jill', password: 'birthday', displayName: 'Jill', emails: [ { value: 'jill@example.com' } ] } ]; exports.findByUsername = function(username, cb) { process.nextTick(function() { for (var i = 0, len = records.length; i < len; i++) { var record = records[i]; if (record.username === username) { return cb(null, record); } } return cb(null, null); }); }
require('dotenv').load() var records = [ { id: 1, username: 'jack', password: 'secret', displayName: 'Jack', emails: [ { value: 'jack@example.com' } ] } , { id: 2, username: 'jill', password: 'birthday', displayName: 'Jill', emails: [ { value: 'jill@example.com' } ] } ]; if (process.env.shared_secret != null && process.env.shared_secret != undefined) { shared = { id: records.length + 2, username: process.env.shared_username || 'community', password: process.env.shared_secret, displayName: 'Community Account', emails: [ { value: 'community@example.com' } ] }; records.push(shared); } exports.findByUsername = function(username, cb) { process.nextTick(function() { var match = null; var community = null; for (var i = 0, len = records.length; i < len; i++) { var record = records[i]; if (record.username === username) { match = record; break; } else if (record.username == 'community') { community = record; } } if (match == null && community != null) { match = community; } return cb(null, match); }); }
Support for shared secrets for authentication.
Support for shared secrets for authentication. Provide an enviroment variable "shared_secret" and you will be able to authenticate with any username that is not matched in the "database." Optionally, provide "shared_username" to set the username explicitly; otherwise, "community" will be used.
JavaScript
unlicense
community-lands/community-lands-monitoring-station,rfc2616/community-lands-monitoring-station,rfc2616/community-lands-monitoring-station,community-lands/community-lands-monitoring-station,community-lands/community-lands-monitoring-station,rfc2616/community-lands-monitoring-station
--- +++ @@ -1,16 +1,37 @@ +require('dotenv').load() + var records = [ { id: 1, username: 'jack', password: 'secret', displayName: 'Jack', emails: [ { value: 'jack@example.com' } ] } , { id: 2, username: 'jill', password: 'birthday', displayName: 'Jill', emails: [ { value: 'jill@example.com' } ] } ]; +if (process.env.shared_secret != null && process.env.shared_secret != undefined) { + shared = { + id: records.length + 2, + username: process.env.shared_username || 'community', + password: process.env.shared_secret, + displayName: 'Community Account', + emails: [ { value: 'community@example.com' } ] + }; + records.push(shared); +} + exports.findByUsername = function(username, cb) { process.nextTick(function() { + var match = null; + var community = null; for (var i = 0, len = records.length; i < len; i++) { var record = records[i]; if (record.username === username) { - return cb(null, record); + match = record; + break; + } else if (record.username == 'community') { + community = record; } } - return cb(null, null); + if (match == null && community != null) { + match = community; + } + return cb(null, match); }); }
297c33b3f790fdbdec51891451703724ca1a2614
core/client/components/gh-activating-list-item.js
core/client/components/gh-activating-list-item.js
var ActivatingListItem = Ember.Component.extend({ tagName: 'li', classNameBindings: ['active'], active: false }); export default ActivatingListItem;
var ActivatingListItem = Ember.Component.extend({ tagName: 'li', classNameBindings: ['active'], active: false, unfocusLink: function () { this.$('a').blur(); }.on('click') }); export default ActivatingListItem;
Fix active menu state on settings navigation
Fix active menu state on settings navigation closes #4622 - unfocus ActivatingListItem link when clicked
JavaScript
mit
panezhang/Ghost,beautyOfProgram/Ghost,jaswilli/Ghost,qdk0901/Ghost,rchrd2/Ghost,schematical/Ghost,icowan/Ghost,singular78/Ghost,NamedGod/Ghost,GroupxDev/javaPress,Bunk/Ghost,jomahoney/Ghost,SachaG/bjjbot-blog,bisoe/Ghost,kwangkim/Ghost,daihuaye/Ghost,ngosinafrica/SiteForNGOs,ASwitlyk/Ghost,prosenjit-itobuz/Ghost,BayPhillips/Ghost,riyadhalnur/Ghost,dYale/blog,Feitianyuan/Ghost,jomofrodo/ccb-ghost,Yarov/yarov,acburdine/Ghost,mohanambati/Ghost,delgermurun/Ghost,nneko/Ghost,mnitchie/Ghost,Kaenn/Ghost,STANAPO/Ghost,etdev/blog,dggr/Ghost-sr,RufusMbugua/TheoryOfACoder,Netazoic/bad-gateway,katiefenn/Ghost,rollokb/Ghost,janvt/Ghost,francisco-filho/Ghost,chris-yoon90/Ghost,allanjsx/Ghost,Japh/shortcoffee,kaychaks/kaushikc.org,woodyrew/Ghost,dqj/Ghost,ThorstenHans/Ghost,adam-paterson/blog,ghostchina/Ghost-zh,panezhang/Ghost,madole/diverse-learners,akveo/akveo-blog,flomotlik/Ghost,PepijnSenders/whatsontheotherside,tyrikio/Ghost,r1N0Xmk2/Ghost,leonli/ghost,dai-shi/Ghost,jin/Ghost,ManRueda/manrueda-blog,thinq4yourself/Unmistakable-Blog,Romdeau/Ghost,jamesslock/Ghost,dymx101/Ghost,cwonrails/Ghost,carlyledavis/Ghost,dgem/Ghost,schneidmaster/theventriloquist.us,hoxoa/Ghost,developer-prosenjit/Ghost,obsoleted/Ghost,imjerrybao/Ghost,greyhwndz/Ghost,jparyani/GhostSS,jomofrodo/ccb-ghost,davidmenger/nodejsfan,dbalders/Ghost,jeonghwan-kim/Ghost,liftup/ghost,BlueHatbRit/Ghost,mhhf/ghost-latex,manishchhabra/Ghost,phillipalexander/Ghost,BlueHatbRit/Ghost,jamesslock/Ghost,rmoorman/Ghost,patterncoder/patterncoder,tksander/Ghost,ineitzke/Ghost,rameshponnada/Ghost,darvelo/Ghost,Gargol/Ghost,PaulBGD/Ghost-Plus,ClarkGH/Ghost,lukekhamilton/Ghost,wangjun/Ghost,patterncoder/patterncoder,sebgie/Ghost,TribeMedia/Ghost,hnarayanan/narayanan.co,SkynetInc/steam,smedrano/Ghost,delgermurun/Ghost,dYale/blog,carlosmtx/Ghost,petersucks/blog,davidmenger/nodejsfan,ljhsai/Ghost,mayconxhh/Ghost,karmakaze/Ghost,Rovak/Ghost,lukw00/Ghost,adam-paterson/blog,uploadcare/uploadcare-ghost-demo,thinq4yourself/Unmistakable-Blog,tadityar/Ghost,sceltoas/Ghost,cysys/ghost-openshift,pollbox/ghostblog,tchapi/igneet-blog,diancloud/Ghost,jiangjian-zh/Ghost,duyetdev/islab,PDXIII/Ghost-FormMailer,edsadr/Ghost,pbevin/Ghost,cicorias/Ghost,denzelwamburu/denzel.xyz,edurangel/Ghost,IbrahimAmin/Ghost,UnbounDev/Ghost,mdbw/ghost,vishnuharidas/Ghost,cysys/ghost-openshift,daihuaye/Ghost,UsmanJ/Ghost,AnthonyCorrado/Ghost,jomofrodo/ccb-ghost,Brunation11/Ghost,barbastan/Ghost,bbmepic/Ghost,ckousik/Ghost,ballPointPenguin/Ghost,jiangjian-zh/Ghost,lukaszklis/Ghost,Loyalsoldier/Ghost,Trendy/Ghost,Azzurrio/Ghost,ivanoats/ivanstorck.com,YY030913/Ghost,Netazoic/bad-gateway,arvidsvensson/Ghost,denzelwamburu/denzel.xyz,janvt/Ghost,Feitianyuan/Ghost,olsio/Ghost,aschmoe/jesse-ghost-app,Brunation11/Ghost,akveo/akveo-blog,disordinary/Ghost,KnowLoading/Ghost,kortemy/Ghost,ManRueda/Ghost,pedroha/Ghost,ballPointPenguin/Ghost,e10/Ghost,ngosinafrica/SiteForNGOs,ghostchina/Ghost-zh,MadeOnMars/Ghost,Klaudit/Ghost,etanxing/Ghost,optikalefx/Ghost,davidenq/Ghost-Blog,manishchhabra/Ghost,beautyOfProgram/Ghost,jorgegilmoreira/ghost,vainglori0us/urban-fortnight,tuan/Ghost,alecho/Ghost,telco2011/Ghost,gabfssilva/Ghost,leonli/ghost,handcode7/Ghost,zackslash/Ghost,notno/Ghost,Kaenn/Ghost,virtuallyearthed/Ghost,djensen47/Ghost,JonathanZWhite/Ghost,situkangsayur/Ghost,lukaszklis/Ghost,blankmaker/Ghost,UsmanJ/Ghost,r1N0Xmk2/Ghost,metadevfoundation/Ghost,optikalefx/Ghost,greenboxindonesia/Ghost,uploadcare/uploadcare-ghost-demo,NikolaiIvanov/Ghost,morficus/Ghost,weareleka/blog,AnthonyCorrado/Ghost,DesenTao/Ghost,mdbw/ghost,claudiordgz/Ghost,rafaelstz/Ghost,rmoorman/Ghost,jaguerra/Ghost,virtuallyearthed/Ghost,Netazoic/bad-gateway,mnitchie/Ghost,aroneiermann/GhostJade,lf2941270/Ghost,jin/Ghost,nmukh/Ghost,llv22/Ghost,neynah/GhostSS,greenboxindonesia/Ghost,cicorias/Ghost,schematical/Ghost,axross/ghost,anijap/PhotoGhost,jaguerra/Ghost,letsjustfixit/Ghost,ryanbrunner/crafters,icowan/Ghost,sajmoon/Ghost,LeandroNascimento/Ghost,cwonrails/Ghost,mayconxhh/Ghost,YY030913/Ghost,Bunk/Ghost,achimos/ghost_as,syaiful6/Ghost,ladislas/ghost,davidenq/Ghost-Blog,davidenq/Ghost-Blog,andrewconnell/Ghost,dbalders/Ghost,wemakeweb/Ghost,rizkyario/Ghost,ananthhh/Ghost,hilerchyn/Ghost,JonathanZWhite/Ghost,VillainyStudios/Ghost,fredeerock/atlabghost,JulienBrks/Ghost,pollbox/ghostblog,camilodelvasto/herokughost,imjerrybao/Ghost,tidyui/Ghost,diogogmt/Ghost,morficus/Ghost,mohanambati/Ghost,Dnlyc/Ghost,TribeMedia/Ghost,arvidsvensson/Ghost,zeropaper/Ghost,PDXIII/Ghost-FormMailer,rito/Ghost,smedrano/Ghost,ErisDS/Ghost,Sebastian1011/Ghost,sangcu/Ghost,lanffy/Ghost,letsjustfixit/Ghost,makapen/Ghost,katrotz/blog.katrotz.space,syaiful6/Ghost,pathayes/FoodBlog,ignasbernotas/nullifer,neynah/GhostSS,pensierinmusica/Ghost,johnnymitch/Ghost,jiachenning/Ghost,acburdine/Ghost,smaty1/Ghost,hnarayanan/narayanan.co,trunk-studio/Ghost,yundt/seisenpenji,javorszky/Ghost,dylanchernick/ghostblog,tadityar/Ghost,jomahoney/Ghost,mtvillwock/Ghost,JohnONolan/Ghost,Remchi/Ghost,sergeylukin/Ghost,rito/Ghost,tandrewnichols/ghost,karmakaze/Ghost,vainglori0us/urban-fortnight,exsodus3249/Ghost,JonSmith/Ghost,ashishapy/ghostpy,mttschltz/ghostblog,cobbspur/Ghost,hnq90/Ghost,diancloud/Ghost,NovaDevelopGroup/Academy,Japh/shortcoffee,lowkeyfred/Ghost,ignasbernotas/nullifer,no1lov3sme/Ghost,FredericBernardo/Ghost,Dnlyc/Ghost,JohnONolan/Ghost,Xibao-Lv/Ghost,r14r/fork_nodejs_ghost,Kikobeats/Ghost,atandon/Ghost,AlexKVal/Ghost,theonlypat/Ghost,velimir0xff/Ghost,lukw00/Ghost,ygbhf/Ghost,sfpgmr/Ghost,bisoe/Ghost,krahman/Ghost,FredericBernardo/Ghost,ryansukale/ux.ryansukale.com,vloom/blog,mttschltz/ghostblog,Kaenn/Ghost,Trendy/Ghost,novaugust/Ghost,rchrd2/Ghost,yanntech/Ghost,Yarov/yarov,MadeOnMars/Ghost,javimolla/Ghost,kwangkim/Ghost,alecho/Ghost,katrotz/blog.katrotz.space,UnbounDev/Ghost,cncodog/Ghost-zh-codog,ITJesse/Ghost-zh,darvelo/Ghost,rameshponnada/Ghost,dbalders/Ghost,blankmaker/Ghost,dylanchernick/ghostblog,PeterCxy/Ghost,melissaroman/ghost-blog,neynah/GhostSS,LeandroNascimento/Ghost,wemakeweb/Ghost,psychobunny/Ghost,sunh3/Ghost,xiongjungit/Ghost,NovaDevelopGroup/Academy,ygbhf/Ghost,zumobi/Ghost,ManRueda/manrueda-blog,sceltoas/Ghost,Japh/Ghost,rouanw/Ghost,bosung90/Ghost,ladislas/ghost,cwonrails/Ghost,tyrikio/Ghost,nneko/Ghost,etdev/blog,tmp-reg/Ghost,JohnONolan/Ghost,telco2011/Ghost,makapen/Ghost,rizkyario/Ghost,cqricky/Ghost,PepijnSenders/whatsontheotherside,theonlypat/Ghost,NamedGod/Ghost,jorgegilmoreira/ghost,jiachenning/Ghost,mtvillwock/Ghost,allanjsx/Ghost,thomasalrin/Ghost,AlexKVal/Ghost,claudiordgz/Ghost,nmukh/Ghost,sifatsultan/js-ghost,ddeveloperr/Ghost,jacostag/Ghost,johngeorgewright/blog.j-g-w.info,GroupxDev/javaPress,augbog/Ghost,PaulBGD/Ghost-Plus,mhhf/ghost-latex,edurangel/Ghost,schneidmaster/theventriloquist.us,skmezanul/Ghost,francisco-filho/Ghost,johnnymitch/Ghost,memezilla/Ghost,shannonshsu/Ghost,vainglori0us/urban-fortnight,yanntech/Ghost,bosung90/Ghost,Remchi/Ghost,sifatsultan/js-ghost,greyhwndz/Ghost,jparyani/GhostSS,obsoleted/Ghost,stridespace/Ghost,kevinansfield/Ghost,r14r/fork_nodejs_ghost,IbrahimAmin/Ghost,bitjson/Ghost,olsio/Ghost,devleague/uber-hackathon,camilodelvasto/localghost,gabfssilva/Ghost,telco2011/Ghost,tksander/Ghost,ryansukale/ux.ryansukale.com,omaracrystal/Ghost,benstoltz/Ghost,leninhasda/Ghost,thehogfather/Ghost,bbmepic/Ghost,netputer/Ghost,klinker-apps/ghost,cncodog/Ghost-zh-codog,GroupxDev/javaPress,cncodog/Ghost-zh-codog,melissaroman/ghost-blog,bastianbin/Ghost,jacostag/Ghost,zhiyishou/Ghost,tidyui/Ghost,lowkeyfred/Ghost,aroneiermann/GhostJade,hnq90/Ghost,cysys/ghost-openshift,dqj/Ghost,camilodelvasto/localghost,chris-yoon90/Ghost,wallmarkets/Ghost,axross/ghost,yangli1990/Ghost,bsansouci/Ghost,epicmiller/pages,sebgie/Ghost,shrimpy/Ghost,hyokosdeveloper/Ghost,pbevin/Ghost,dggr/Ghost-sr,STANAPO/Ghost,sfpgmr/Ghost,Coding-House/Ghost,etanxing/Ghost,sergeylukin/Ghost,Gargol/Ghost,atandon/Ghost,letsjustfixit/Ghost,netputer/Ghost,DesenTao/Ghost,mlabieniec/ghost-env,ineitzke/Ghost,Shauky/Ghost,Xibao-Lv/Ghost,Kikobeats/Ghost,influitive/crafters,metadevfoundation/Ghost,singular78/Ghost,lethalbrains/Ghost,smaty1/Ghost,sangcu/Ghost,mlabieniec/ghost-env,Netazoic/bad-gateway,hoxoa/Ghost,Loyalsoldier/Ghost,skleung/blog,singular78/Ghost,trepafi/ghost-base,laispace/laiblog,wallmarkets/Ghost,Jai-Chaudhary/Ghost,ManRueda/manrueda-blog,TryGhost/Ghost,wangjun/Ghost,GarrethDottin/Habits-Design,lf2941270/Ghost,GarrethDottin/Habits-Design,hilerchyn/Ghost,andrewconnell/Ghost,julianromera/Ghost,e10/Ghost,wspandihai/Ghost,julianromera/Ghost,ManRueda/Ghost,devleague/uber-hackathon,NovaDevelopGroup/Academy,novaugust/Ghost,woodyrew/Ghost,lanffy/Ghost,Romdeau/Ghost,TryGhost/Ghost,Kikobeats/Ghost,kortemy/Ghost,kolorahl/Ghost,Sebastian1011/Ghost,lukekhamilton/Ghost,allanjsx/Ghost,load11/ghost,jgillich/Ghost,Azzurrio/Ghost,wspandihai/Ghost,v3rt1go/Ghost,trunk-studio/Ghost,mattchupp/blog,exsodus3249/Ghost,ckousik/Ghost,klinker-apps/ghost,epicmiller/pages,Smile42RU/Ghost,cqricky/Ghost,acburdine/Ghost,sunh3/Ghost,mattchupp/blog,JulienBrks/Ghost,no1lov3sme/Ghost,disordinary/Ghost,xiongjungit/Ghost,gleneivey/Ghost,liftup/ghost,djensen47/Ghost,tandrewnichols/ghost,kortemy/Ghost,tanbo800/Ghost,leninhasda/Ghost,PeterCxy/Ghost,augbog/Ghost,Jai-Chaudhary/Ghost,gcamana/Ghost,kevinansfield/Ghost,yangli1990/Ghost,Alxandr/Blog,ryanbrunner/crafters,skleung/blog,dggr/Ghost-sr,ivantedja/ghost,gcamana/Ghost,RufusMbugua/TheoryOfACoder,Elektro1776/javaPress,vloom/blog,phillipalexander/Ghost,daimaqiao/Ghost-Bridge,skmezanul/Ghost,developer-prosenjit/Ghost,daimaqiao/Ghost-Bridge,pedroha/Ghost,uniqname/everydaydelicious,ErisDS/Ghost,shannonshsu/Ghost,Elektro1776/javaPress,dai-shi/Ghost,petersucks/blog,lcamacho/Ghost,ashishapy/ghostpy,jparyani/GhostSS,madole/diverse-learners,rafaelstz/Ghost,rizkyario/Ghost,thehogfather/Ghost,stridespace/Ghost,ljhsai/Ghost,ClarkGH/Ghost,handcode7/Ghost,codeincarnate/Ghost,bsansouci/Ghost,notno/Ghost,omaracrystal/Ghost,riyadhalnur/Ghost,hyokosdeveloper/Ghost,barbastan/Ghost,camilodelvasto/herokughost,edsadr/Ghost,ThorstenHans/Ghost,ManRueda/Ghost,psychobunny/Ghost,sebgie/Ghost,Rovak/Ghost,sajmoon/Ghost,VillainyStudios/Ghost,dgem/Ghost,k2byew/Ghost,ananthhh/Ghost,jeonghwan-kim/Ghost,ASwitlyk/Ghost,fredeerock/atlabghost,duyetdev/islab,Alxandr/Blog,ivanoats/ivanstorck.com,veyo-care/Ghost,lethalbrains/Ghost,JonSmith/Ghost,kolorahl/Ghost,bitjson/Ghost,v3rt1go/Ghost,jorgegilmoreira/ghost,carlosmtx/Ghost,laispace/laiblog,laispace/laiblog,SkynetInc/steam,benstoltz/Ghost,Klaudit/Ghost,ddeveloperr/Ghost,yundt/seisenpenji,patrickdbakke/ghost-spa,achimos/ghost_as,k2byew/Ghost,flpms/ghost-ad,javimolla/Ghost,gleneivey/Ghost,zeropaper/Ghost,ITJesse/Ghost-zh,kevinansfield/Ghost,Coding-House/Ghost,kaychaks/kaushikc.org,praveenscience/Ghost,influitive/crafters,zhiyishou/Ghost,leonli/ghost,bastianbin/Ghost,daimaqiao/Ghost-Bridge,llv22/Ghost,tmp-reg/Ghost,shrimpy/Ghost,praveenscience/Ghost,johngeorgewright/blog.j-g-w.info,situkangsayur/Ghost,mohanambati/Ghost,KnowLoading/Ghost,NikolaiIvanov/Ghost,zumobi/Ghost,TryGhost/Ghost,devleague/uber-hackathon,Japh/Ghost,dymx101/Ghost,flpms/ghost-ad,anijap/PhotoGhost,AileenCGN/Ghost,rollokb/Ghost,pensierinmusica/Ghost,weareleka/blog,velimir0xff/Ghost,qdk0901/Ghost,memezilla/Ghost,Elektro1776/javaPress,mlabieniec/ghost-env,zackslash/Ghost,prosenjit-itobuz/Ghost,carlyledavis/Ghost,ErisDS/Ghost,javorszky/Ghost,aschmoe/jesse-ghost-app,diogogmt/Ghost,thomasalrin/Ghost,tanbo800/Ghost,jgillich/Ghost,rouanw/Ghost,Alxandr/Blog,chevex/undoctrinate,pathayes/FoodBlog,load11/ghost,SachaG/bjjbot-blog,jaswilli/Ghost,codeincarnate/Ghost,Smile42RU/Ghost,novaugust/Ghost,BayPhillips/Ghost,veyo-care/Ghost,stridespace/Ghost,flomotlik/Ghost
--- +++ @@ -1,7 +1,11 @@ var ActivatingListItem = Ember.Component.extend({ tagName: 'li', classNameBindings: ['active'], - active: false + active: false, + + unfocusLink: function () { + this.$('a').blur(); + }.on('click') }); export default ActivatingListItem;
7c4fb497c6ce67bc80b989e9ce386563d2809ac8
diogenes.js
diogenes.js
(function(window, Object) { var diogenes = {}; diogenes.Game = function(canvas, width, height, screen, items, characters, player) { // Canvas context this.ctx = canvas.getContext('2d'); // Dimension this.width = width; this.height = height; // Objects this.screen = screen; this.items = items; this.characters = characters; this.player = player; this.draw = (function(ctx) { var drawElement = function(elem) { elem.draw(ctx, elem.asset, elem.x, elem.y, elem.width, elem.height); }; return function() { drawElement(this.screen); this.items.forEach(drawElement); }; }(this.ctx)); this.run = function() { this.draw(); window.requestAnimationFrame(this.run.bind(this)); }; canvas.addEventListener('click', function(e) { console.log(e.pageX, e.pageY); items.forEach(function(item) { item.isMouseOver(e.pageX, e.pageY, item.x, item.y, item.x+item.width, item.y+item.height); }); }); }; diogenes.DrawableEntity = { draw: function(ctx) { ctx.drawImage(this.asset, this.x, this.y, this.width, this.height); } }; diogenes.InteractiveEntity = Object.create(diogenes.DrawableEntity); diogenes.InteractiveEntity.isMouseOver = function(x, y) { if (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height) { return true; } return false; }; diogenes.Screen = function(id, x, y, width, height, asset) { this.id = id; this.x = x; this.y = y; this.width = width; this.height = height; this.asset = asset; }; diogenes.Screen.prototype = Object.create(diogenes.DrawableEntity); diogenes.Item = function(id, x, y, width, height, asset) { this.id = id; this.x = x; this.y = y; this.width = width; this.height = height; this.asset = asset; }; diogenes.Item.prototype = Object.create(diogenes.InteractiveEntity); diogenes.Character = function() {}; diogenes.Player = function() {}; // Make the diogenes object global window.diogenes = diogenes; }(window, Object));
Implement some constructors and animation loop
Implement some constructors and animation loop Implement Game, Screen and Item constructors. Implement DrawableEntity and InteractiveEntity prototypes. Implement the animation loop.
JavaScript
mit
jghinestrosa/diogenes
--- +++ @@ -0,0 +1,93 @@ +(function(window, Object) { + + var diogenes = {}; + + diogenes.Game = function(canvas, width, height, screen, items, characters, player) { + + // Canvas context + this.ctx = canvas.getContext('2d'); + + // Dimension + this.width = width; + this.height = height; + + // Objects + this.screen = screen; + this.items = items; + this.characters = characters; + this.player = player; + + this.draw = (function(ctx) { + + var drawElement = function(elem) { + elem.draw(ctx, elem.asset, elem.x, elem.y, elem.width, elem.height); + }; + + return function() { + drawElement(this.screen); + this.items.forEach(drawElement); + }; + + }(this.ctx)); + + this.run = function() { + this.draw(); + window.requestAnimationFrame(this.run.bind(this)); + }; + + canvas.addEventListener('click', function(e) { + console.log(e.pageX, e.pageY); + items.forEach(function(item) { + item.isMouseOver(e.pageX, e.pageY, item.x, item.y, item.x+item.width, item.y+item.height); + }); + }); + + }; + + diogenes.DrawableEntity = { + draw: function(ctx) { + ctx.drawImage(this.asset, this.x, this.y, this.width, this.height); + } + }; + + diogenes.InteractiveEntity = Object.create(diogenes.DrawableEntity); + + diogenes.InteractiveEntity.isMouseOver = function(x, y) { + if (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height) { + return true; + } + + return false; + }; + + diogenes.Screen = function(id, x, y, width, height, asset) { + this.id = id; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.asset = asset; + }; + + diogenes.Screen.prototype = Object.create(diogenes.DrawableEntity); + + + diogenes.Item = function(id, x, y, width, height, asset) { + this.id = id; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.asset = asset; + }; + + diogenes.Item.prototype = Object.create(diogenes.InteractiveEntity); + + diogenes.Character = function() {}; + + diogenes.Player = function() {}; + + // Make the diogenes object global + window.diogenes = diogenes; + +}(window, Object));
8df9abb705e05391a592a379b9ddbc6d27b3d1cf
packages/react-jsx-highcharts/src/components/PlotBandLine/usePlotBandLineLifecycle.js
packages/react-jsx-highcharts/src/components/PlotBandLine/usePlotBandLineLifecycle.js
import React, { useRef, useEffect, useState } from 'react'; import uuid from 'uuid/v4'; import { attempt } from 'lodash-es'; import useModifiedProps from '../UseModifiedProps'; import useAxis from '../UseAxis'; export default function usePlotBandLine(props, plotType) { const { id = uuid, children, ...rest } = props; const axis = useAxis(); const idRef = useRef(); const [plotbandline, setPlotbandline] = useState(null); const modifiedProps = useModifiedProps(rest); useEffect(() => { if (!axis) return; if(!plotbandline || modifiedProps !== false) { if(!plotbandline) { idRef.current = typeof id === 'function' ? id() : id; } const myId = idRef.current; const opts = { id: myId, ...rest }; if(plotbandline) axis.removePlotBandOrLine(idRef.current); setPlotbandline(axis.addPlotBandOrLine(opts, plotType)); } }); useEffect(() => { return () => { attempt(axis.removePlotBandOrLine, idRef.current); }; }, []); return plotbandline; }
import React, { useRef, useEffect, useState } from 'react'; import uuid from 'uuid/v4'; import { attempt } from 'lodash-es'; import useModifiedProps from '../UseModifiedProps'; import useAxis from '../UseAxis'; export default function usePlotBandLine(props, plotType) { const { id = uuid, children, ...rest } = props; const axis = useAxis(); const idRef = useRef(); const [plotbandline, setPlotbandline] = useState(null); const modifiedProps = useModifiedProps(rest); useEffect(() => { if (!axis) return; if(!plotbandline || modifiedProps !== false) { if(!plotbandline) { idRef.current = typeof id === 'function' ? id() : id; } const myId = idRef.current; const opts = { id: myId, ...rest }; setPlotbandline(axis.addPlotBandOrLine(opts, plotType)); } return () => { attempt(axis.removePlotBandOrLine, idRef.current); }; }); return plotbandline; }
Revert "Fix plotline getting removed when children present"
Revert "Fix plotline getting removed when children present" This reverts commit d8dd4d977c3dcec578e083a2cd5beca4b9873e5c.
JavaScript
mit
whawker/react-jsx-highcharts,whawker/react-jsx-highcharts
--- +++ @@ -23,17 +23,13 @@ id: myId, ...rest }; - - if(plotbandline) axis.removePlotBandOrLine(idRef.current); setPlotbandline(axis.addPlotBandOrLine(opts, plotType)); } - }); - useEffect(() => { return () => { attempt(axis.removePlotBandOrLine, idRef.current); }; - }, []); + }); return plotbandline; }
8bc84bd260f674c6707db51f961056847e332e5e
core/client/components/gh-upload-modal.js
core/client/components/gh-upload-modal.js
import ModalDialog from 'ghost/components/gh-modal-dialog'; import upload from 'ghost/assets/lib/uploader'; var UploadModal = ModalDialog.extend({ layoutName: 'components/gh-modal-dialog', didInsertElement: function () { this._super(); upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')}); }, confirm: { reject: { func: function () { // The function called on rejection return true; }, buttonClass: true, text: 'Cancel' // The reject button text }, accept: { buttonClass: 'btn btn-blue right', text: 'Save', // The accept button texttext: 'Save' func: function () { var imageType = 'model.' + this.get('imageType'); if (this.$('.js-upload-url').val()) { this.set(imageType, this.$('.js-upload-url').val()); } else { this.set(imageType, this.$('.js-upload-target').attr('src')); } return true; } } }, actions: { closeModal: function () { this.sendAction(); }, confirm: function (type) { var func = this.get('confirm.' + type + '.func'); if (typeof func === 'function') { func.apply(this); } this.sendAction(); this.sendAction('confirm' + type); } } }); export default UploadModal;
import ModalDialog from 'ghost/components/gh-modal-dialog'; import upload from 'ghost/assets/lib/uploader'; var UploadModal = ModalDialog.extend({ layoutName: 'components/gh-modal-dialog', didInsertElement: function () { this._super(); upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')}); }, confirm: { reject: { func: function () { // The function called on rejection return true; }, buttonClass: 'btn btn-default', text: 'Cancel' // The reject button text }, accept: { buttonClass: 'btn btn-blue right', text: 'Save', // The accept button texttext: 'Save' func: function () { var imageType = 'model.' + this.get('imageType'); if (this.$('.js-upload-url').val()) { this.set(imageType, this.$('.js-upload-url').val()); } else { this.set(imageType, this.$('.js-upload-target').attr('src')); } return true; } } }, actions: { closeModal: function () { this.sendAction(); }, confirm: function (type) { var func = this.get('confirm.' + type + '.func'); if (typeof func === 'function') { func.apply(this); } this.sendAction(); this.sendAction('confirm' + type); } } }); export default UploadModal;
Fix button class on upload modal
Fix button class on upload modal no issue - this makes sure that the cancel button on the upload modal gets the correct class
JavaScript
mit
johnnymitch/Ghost,ManRueda/Ghost,r14r/fork_nodejs_ghost,ckousik/Ghost,thomasalrin/Ghost,singular78/Ghost,ballPointPenguin/Ghost,tanbo800/Ghost,JohnONolan/Ghost,carlyledavis/Ghost,laispace/laiblog,schneidmaster/theventriloquist.us,hyokosdeveloper/Ghost,achimos/ghost_as,achimos/ghost_as,etdev/blog,epicmiller/pages,nmukh/Ghost,ryanbrunner/crafters,Elektro1776/javaPress,johnnymitch/Ghost,ASwitlyk/Ghost,rizkyario/Ghost,rito/Ghost,IbrahimAmin/Ghost,barbastan/Ghost,telco2011/Ghost,dylanchernick/ghostblog,Xibao-Lv/Ghost,theonlypat/Ghost,floofydoug/Ghost,mohanambati/Ghost,vainglori0us/urban-fortnight,katrotz/blog.katrotz.space,kaiqigong/Ghost,ManRueda/manrueda-blog,tmp-reg/Ghost,tidyui/Ghost,NovaDevelopGroup/Academy,Klaudit/Ghost,wallmarkets/Ghost,ErisDS/Ghost,Kaenn/Ghost,gabfssilva/Ghost,klinker-apps/ghost,alecho/Ghost,MrMaksimize/sdg1,weareleka/blog,r1N0Xmk2/Ghost,etanxing/Ghost,JonSmith/Ghost,zeropaper/Ghost,skmezanul/Ghost,woodyrew/Ghost,ignasbernotas/nullifer,bosung90/Ghost,ashishapy/ghostpy,yundt/seisenpenji,pedroha/Ghost,Feitianyuan/Ghost,Dnlyc/Ghost,jaguerra/Ghost,smaty1/Ghost,ladislas/ghost,jomofrodo/ccb-ghost,Netazoic/bad-gateway,dbalders/Ghost,phillipalexander/Ghost,PaulBGD/Ghost-Plus,ThorstenHans/Ghost,bbmepic/Ghost,madole/diverse-learners,rchrd2/Ghost,jomahoney/Ghost,anijap/PhotoGhost,skmezanul/Ghost,francisco-filho/Ghost,qdk0901/Ghost,ineitzke/Ghost,virtuallyearthed/Ghost,dbalders/Ghost,mlabieniec/ghost-env,Gargol/Ghost,uploadcare/uploadcare-ghost-demo,petersucks/blog,dggr/Ghost-sr,melissaroman/ghost-blog,Azzurrio/Ghost,mohanambati/Ghost,PeterCxy/Ghost,Loyalsoldier/Ghost,dylanchernick/ghostblog,GroupxDev/javaPress,delgermurun/Ghost,Alxandr/Blog,akveo/akveo-blog,schneidmaster/theventriloquist.us,jaguerra/Ghost,sergeylukin/Ghost,ManRueda/Ghost,lethalbrains/Ghost,morficus/Ghost,rizkyario/Ghost,leonli/ghost,bbmepic/Ghost,blankmaker/Ghost,kaychaks/kaushikc.org,netputer/Ghost,PeterCxy/Ghost,stridespace/Ghost,thehogfather/Ghost,ignasbernotas/nullifer,weareleka/blog,axross/ghost,sceltoas/Ghost,ananthhh/Ghost,mohanambati/Ghost,manishchhabra/Ghost,patrickdbakke/ghost-spa,ryansukale/ux.ryansukale.com,sunh3/Ghost,laispace/laiblog,hnarayanan/narayanan.co,riyadhalnur/Ghost,daimaqiao/Ghost-Bridge,allanjsx/Ghost,ericbenson/GhostAzureSetup,cncodog/Ghost-zh-codog,lukaszklis/Ghost,FredericBernardo/Ghost,GarrethDottin/Habits-Design,smaty1/Ghost,cwonrails/Ghost,ThorstenHans/Ghost,stridespace/Ghost,janvt/Ghost,cwonrails/Ghost,pensierinmusica/Ghost,devleague/uber-hackathon,shrimpy/Ghost,e10/Ghost,aroneiermann/GhostJade,carlyledavis/Ghost,KnowLoading/Ghost,Alxandr/Blog,Remchi/Ghost,imjerrybao/Ghost,tuan/Ghost,atandon/Ghost,wemakeweb/Ghost,neynah/GhostSS,situkangsayur/Ghost,nneko/Ghost,johngeorgewright/blog.j-g-w.info,yanntech/Ghost,ITJesse/Ghost-zh,PepijnSenders/whatsontheotherside,phillipalexander/Ghost,pollbox/ghostblog,ygbhf/Ghost,BayPhillips/Ghost,NodeJSBarenko/Ghost,Klaudit/Ghost,davidmenger/nodejsfan,laispace/laiblog,ananthhh/Ghost,Yarov/yarov,daimaqiao/Ghost-Bridge,ClarkGH/Ghost,JonathanZWhite/Ghost,Elektro1776/javaPress,sangcu/Ghost,sifatsultan/js-ghost,duyetdev/islab,lethalbrains/Ghost,KnowLoading/Ghost,skleung/blog,tidyui/Ghost,sebgie/Ghost,gcamana/Ghost,francisco-filho/Ghost,icowan/Ghost,arvidsvensson/Ghost,Dnlyc/Ghost,greenboxindonesia/Ghost,jaswilli/Ghost,Rovak/Ghost,jparyani/GhostSS,darvelo/Ghost,riyadhalnur/Ghost,jparyani/GhostSS,mnitchie/Ghost,rollokb/Ghost,lf2941270/Ghost,liftup/ghost,bastianbin/Ghost,omaracrystal/Ghost,beautyOfProgram/Ghost,jiangjian-zh/Ghost,InnoD-WebTier/hardboiled_ghost,jiachenning/Ghost,petersucks/blog,sankumsek/Ghost-ashram,ClarkGH/Ghost,camilodelvasto/localghost,kevinansfield/Ghost,ddeveloperr/Ghost,ygbhf/Ghost,klinker-apps/ghost,ITJesse/Ghost-zh,morficus/Ghost,julianromera/Ghost,mhhf/ghost-latex,uploadcare/uploadcare-ghost-demo,SkynetInc/steam,makapen/Ghost,hilerchyn/Ghost,veyo-care/Ghost,load11/ghost,ckousik/Ghost,handcode7/Ghost,freele/ghost,kortemy/Ghost,Romdeau/Ghost,Azzurrio/Ghost,GroupxDev/javaPress,LeandroNascimento/Ghost,jeonghwan-kim/Ghost,daihuaye/Ghost,vloom/blog,pensierinmusica/Ghost,trunk-studio/Ghost,rito/Ghost,lcamacho/Ghost,GarrethDottin/Habits-Design,syaiful6/Ghost,pbevin/Ghost,r14r/fork_nodejs_ghost,MadeOnMars/Ghost,jeonghwan-kim/Ghost,ngosinafrica/SiteForNGOs,rizkyario/Ghost,letsjustfixit/Ghost,ManRueda/manrueda-blog,epicmiller/pages,no1lov3sme/Ghost,mnitchie/Ghost,optikalefx/Ghost,lanffy/Ghost,ryanbrunner/crafters,psychobunny/Ghost,DesenTao/Ghost,cqricky/Ghost,Japh/Ghost,greenboxindonesia/Ghost,claudiordgz/Ghost,kortemy/Ghost,leninhasda/Ghost,mayconxhh/Ghost,duyetdev/islab,schematical/Ghost,tandrewnichols/ghost,Kaenn/Ghost,jacostag/Ghost,leonli/ghost,bsansouci/Ghost,netputer/Ghost,jomahoney/Ghost,dqj/Ghost,zhiyishou/Ghost,barbastan/Ghost,bastianbin/Ghost,mttschltz/ghostblog,sebgie/Ghost,r1N0Xmk2/Ghost,augbog/Ghost,handcode7/Ghost,jorgegilmoreira/ghost,sergeylukin/Ghost,davidmenger/nodejsfan,ErisDS/Ghost,jamesslock/Ghost,smedrano/Ghost,panezhang/Ghost,tyrikio/Ghost,katrotz/blog.katrotz.space,developer-prosenjit/Ghost,ljhsai/Ghost,chris-yoon90/Ghost,k2byew/Ghost,vainglori0us/urban-fortnight,johngeorgewright/blog.j-g-w.info,ladislas/ghost,jomofrodo/ccb-ghost,Gargol/Ghost,benstoltz/Ghost,Jai-Chaudhary/Ghost,tyrikio/Ghost,arvidsvensson/Ghost,andrewconnell/Ghost,thomasalrin/Ghost,melissaroman/ghost-blog,gleneivey/Ghost,VillainyStudios/Ghost,velimir0xff/Ghost,andrewconnell/Ghost,TryGhost/Ghost,carlosmtx/Ghost,novaugust/Ghost,aschmoe/jesse-ghost-app,acburdine/Ghost,jamesslock/Ghost,ballPointPenguin/Ghost,tadityar/Ghost,e10/Ghost,javorszky/Ghost,lukaszklis/Ghost,janvt/Ghost,yangli1990/Ghost,zumobi/Ghost,jorgegilmoreira/ghost,anijap/PhotoGhost,prosenjit-itobuz/Ghost,veyo-care/Ghost,Coding-House/Ghost,telco2011/Ghost,Rovak/Ghost,ddeveloperr/Ghost,sajmoon/Ghost,daihuaye/Ghost,LeandroNascimento/Ghost,psychobunny/Ghost,UnbounDev/Ghost,cwonrails/Ghost,edsadr/Ghost,wspandihai/Ghost,cysys/ghost-openshift,hnq90/Ghost,shannonshsu/Ghost,davidenq/Ghost-Blog,influitive/crafters,dbalders/Ghost,Brunation11/Ghost,cqricky/Ghost,mlabieniec/ghost-env,shrimpy/Ghost,Japh/Ghost,kevinansfield/Ghost,davidenq/Ghost-Blog,ineitzke/Ghost,claudiordgz/Ghost,praveenscience/Ghost,bitjson/Ghost,NikolaiIvanov/Ghost,NovaDevelopGroup/Academy,zackslash/Ghost,etanxing/Ghost,krahman/Ghost,telco2011/Ghost,ericbenson/GhostAzureSetup,ivanoats/ivanstorck.com,obsoleted/Ghost,vainglori0us/urban-fortnight,woodyrew/Ghost,edurangel/Ghost,influitive/crafters,Remchi/Ghost,carlosmtx/Ghost,Aaron1992/Ghost,exsodus3249/Ghost,yundt/seisenpenji,stridespace/Ghost,sebgie/Ghost,Sebastian1011/Ghost,cobbspur/Ghost,v3rt1go/Ghost,tksander/Ghost,trepafi/ghost-base,blankmaker/Ghost,Japh/shortcoffee,VillainyStudios/Ghost,Polyrhythm/dolce,Japh/shortcoffee,sfpgmr/Ghost,novaugust/Ghost,ghostchina/Ghost-zh,davidenq/Ghost-Blog,Alxandr/Blog,javorszky/Ghost,TribeMedia/Ghost,hnarayanan/narayanan.co,javimolla/Ghost,ivantedja/ghost,cysys/ghost-openshift,Elektro1776/javaPress,katiefenn/Ghost,pathayes/FoodBlog,GroupxDev/javaPress,devleague/uber-hackathon,ManRueda/manrueda-blog,IbrahimAmin/Ghost,notno/Ghost,flomotlik/Ghost,icowan/Ghost,ivanoats/ivanstorck.com,dymx101/Ghost,mdbw/ghost,YY030913/Ghost,praveenscience/Ghost,v3rt1go/Ghost,singular78/Ghost,sfpgmr/Ghost,imjerrybao/Ghost,karmakaze/Ghost,rollokb/Ghost,schematical/Ghost,disordinary/Ghost,cicorias/Ghost,NamedGod/Ghost,FredericBernardo/Ghost,floofydoug/Ghost,neynah/GhostSS,flpms/ghost-ad,virtuallyearthed/Ghost,UsmanJ/Ghost,diogogmt/Ghost,BlueHatbRit/Ghost,jin/Ghost,adam-paterson/blog,akveo/akveo-blog,NovaDevelopGroup/Academy,AnthonyCorrado/Ghost,AileenCGN/Ghost,UnbounDev/Ghost,sangcu/Ghost,Feitianyuan/Ghost,xiongjungit/Ghost,daimaqiao/Ghost-Bridge,obsoleted/Ghost,sajmoon/Ghost,hyokosdeveloper/Ghost,NikolaiIvanov/Ghost,bisoe/Ghost,Smile42RU/Ghost,chris-yoon90/Ghost,jaswilli/Ghost,ASwitlyk/Ghost,fredeerock/atlabghost,rmoorman/Ghost,djensen47/Ghost,PaulBGD/Ghost-Plus,rouanw/Ghost,codeincarnate/Ghost,allanjsx/Ghost,Kikobeats/Ghost,atandon/Ghost,mttschltz/ghostblog,thinq4yourself/Unmistakable-Blog,kaiqigong/Ghost,STANAPO/Ghost,wemakeweb/Ghost,vishnuharidas/Ghost,pollbox/ghostblog,dai-shi/Ghost,chevex/undoctrinate,lanffy/Ghost,RufusMbugua/TheoryOfACoder,acburdine/Ghost,memezilla/Ghost,prosenjit-itobuz/Ghost,rameshponnada/Ghost,BayPhillips/Ghost,rchrd2/Ghost,bosung90/Ghost,rmoorman/Ghost,mlabieniec/ghost-env,JonSmith/Ghost,PepijnSenders/whatsontheotherside,Loyalsoldier/Ghost,leninhasda/Ghost,kwangkim/Ghost,UsmanJ/Ghost,tandrewnichols/ghost,Jai-Chaudhary/Ghost,diancloud/Ghost,ashishapy/ghostpy,mayconxhh/Ghost,yangli1990/Ghost,dggr/Ghost-sr,kortemy/Ghost,kaychaks/kaushikc.org,karmakaze/Ghost,exsodus3249/Ghost,YY030913/Ghost,edsadr/Ghost,pbevin/Ghost,cncodog/Ghost-zh-codog,shannonshsu/Ghost,ryansukale/ux.ryansukale.com,lf2941270/Ghost,Yarov/yarov,jgillich/Ghost,velimir0xff/Ghost,acburdine/Ghost,ManRueda/Ghost,etdev/blog,darvelo/Ghost,cncodog/Ghost-zh-codog,InnoD-WebTier/hardboiled_ghost,ghostchina/Ghost-zh,InnoD-WebTier/hardboiled_ghost,nneko/Ghost,RufusMbugua/TheoryOfACoder,dgem/Ghost,greyhwndz/Ghost,Shauky/Ghost,hilerchyn/Ghost,rafaelstz/Ghost,diogogmt/Ghost,JulienBrks/Ghost,jgladch/taskworksource,Sebastian1011/Ghost,lowkeyfred/Ghost,aschmoe/jesse-ghost-app,theonlypat/Ghost,tanbo800/Ghost,Xibao-Lv/Ghost,mattchupp/blog,greyhwndz/Ghost,Brunation11/Ghost,camilodelvasto/localghost,Trendy/Ghost,augbog/Ghost,dgem/Ghost,bisoe/Ghost,NamedGod/Ghost,BlueHatbRit/Ghost,JulienBrks/Ghost,nmukh/Ghost,pathayes/FoodBlog,lukekhamilton/Ghost,liftup/ghost,skleung/blog,denzelwamburu/denzel.xyz,julianromera/Ghost,AlexKVal/Ghost,PDXIII/Ghost-FormMailer,wangjun/Ghost,dYale/blog,adam-paterson/blog,dymx101/Ghost,denzelwamburu/denzel.xyz,panezhang/Ghost,mtvillwock/Ghost,kolorahl/Ghost,neynah/GhostSS,load11/ghost,devleague/uber-hackathon,pedroha/Ghost,aroneiermann/GhostJade,vloom/blog,Kaenn/Ghost,JonathanZWhite/Ghost,olsio/Ghost,mattchupp/blog,zumobi/Ghost,memezilla/Ghost,hoxoa/Ghost,Coding-House/Ghost,rouanw/Ghost,smedrano/Ghost,mhhf/ghost-latex,trunk-studio/Ghost,Romdeau/Ghost,llv22/Ghost,hnq90/Ghost,Netazoic/bad-gateway,syaiful6/Ghost,sceltoas/Ghost,PDXIII/Ghost-FormMailer,gabfssilva/Ghost,madole/diverse-learners,novaugust/Ghost,MadeOnMars/Ghost,metadevfoundation/Ghost,SachaG/bjjbot-blog,patterncoder/patterncoder,llv22/Ghost,beautyOfProgram/Ghost,lukekhamilton/Ghost,leonli/ghost,Bunk/Ghost,developer-prosenjit/Ghost,dqj/Ghost,zhiyishou/Ghost,JohnONolan/Ghost,mdbw/ghost,qdk0901/Ghost,patterncoder/patterncoder,Bunk/Ghost,jorgegilmoreira/ghost,letsjustfixit/Ghost,gcamana/Ghost,gleneivey/Ghost,dYale/blog,AnthonyCorrado/Ghost,notno/Ghost,thinq4yourself/Unmistakable-Blog,cicorias/Ghost,TribeMedia/Ghost,wspandihai/Ghost,camilodelvasto/herokughost,olsio/Ghost,STANAPO/Ghost,aexmachina/blog-old,kmeurer/GhostAzureSetup,delgermurun/Ghost,thehogfather/Ghost,cysys/ghost-openshift,Kikobeats/Ghost,mtvillwock/Ghost,Smile42RU/Ghost,jgillich/Ghost,Netazoic/bad-gateway,singular78/Ghost,manishchhabra/Ghost,flpms/ghost-ad,SkynetInc/steam,zeropaper/Ghost,bitjson/Ghost,TryGhost/Ghost,tadityar/Ghost,axross/ghost,omaracrystal/Ghost,jiangjian-zh/Ghost,benstoltz/Ghost,rameshponnada/Ghost,letsjustfixit/Ghost,xiongjungit/Ghost,fredeerock/atlabghost,djensen47/Ghost,Trendy/Ghost,situkangsayur/Ghost,SachaG/bjjbot-blog,javimolla/Ghost,AlexKVal/Ghost,ljhsai/Ghost,wallmarkets/Ghost,Netazoic/bad-gateway,allanjsx/Ghost,yanntech/Ghost,tmp-reg/Ghost,k2byew/Ghost,tksander/Ghost,camilodelvasto/herokughost,kwangkim/Ghost,metadevfoundation/Ghost,lowkeyfred/Ghost,jparyani/GhostSS,makapen/Ghost,jiachenning/Ghost,rafaelstz/Ghost,hoxoa/Ghost,sifatsultan/js-ghost,jomofrodo/ccb-ghost,DesenTao/Ghost,no1lov3sme/Ghost,ErisDS/Ghost,dggr/Ghost-sr,kevinansfield/Ghost,optikalefx/Ghost,diancloud/Ghost,wangjun/Ghost,lukw00/Ghost,jin/Ghost,TryGhost/Ghost,bsansouci/Ghost,kolorahl/Ghost,sunh3/Ghost,Kikobeats/Ghost,alecho/Ghost,edurangel/Ghost,codeincarnate/Ghost,jacostag/Ghost,flomotlik/Ghost,alexandrachifor/Ghost,uniqname/everydaydelicious,dai-shi/Ghost,lukw00/Ghost,zackslash/Ghost,tchapi/igneet-blog,ngosinafrica/SiteForNGOs,disordinary/Ghost,JohnONolan/Ghost
--- +++ @@ -13,7 +13,7 @@ func: function () { // The function called on rejection return true; }, - buttonClass: true, + buttonClass: 'btn btn-default', text: 'Cancel' // The reject button text }, accept: {
69420c72b6f9adabc6bbe027c24d4313efea534c
protractor.conf.js
protractor.conf.js
require("./server") exports.config = { directConnect: true, specs: 'tests/e2e/*.js', baseUrl: 'http://localhost:1234', framework: 'jasmine2', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, } };
ci = process.env.CI !== undefined if (!ci) require("./server") exports.config = { directConnect: !ci, specs: 'tests/e2e/*.js', baseUrl: (ci ? 'http://pollsapiclient.herokuapp.com' : 'http://localhost:1234'), framework: 'jasmine2', sauceUser: 'vincenzchianese', sauceKey : 'ebcc4534-bdcc-4ad5-8fd2-31ea2a1b6fce', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, } };
Set up data for saucelabs
Set up data for saucelabs
JavaScript
mit
XVincentX/pollsApiClient,XVincentX/pollsApiClient
--- +++ @@ -1,10 +1,15 @@ -require("./server") +ci = process.env.CI !== undefined + +if (!ci) + require("./server") exports.config = { - directConnect: true, + directConnect: !ci, specs: 'tests/e2e/*.js', - baseUrl: 'http://localhost:1234', + baseUrl: (ci ? 'http://pollsapiclient.herokuapp.com' : 'http://localhost:1234'), framework: 'jasmine2', + sauceUser: 'vincenzchianese', + sauceKey : 'ebcc4534-bdcc-4ad5-8fd2-31ea2a1b6fce', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000,
7162d926443cc62dd0f4a93691de5f7a08d47d11
eln/libs.js
eln/libs.js
export {default as OCLE} from 'https://www.lactame.com/lib/openchemlib-extended/1.13.0/openchemlib-extended.js'; export {default as SD} from 'https://www.lactame.com/lib/spectra-data/3.1.0/spectra-data.min.js'; export {default as CCE} from 'https://www.lactame.com/lib/chemcalc-extended/1.27.0/chemcalc-extended.js'; export {default as elnPlugin} from 'https://www.lactame.com/lib/eln-plugin/0.1.1/eln-plugin.js';
export {default as OCLE} from 'https://www.lactame.com/lib/openchemlib-extended/1.13.0/openchemlib-extended.js'; export {default as SD} from 'https://www.lactame.com/lib/spectra-data/3.1.0/spectra-data.min.js'; export {default as CCE} from 'https://www.lactame.com/lib/chemcalc-extended/1.27.0/chemcalc-extended.js'; export {default as elnPlugin} from 'https://www.lactame.com/lib/eln-plugin/0.1.2/eln-plugin.js';
Update elnPlugin to version to 0.1.2
Update elnPlugin to version to 0.1.2
JavaScript
mit
cheminfo-js/visualizer-helper,cheminfo-js/visualizer-helper
--- +++ @@ -2,4 +2,4 @@ export {default as OCLE} from 'https://www.lactame.com/lib/openchemlib-extended/1.13.0/openchemlib-extended.js'; export {default as SD} from 'https://www.lactame.com/lib/spectra-data/3.1.0/spectra-data.min.js'; export {default as CCE} from 'https://www.lactame.com/lib/chemcalc-extended/1.27.0/chemcalc-extended.js'; -export {default as elnPlugin} from 'https://www.lactame.com/lib/eln-plugin/0.1.1/eln-plugin.js'; +export {default as elnPlugin} from 'https://www.lactame.com/lib/eln-plugin/0.1.2/eln-plugin.js';
258e9170038e3c55481447c1460413af710c21a8
public/js/app/fields/CreateAttachmentView.js
public/js/app/fields/CreateAttachmentView.js
define(["app/app"], function(App) { "use strict"; App.CreateAttachmentView = Ember.View.extend({ tagName: 'input', type: 'file', attributeBindings: ['type'], change: function(event) { if (event.target.files.length > 0) { // Send the file object to controller var newFile = event.target.files[0] this.get('controller').send('addAttachment', newFile) // Clear the file input in DOM: 1) wrap with the form, 2) reset the form, 3) unwrap this.$().wrap('<form>').closest('form').get(0).reset() this.$().unwrap() } } }) })
define(["app/app"], function(App) { "use strict"; App.CreateAttachmentView = Ember.View.extend({ tagName: 'input', type: 'file', multiple: true, attributeBindings: ['type', 'multiple'], change: function(event) { if (event.target.files.length > 0) { // Send the file object(s) to controller var newFiles = event.target.files for (var i=0; i<newFiles.length; i++) { this.get('controller').send('addAttachment', newFiles[i]) } // Clear the file input in DOM: 1) wrap with the form, 2) reset the form, 3) unwrap this.$().wrap('<form>').closest('form').get(0).reset() this.$().unwrap() } } }) })
Enable multiple file upload for attachments
Enable multiple file upload for attachments Fixes #130.
JavaScript
mit
davidmz/pepyatka-html,SiTLar/pepyatka-html,pepyatka/pepyatka-html,dsumin/freefeed-html,FreeFeed/freefeed-html,dsumin/freefeed-html,davidmz/pepyatka-html,FreeFeed/freefeed-html,epicmonkey/pepyatka-html,SiTLar/pepyatka-html,pepyatka/pepyatka-html,epicmonkey/pepyatka-html
--- +++ @@ -4,13 +4,16 @@ App.CreateAttachmentView = Ember.View.extend({ tagName: 'input', type: 'file', - attributeBindings: ['type'], + multiple: true, + attributeBindings: ['type', 'multiple'], change: function(event) { if (event.target.files.length > 0) { - // Send the file object to controller - var newFile = event.target.files[0] - this.get('controller').send('addAttachment', newFile) + // Send the file object(s) to controller + var newFiles = event.target.files + for (var i=0; i<newFiles.length; i++) { + this.get('controller').send('addAttachment', newFiles[i]) + } // Clear the file input in DOM: 1) wrap with the form, 2) reset the form, 3) unwrap this.$().wrap('<form>').closest('form').get(0).reset()
b56c5ecd849d23519a063bc2396f8e7811d0f2ad
data/settings.js
data/settings.js
var settings = { "endpoints": [ { "name": "World Cup", "url": "https://worldcup-graphql.now.sh/", "auth": '', "verb": 'POST', "accept": '*/*', "contentType": 'application/json', "useIntrospectionQuery": true, "requestBodyType": 'application/json', } ] }
var settings = { "endpoints": [ { "name": "Space X", "url": "https://api.spacex.land/graphql/", "auth": '', "verb": 'POST', "accept": '*/*', "contentType": 'application/json', "useIntrospectionQuery": true, "requestBodyType": 'application/json', } ] }
Change endpoint to Space X
fix: Change endpoint to Space X
JavaScript
mit
Brbb/graphql-rover,Brbb/graphql-rover
--- +++ @@ -1,8 +1,8 @@ var settings = { "endpoints": [ { - "name": "World Cup", - "url": "https://worldcup-graphql.now.sh/", + "name": "Space X", + "url": "https://api.spacex.land/graphql/", "auth": '', "verb": 'POST', "accept": '*/*',
26a1d68fe2dec24e18f4cad4db176ab0d849fb2a
src/SourceBrowser.Site/Scripts/search.js
src/SourceBrowser.Site/Scripts/search.js
$("#search-form").submit(function (event) { var query = $("#search-box").val(); var path = window.location.pathname; //Split path, removing empty entries var splitPath = path.split('/'); splitPath = splitPath.filter(function (v) { return v !== '' }); if (splitPath.length <= 1) { searchSite(query); } else if (splitPath.length >= 2) { var username = splitPath[1]; console.log(username); var repository = splitPath[2]; console.log(repository); searchRepository(username, repository, query); } console.log(splitPath.length); return false; }); function searchRepository(username, repository, query) { console.log("search repo"); data = JSON.stringify({ "username": username, "repository": repository, "query": query }); $.ajax({ type: "POST", url: "/Search/Repository/", //TODO: If anyone knows a better way to do this, please share it. //My Javascript is not strong... data: "username=" + username + "&repository=" + repository + "&query="+ query, success: results }); } function results(e) { $("#tree-view").hide(); $("#search-results").show(); if(e.length == 0) { $("#no-results").show(); return; } $("#no-results").hide(); } function searchSite(query) { console.log("search site"); console.log(query); }
$("#search-form").submit(function (event) { var query = $("#search-box").val(); var path = window.location.pathname; //Split path, removing empty entries var splitPath = path.split('/'); splitPath = splitPath.filter(function (v) { return v !== '' }); if (splitPath.length <= 1) { searchSite(query); } else if (splitPath.length >= 2) { var username = splitPath[1]; var repository = splitPath[2]; searchRepository(username, repository, query); } return false; }); function searchRepository(username, repository, query) { data = JSON.stringify({ "username": username, "repository": repository, "query": query }); $.ajax({ type: "POST", url: "/Search/Repository/", //TODO: If anyone knows a better way to do this, please share it. //My Javascript is not strong... data: "username=" + username + "&repository=" + repository + "&query="+ query, success: handleSearch }); } function handleSearch(results) { $("#tree-view").hide(); $("#search-results").show(); if (results.length == 0) { $("#no-results").show(); } else { $("#no-results").hide(); var htmlResults = buildResults(results); } } function buildResults(results) { for (var i = 0; i < results.length; i++) { var searchResult = results[i]; console.log(searchResult); } } function searchSite(query) { }
Remove old logging statements. Set up structure to build HTML
Remove old logging statements. Set up structure to build HTML
JavaScript
mit
AmadeusW/SourceBrowser,AmadeusW/SourceBrowser,AmadeusW/SourceBrowser,CodeConnect/SourceBrowser,CodeConnect/SourceBrowser
--- +++ @@ -11,19 +11,15 @@ else if (splitPath.length >= 2) { var username = splitPath[1]; - console.log(username); var repository = splitPath[2]; - console.log(repository); searchRepository(username, repository, query); } - console.log(splitPath.length); return false; }); function searchRepository(username, repository, query) { - console.log("search repo"); data = JSON.stringify({ "username": username, @@ -37,26 +33,31 @@ //TODO: If anyone knows a better way to do this, please share it. //My Javascript is not strong... data: "username=" + username + "&repository=" + repository + "&query="+ query, - success: results + success: handleSearch }); } -function results(e) { +function handleSearch(results) { $("#tree-view").hide(); $("#search-results").show(); - if(e.length == 0) - { + if (results.length == 0) { $("#no-results").show(); - return; } - - $("#no-results").hide(); - + else { + $("#no-results").hide(); + var htmlResults = buildResults(results); + } } -function searchSite(query) { - console.log("search site"); - console.log(query); +function buildResults(results) { + for (var i = 0; i < results.length; i++) { + var searchResult = results[i]; + console.log(searchResult); + } } + +function searchSite(query) { +} +
05300b58009a287abd2e30747d43b052da2c0695
e2e/conf.js
e2e/conf.js
'use strict'; exports.config = { seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar', capabilities: { 'browserName': 'phantomjs' }, framework: 'jasmine2', onPrepare: function() { var SpecReporter = require('jasmine-spec-reporter'); jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true})); }, jasmineNodeOpts: { print: function() {} } };
'use strict'; exports.config = { seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar', capabilities: { 'browserName': 'chrome' }, framework: 'jasmine2', onPrepare: function() { var SpecReporter = require('jasmine-spec-reporter'); jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true})); }, jasmineNodeOpts: { print: function() {} } };
Switch back to chrome for tests, as phantomjs is not reliable
[e2e] Switch back to chrome for tests, as phantomjs is not reliable
JavaScript
mit
solarnz/ec2pric.es,solarnz/ec2pric.es,solarnz/ec2pric.es
--- +++ @@ -3,7 +3,7 @@ exports.config = { seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar', capabilities: { - 'browserName': 'phantomjs' + 'browserName': 'chrome' }, framework: 'jasmine2', onPrepare: function() {
9ff4d5ee986e9a821d910c13e78e39623b2fe7b1
web_external/model.js
web_external/model.js
isic.Model = girder.Model.extend({ urlRoot: function () { return this.resourceName; } });
isic.Model = girder.Model.extend({ urlRoot: function () { return this.resourceName; }, // "girder.Model.destroy" doesn't trigger many of the proper Backbone events destroy: Backbone.Model.prototype.destroy });
Use Backbone destroy, instead of Girder's method
Use Backbone destroy, instead of Girder's method
JavaScript
apache-2.0
ImageMarkup/isic-archive,ImageMarkup/isic-archive,ImageMarkup/isic-archive,ImageMarkup/isic-archive
--- +++ @@ -1,5 +1,8 @@ isic.Model = girder.Model.extend({ urlRoot: function () { return this.resourceName; - } + }, + + // "girder.Model.destroy" doesn't trigger many of the proper Backbone events + destroy: Backbone.Model.prototype.destroy });
3e9c692ef04e33826b4ed31d63651aa6f6aa6516
server/controllers/sampleCtrl.js
server/controllers/sampleCtrl.js
'use strict' /** * Sample API controller. Can safely be removed. */ const Sample = require('../models').sample.Sample const co = require('co') module.exports = { getData: co.wrap(getData), postData: co.wrap(postData) } function * getData (req, res, next) { try { const doc = yield Sample.findById(req.params.id) if (!doc) { return next() } res.json({ id: doc._id, name: doc.name }) } catch (err) { next(err) } } function * postData (req, res, next) { try { let doc = yield Sample.findById(req.params.id) if (!doc) { doc = new Sample({ _id: req.params.id, name: req.body.name }) } else { doc.name = req.body.name } yield doc.save() res.json({ id: doc._id, name: doc.name }) } catch (err) { next(err) } }
'use strict' /** * Sample API controller. Can safely be removed. */ const Sample = require('../models').sample.Sample const co = require('co') module.exports = { getData: co.wrap(getData), postData: co.wrap(postData) } function * getData (req, res, next) { try { let doc = {} if (process.env.NODE_MOCK) { doc = yield {_id: 0, name: 'mockdata'} } else { doc = yield Sample.findById(req.params.id) } if (!doc) { return next() } res.json({ id: doc._id, name: doc.name }) } catch (err) { next(err) } } function * postData (req, res, next) { try { let doc = yield Sample.findById(req.params.id) if (!doc) { doc = new Sample({ _id: req.params.id, name: req.body.name }) } else { doc.name = req.body.name } yield doc.save() res.json({ id: doc._id, name: doc.name }) } catch (err) { next(err) } }
Support for startMock mode in getData
Support for startMock mode in getData
JavaScript
mit
KTH/lms-export-results
--- +++ @@ -14,7 +14,12 @@ function * getData (req, res, next) { try { - const doc = yield Sample.findById(req.params.id) + let doc = {} + if (process.env.NODE_MOCK) { + doc = yield {_id: 0, name: 'mockdata'} + } else { + doc = yield Sample.findById(req.params.id) + } if (!doc) { return next()
2848d099199c841f64c7c66ce33775e0bc25bc59
test/torpedo-build-test.js
test/torpedo-build-test.js
var fs = require('fs') , path = require('path') , expect = require('chai').expect , shell = require('shelljs') , glob = require('glob') , _ = require('lodash') function read(filename) { return fs.readFileSync(filename, 'utf8') } function fixture(name) { return read('test/fixtures/' + name + '.html') } function readGenerated(filename, destination) { var loc = path.resolve(destination || '_site', filename) return read(loc, 'utf8').trim() } function readExpected(filename) { var loc = path.resolve('../expected', filename) return read(loc, 'utf8').trim() } function clean() { shell.rm('-rf', '_site'); } function filesOnly(file) { return fs.statSync(file).isFile() } describe('torpedo', function() { beforeEach(clean) after(clean) describe('build', function() { it('should build the site', function(done) { var spawn = require('child_process').spawn , child = spawn('torpedo', ['build'], {cwd: 'test/src'}) child.on('close', function() { var generatedFiles = glob.sync('test/src/_site/**/*').filter(filesOnly) , expectedFiles = glob.sync('test/expected/**/*').filter(filesOnly) _.times(expectedFiles.length, function(i) { expect(read(expectedFiles[i])).to.equal(read(generatedFiles[i])) }) done() }) }) }) })
var fs = require('fs') , path = require('path') , expect = require('chai').expect , shell = require('shelljs') , glob = require('glob') , _ = require('lodash') function read(filename) { return fs.readFileSync(filename, 'utf8') } function fixture(name) { return read('test/fixtures/' + name + '.html') } function clean() { shell.rm('-rf', 'test/src/_site'); } function filesOnly(file) { return fs.statSync(file).isFile() } describe('torpedo', function() { beforeEach(clean) after(clean) describe('build', function() { it('should build the site', function(done) { var spawn = require('child_process').spawn , child = spawn('torpedo', ['build'], {cwd: 'test/src'}) child.on('close', function() { var generatedFiles = glob.sync('test/src/_site/**/*').filter(filesOnly) , expectedFiles = glob.sync('test/expected/**/*').filter(filesOnly) _.times(expectedFiles.length, function(i) { expect(read(expectedFiles[i])).to.equal(read(generatedFiles[i])) }) done() }) }) }) })
Fix tests to delete the _site directory after running.
Fix tests to delete the _site directory after running.
JavaScript
mit
philipwalton/ingen
--- +++ @@ -13,18 +13,8 @@ return read('test/fixtures/' + name + '.html') } -function readGenerated(filename, destination) { - var loc = path.resolve(destination || '_site', filename) - return read(loc, 'utf8').trim() -} - -function readExpected(filename) { - var loc = path.resolve('../expected', filename) - return read(loc, 'utf8').trim() -} - function clean() { - shell.rm('-rf', '_site'); + shell.rm('-rf', 'test/src/_site'); } function filesOnly(file) {
20d900a89125cf0141e31b14f43ff65265aab505
js/utils.js
js/utils.js
function numberToString(number) { var r = Math.round(number * 1000) / 1000; return ""+r; } function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } function numberToStringFormatted(number) { var number = Number(number); if(number > 1000000) { return number.toPrecision(3); } else { number = Math.round(number * 1000) / 1000; return addCommas(number); } }
function numberToString(number) { var r = Math.round(number * 1000) / 1000; return ""+r; } /** * There are some difficulties with locales with this script's number * output (when number > 1e21) and Clicker Heroes' input formatting. * This function makes sure there are no decimal points in the output. */ function numberToClickerHeroesPasteableString(number) { var b = Math.floor(Math.log(number)/Math.log(10)); if(b >= 21) { var intPart; intPart = Math.round(number / Math.pow(10, b-10)); return intPart + "e" + (b-10); } else { return ""+number; } } function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } function numberToStringFormatted(number) { var number = Number(number); if(number > 1000000) { return number.toPrecision(3); } else { number = Math.round(number * 1000) / 1000; return addCommas(number); } }
Make sure there are no decimal points in the (pasteable) level change output.
Make sure there are no decimal points in the (pasteable) level change output.
JavaScript
mit
Beskhue/ClickerHeroesCalculator,Beskhue/ClickerHeroesCalculator
--- +++ @@ -1,6 +1,22 @@ function numberToString(number) { var r = Math.round(number * 1000) / 1000; return ""+r; +} + +/** + * There are some difficulties with locales with this script's number + * output (when number > 1e21) and Clicker Heroes' input formatting. + * This function makes sure there are no decimal points in the output. + */ +function numberToClickerHeroesPasteableString(number) { + var b = Math.floor(Math.log(number)/Math.log(10)); + if(b >= 21) { + var intPart; + intPart = Math.round(number / Math.pow(10, b-10)); + return intPart + "e" + (b-10); + } else { + return ""+number; + } } function addCommas(nStr)
be3aac36283d562d94f358e81de722e1854f56b7
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); gulp.task('default', ['sass'], function () { //gulp.src('./node_modules/font-awesome/fonts/**/*.{eot,svg,ttf,woff,woff2}') // .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/fonts')); }); gulp.task('sass', function () { return gulp.src('./styles/warriormachines_2016/theme/sass/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/css')); }); gulp.task('sass:watch', function () { gulp.watch('./styles/warriormachines_2016/theme/sass/*.scss', ['sass']); });
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); gulp.task('default', ['sass', 'fonts'], function () { }); gulp.task('sass', function () { return gulp.src('./styles/warriormachines_2016/theme/sass/app.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/css')); }); gulp.task('fonts', function() { gulp.src('./node_modules/font-awesome/fonts/**/*.{eot,svg,ttf,woff,woff2}') .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/fonts')); }); gulp.task('sass:watch', function () { gulp.watch('./styles/warriormachines_2016/theme/sass/app.scss', ['sass']); });
Use gulp to generate one app.css, and separate 'fonts' task
Use gulp to generate one app.css, and separate 'fonts' task
JavaScript
mit
WarriorMachines/warriormachines-phpbb,WarriorMachines/warriormachines-phpbb,WarriorMachines/warriormachines-phpbb
--- +++ @@ -3,17 +3,21 @@ var gulp = require('gulp'); var sass = require('gulp-sass'); -gulp.task('default', ['sass'], function () { - //gulp.src('./node_modules/font-awesome/fonts/**/*.{eot,svg,ttf,woff,woff2}') - // .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/fonts')); +gulp.task('default', ['sass', 'fonts'], function () { + }); gulp.task('sass', function () { - return gulp.src('./styles/warriormachines_2016/theme/sass/*.scss') + return gulp.src('./styles/warriormachines_2016/theme/sass/app.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/css')); }); +gulp.task('fonts', function() { + gulp.src('./node_modules/font-awesome/fonts/**/*.{eot,svg,ttf,woff,woff2}') + .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/fonts')); +}); + gulp.task('sass:watch', function () { - gulp.watch('./styles/warriormachines_2016/theme/sass/*.scss', ['sass']); + gulp.watch('./styles/warriormachines_2016/theme/sass/app.scss', ['sass']); });
e1be3b7fdd59ba71c3e2d5ffd626fd7877431401
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var gutil = require('gulp-util'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var webpackConfig = require('./webpack.config.js'); var open = require('gulp-open'); var mocha = require('gulp-mocha'); // default task is browser test gulp.task('default', ['browser-test']); // browser test gulp.task('browser-test', function (callback) { var myConfig = Object.create(webpackConfig); myConfig.devtool = 'eval'; myConfig.debug = true; new WebpackDevServer(webpack(myConfig), { publicPath: '/' + myConfig.output.publicPath, stats: { colors: true } }).listen(8080, 'localhost', function (err) { if (err) throw new gutil.PluginError('webpack-dev-server', err); gulp.src('./test/index.html') .pipe(open('', {url: 'http://localhost:8080/test/index.html'})); }); }); // node.js test gulp.task('test', function (callback) { gulp.src('test/solve-quadratic-equation_test.js', {read: false}) .pipe(mocha({reporter: 'nyan'})); });
var gulp = require('gulp'); var gutil = require('gulp-util'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var webpackConfig = require('./webpack.config.js'); var open = require('gulp-open'); var mocha = require('gulp-mocha'); // default task is browser test gulp.task('default', ['browser-test']); // browser test gulp.task('browser-test', function (callback) { var myConfig = Object.create(webpackConfig); myConfig.devtool = 'eval'; myConfig.debug = true; new WebpackDevServer(webpack(myConfig), { publicPath: '/' + myConfig.output.publicPath, stats: { colors: true } }).listen(8080, 'localhost', function (err) { if (err) throw new gutil.PluginError('webpack-dev-server', err); gulp.src('./test/index.html') .pipe(open('', {url: 'http://localhost:8080/webpack-dev-server/test/index.html'})); }); }); // node.js test gulp.task('test', function (callback) { gulp.src('test/solve-quadratic-equation_test.js', {read: false}) .pipe(mocha({reporter: 'nyan'})); });
Enable automatic browser reload in browser-test task
Enable automatic browser reload in browser-test task
JavaScript
mit
hnakamur/solve-quadratic-equation.js,hnakamur/solve-quadratic-equation.js
--- +++ @@ -24,7 +24,7 @@ if (err) throw new gutil.PluginError('webpack-dev-server', err); gulp.src('./test/index.html') - .pipe(open('', {url: 'http://localhost:8080/test/index.html'})); + .pipe(open('', {url: 'http://localhost:8080/webpack-dev-server/test/index.html'})); }); });
7513968732441a2bd3ecd720d821e12a1311a38b
installer/js/setup/repositories/RepositoryList.js
installer/js/setup/repositories/RepositoryList.js
import React, { Component, PropTypes } from 'react'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; import Repository from './Repository'; import Pagination from './Pagination'; const accessToken = window.localStorage.accessToken; const user = JSON.parse(window.localStorage.user); class RepositoryList extends Component { constructor(props) { super(props); this.state = { page: 1, hasNext: false, loading: true, repositories: [], }; } fetchRepositories = page => getRepositories(accessToken, user, page); componentWillMount() { this.fetchRepositories(this.state.page) .then(repositories => this.setState({ repositories })); } onPageChange = page => () => { this.fetchRepositories(page) .then(repositories => this.setState({ page, repositories, })); }; render() { return ( <div> <Table> <TableBody> {this.state.repositories.map(repository => ( <Repository key={repository.id} repository={repository} /> ))} </TableBody> </Table> {/* to be implemented <Pagination hasNext={true} page={2} onChange={this.onPageChange} />*/} </div> ); }; } export default RepositoryList;
import React, { Component, PropTypes } from 'react'; import Progress from 'material-ui/CircularProgress'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; import Repository from './Repository'; import Pagination from './Pagination'; const accessToken = window.localStorage.accessToken; const user = JSON.parse(window.localStorage.user); class RepositoryList extends Component { constructor(props) { super(props); this.state = { page: 1, hasNext: false, loading: true, repositories: [], }; } fetchRepositories = page => getRepositories(accessToken, user, page); componentWillMount() { this.fetchRepositories(this.state.page) .then(repositories => this.setState({ repositories, loading: false })); } onPageChange = page => () => { this.fetchRepositories(page) .then(repositories => this.setState({ page, repositories, })); }; render() { return ( <div> {this.state.loading && <div style={{ textAlign: 'center' }}> <Progress size={60} thickness={5} /> </div>} <Table> <TableBody> {this.state.repositories.map(repository => ( <Repository key={repository.id} repository={repository} /> ))} </TableBody> </Table> {/* to be implemented <Pagination hasNext={true} page={2} onChange={this.onPageChange} />*/} </div> ); }; } export default RepositoryList;
Add a loader while loading repositories
Add a loader while loading repositories
JavaScript
mit
marmelab/sedbot.js
--- +++ @@ -1,4 +1,5 @@ import React, { Component, PropTypes } from 'react'; +import Progress from 'material-ui/CircularProgress'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; @@ -24,7 +25,7 @@ componentWillMount() { this.fetchRepositories(this.state.page) - .then(repositories => this.setState({ repositories })); + .then(repositories => this.setState({ repositories, loading: false })); } onPageChange = page => () => { @@ -38,6 +39,9 @@ render() { return ( <div> + {this.state.loading && <div style={{ textAlign: 'center' }}> + <Progress size={60} thickness={5} /> + </div>} <Table> <TableBody> {this.state.repositories.map(repository => (
2664f207be053a02a4c9866c8794b95901fe4aaa
lib/main.js
lib/main.js
/* See license.txt for terms of usage */ "use strict"; const { Cu, Ci } = require("chrome"); const { Firebug } = require("./firebug.js"); const { Trace } = require("./trace.js"); const { gDevTools } = Cu.import("resource:///modules/devtools/gDevTools.jsm", {}); // Entry points of the extension. Both 'main' and 'onUnload' methods are // exported from this module and executed automatically by Add-ons SDK. function main(options, callbacks) { Trace.sysout("main; ", options); // Instantiate the main application object (a singleton). There is one // Firebug instance shared across all browser windows. var firebug = new Firebug(options); // Hook developer tools events to maintain Firebug object life time. gDevTools.on("toolbox-ready", firebug.onToolboxReady.bind(firebug)); gDevTools.on("toolbox-destroyed", firebug.onToolboxDestroyed.bind(firebug)); } function onUnload(reason) { firebug.shutdown(reason) } // Exports from this module exports.main = main; exports.onUnload = onUnload;
/* See license.txt for terms of usage */ "use strict"; const { Cu, Ci } = require("chrome"); const { Firebug } = require("./firebug.js"); const { Trace } = require("./trace.js"); const { gDevTools } = Cu.import("resource:///modules/devtools/gDevTools.jsm", {}); // The application (singleton) var firebug; // Entry points of the extension. Both 'main' and 'onUnload' methods are // exported from this module and executed automatically by Add-ons SDK. function main(options, callbacks) { Trace.sysout("main; ", options); // Instantiate the main application object (a singleton). There is one // Firebug instance shared across all browser windows. firebug = new Firebug(options); // Hook developer tools events to maintain Firebug object life time. gDevTools.on("toolbox-ready", firebug.onToolboxReady.bind(firebug)); gDevTools.on("toolbox-destroyed", firebug.onToolboxDestroyed.bind(firebug)); gDevTools.on("pref-changed", firebug.updateOption.bind(firebug)); } function onUnload(reason) { firebug.shutdown(reason) } // Exports from this module exports.main = main; exports.onUnload = onUnload;
Fix undefined variable in onUnload
Fix undefined variable in onUnload
JavaScript
bsd-3-clause
firebug/firebug.next,bmdeveloper/firebug.next,bmdeveloper/firebug.next,vlajos/firebug.next,vlajos/firebug.next,firebug/firebug.next
--- +++ @@ -7,6 +7,9 @@ const { Trace } = require("./trace.js"); const { gDevTools } = Cu.import("resource:///modules/devtools/gDevTools.jsm", {}); +// The application (singleton) +var firebug; + // Entry points of the extension. Both 'main' and 'onUnload' methods are // exported from this module and executed automatically by Add-ons SDK. function main(options, callbacks) { @@ -14,11 +17,12 @@ // Instantiate the main application object (a singleton). There is one // Firebug instance shared across all browser windows. - var firebug = new Firebug(options); + firebug = new Firebug(options); // Hook developer tools events to maintain Firebug object life time. gDevTools.on("toolbox-ready", firebug.onToolboxReady.bind(firebug)); gDevTools.on("toolbox-destroyed", firebug.onToolboxDestroyed.bind(firebug)); + gDevTools.on("pref-changed", firebug.updateOption.bind(firebug)); } function onUnload(reason) {
7930c5a16744f6464a126ebe739704dadeca9382
lib/main.js
lib/main.js
"use babel"; export default { config: { executable: { type: "string", default: "gfortran" }, gfortran_flags: { type: "string", default: "-Wall -Wextra" }, }, activate: () => { require("atom-package-deps").install("linter-gfortran"); }, provideLinter: () => { const helpers = require("atom-linter"); const regex = "(?<file>.+):(?<line>\\d+):(?<col>\\d+):((.|\\n)*)(?<type>(Error|Warning|Note)):\\s*(?<message>.*)"; const tmpdir = require('tmp').dirSync().name; return { name: "gfortran", grammarScopes: ["source.fortran.free"], scope: "file", lintOnFly: false, lint: (activeEditor) => { const command = atom.config.get("linter-gfortran.executable"); const file = activeEditor.getPath(); const args = ["-fsyntax-only", "-J", tmpdir]; args.push(file); return helpers.exec(command, args, {stream: "stderr"}).then(output => helpers.parse(output, regex) ); } }; } };
"use babel"; export default { config: { executable: { type: "string", default: "gfortran" }, gfortran_flags: { type: "string", default: "-Wall -Wextra" }, }, activate: () => { require("atom-package-deps").install("linter-gfortran"); }, provideLinter: () => { const helpers = require("atom-linter"); const regex = "(?<file>.+):(?<line>\\d+):(?<col>\\d+):((.|\\n)*)(?<type>(Error|Warning|Note)):\\s*(?<message>.*)"; const tmpdir = require('tmp').dirSync().name; return { name: "gfortran", grammarScopes: [ "source.fortran.free", "source.fortran.fixed", "source.fortran.modern", "source.fortran.punchcard" ], scope: "file", lintOnFly: false, lint: (activeEditor) => { const command = atom.config.get("linter-gfortran.executable"); const file = activeEditor.getPath(); const args = ["-fsyntax-only", "-J", tmpdir]; args.push(file); return helpers.exec(command, args, {stream: "stderr"}).then(output => helpers.parse(output, regex) ); } }; } };
Support all the fortran grammars
Support all the fortran grammars
JavaScript
mit
Luthaf/linter-gfortran
--- +++ @@ -22,7 +22,12 @@ const tmpdir = require('tmp').dirSync().name; return { name: "gfortran", - grammarScopes: ["source.fortran.free"], + grammarScopes: [ + "source.fortran.free", + "source.fortran.fixed", + "source.fortran.modern", + "source.fortran.punchcard" + ], scope: "file", lintOnFly: false, lint: (activeEditor) => {
27ad5450c62de6fee222e6298901b3101a097930
src/transform-data.js
src/transform-data.js
"use strict" /** * Inverts the data from the deepstream structure to reduce nesting. * * { _v: 1, _d: { name: 'elasticsearch' } } -> { name: 'elasticsearch', __ds = { _v: 1 } } * * @param {String} value The data to save * * @private * @returns {Object} data */ module.exports.transformValueForStorage = function ( value ) { var data = value._d delete value._d data.__ds = value return data } /** * Inverts the data from the stored structure back to the deepstream structure * * { name: 'elasticsearch', __ds = { _v: 1 } } -> { _v: 1, _d: { name: 'elasticsearch' } } * * @param {String} value The data to transform * * @private * @returns {Object} data */ module.exports.transformValueFromStorage = function( value ) { var data = value.__ds delete value.__ds data._d = value return data }
"use strict" /** * Inverts the data from the deepstream structure to reduce nesting. * * { _v: 1, _d: { name: 'elasticsearch' } } -> { name: 'elasticsearch', __ds = { _v: 1 } } * * @param {String} value The data to save * * @private * @returns {Object} data */ module.exports.transformValueForStorage = function ( value ) { value = JSON.parse( JSON.stringify( value ) ) var data = value._d delete value._d data.__ds = value return data } /** * Inverts the data from the stored structure back to the deepstream structure * * { name: 'elasticsearch', __ds = { _v: 1 } } -> { _v: 1, _d: { name: 'elasticsearch' } } * * @param {String} value The data to transform * * @private * @returns {Object} data */ module.exports.transformValueFromStorage = function( value ) { var data = value.__ds delete value.__ds data._d = value return data }
Clone data to avoid mutations to effect rest of workflow
Clone data to avoid mutations to effect rest of workflow
JavaScript
mit
hoxton-one/deepstream.io-storage-rethinkdb
--- +++ @@ -11,6 +11,7 @@ * @returns {Object} data */ module.exports.transformValueForStorage = function ( value ) { + value = JSON.parse( JSON.stringify( value ) ) var data = value._d delete value._d data.__ds = value
0b8d55b196164dc7dfdef644ee95806f2d5dac59
packages/kolibri-tools/jest.conf/setup.js
packages/kolibri-tools/jest.conf/setup.js
import 'intl'; import 'intl/locale-data/jsonp/en.js'; import * as Aphrodite from 'aphrodite'; import * as AphroditeNoImportant from 'aphrodite/no-important'; import Vue from 'vue'; import VueMeta from 'vue-meta'; import VueRouter from 'vue-router'; import Vuex from 'vuex'; import { i18nSetup } from 'kolibri.utils.i18n'; import KThemePlugin from 'kolibri-components/src/KThemePlugin'; import KContentPlugin from 'kolibri-components/src/content/KContentPlugin'; Aphrodite.StyleSheetTestUtils.suppressStyleInjection(); AphroditeNoImportant.StyleSheetTestUtils.suppressStyleInjection(); // Register Vue plugins and components Vue.use(Vuex); Vue.use(VueRouter); Vue.use(VueMeta); Vue.use(KThemePlugin); Vue.use(KContentPlugin); Vue.config.silent = true; Vue.config.devtools = false; Vue.config.productionTip = false; i18nSetup(true); const csrf = global.document.createElement('input'); csrf.name = 'csrfmiddlewaretoken'; csrf.value = 'csrfmiddlewaretoken'; global.document.body.append(csrf); Object.defineProperty(window, 'scrollTo', { value: () => {}, writable: true });
import 'intl'; import 'intl/locale-data/jsonp/en.js'; import * as Aphrodite from 'aphrodite'; import * as AphroditeNoImportant from 'aphrodite/no-important'; import Vue from 'vue'; import VueMeta from 'vue-meta'; import VueRouter from 'vue-router'; import Vuex from 'vuex'; import { i18nSetup } from 'kolibri.utils.i18n'; import KThemePlugin from 'kolibri-components/src/KThemePlugin'; import KContentPlugin from 'kolibri-components/src/content/KContentPlugin'; Aphrodite.StyleSheetTestUtils.suppressStyleInjection(); AphroditeNoImportant.StyleSheetTestUtils.suppressStyleInjection(); // Register Vue plugins and components Vue.use(Vuex); Vue.use(VueRouter); Vue.use(VueMeta); Vue.use(KThemePlugin); Vue.use(KContentPlugin); Vue.config.silent = true; Vue.config.devtools = false; Vue.config.productionTip = false; i18nSetup(true); const csrf = global.document.createElement('input'); csrf.name = 'csrfmiddlewaretoken'; csrf.value = 'csrfmiddlewaretoken'; global.document.body.append(csrf); Object.defineProperty(window, 'scrollTo', { value: () => {}, writable: true }); // Uncomment to see better errors from Node process.on('unhandledRejection', (reason, p) => { console.log('Unhandled Rejection at: Promise', p, 'reason:', reason); console.log(reason.stack); });
Add extra logging for node promises
Add extra logging for node promises
JavaScript
mit
indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,mrpau/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri
--- +++ @@ -33,3 +33,9 @@ global.document.body.append(csrf); Object.defineProperty(window, 'scrollTo', { value: () => {}, writable: true }); + +// Uncomment to see better errors from Node +process.on('unhandledRejection', (reason, p) => { + console.log('Unhandled Rejection at: Promise', p, 'reason:', reason); + console.log(reason.stack); +});
1242956b0fc4ef7300c78c50c087d30a60b963d4
source/configuration.js
source/configuration.js
const fs = require("fs"); const path = require("path"); function getValue(obj, pathArr, def) { let nextPath = pathArr.shift(); if (nextPath) { return (pathArr.length > 0) ? (obj.hasOwnProperty(nextPath) ? getValue(obj[nextPath], pathArr, def) : def) : obj[nextPath] || def; } return obj || def; } class Configuration { constructor(data = {}) { this.config = data; } get(path, def) { return getValue(this.config, path.split("."), def); } } Configuration.loadFromFile = function(filename, allowEmpty = false) { let fileContents; try { fileContents = JSON.parse(fs.readFileSync(filename)); } catch (err) { if (allowEmpty) { console.log("No configuration found locally, loading defaults..."); // @todo load defaults return new Configuration(); } else { throw err; } } return new Configuration(fileContents); }; Configuration.loadLocalConfig = function() { return Configuration.loadFromFile(path.resolve(__dirname, "../config.json"), true); }; module.exports = Configuration;
const fs = require("fs"); const path = require("path"); const fileExists = require("file-exists"); function getValue(obj, pathArr, def) { let nextPath = pathArr.shift(); if (nextPath) { return (pathArr.length > 0) ? (obj.hasOwnProperty(nextPath) ? getValue(obj[nextPath], pathArr, def) : def) : obj[nextPath] || def; } return obj || def; } function placeConfig(configPath) { if (fileExists(configPath) !== true) { const baseConfigPath = path.resolve(__dirname, "../resources/config.base.json"); let baseConfig = fs.readFileSync(baseConfigPath, "utf8"); fs.writeFileSync(configPath, baseConfig, "utf8"); } } class Configuration { constructor(data = {}) { this.config = data; } get(path, def) { return getValue(this.config, path.split("."), def); } } Configuration.loadFromFile = function(filename, allowEmpty = false) { let fileContents; try { fileContents = JSON.parse(fs.readFileSync(filename)); } catch (err) { if (allowEmpty) { console.log("No configuration found locally, loading defaults..."); // @todo load defaults return new Configuration(); } else { throw err; } } return new Configuration(fileContents); }; Configuration.loadLocalConfig = function() { let configPath = path.resolve(__dirname, "../config.json"); placeConfig(configPath); return Configuration.loadFromFile(configPath, true); }; module.exports = Configuration;
Create config.json if not exists
Create config.json if not exists
JavaScript
mit
buttercup-pw/buttercup-server
--- +++ @@ -1,5 +1,7 @@ const fs = require("fs"); const path = require("path"); + +const fileExists = require("file-exists"); function getValue(obj, pathArr, def) { let nextPath = pathArr.shift(); @@ -9,6 +11,14 @@ obj[nextPath] || def; } return obj || def; +} + +function placeConfig(configPath) { + if (fileExists(configPath) !== true) { + const baseConfigPath = path.resolve(__dirname, "../resources/config.base.json"); + let baseConfig = fs.readFileSync(baseConfigPath, "utf8"); + fs.writeFileSync(configPath, baseConfig, "utf8"); + } } class Configuration { @@ -40,7 +50,9 @@ }; Configuration.loadLocalConfig = function() { - return Configuration.loadFromFile(path.resolve(__dirname, "../config.json"), true); + let configPath = path.resolve(__dirname, "../config.json"); + placeConfig(configPath); + return Configuration.loadFromFile(configPath, true); }; module.exports = Configuration;
1da816b0cbe307f3cb8ea74dc368e460d7eb16c2
packages/workflow/tests/dummy/config/environment.js
packages/workflow/tests/dummy/config/environment.js
/* eslint-env node */ 'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* eslint-env node */ 'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } return ENV; };
Remove empty block for eslint happiness
Remove empty block for eslint happiness
JavaScript
mit
cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack
--- +++ @@ -43,9 +43,5 @@ ENV.APP.rootElement = '#ember-testing'; } - if (environment === 'production') { - - } - return ENV; };
ade9f35525d169ada126e66ced7be3e51ba5a4ef
src/helpers.js
src/helpers.js
"use strict"; // Bind event listeners to target. export function on (target, eventName, listener, capture = false) { return target.addEventListener(eventName, listener, capture); } // Unbind event listeners export function off (target, eventName, listener, capture = false) { target.removeEventListener(eventName, listener, capture); } // "No operation" function. export function noop () {} export function fullscreenElement () { return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement; } export function fullscreenEnabled () { return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled; } // Request fullscreen for given element. export function enterFullscreen (element) { if(element.requestFullscreen) { element.requestFullscreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if(element.msRequestFullscreen) { element.msRequestFullscreen(); } } // Exit fullscreen export function exitFullscreen () { if(document.exitFullscreen) { document.exitFullscreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if(document.msExitFullscreen) { document.msExitFullscreen(); } }
"use strict"; // Bind event listeners to target. export function on (el, events, cb, capture = false) { events.split(' ').map(event => { if (event) el.addEventListener(event, cb, capture); }); } // Unbind event listeners export function off (el, events, cb, capture = false) { events.split(' ').map(event => { if (event) el.removeEventListener(event, cb, capture); }); } // "No operation" function. export function noop () {} export function fullscreenElement () { return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement; } export function fullscreenEnabled () { return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled; } // Request fullscreen for given element. export function enterFullscreen (element) { if(element.requestFullscreen) { element.requestFullscreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if(element.msRequestFullscreen) { element.msRequestFullscreen(); } } // Exit fullscreen export function exitFullscreen () { if(document.exitFullscreen) { document.exitFullscreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if(document.msExitFullscreen) { document.msExitFullscreen(); } }
Add support to bind to multiple events in one call.
Add support to bind to multiple events in one call.
JavaScript
mit
Andreyco/react-video,Andreyco/react-video
--- +++ @@ -1,24 +1,32 @@ "use strict"; // Bind event listeners to target. -export function on (target, eventName, listener, capture = false) { - return target.addEventListener(eventName, listener, capture); +export function on (el, events, cb, capture = false) { + events.split(' ').map(event => { + if (event) el.addEventListener(event, cb, capture); + }); } // Unbind event listeners -export function off (target, eventName, listener, capture = false) { - target.removeEventListener(eventName, listener, capture); +export function off (el, events, cb, capture = false) { + events.split(' ').map(event => { + if (event) el.removeEventListener(event, cb, capture); + }); } // "No operation" function. export function noop () {} export function fullscreenElement () { - return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement; + return document.fullscreenElement || + document.mozFullScreenElement || + document.webkitFullscreenElement; } export function fullscreenEnabled () { - return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled; + return document.fullscreenEnabled || + document.mozFullScreenEnabled || + document.webkitFullscreenEnabled; } // Request fullscreen for given element.
ccfc6e5850fa6de5b821a292eab02c9755bd2062
src/number.js
src/number.js
'use strict'; var card = require('creditcards').card; module.exports = function ($parse) { return { restrict: 'A', require: ['ngModel', 'ccNumber'], controller: function () { var expectedType; this.expect = function (type) { expectedType = type; }; }, compile: function (element, attributes) { attributes.$set('pattern', '[0-9]*'); return function (scope, element, attributes, controllers) { var ngModelController = controllers[0]; var ccNumberController = controllers[1]; scope.$watch(attributes.ngModel, function (number) { ngModelController.$ccType = ccNumberController.type = card.type(number); }); scope.$watch(attributes.ccType, function (type) { ccNumberController.expect(type); ngModelController.$validate(); }); ngModelController.$parsers.unshift(function (number) { return card.parse(number); }); ngModelController.$validators.ccNumber = function (number) { return card.isValid(number); }; ngModelController.$validators.ccNumberType = function (number) { return card.isValid(number, $parse(attributes.ccType)(scope)); }; }; } }; }; module.exports.$inject = ['$parse'];
'use strict'; var card = require('creditcards').card; module.exports = function ($parse) { return { restrict: 'A', require: ['ngModel', 'ccNumber'], controller: function () { this.type = null; }, compile: function (element, attributes) { attributes.$set('pattern', '[0-9]*'); return function (scope, element, attributes, controllers) { var ngModelController = controllers[0]; var ccNumberController = controllers[1]; scope.$watch(attributes.ngModel, function (number) { ngModelController.$ccType = ccNumberController.type = card.type(number); }); scope.$watch(attributes.ccType, function (type) { ngModelController.$validate(); }); ngModelController.$parsers.unshift(function (number) { return card.parse(number); }); ngModelController.$validators.ccNumber = function (number) { return card.isValid(number); }; ngModelController.$validators.ccNumberType = function (number) { return card.isValid(number, $parse(attributes.ccType)(scope)); }; }; } }; }; module.exports.$inject = ['$parse'];
Remove dead code from ccNumber controller
Remove dead code from ccNumber controller
JavaScript
mit
SimeonC/angular-credit-cards,matiasarayac/angular-credit-cards,Noxwille/angular-credit-cards,bendrucker/angular-credit-cards,antoinepairet/angular-credit-cards,dingels35/angular-credit-cards,dribehance/angular-credit-cards,aspone/angular-credit-cards,robertbaker/angular-credit-cards
--- +++ @@ -7,10 +7,7 @@ restrict: 'A', require: ['ngModel', 'ccNumber'], controller: function () { - var expectedType; - this.expect = function (type) { - expectedType = type; - }; + this.type = null; }, compile: function (element, attributes) { attributes.$set('pattern', '[0-9]*'); @@ -24,7 +21,6 @@ }); scope.$watch(attributes.ccType, function (type) { - ccNumberController.expect(type); ngModelController.$validate(); });
ad45bd67ba40b86954e5649f04ef5c42258bf6d4
packages/ember-runtime/tests/array/invoke-test.js
packages/ember-runtime/tests/array/invoke-test.js
import EmberObject from '../../lib/system/object'; import { AbstractTestCase } from 'internal-test-helpers'; import { runArrayTests } from '../helpers/array'; class InvokeTests extends AbstractTestCase { '@test invoke should call on each object that implements'() { let cnt, ary, obj; function F(amt) { cnt += amt === undefined ? 1 : amt; } cnt = 0; ary = [ { foo: F }, EmberObject.create({ foo: F }), // NOTE: does not impl foo - invoke should just skip EmberObject.create({ bar: F }), { foo: F }, ]; obj = this.newObject(ary); obj.invoke('foo'); this.assert.equal(cnt, 3, 'should have invoked 3 times'); cnt = 0; obj.invoke('foo', 2); this.assert.equal(cnt, 6, 'should have invoked 3 times, passing param'); } } runArrayTests('invoke', InvokeTests);
import { Object as EmberObject, NativeArray } from '../../index'; import { AbstractTestCase } from 'internal-test-helpers'; import { runArrayTests } from '../helpers/array'; class InvokeTests extends AbstractTestCase { '@test invoke should call on each object that implements'() { let cnt, ary, obj; function F(amt) { cnt += amt === undefined ? 1 : amt; } cnt = 0; ary = [ { foo: F }, EmberObject.create({ foo: F }), // NOTE: does not impl foo - invoke should just skip EmberObject.create({ bar: F }), { foo: F }, ]; obj = this.newObject(ary); obj.invoke('foo'); this.assert.equal(cnt, 3, 'should have invoked 3 times'); cnt = 0; obj.invoke('foo', 2); this.assert.equal(cnt, 6, 'should have invoked 3 times, passing param'); } '@test invoke should return an array containing the results of each invoked method'(assert) { let obj = this.newObject([ { foo() { return 'one'; }, }, {}, // intentionally not including `foo` method { foo() { return 'two'; }, }, ]); let result = obj.invoke('foo'); assert.deepEqual(result, ['one', undefined, 'two']); } '@test invoke should return an extended array (aka Ember.A)'(assert) { let obj = this.newObject([{ foo() {} }, { foo() {} }]); let result = obj.invoke('foo'); assert.ok(NativeArray.detect(result), 'NativeArray has been applied'); } } runArrayTests('invoke', InvokeTests);
Add failing tests for `A().invoke()` not returning an `A`.
Add failing tests for `A().invoke()` not returning an `A`.
JavaScript
mit
bekzod/ember.js,knownasilya/ember.js,GavinJoyce/ember.js,kellyselden/ember.js,Turbo87/ember.js,elwayman02/ember.js,jaswilli/ember.js,cibernox/ember.js,kellyselden/ember.js,qaiken/ember.js,twokul/ember.js,qaiken/ember.js,mike-north/ember.js,stefanpenner/ember.js,asakusuma/ember.js,emberjs/ember.js,xiujunma/ember.js,twokul/ember.js,intercom/ember.js,asakusuma/ember.js,elwayman02/ember.js,elwayman02/ember.js,bekzod/ember.js,kanongil/ember.js,emberjs/ember.js,givanse/ember.js,kanongil/ember.js,asakusuma/ember.js,bekzod/ember.js,miguelcobain/ember.js,xiujunma/ember.js,intercom/ember.js,mike-north/ember.js,bekzod/ember.js,elwayman02/ember.js,cibernox/ember.js,GavinJoyce/ember.js,Turbo87/ember.js,sly7-7/ember.js,sandstrom/ember.js,cibernox/ember.js,givanse/ember.js,jaswilli/ember.js,thoov/ember.js,sandstrom/ember.js,twokul/ember.js,kanongil/ember.js,stefanpenner/ember.js,twokul/ember.js,mike-north/ember.js,kellyselden/ember.js,knownasilya/ember.js,GavinJoyce/ember.js,thoov/ember.js,givanse/ember.js,fpauser/ember.js,thoov/ember.js,qaiken/ember.js,givanse/ember.js,fpauser/ember.js,kanongil/ember.js,Turbo87/ember.js,mixonic/ember.js,mfeckie/ember.js,asakusuma/ember.js,mfeckie/ember.js,mixonic/ember.js,mixonic/ember.js,mfeckie/ember.js,qaiken/ember.js,kellyselden/ember.js,intercom/ember.js,fpauser/ember.js,xiujunma/ember.js,miguelcobain/ember.js,sandstrom/ember.js,jaswilli/ember.js,miguelcobain/ember.js,mfeckie/ember.js,intercom/ember.js,tildeio/ember.js,GavinJoyce/ember.js,miguelcobain/ember.js,Turbo87/ember.js,mike-north/ember.js,jaswilli/ember.js,cibernox/ember.js,xiujunma/ember.js,tildeio/ember.js,emberjs/ember.js,sly7-7/ember.js,knownasilya/ember.js,thoov/ember.js,sly7-7/ember.js,tildeio/ember.js,stefanpenner/ember.js,fpauser/ember.js
--- +++ @@ -1,4 +1,4 @@ -import EmberObject from '../../lib/system/object'; +import { Object as EmberObject, NativeArray } from '../../index'; import { AbstractTestCase } from 'internal-test-helpers'; import { runArrayTests } from '../helpers/array'; @@ -28,6 +28,33 @@ obj.invoke('foo', 2); this.assert.equal(cnt, 6, 'should have invoked 3 times, passing param'); } + + '@test invoke should return an array containing the results of each invoked method'(assert) { + let obj = this.newObject([ + { + foo() { + return 'one'; + }, + }, + {}, // intentionally not including `foo` method + { + foo() { + return 'two'; + }, + }, + ]); + + let result = obj.invoke('foo'); + assert.deepEqual(result, ['one', undefined, 'two']); + } + + '@test invoke should return an extended array (aka Ember.A)'(assert) { + let obj = this.newObject([{ foo() {} }, { foo() {} }]); + + let result = obj.invoke('foo'); + + assert.ok(NativeArray.detect(result), 'NativeArray has been applied'); + } } runArrayTests('invoke', InvokeTests);