commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
2c1b060470eb3cb5b9c876a3fe64ccebc1bdbcab
app/assets/javascripts/respondent/question_answered.js
app/assets/javascripts/respondent/question_answered.js
$(document).ready(function() { $(document).on('change', '.question-answered-box', function(){ the_id = $(this).data('the-id') text_answer_field = $(this).closest('.text-answer').find('.text-answer-field') matrix_answer_field = $(this).closest('.answer_fields_wrapper').find('.submission-matrix') if($(this).prop('checked')) { $(text_answer_field).attr("readonly", true) $(text_answer_field).addClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", true) $("li.answer-option-"+the_id+" textarea").attr("disabled", true) $("select#answers_"+the_id).attr("disabled", true) $(matrix_answer_field).find('select').attr("disabled", true) } else { $(text_answer_field).attr("disabled", false) $(text_answer_field).attr("readonly", false) $(text_answer_field).removeClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", false) $("li.answer-option-"+the_id+" textarea").attr("disabled", false) $("select#answers_"+the_id).attr("disabled", false) $(matrix_answer_field).find('select').attr("disabled", false) $('.sticky_save_all').click(); } }); });
$(document).ready(function() { $(document).on('change', '.question-answered-box', function(){ the_id = $(this).data('the-id') text_answer_field = $(this).closest('.text-answer').find('.text-answer-field') matrix_answer_field = $(this).closest('.answer_fields_wrapper').find('.submission-matrix') if($(this).prop('checked')) { $(text_answer_field).attr("readonly", true) $(text_answer_field).addClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", true) $("li.answer-option-"+the_id+" textarea").attr("disabled", true) $("select#answers_"+the_id).attr("disabled", true) $(matrix_answer_field).find('select').attr("disabled", true) $(matrix_answer_field).find('input').attr("disabled", true) } else { $(text_answer_field).attr("disabled", false) $(text_answer_field).attr("readonly", false) $(text_answer_field).removeClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", false) $("li.answer-option-"+the_id+" textarea").attr("disabled", false) $("select#answers_"+the_id).attr("disabled", false) $(matrix_answer_field).find('select').attr("disabled", false) $(matrix_answer_field).find('input').attr("disabled", false) $('.sticky_save_all').click(); } }); });
Mark as answered to disable all matrix input types
Mark as answered to disable all matrix input types
JavaScript
bsd-3-clause
unepwcmc/ORS,unepwcmc/ORS,unepwcmc/ORS,unepwcmc/ORS,unepwcmc/ORS
d76319bf9ba2d629fd21c1cd5ac90f0f5b8a9981
history-handler.js
history-handler.js
/* * Copyright (c) 2010 Kevin Decker (http://www.incaseofstairs.com/) * See LICENSE for license information */ var HistoryHandler = (function() { var currentHash, callbackFn; function loadHash() { return decodeURIComponent(/#(.*)$/.exec(location.href)[1]); } function checkHistory(){ var hashValue = loadHash(); if(hashValue !== currentHash) { currentHash = hashValue; callbackFn(currentHash); } } return { init: function(callback) { callbackFn = callback; currentHash = loadHash(); callbackFn(currentHash); setInterval(checkHistory, 500); }, store: function(state) { currentHash = state; location = "#" + encodeURIComponent(state); } } })();
/* * Copyright (c) 2010 Kevin Decker (http://www.incaseofstairs.com/) * See LICENSE for license information */ var HistoryHandler = (function() { var currentHash, callbackFn; function loadHash() { return decodeURIComponent(/#(.*)$/.exec((location.href || []))[1] || ""); } function checkHistory(){ var hashValue = loadHash(); if(hashValue !== currentHash) { currentHash = hashValue; callbackFn(currentHash); } } return { init: function(callback) { callbackFn = callback; currentHash = loadHash(); callbackFn(currentHash); setInterval(checkHistory, 500); }, store: function(state) { currentHash = state; location = "#" + encodeURIComponent(state); } } })();
Fix no hash case in history handler
Fix no hash case in history handler
JavaScript
bsd-3-clause
leonardohipolito/border-image-generator,kpdecker/border-image-generator,kpdecker/border-image-generator,leonardohipolito/border-image-generator
f6596240ba68ce13c08254cb864f0f353320e313
application/widgets/source/class/widgets/view/Start.js
application/widgets/source/class/widgets/view/Start.js
/* ************************************************************************ widgets Copyright: 2009 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /** * Start View */ qx.Class.define("widgets.view.Start", { extend : unify.view.StaticView, type : "singleton", members : { // overridden getTitle : function(type, param) { return "Start"; }, // overridden _createView : function() { var layer = new unify.ui.Layer(this); //var titlebar = new unify.ui.ToolBar(this); //layer.add(titlebar); /*var content = new unify.ui.Content; content.add("Hello World"); layer.add(content);*/ var layerWidget = new unify.ui.widget.core.Layer(layer); var cont = new unify.ui.widget.basic.Label("Das ist ein Test"); layerWidget.add(cont, { left: 50, top: 10 }); cont.set({ width: 100, height: 50 }); return layer; } } });
/* ************************************************************************ widgets Copyright: 2009 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /** * Start View */ qx.Class.define("widgets.view.Start", { extend : unify.view.StaticView, type : "singleton", members : { // overridden getTitle : function(type, param) { return "Start"; }, // overridden _createView : function() { var layer = new unify.ui.Layer(this); //var titlebar = new unify.ui.ToolBar(this); //layer.add(titlebar); /*var content = new unify.ui.Content; content.add("Hello World"); layer.add(content);*/ var layerWidget = new unify.ui.widget.core.Layer(layer); /*var cont = new unify.ui.widget.basic.Label("Das ist ein Test"); layerWidget.add(cont, { left: 50, top: 10 }); cont.set({ width: 100, height: 50 });*/ var scroller = new unify.ui.widget.container.Scroll(); layerWidget.add(scroller, { left: 50, top: 50 }); scroller.set({ width: 300, height: 300 }); var label = new unify.ui.widget.basic.Label("Das ist ein Test"); scroller.add(label, { left: 50, top: 10 }); label.set({ width: 100, height: 50 }); return layer; } } });
Add scroll area to test application
Add scroll area to test application
JavaScript
mit
unify/unify,unify/unify,unify/unify,unify/unify,unify/unify,unify/unify
5af993b0c7a5abbf3aca3816458cc8b73055a158
blueprints/factory/files/app/mirage/factories/__name__.js
blueprints/factory/files/app/mirage/factories/__name__.js
import Mirage, {faker} from 'ember-cli-mirage'; export default Mirage.Factory.extend({ });
import Mirage/*, {faker} */ from 'ember-cli-mirage'; export default Mirage.Factory.extend({ });
Update factory blueprint to pass JSHint
Update factory blueprint to pass JSHint JSHint complains about unused {faker} import in default factory.
JavaScript
mit
cs3b/ember-cli-mirage,LevelbossMike/ember-cli-mirage,lazybensch/ember-cli-mirage,jherdman/ember-cli-mirage,ballPointPenguin/ember-cli-mirage,cs3b/ember-cli-mirage,ballPointPenguin/ember-cli-mirage,jherdman/ember-cli-mirage,cibernox/ember-cli-mirage,lependu/ember-cli-mirage,mixonic/ember-cli-mirage,jerel/ember-cli-mirage,ronco/ember-cli-mirage,constantm/ember-cli-mirage,cibernox/ember-cli-mirage,IAmJulianAcosta/ember-cli-mirage,seawatts/ember-cli-mirage,jamesdixon/ember-cli-mirage,mydea/ember-cli-mirage,samselikoff/ember-cli-mirage,martinmaillard/ember-cli-mirage,makepanic/ember-cli-mirage,oliverbarnes/ember-cli-mirage,escobera/ember-cli-mirage,blimmer/ember-cli-mirage,kategengler/ember-cli-mirage,alecho/ember-cli-mirage,alvinvogelzang/ember-cli-mirage,jamesdixon/ember-cli-mirage,oliverbarnes/ember-cli-mirage,constantm/ember-cli-mirage,unchartedcode/ember-cli-mirage,seawatts/ember-cli-mirage,flexyford/ember-cli-mirage,unchartedcode/ember-cli-mirage,lazybensch/ember-cli-mirage,makepanic/ember-cli-mirage,jherdman/ember-cli-mirage,ronco/ember-cli-mirage,lependu/ember-cli-mirage,blimmer/ember-cli-mirage,jherdman/ember-cli-mirage,IAmJulianAcosta/ember-cli-mirage,jerel/ember-cli-mirage,mydea/ember-cli-mirage,ibroadfo/ember-cli-mirage,samselikoff/ember-cli-mirage,LevelbossMike/ember-cli-mirage,samselikoff/ember-cli-mirage,samselikoff/ember-cli-mirage,HeroicEric/ember-cli-mirage,alecho/ember-cli-mirage,ibroadfo/ember-cli-mirage,alvinvogelzang/ember-cli-mirage,HeroicEric/ember-cli-mirage,martinmaillard/ember-cli-mirage,unchartedcode/ember-cli-mirage,mixonic/ember-cli-mirage,kategengler/ember-cli-mirage,flexyford/ember-cli-mirage,unchartedcode/ember-cli-mirage,escobera/ember-cli-mirage
72e9f05a844f38eb03611625f5bc639c3c2a5f20
app/javascript/packs/application.js
app/javascript/packs/application.js
/* eslint no-console:0 */ // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. // // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb console.log('Hello World from Webpacker')
/* eslint no-console:0 */ // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. // // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb
Remove default message from webpack
Remove default message from webpack
JavaScript
mit
apvale/apvale.github.io,apvale/apvale.github.io,apvale/apvale.github.io
80d3bccc16c15681292e67edd69ec1631a4c63d1
chrome/browser/resources/net_internals/http_cache_view.js
chrome/browser/resources/net_internals/http_cache_view.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information on the HTTP cache. * @constructor */ function HttpCacheView() { const mainBoxId = 'http-cache-view-tab-content'; const statsDivId = 'http-cache-view-cache-stats'; DivView.call(this, mainBoxId); this.statsDiv_ = $(statsDivId); // Register to receive http cache info. g_browser.addHttpCacheInfoObserver(this); } inherits(HttpCacheView, DivView); HttpCacheView.prototype.onLoadLogFinish = function(data) { return this.onHttpCacheInfoChanged(data.httpCacheInfo); }; HttpCacheView.prototype.onHttpCacheInfoChanged = function(info) { this.statsDiv_.innerHTML = ''; if (!info) return false; // Print the statistics. var statsUl = addNode(this.statsDiv_, 'ul'); for (var statName in info.stats) { var li = addNode(statsUl, 'li'); addTextNode(li, statName + ': ' + info.stats[statName]); } return true; };
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information on the HTTP cache. */ var HttpCacheView = (function() { // IDs for special HTML elements in http_cache_view.html const MAIN_BOX_ID = 'http-cache-view-tab-content'; const STATS_DIV_ID = 'http-cache-view-cache-stats'; // We inherit from DivView. var superClass = DivView; /** * @constructor */ function HttpCacheView() { // Call superclass's constructor. superClass.call(this, MAIN_BOX_ID); this.statsDiv_ = $(STATS_DIV_ID); // Register to receive http cache info. g_browser.addHttpCacheInfoObserver(this); } cr.addSingletonGetter(HttpCacheView); HttpCacheView.prototype = { // Inherit the superclass's methods. __proto__: superClass.prototype, onLoadLogFinish: function(data) { return this.onHttpCacheInfoChanged(data.httpCacheInfo); }, onHttpCacheInfoChanged: function(info) { this.statsDiv_.innerHTML = ''; if (!info) return false; // Print the statistics. var statsUl = addNode(this.statsDiv_, 'ul'); for (var statName in info.stats) { var li = addNode(statsUl, 'li'); addTextNode(li, statName + ': ' + info.stats[statName]); } return true; } }; return HttpCacheView; })();
Refactor HttpCacheView to be defined inside an anonymous namespace.
Refactor HttpCacheView to be defined inside an anonymous namespace. BUG=90857 Review URL: http://codereview.chromium.org/7544008 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@94868 0039d316-1c4b-4281-b951-d872f2087c98
JavaScript
bsd-3-clause
PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,rogerwang/chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,patrickm/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,ltilve/chromium,junmin-zhu/chromium-rivertrail,keishi/chromium,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,robclark/chromium,ondra-novak/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,ltilve/chromium,Fireblend/chromium-crosswalk,ltilve/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,robclark/chromium,patrickm/chromium.src,robclark/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,keishi/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,chuan9/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,keishi/chromium,Jonekee/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,Just-D/chromium-1,keishi/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,timopulkkinen/BubbleFish,keishi/chromium,jaruba/chromium.src,rogerwang/chromium,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,zcbenz/cefode-chromium,Chilledheart/chromium,bright-sparks/chromium-spacewalk,robclark/chromium,M4sse/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,anirudhSK/chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,dushu1203/chromium.src,robclark/chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,anirudhSK/chromium,ltilve/chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,keishi/chromium,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,rogerwang/chromium,junmin-zhu/chromium-rivertrail,keishi/chromium,rogerwang/chromium,hujiajie/pa-chromium,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,dushu1203/chromium.src,robclark/chromium,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,Just-D/chromium-1,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,anirudhSK/chromium,jaruba/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,ltilve/chromium,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,markYoungH/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,robclark/chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,anirudhSK/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,markYoungH/chromium.src,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,robclark/chromium,hujiajie/pa-chromium,robclark/chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src
679962935ae5303bde46ca18a216b14504e2327c
worldGenerator/DungeonBluePrints.js
worldGenerator/DungeonBluePrints.js
'use strict'; const common = require('./../server/common'); export class DungeonBluePrints { constructor (number, worldSize, locationSize) { this.number = number; this.worldSize = worldSize; this.locationSize = locationSize; this.blueprints = {}; } generate () { for (let i = 0; i < this.worldSize; i++) { let dungeonId = `dungeon_${i}`; let lx = common.getRandomInt(0, this.worldSize - 1); let ly = common.getRandomInt(0, this.worldSize - 1); let locationId = `location_${ly}_${lx}`; let levels = common.getRandomInt(1, this.worldSize); let entrances = []; for (let l = 0; l < levels; l++) { let x = common.getRandomInt(0, this.locationSize - 1); let y = common.getRandomInt(0, this.locationSize - 1); entrances.push([x, y]); } this.blueprints[dungeonId] = { 'locationId': locationId, 'levels': levels, 'entrances': entrances }; } } }
'use strict'; const common = require('./../server/common'); export class DungeonBluePrints { constructor (number, worldSize, locationSize) { this.number = number; this.worldSize = worldSize; this.locationSize = locationSize; this.blueprints = {}; } generate () { const idList = []; while (this.number) { let lx = common.getRandomInt(0, this.worldSize - 1); let ly = common.getRandomInt(0, this.worldSize - 1); let locationId = `location_${ly}_${lx}`; if (locationId in idList) continue; idList.push(locationId); this.number--; let dungeonId = `dungeon_${this.number}`; let levels = common.getRandomInt(1, this.worldSize); let entrances = []; for (let l = 0; l < levels; l++) { let x = common.getRandomInt(0, this.locationSize - 1); let y = common.getRandomInt(0, this.locationSize - 1); entrances.push([x, y]); } this.blueprints[dungeonId] = { 'locationId': locationId, 'levels': levels, 'entrances': entrances }; } } }
Improve generate method for uniq locations
Improve generate method for uniq locations
JavaScript
mit
nobus/Labyrinth,nobus/Labyrinth
bd7bd1f25231434489d425613f41e1bda888a291
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { entry: "./src/index.tsx", output: { filename: "bundle.js", path: path.resolve(__dirname, "public/") }, resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".ts", ".tsx", ".js", ".json"] }, module: { rules: [ { test: /\.tsx?$/, use: "awesome-typescript-loader" }, { test: /\.js$/, use: "source-map-loader", enforce: "pre" }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(otf|eot|svg|ttf|woff|woff2|jpg|png)(\?.+)?$/, use: 'url-loader' } ] } };
const path = require('path'); module.exports = { entry: "./src/index.tsx", output: { filename: "bundle.js", path: path.resolve(__dirname, "public/") }, resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".ts", ".tsx", ".js", ".json"] }, module: { rules: [ { test: /\.tsx?$/, use: "awesome-typescript-loader" }, { test: /\.js$/, use: "source-map-loader", exclude: /node_modules/, enforce: "pre" }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(otf|eot|svg|ttf|woff|woff2|jpg|png)(\?.+)?$/, use: 'url-loader' } ] } };
Fix for a source-map warning
:hammer: Fix for a source-map warning
JavaScript
mit
tadashi-aikawa/owlora,tadashi-aikawa/owlora,tadashi-aikawa/owlora
6d40c5a2511368407c86e4f9fc39850d3f2a74c2
js/musichipster.js
js/musichipster.js
window.onload = function() { var tabs = function() { var args = models.application.arguments; var current = $("#"+args[0]); var sections = $(".section"); sections.hide(); current.show(); } sp = getSpotifyApi(1); var models = sp.require("sp://import/scripts/api/models"); models.application.observe(models.EVENT.ARGUMENTSCHANGED, tabs); }
window.onload = function() { var tabs = function() { var args = models.application.arguments; var current = $("#"+args[0]); var sections = $(".section"); sections.hide(); current.show(); } sp = getSpotifyApi(1); var models = sp.require("sp://import/scripts/api/models"); models.application.observe(models.EVENT.ARGUMENTSCHANGED, tabs); $("#judgeMeButton").click(function() { console.info("judging..."); }); }
Add handler for Judging button
Add handler for Judging button
JavaScript
mit
hassy/music_hipster
22e747a989a343402fe54193b2780ef3d91c5d4a
node-tests/unit/utils/make-dir-test.js
node-tests/unit/utils/make-dir-test.js
'use strict'; const td = require('testdouble'); const MakeDir = require('../../../src/utils/make-dir'); const fs = require('fs'); const path = require('path'); describe('MakeDir', () => { context('when base and destPath', () => { afterEach(() => { td.reset(); }); it('makes the directory', () => { var mkdirSync = td.replace(fs, 'mkdirSync'); let base = './'; const destPath = 'foo/bar'; MakeDir(base, destPath); // Verify replaced property was invoked. destPath.split('/').forEach((segment) => { base = path.join(base, segment); td.verify(mkdirSync(base)); }); }); }); });
'use strict'; const td = require('testdouble'); const MakeDir = require('../../../src/utils/make-dir'); const fs = require('fs'); const path = require('path'); describe('MakeDir', () => { context('when base and destPath', () => { let mkdirSync; beforeEach(() => { mkdirSync = td.replace(fs, 'mkdirSync'); }); afterEach(() => { td.reset(); }); it('makes the directory', () => { let base = './'; const destPath = 'foo/bar'; MakeDir(base, destPath); // Verify replaced property was invoked. destPath.split('/').forEach((segment) => { base = path.join(base, segment); td.verify(mkdirSync(base)); }); }); }); });
Update test to move test double replacement to before block
refactor(make-dir): Update test to move test double replacement to before block
JavaScript
mit
isleofcode/splicon
85ff298cf9f22036f83388a72cc99a868a2fabe5
examples/Node.js/exportTadpoles.js
examples/Node.js/exportTadpoles.js
require('../../index.js'); var scope = require('./Tadpoles'); scope.view.exportFrames({ amount: 200, directory: __dirname, onComplete: function() { console.log('Done exporting.'); }, onProgress: function(event) { console.log(event.percentage + '% complete, frame took: ' + event.delta); } });
require('../../node.js/'); var paper = require('./Tadpoles'); paper.view.exportFrames({ amount: 400, directory: __dirname, onComplete: function() { console.log('Done exporting.'); }, onProgress: function(event) { console.log(event.percentage + '% complete, frame took: ' + event.delta); } });
Clean up Node.js tadpoles example.
Clean up Node.js tadpoles example.
JavaScript
mit
NHQ/paper,NHQ/paper
c5a54ec1b1de01baf05788b0602e20d41ebfc767
packages/babel-plugin-inline-view-configs/__tests__/index-test.js
packages/babel-plugin-inline-view-configs/__tests__/index-test.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+react_native * @format */ 'use strict'; const {transform: babelTransform} = require('@babel/core'); const fixtures = require('../__test_fixtures__/fixtures.js'); const failures = require('../__test_fixtures__/failures.js'); function transform(fixture, filename) { return babelTransform(fixture, { babelrc: false, cwd: '/', filename: filename, highlightCode: false, plugins: [require('@babel/plugin-syntax-flow'), require('../index')], }).code; } describe('Babel plugin inline view configs', () => { Object.keys(fixtures) .sort() .forEach(fixtureName => { it(`can inline config for ${fixtureName}`, () => { expect(transform(fixtures[fixtureName], fixtureName)).toMatchSnapshot(); }); }); Object.keys(failures) .sort() .forEach(fixtureName => { it(`fails on inline config for ${fixtureName}`, () => { expect(() => { transform(failures[fixtureName], fixtureName); }).toThrowErrorMatchingSnapshot(); }); }); });
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+react_native * @format */ 'use strict'; const {transform: babelTransform} = require('@babel/core'); const fixtures = require('../__test_fixtures__/fixtures.js'); const failures = require('../__test_fixtures__/failures.js'); const transform = (fixture, filename) => babelTransform(fixture, { babelrc: false, cwd: '/', filename: filename, highlightCode: false, plugins: [require('@babel/plugin-syntax-flow'), require('../index')], }).code.replace(/^[A-Z]:\\/g, '/'); // Ensure platform consistent snapshots. describe('Babel plugin inline view configs', () => { Object.keys(fixtures) .sort() .forEach(fixtureName => { it(`can inline config for ${fixtureName}`, () => { expect(transform(fixtures[fixtureName], fixtureName)).toMatchSnapshot(); }); }); Object.keys(failures) .sort() .forEach(fixtureName => { it(`fails on inline config for ${fixtureName}`, () => { expect(() => { transform(failures[fixtureName], fixtureName); }).toThrowErrorMatchingSnapshot(); }); }); });
Fix inline-view-configs test on Windows.
Fix inline-view-configs test on Windows. Summary: *facepalm* The file path is platform specific. Changelog: [Internal] Reviewed By: GijsWeterings Differential Revision: D20793023 fbshipit-source-id: 4fbcbf982911ee449a4fa5067cc0c5d81088ce04
JavaScript
bsd-3-clause
hammerandchisel/react-native,hoangpham95/react-native,janicduplessis/react-native,exponent/react-native,hammerandchisel/react-native,hoangpham95/react-native,exponentjs/react-native,facebook/react-native,hammerandchisel/react-native,myntra/react-native,javache/react-native,pandiaraj44/react-native,hammerandchisel/react-native,facebook/react-native,pandiaraj44/react-native,janicduplessis/react-native,myntra/react-native,exponent/react-native,pandiaraj44/react-native,arthuralee/react-native,pandiaraj44/react-native,myntra/react-native,exponentjs/react-native,facebook/react-native,javache/react-native,facebook/react-native,myntra/react-native,arthuralee/react-native,hoangpham95/react-native,hammerandchisel/react-native,hammerandchisel/react-native,javache/react-native,hammerandchisel/react-native,pandiaraj44/react-native,exponent/react-native,exponentjs/react-native,javache/react-native,janicduplessis/react-native,hoangpham95/react-native,myntra/react-native,arthuralee/react-native,janicduplessis/react-native,facebook/react-native,pandiaraj44/react-native,exponent/react-native,exponent/react-native,exponentjs/react-native,exponentjs/react-native,exponentjs/react-native,javache/react-native,facebook/react-native,javache/react-native,arthuralee/react-native,hoangpham95/react-native,exponent/react-native,myntra/react-native,janicduplessis/react-native,facebook/react-native,hoangpham95/react-native,exponentjs/react-native,pandiaraj44/react-native,janicduplessis/react-native,javache/react-native,arthuralee/react-native,pandiaraj44/react-native,hoangpham95/react-native,myntra/react-native,myntra/react-native,exponentjs/react-native,javache/react-native,hammerandchisel/react-native,exponent/react-native,exponent/react-native,javache/react-native,facebook/react-native,myntra/react-native,janicduplessis/react-native,janicduplessis/react-native,facebook/react-native,hoangpham95/react-native
0cae8b6bebd3f28a92084289951b944bed35c937
webpack.config.js
webpack.config.js
var webpack = require('webpack'); var path = require('path'); module.exports = { context: __dirname + '/app', entry: './index.js', output: { path: __dirname + '/bin', publicPath: '/', filename: 'bundle.js', }, stats: { colors: true, progress: true, }, resolve: { extensions: ['', '.webpack.js', '.js'], }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, query: { presets: ['es2015'], }, loader: 'babel', }, ], }, };
var webpack = require('webpack'); var path = require('path'); module.exports = { context: __dirname + '/app', entry: './index.js', output: { path: __dirname + '/bin', publicPath: '/', filename: 'bundle.js', }, stats: { colors: true, progress: true, }, resolve: { extensions: ['', '.webpack.js', '.js'], modulesDirectories: [ 'app', 'node_modules', ], }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, query: { presets: ['es2015'], }, loader: 'babel', }, ], }, };
Resolve directories in the app folder
Resolve directories in the app folder
JavaScript
mit
oliverbenns/pong,oliverbenns/pong
219c639530f7e72ac12980291d03b2e9a2808d3e
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { devtool: 'inline-source-map', entry: './src/index.js', module: { rules: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', exclude: /node_modules/, options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, output: { library: 'Muxy', libraryTarget: 'umd', umdNamedDefine: true, path: path.resolve(__dirname, 'dist'), filename: 'muxy-extensions-sdk.js' } };
const path = require('path'); const port = process.env.PORT || 9000; module.exports = { devtool: 'inline-source-map', entry: './src/index.js', module: { rules: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', exclude: /node_modules/, options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, output: { library: 'Muxy', libraryTarget: 'umd', umdNamedDefine: true, path: path.resolve(__dirname, 'dist'), filename: 'muxy-extensions-sdk.js' }, devServer: { port } };
Use PORT env for dev server
Use PORT env for dev server
JavaScript
isc
muxy/extensions-js,muxy/extensions-js,muxy/extensions-js
cdce8405c85996b5362ef05fc4c715725e640394
webpack.config.prod.js
webpack.config.prod.js
const path = require('path'); const webpack = require('webpack'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const project = require('./project.config.json'); const plugins = [ new CleanWebpackPlugin(['public']), new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'js/common.js' }), new HtmlWebpackPlugin({ title: project.title, filename: '../index.html', template: 'index_template.ejs', inject: true }) ]; module.exports = { entry: { 'app': './src' }, output: { path: path.join(__dirname, './public/assets'), publicPath: project.repoName + '/assets/', filename: 'js/[name].js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: 'style!css' } ] }, resolve: { root: [ path.resolve(__dirname, 'src') ], extensions: ['', '.js', '.jsx'], }, plugins: plugins };
const path = require('path'); const webpack = require('webpack'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const project = require('./project.config.json'); const plugins = [ new CleanWebpackPlugin(['public']), new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'js/common.js' }), new HtmlWebpackPlugin({ title: project.title, filename: '../index.html', template: 'index_template.ejs', inject: true, hash: true }) ]; module.exports = { entry: { 'app': './src' }, output: { path: path.join(__dirname, './public/assets'), publicPath: project.repoName + '/assets/', filename: 'js/[name].js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: 'style!css' } ] }, resolve: { root: [ path.resolve(__dirname, 'src') ], extensions: ['', '.js', '.jsx'], }, plugins: plugins };
Add hashing in build HMTL
Add hashing in build HMTL
JavaScript
mit
ibleedfilm/fcc-react-project,ibleedfilm/recipe-box,ibleedfilm/fcc-react-project,ibleedfilm/recipe-box
fb03f18dd8bbf6634e8b9fa69ffc32cb1a71d719
webpack.prod.config.js
webpack.prod.config.js
var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var path = require("path"); module.exports = { context: __dirname, entry: [ './ditto/static/chat/js/base.js', ], output: { path: path.resolve('./ditto/static/dist'), publicPath: '/static/dist/', // This will override the url generated by django's staticfiles filename: "[name]-[hash].js", }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ["babel-loader?optional[]=es7.comprehensions&optional[]=es7.classProperties&optional[]=es7.objectRestSpread&optional[]=es7.decorators"], } ] }, plugins: [ new BundleTracker({filename: './webpack-stats-prod.json'}), // removes a lot of debugging code in React new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') }}), // keeps hashes consistent between compilations new webpack.optimize.OccurenceOrderPlugin(), // minifies your code new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ], resolve: { extensions: ['', '.js', '.jsx'] } };
var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var path = require("path"); module.exports = { context: __dirname, entry: [ './ditto/static/chat/js/base.js', ], output: { path: path.resolve('./ditto/static/dist'), publicPath: '/static/dist/', // This will override the url generated by django's staticfiles filename: "[name]-[hash].js", }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ["babel-loader?optional[]=es7.comprehensions&optional[]=es7.classProperties&optional[]=es7.objectRestSpread&optional[]=es7.decorators"], } ] }, plugins: [ new BundleTracker({filename: './webpack-stats-prod.json'}), // removes a lot of debugging code in React new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') }}), // keeps hashes consistent between compilations new webpack.optimize.OccurenceOrderPlugin(), // minifies your code new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ], resolve: { fallback: path.join(__dirname, 'node_modules'), extensions: ['', '.js', '.jsx'] } };
Fix prod'n webpack conf for linked deps
Fix prod'n webpack conf for linked deps
JavaScript
bsd-3-clause
Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto
93d9d4bba873aba0af6c4419b7c731ebd187797c
geoportailv3/static/js/scalelinedirective.js
geoportailv3/static/js/scalelinedirective.js
goog.provide('app_scaleline_directive'); goog.require('app'); goog.require('ngeo_control_directive'); goog.require('ol.control.ScaleLine'); (function() { var module = angular.module('app'); module.directive('appScaleline', [ /** * @return {angular.Directive} The Directive Object Definition. */ function() { return { restrict: 'E', scope: { map: '=appScalelineMap' }, controller: function() { this['createControl'] = function(target) { return new ol.control.ScaleLine({ target: target }); }; }, controllerAs: 'ctrl', bindToController: true, template: '<div ngeo-control="ctrl.createControl"' + 'ngeo-control-map="ctrl.map">' }; } ]); })();
goog.provide('app_scaleline_directive'); goog.require('app'); goog.require('ngeo_control_directive'); goog.require('ol.control.ScaleLine'); (function() { var module = angular.module('app'); module.directive('appScaleline', [ /** * @return {angular.Directive} The Directive Object Definition. */ function() { return { restrict: 'E', scope: { 'map': '=appScalelineMap' }, controller: function() { this['createControl'] = function(target) { return new ol.control.ScaleLine({ target: target }); }; }, controllerAs: 'ctrl', bindToController: true, template: '<div ngeo-control="ctrl.createControl"' + 'ngeo-control-map="ctrl.map">' }; } ]); })();
Use quotes for scope properties
Use quotes for scope properties
JavaScript
mit
geoportallux/geoportailv3-gisgr,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3
26e3988ea21f5dea1e47cefe51eb546ea6a06f64
blueocean-web/src/main/js/try.js
blueocean-web/src/main/js/try.js
var $ = require('jquery-detached').getJQuery(); var jsModules = require('@jenkins-cd/js-modules'); $(document).ready(function () { var tryBlueOcean = $('<div class="try-blueocean header-callout">Try Blue Ocean UI ...</div>'); tryBlueOcean.click(function () { // We could enhance this further by looking at the current // URL and going to different places in the BO UI depending // on where the user is in classic jenkins UI e.g. if they // are currently in a job on classic UI, bring them to the // same job in BO UI Vs just brining them to the root of // BO UI i.e. make the button context sensitive. window.location.replace(jsModules.getRootURL() + '/blue'); }); $('#page-head #header').append(tryBlueOcean); });
var $ = require('jquery-detached').getJQuery(); var jsModules = require('@jenkins-cd/js-modules'); $(document).ready(() => { var tryBlueOcean = $('<div class="try-blueocean header-callout">Try Blue Ocean UI ...</div>'); tryBlueOcean.click(() => { // We could enhance this further by looking at the current // URL and going to different places in the BO UI depending // on where the user is in classic jenkins UI e.g. if they // are currently in a job on classic UI, bring them to the // same job in BO UI Vs just brining them to the root of // BO UI i.e. make the button context sensitive. window.location.replace(`${jsModules.getRootURL()}/blue`); }); $('#page-head #header').append(tryBlueOcean); });
Add a "Try Blue Ocean UI" button in classic Jenkins - fix lint errors
Add a "Try Blue Ocean UI" button in classic Jenkins - fix lint errors
JavaScript
mit
kzantow/blueocean-plugin,kzantow/blueocean-plugin,tfennelly/blueocean-plugin,alvarolobato/blueocean-plugin,jenkinsci/blueocean-plugin,tfennelly/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,ModuloM/blueocean-plugin,tfennelly/blueocean-plugin,alvarolobato/blueocean-plugin,ModuloM/blueocean-plugin,kzantow/blueocean-plugin,kzantow/blueocean-plugin,ModuloM/blueocean-plugin,alvarolobato/blueocean-plugin,ModuloM/blueocean-plugin,alvarolobato/blueocean-plugin,jenkinsci/blueocean-plugin,tfennelly/blueocean-plugin
bc864168d477192120b67ff32f71d07ea1674d76
client/src/js/dispatcher/user.js
client/src/js/dispatcher/user.js
/** * Copyright 2015, Government of Canada. * All rights reserved. * * This source code is licensed under the MIT license. * * @providesModule User */ var Cookie = require('react-cookie'); var Events = require('./Events'); /** * An object that manages all user authentication and the user profile. * * @constructor */ var User = function () { this.name = null; this.events = new Events(['change', 'logout'], this); this.load = function (data) { // Update the username, token, and reset properties with the authorized values. _.assign(this, _.omit(data, '_id')); this.name = data._id; Cookie.save('token', data.token); this.emit('change'); }; this.authorize = function (data) { this.load(data); dispatcher.sync(); }; this.deauthorize = function (data) { dispatcher.storage.deleteDatabase(function () { location.hash = 'home/welcome'; this.name = null; _.forIn(dispatcher.db, function (collection) { collection.documents = []; collection.synced = false; }); this.emit('logout', data); }.bind(this)); }.bind(this); this.logout = function () { dispatcher.send({ collectionName: 'users', methodName: 'logout', data: { token: this.token } }, this.deauthorize); }; }; module.exports = User;
/** * Copyright 2015, Government of Canada. * All rights reserved. * * This source code is licensed under the MIT license. * * @providesModule User */ var Cookie = require('react-cookie'); var Events = require('./Events'); /** * An object that manages all user authentication and the user profile. * * @constructor */ var User = function () { this.name = null; this.events = new Events(['change', 'logout'], this); this.load = function (data) { // Update the username, token, and reset properties with the authorized values. _.assign(this, _.omit(data, '_id')); this.name = data._id; Cookie.save('token', data.token); this.emit('change'); }; this.authorize = function (data) { this.load(data); dispatcher.sync(); }; this.deauthorize = function (data) { dispatcher.db.loki.deleteDatabase({}, function () { location.hash = 'home/welcome'; this.name = null; _.forIn(dispatcher.db, function (collection) { collection.documents = []; collection.synced = false; }); this.emit('logout', data); }.bind(this)); }.bind(this); this.logout = function () { dispatcher.send({ collectionName: 'users', methodName: 'logout', data: { token: this.token } }, this.deauthorize); }; }; module.exports = User;
Delete Loki database and persistent storage on logout.
Delete Loki database and persistent storage on logout.
JavaScript
mit
igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool
64019f0ffd4582e8bb047e261152c9a034bfe378
index.js
index.js
window.onload = function() { sectionShow(); blogController(); }; function sectionShow() { var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'} document.getElementById('menu').addEventListener('click', function(event) { event.preventDefault(); hideSections(sectionControls); document.getElementById(sectionControls[event.target.id]).style.display = 'inline'; }); }; function hideSections(sections) { for (i in sections) { document.getElementById(sections[i]).style.display = 'none'; }; }; function blogController() { document.getElementById('blog_control').addEventListener('click', function(event) { event.preventDefault(); ajaxWrapper(blogList[i]); }; }); }; function ajaxWrapper(blog_page) { var xml = new XMLHttpRequest(); xml.onreadystatechange = function() { if (xml.readyState == 4 && xml.status == 200) { blog_div = document.getElementById('blog_show'); blog_div.style.display = 'inline'; blog_div.innerHTML = xml.responseText; }; }; xml.open('GET', blog_page, true); xml.send(); };
window.onload = function() { sectionShow(); }; function sectionShow() { var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'} document.getElementById('menu').addEventListener('click', function(event) { event.preventDefault(); hideSections(sectionControls); document.getElementById(sectionControls[event.target.id]).style.display = 'inline'; if (event.target.id == 'blog_btn') { blogController() }; }); }; function hideSections(sections) { for (i in sections) { document.getElementById(sections[i]).style.display = 'none'; }; }; function blogController() { document.getElementById('blog_control').addEventListener('click', function(event) { event.preventDefault(); ajaxWrapper(blogList[i]); }; }); }; function ajaxWrapper(blog_page) { var xml = new XMLHttpRequest(); xml.onreadystatechange = function() { if (xml.readyState == 4 && xml.status == 200) { blog_div = document.getElementById('blog_show'); blog_div.style.display = 'inline'; blog_div.innerHTML = xml.responseText; }; }; xml.open('GET', blog_page, true); xml.send(); };
Move blogController to run only if blog section is loaded
Index.js: Move blogController to run only if blog section is loaded
JavaScript
mit
jorgerc85/jorgerc85.github.io,jorgerc85/jorgerc85.github.io
36fd7e3ea6bdaf58995bc1c9da9522c4c0911dee
samples/msal-node-samples/standalone-samples/device-code/index.js
samples/msal-node-samples/standalone-samples/device-code/index.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ var msal = require('@azure/msal-node'); const msalConfig = { auth: { clientId: "6c04f413-f6e7-4690-b372-dbdd083e7e5a", authority: "https://login.microsoftonline.com/sgonz.onmicrosoft.com", } }; const pca = new msal.PublicClientApplication(msalConfig); const deviceCodeRequest = { deviceCodeCallback: (response) => (console.log(response.message)), scopes: ["user.read"], timeout: 5, }; pca.acquireTokenByDeviceCode(deviceCodeRequest).then((response) => { console.log(JSON.stringify(response)); }).catch((error) => { console.log(JSON.stringify(error)); }); // Uncomment to test cancellation // setTimeout(function() { // deviceCodeRequest.cancel = true; // }, 12000);
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ var msal = require('@azure/msal-node'); const msalConfig = { auth: { clientId: "6c04f413-f6e7-4690-b372-dbdd083e7e5a", authority: "https://login.microsoftonline.com/sgonz.onmicrosoft.com", } }; const pca = new msal.PublicClientApplication(msalConfig); const deviceCodeRequest = { deviceCodeCallback: (response) => (console.log(response.message)), scopes: ["user.read"], timeout: 5, }; pca.acquireTokenByDeviceCode(deviceCodeRequest).then((response) => { console.log(JSON.stringify(response)); }).catch((error) => { console.log(JSON.stringify(error)); }); // Uncomment to test cancellation // setTimeout(function() { // deviceCodeRequest.cancel = true; // }, 12000);
Fix formating in the device-code sample
Fix formating in the device-code sample
JavaScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
c1928257ac5233ad15866c5d4675ebdf7f552203
index.js
index.js
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-docker-config', contentFor: function(type, config) { if (type === 'head') { return '<script type="text/javascript">window.DynamicENV = ' + this.dynamicConfig(config.DynamicConfig) + ';</script>'; } }, dynamicConfig: function(config) { var param; if (!config) { return ''; } var configParams = []; for (param in config) { if (typeof config[param] === 'object') { configParams.push('"' + param + '": ' + this.dynamicConfig(config[param])); } else { if (process.env[config[param]]) { configParams.push('"' + param + '": "' + process.env[config[param]] + '"'); } } } return '{' + configParams.join(',') + '}'; } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-docker-config', contentFor: function(type, config) { if (type === 'head') { return '<script type="text/javascript">window.DynamicENV = ' + this.dynamicConfig(config.DynamicConfig) + ';</script>'; } }, dynamicConfig: function(config) { var param; if (!config) { return ''; } var configParams = []; for (param in config) { switch (typeof config[param]) { case 'object': configParams.push('"' + param + '": ' + this.dynamicConfig(config[param])); break; case 'string': if (process.env[config[param]]) { configParams.push('"' + param + '": "' + process.env[config[param]] + '"'); } break; case 'function': configParams.push('"' + param + '": "' + config[param](process.env) + '"'); break; } } return '{' + configParams.join(',') + '}'; } };
Add ability to specify a function instead of a string for dynamic configs
Add ability to specify a function instead of a string for dynamic configs
JavaScript
mit
pk4media/ember-cli-docker-config,pk4media/ember-cli-docker-config
d09cd9ef89e9860c7b972cba9fcb1736f4de17c7
lib/node_modules/@stdlib/repl/lib/context/regexp/index.js
lib/node_modules/@stdlib/repl/lib/context/regexp/index.js
'use strict'; var NS = {}; // MODULES // var getKeys = require( 'object-keys' ).shim(); NS.RE_EOL = require( '@stdlib/regexp/eol' ); NS.RE_EXTNAME = require( '@stdlib/regexp/extname' ); NS.RE_EXTNAME_POSIX = require( '@stdlib/regexp/extname-posix' ); NS.RE_EXTNAME_WINDOWS = require( '@stdlib/regexp/extname-windows' ); NS.RE_FUNCTION_NAME = require( '@stdlib/regexp/function-name' ); // VARIABLES // var KEYS = getKeys( NS ); // BIND // /** * Binds functions to a REPL namespace. * * @private * @param {Object} ns - namespace * @returns {Object} input namespace * * @example * var ns = {}; * bind( ns ); * // returns <input_namespace> */ function bind( ns ) { var key; var i; for ( i = 0; i < KEYS.length; i++ ) { key = KEYS[ i ]; ns[ key ] = NS[ key ]; } return ns; } // end FUNCTION bind() // EXPORTS // module.exports = bind;
'use strict'; var NS = {}; // MODULES // var getKeys = require( 'object-keys' ).shim(); NS.RE_EOL = require( '@stdlib/regexp/eol' ); NS.RE_DIRNAME = require( '@stdlib/regexp/dirname' ); NS.RE_DIRNAME_POSIX = require( '@stdlib/regexp/dirname-posix' ); NS.RE_DIRNAME_WINDOWS = require( '@stdlib/regexp/dirname-windows' ); NS.RE_EXTNAME = require( '@stdlib/regexp/extname' ); NS.RE_EXTNAME_POSIX = require( '@stdlib/regexp/extname-posix' ); NS.RE_EXTNAME_WINDOWS = require( '@stdlib/regexp/extname-windows' ); NS.RE_FUNCTION_NAME = require( '@stdlib/regexp/function-name' ); // VARIABLES // var KEYS = getKeys( NS ); // BIND // /** * Binds functions to a REPL namespace. * * @private * @param {Object} ns - namespace * @returns {Object} input namespace * * @example * var ns = {}; * bind( ns ); * // returns <input_namespace> */ function bind( ns ) { var key; var i; for ( i = 0; i < KEYS.length; i++ ) { key = KEYS[ i ]; ns[ key ] = NS[ key ]; } return ns; } // end FUNCTION bind() // EXPORTS // module.exports = bind;
Add dirname RegExps to REPL context
Add dirname RegExps to REPL context
JavaScript
apache-2.0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
2beadbe92492133a4b643ec257ab40910e520031
src/bot.js
src/bot.js
const Eris = require("eris"); const config = require("./cfg"); const bot = new Eris.Client(config.token, { getAllUsers: true, restMode: true, }); module.exports = bot;
const Eris = require("eris"); const config = require("./cfg"); const bot = new Eris.Client(config.token, { restMode: true, }); module.exports = bot;
Disable getAllUsers from the client
Disable getAllUsers from the client We can lazy-load members instead.
JavaScript
mit
Dragory/modmailbot
2efd96c382e193197acbbc30c0e0d6be135cd09c
lib/js/tabulate.js
lib/js/tabulate.js
(function($) { $(document).ready(function() { $('#template-entry-hidden').load("entry.template.html"); $('#btn-load-project').click(function(){ var project = $('#project-name').val(); $.getJSON(project, renderData); }); }); function renderData(data) { $.each(data, function(index, entry) { var entryDiv = $('#template-entry-hidden').clone().children(); entryDiv.find(".tabula-command").html(entry.entry.command); entryDiv.appendTo('div#project-data'); }); } })(jQuery);
(function($) { $(document).ready(function() { $('#template-entry-hidden').load("entry.template.html"); $('#btn-load-project').click(function(){ var project = $('#project-name').val(); $.getJSON(project, renderData); }); }); function renderData(data) { // For each entry $.each(data, function(index, entry) { // Clone the template var entryDiv = $('#template-entry-hidden').clone().children(); // Set background colour based on exit status entryDiv.css("background-color", pickExitColour(entry.entry.exitStatus)) entryDiv.find(".tabula-command").html(entry.entry.command); // Append to the main div entryDiv.appendTo('div#project-data'); }); } function pickExitColour(exitStatus) { if (exitStatus === 0) { // Successful return "#00FF00"; } else if (exitStatus > 127) { // Killed by user return "#FFFF00"; } else { // Failed for some reason. return "#FF0000"; } } })(jQuery);
Set the background colour based on exit status.
Set the background colour based on exit status.
JavaScript
bsd-3-clause
nc6/tabula-viewer
feab634e3d57c84f1e76ee6d00f13b2e99050b94
src/view/table/cell/AmountEntryCell.js
src/view/table/cell/AmountEntryCell.js
/** * Cell used for showing an AmountEntry * * Copyright 2015 Ethan Smith */ var Marionette = require('backbone.marionette'); var AmountEntryCell = Marionette.ItemView.extend({ tagName: 'td', render: function() { this.$el.html(this.model.entry.readable()); } }); module.exports = AmountEntryCell;
/** * Cell used for showing an AmountEntry * * Copyright 2015 Ethan Smith */ var Marionette = require('backbone.marionette'); var AmountEntryCell = Marionette.ItemView.extend({ tagName: 'td', className: function() { return this.model.entry.get() === 0 ? 'zero' : ''; }, render: function() { this.$el.html(this.model.entry.readable()); } }); module.exports = AmountEntryCell;
Add zero class to new AmountEntry cell
Add zero class to new AmountEntry cell
JavaScript
mit
onebytegone/banknote-client,onebytegone/banknote-client
f937a7643eb831c8ab4d5f4b2356a1ec2335acfa
db/migrations/20131219233339-ripple-addresses.js
db/migrations/20131219233339-ripple-addresses.js
var dbm = require('db-migrate'); var type = dbm.dataType; exports.up = function(db, callback) { db.createTable('ripple_addresses', { id: { type: 'int', primaryKey: true, autoIncrement: true }, user_id: { type: 'int', notNull: true }, managed: { type: 'boolean', default: false, notNull: true}, address: { type: 'string', notNull: true, unique: true }, type: { type: 'string', notNull: true }, tag: { type: 'string' }, secret: { type: 'string' }, previous_transaction_hash: { type: 'string' } }, callback); }; exports.down = function(db, callback) { db.dropTable('ripple_addresses', callback); };
var dbm = require('db-migrate'); var type = dbm.dataType; exports.up = function(db, callback) { db.createTable('ripple_addresses', { id: { type: 'int', primaryKey: true, autoIncrement: true }, user_id: { type: 'int', notNull: true }, managed: { type: 'boolean', default: false, notNull: true}, address: { type: 'string', notNull: true }, type: { type: 'string', notNull: true }, tag: { type: 'string' }, secret: { type: 'string' }, previous_transaction_hash: { type: 'string' }, createdAt: { type: 'datetime' }, updatedAt: { type: 'datetime' } }, callback); }; exports.down = function(db, callback) { db.dropTable('ripple_addresses', callback); };
Make ripple_address address column not required. Add timestamps.
[FEATURE] Make ripple_address address column not required. Add timestamps.
JavaScript
isc
xdv/gatewayd,zealord/gatewayd,Parkjeahwan/awegeeks,whotooktwarden/gatewayd,xdv/gatewayd,crazyquark/gatewayd,whotooktwarden/gatewayd,crazyquark/gatewayd,Parkjeahwan/awegeeks,zealord/gatewayd
9b6a769d4c96ea4834c3659c957d0d84b6eb41cc
example/drummer/src/createPredictedFutureElem.js
example/drummer/src/createPredictedFutureElem.js
const renderWay = require('./renderWay'); const predict = require('./predict'); module.exports = (model, dispatch) => { const prediction = predict(model); return renderWay(prediction, { label: 'prediction', numbers: true, numbersBegin: model.history[0].length }); };
const renderWay = require('./renderWay'); const predict = require('./predict'); module.exports = (model, dispatch) => { const prediction = predict(model); return renderWay(prediction, { label: 'future', numbers: true, numbersBegin: model.history[0].length }); };
Rename prediction label to future
Rename prediction label to future
JavaScript
mit
axelpale/lately,axelpale/lately
ee71493015ea0a949d6f9dcc77e641ffc77659f0
misc/chrome_plugins/clean_concourse_pipeline/src/inject.user.js
misc/chrome_plugins/clean_concourse_pipeline/src/inject.user.js
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","") var element = document.getElementsByTagName("nav")[0]; element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; } }, 10);
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","") var element = document.getElementById("top-bar-app"); element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; } }, 10);
Update chrome plugin for concourse 2.1.0
Update chrome plugin for concourse 2.1.0 It was mostly working, but just left a dark bar across the top with the env name in it. This updates it to remove that bar as well to maintain consistency with the existing appearence.
JavaScript
mit
alphagov/paas-cf,alphagov/paas-cf,jimconner/paas-cf,jimconner/paas-cf,alphagov/paas-cf,jimconner/paas-cf,jimconner/paas-cf,jimconner/paas-cf,alphagov/paas-cf,alphagov/paas-cf,jimconner/paas-cf,alphagov/paas-cf,alphagov/paas-cf,jimconner/paas-cf,alphagov/paas-cf
e7004fd93bd36390c4d644f1ec0cd66e267ff61a
app/shared/current_user/currentUser.spec.js
app/shared/current_user/currentUser.spec.js
describe('current-user module', function() { var currentUser; beforeEach(module('current-user')); beforeEach(inject(function(_currentUser_) { currentUser = _currentUser_; })); describe('currentUser', function() { it("should be a resource", function() { expect(currentUser).toBeDefined(); }); it('should default as empty', function() { expect(currentUser.getCurrentUser()).toEqual({}); }); it('should update user with setter', function() { expect(currentUser.getCurrentUser()).toEqual({}); currentUser.setCurrentUser({ 'name': 'tester', }); expect(currentUser.getCurrentUser()).toEqual({ 'name': 'tester', }); }); }); });
describe('current-user module', function() { var currentUser; beforeEach(module('current-user')); beforeEach(inject(function(_currentUser_) { currentUser = _currentUser_; })); describe('currentUser', function() { it("should be a resource", function() { expect(currentUser).toBeDefined(); }); it('should default as empty', function() { expect(currentUser.getCurrentUser()).toEqual({}); }); it('should update user with setter', function() { expect(currentUser.getCurrentUser()).toEqual({}); currentUser.setCurrentUser({ 'name': 'tester', }); expect(currentUser.getCurrentUser()).toEqual({ 'name': 'tester', }); }); it('should delete user cache', function() { currentUser.setCurrentUser({ $id: 123, name: '123', }); expect(currentUser.getCurrentUser()).toEqual({ $id: 123, name: '123', }); currentUser.deleteCurrentUser(); expect(currentUser.getCurrentUser()).toEqual({}); }); it('should check if user logged in correctly', function() { currentUser.setCurrentUser({ $id: 123, name: '123', }); expect(currentUser.isLoggedIn()).toEqual(true); currentUser.deleteCurrentUser(); expect(currentUser.isLoggedIn()).toEqual(false); }); }); });
Update currentUser module test cases
Update currentUser module test cases
JavaScript
mit
christse02/project,christse02/project
2013acb3bdc6905b26a52c060309ba2605ad50f4
jujugui/static/gui/src/app/components/spinner/spinner.js
jujugui/static/gui/src/app/components/spinner/spinner.js
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2015 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const Spinner = React.createClass({ displayName: 'Spinner', render: function() { return ( <div className="spinner-container"> <div className="spinner-loading">Loading...</div> </div> ); } }); YUI.add('loading-spinner', function() { juju.components.Spinner = Spinner; }, '0.1.0', { requires: [] });
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2015 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; class Spinner extends React.Component { render() { return ( <div className="spinner-container"> <div className="spinner-loading">Loading...</div> </div> ); } }; YUI.add('loading-spinner', function() { juju.components.Spinner = Spinner; }, '0.1.0', { requires: [] });
Update Spinner to use es6 class.
Update Spinner to use es6 class.
JavaScript
agpl-3.0
mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui
62f3a153dd791bcd8ff30b54aaa2b7c0d8254156
src/utils/math.js
src/utils/math.js
/** * Creates a new 2 dimensional Vector. * * @constructor * @this {Circle} * @param {number} x The x value of the new vector. * @param {number} y The y value of the new vector. */ function Vector2(x, y) { if (typeof x === 'undefined') { x = 0; } if (typeof y === 'undefined') { y = 0; } this.x = x; this.y = y; } Vector2.prototype.add = function(v) { if ( !(v instanceof Vector2) ) { throw new InvalidArgumentError("v", "You can only add a vector to another vector! The object passed was: " + v); } this.x += v.x; this.y += v.y; } Vector2.prototype.toString = function() { return "[" + this.x + ", " + this.y + "]"; }
/** * Creates a new 2 dimensional Vector. * * @constructor * @this {Circle} * @param {number} x The x value of the new vector. * @param {number} y The y value of the new vector. */ function Vector2(x, y) { if (typeof x === 'undefined') { x = 0; } if (typeof y === 'undefined') { y = 0; } this.x = x; this.y = y; } Vector2.prototype.add = function(v) { if ( !(v instanceof Vector2) ) { throw new InvalidArgumentError("v", "You can only add a vector to another vector! The object passed was: " + v); } this.x += v.x; this.y += v.y; return this; } Vector2.prototype.toString = function() { return "[" + this.x + ", " + this.y + "]"; }
Change add to return the vector itself, for method chaining
Change add to return the vector itself, for method chaining
JavaScript
mit
zedutchgandalf/OpenJGL,zedutchgandalf/OpenJGL
e067299612793593a85694901339bcbd78e4d417
themes/hive-learning-networks/js/ui.js
themes/hive-learning-networks/js/ui.js
$("#hive-intro-menu .hive-list li").click(function(event) { var placeName = $(this).find(".the-place").text(); var twitterHandle = $(this).find(".the-details .twitter-handle").text(); var websiteURL = $(this).find(".the-details .website-url").text(); // show content $("#hive-intro-box h2").html(placeName); if ( twitterHandle ) { $("#hive-intro-box .twitter") .attr("href", "http://twitter.com/" + twitterHandle) .text(twitterHandle) .removeClass("hide"); } $("#hive-intro-box .hive-btn") .attr("href", websiteURL) .text("Visit Website"); // hide the general info $("#hive-intro-box .general-cta").hide(); }); /* **************************************** * "Locations" Page */ $("#locations-menu div:not(#hive-coming-menu) a").click(function(){ var locationSelected = $(this).data("profile"); console.log( locationSelected ); // highlight selected item $("#locations-menu li.active").removeClass("active"); $(this).parent("li").addClass("active"); // show corresponding sections, hide the rest $(".hive-profile").parent(".container").addClass("hide"); // profile section of the selected item var profile = $(".hive-profile[data-profile="+ locationSelected +"]").parent(".container"); profile.removeClass("hide"); $("html, body").animate({ scrollTop: profile.offset().top }, "slow"); });
$("#hive-intro-menu .hive-list li").click(function(event) { var placeName = $(this).find(".the-place").text(); var twitterHandle = $(this).find(".the-details .twitter-handle").text(); var websiteURL = $(this).find(".the-details .website-url").text(); // show content $("#hive-intro-box h2").html(placeName); if ( twitterHandle ) { $("#hive-intro-box .twitter") .attr("href", "http://twitter.com/" + twitterHandle) .text(twitterHandle) .removeClass("hide"); } else { $("#hive-intro-box .twitter").addClass("hide"); } $("#hive-intro-box .hive-btn") .attr("href", websiteURL) .text("Visit Website"); // hide the general info $("#hive-intro-box .general-cta").hide(); }); /* **************************************** * "Locations" Page */ $("#locations-menu div:not(#hive-coming-menu) a").click(function(){ var locationSelected = $(this).data("profile"); console.log( locationSelected ); // highlight selected item $("#locations-menu li.active").removeClass("active"); $(this).parent("li").addClass("active"); // show corresponding sections, hide the rest $(".hive-profile").parent(".container").addClass("hide"); // profile section of the selected item var profile = $(".hive-profile[data-profile="+ locationSelected +"]").parent(".container"); profile.removeClass("hide"); $("html, body").animate({ scrollTop: profile.offset().top }, "slow"); });
Hide twitter field if value is empty
Hide twitter field if value is empty
JavaScript
mpl-2.0
mmmavis/hivelearningnetworks.org,mmmavis/hivelearningnetworks.org,mozilla/hivelearningnetworks.org,mmmavis/hivelearningnetworks.org,mozilla/hivelearningnetworks.org
8c6d9d92092b13a86b6cec85be8141757e2da8a4
site/src/electron/ElectronInterface.js
site/src/electron/ElectronInterface.js
class ElectronInterface extends SiteInterface { constructor() { super(); } }
class ElectronInterface extends SiteInterface { constructor() { super(); this.style = new Style(ElectronInterface.STYLE_PATH); } } ElectronInterface.STYLE_PATH = "../interface/SiteInterface/siteInterface.css";
Add style to Electron Interface
Add style to Electron Interface
JavaScript
mit
ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot.github.io,ukahoot/ukahoot.github.io,ukahoot/ukahoot,ukahoot/ukahoot,ukahoot/ukahoot
2282d93db4422eac35ad3f8a65ed60e6c821eee7
tasks/mochacli.js
tasks/mochacli.js
'use strict'; var mocha = require('../lib/mocha'); module.exports = function (grunt) { grunt.registerMultiTask('mochacli', 'Run Mocha server-side tests.', function () { var options = this.options(); if (!options.files) { options.files = this.file.srcRaw; } mocha(options, this.async()); }); };
'use strict'; var mocha = require('../lib/mocha'); module.exports = function (grunt) { grunt.registerMultiTask('mochacli', 'Run Mocha server-side tests.', function () { var options = this.options(); var globs = []; if (!options.files) { this.files.forEach(function (glob) { globs = globs.concat(glob.orig.src); }); options.files = globs; } mocha(options, this.async()); }); };
Fix using the Grunt files format
Fix using the Grunt files format
JavaScript
mit
Rowno/grunt-mocha-cli
f65f19bf7d737cffdbe629247ac4913357c9d1ec
test/feature/Classes/NameBinding.js
test/feature/Classes/NameBinding.js
class ElementHolder { element; getElement() { return this.element; } makeFilterCapturedThis() { var capturedThis = this; return function (x) { return x == capturedThis.element; } } makeFilterLostThis() { return function (x) { return x == this.element; } } makeFilterHidden(element) { return function (x) { return x == element; } } } // ---------------------------------------------------------------------------- var obj = new ElementHolder(); obj.element = 40; assertEquals(40, obj.getElement()); assertTrue(obj.makeFilterCapturedThis()(40)); assertFalse(obj.makeFilterLostThis()(40)); obj.element = 39; assertFalse(obj.makeFilterCapturedThis()(40)); assertTrue(obj.makeFilterCapturedThis()(39)); assertFalse(obj.makeFilterHidden(41)(40)); assertTrue(obj.makeFilterHidden(41)(41));
class ElementHolder { element; getElement() { return this.element; } makeFilterCapturedThis() { var capturedThis = this; return function (x) { return x == capturedThis.element; } } makeFilterLostThis() { return function () { return this; } } makeFilterHidden(element) { return function (x) { return x == element; } } } // ---------------------------------------------------------------------------- var obj = new ElementHolder(); obj.element = 40; assertEquals(40, obj.getElement()); assertTrue(obj.makeFilterCapturedThis()(40)); // http://code.google.com/p/v8/issues/detail?id=1381 // assertUndefined(obj.makeFilterLostThis()()); obj.element = 39; assertFalse(obj.makeFilterCapturedThis()(40)); assertTrue(obj.makeFilterCapturedThis()(39)); assertFalse(obj.makeFilterHidden(41)(40)); assertTrue(obj.makeFilterHidden(41)(41));
Fix invalid test and disable it due to V8 bug
Fix invalid test and disable it due to V8 bug
JavaScript
apache-2.0
ide/traceur,ide/traceur,ide/traceur
5b3a341d2d53223775d7e09ab11819a5d433290f
packages/internal-test-helpers/lib/ember-dev/run-loop.js
packages/internal-test-helpers/lib/ember-dev/run-loop.js
import { cancelTimers, end, getCurrentRunLoop, hasScheduledTimers } from '@ember/runloop'; function RunLoopAssertion(env) { this.env = env; } RunLoopAssertion.prototype = { reset: function() {}, inject: function() {}, assert: function() { let { assert } = QUnit.config.current; if (getCurrentRunLoop()) { assert.ok(false, 'Should not be in a run loop at end of test'); while (getCurrentRunLoop()) { end(); } } if (hasScheduledTimers()) { assert.ok(false, 'Ember run should not have scheduled timers at end of test'); cancelTimers(); } }, restore: function() {}, }; export default RunLoopAssertion;
import { cancelTimers, end, getCurrentRunLoop, hasScheduledTimers } from '@ember/runloop'; export default class RunLoopAssertion { constructor(env) { this.env = env; } reset() {} inject() {} assert() { let { assert } = QUnit.config.current; if (getCurrentRunLoop()) { assert.ok(false, 'Should not be in a run loop at end of test'); while (getCurrentRunLoop()) { end(); } } if (hasScheduledTimers()) { assert.ok(false, 'Ember run should not have scheduled timers at end of test'); cancelTimers(); } } restore() {} }
Convert `RunLoopAssert` to ES6 class
internal-test-helpers: Convert `RunLoopAssert` to ES6 class
JavaScript
mit
kellyselden/ember.js,GavinJoyce/ember.js,mfeckie/ember.js,emberjs/ember.js,kellyselden/ember.js,Turbo87/ember.js,sandstrom/ember.js,stefanpenner/ember.js,bekzod/ember.js,kellyselden/ember.js,tildeio/ember.js,qaiken/ember.js,mixonic/ember.js,stefanpenner/ember.js,fpauser/ember.js,elwayman02/ember.js,fpauser/ember.js,givanse/ember.js,jaswilli/ember.js,knownasilya/ember.js,Turbo87/ember.js,miguelcobain/ember.js,cibernox/ember.js,emberjs/ember.js,sandstrom/ember.js,asakusuma/ember.js,cibernox/ember.js,mfeckie/ember.js,bekzod/ember.js,tildeio/ember.js,sly7-7/ember.js,asakusuma/ember.js,qaiken/ember.js,givanse/ember.js,sly7-7/ember.js,miguelcobain/ember.js,knownasilya/ember.js,cibernox/ember.js,jaswilli/ember.js,givanse/ember.js,mfeckie/ember.js,elwayman02/ember.js,miguelcobain/ember.js,asakusuma/ember.js,qaiken/ember.js,emberjs/ember.js,givanse/ember.js,mixonic/ember.js,GavinJoyce/ember.js,intercom/ember.js,fpauser/ember.js,bekzod/ember.js,jaswilli/ember.js,cibernox/ember.js,stefanpenner/ember.js,sly7-7/ember.js,intercom/ember.js,Turbo87/ember.js,elwayman02/ember.js,jaswilli/ember.js,asakusuma/ember.js,qaiken/ember.js,GavinJoyce/ember.js,fpauser/ember.js,GavinJoyce/ember.js,intercom/ember.js,tildeio/ember.js,bekzod/ember.js,intercom/ember.js,elwayman02/ember.js,miguelcobain/ember.js,sandstrom/ember.js,kellyselden/ember.js,Turbo87/ember.js,mfeckie/ember.js,mixonic/ember.js,knownasilya/ember.js
22d6877b66c928bda0e53fbe4c43a3bdf50f01d2
data/file.js
data/file.js
// TODO docs, see data/breakpoint.js define(function(require, exports, module) { var Data = require("./data"); function File(options) { this.data = options || {}; if (!this.data.items) this.data.items = []; if (!this.data.status) this.data.status = "pending"; this.type = "file"; this.keepChildren = true; } File.prototype = new Data( ["path", "type", "coverage", "passed", "fullOutput", "output", "ownPassed"], ["items"] ); File.prototype.__defineGetter__("passed", function(){ return typeof this.data.ownPassed == "number" ? this.data.ownPassed : this.data.passed; }); File.prototype.equals = function(file) { return this.data.label == file.label; }; File.prototype.addTest = function(def) { var test = Data.fromJSON([def])[0]; this.data.items.push(test); return test; }; module.exports = File; });
// TODO docs, see data/breakpoint.js define(function(require, exports, module) { var Data = require("./data"); function File(options) { this.data = options || {}; if (!this.data.items) this.data.items = []; if (!this.data.status) this.data.status = "pending"; this.type = "file"; this.keepChildren = true; } File.prototype = new Data( ["path", "type", "coverage", "passed", "fullOutput", "output", "ownPassed"], ["items"] ); File.prototype.__defineGetter__("passed", function(){ return typeof this.data.ownPassed == "number" ? this.data.ownPassed : this.data.passed; }); File.prototype.equals = function(file) { return this.data.label == file.label; }; File.prototype.addTest = function(def, parent) { var test = Data.fromJSON([def])[0]; (parent || this).data.items.push(test); return test; }; module.exports = File; });
Create Tests Dynamically When Needed
Create Tests Dynamically When Needed
JavaScript
mit
c9/c9.ide.test
6e3621cb2032e7bf9e6a5ad977efecd70798f8b7
test/util.test.js
test/util.test.js
/* global describe, it, beforeEach */ import React from 'react' import { expect } from 'chai' import { sizeClassNames } from '../src/js/util' describe('Util', () => { describe('sizeClassNames', () => { it('should return one classname given props', () => { const props = { xs: 12 } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12') }) it('should not return classnames given undefined props', () => { const props = { xs: 12, sm: undefined, md: undefined, lg: undefined, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12') }) it('should return all classnames given props', () => { const props = { xs: 12, sm: 6, md: 1, lg: 23, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12 col-sm-6 col-md-1 col-lg-23') }) }) })
/* global describe, it, beforeEach */ import React from 'react' import { expect } from 'chai' import { sizeClassNames } from '../src/js/util' describe('Util', () => { describe('sizeClassNames', () => { describe('using props', () => { it('should return one classname given props', () => { const props = { xs: 12 } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12') }) it('should not return classnames given undefined props', () => { const props = { xs: 12, sm: undefined, md: undefined, lg: undefined, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12') }) it('should return all classnames given props', () => { const props = { xs: 12, sm: 6, md: 1, lg: 23, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12 col-sm-6 col-md-1 col-lg-23') }) }) describe('using props and offset', () => { it('should return one offset classname given props', () => { const props = { xsOffset: 20 } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-offset-20') }) it('should not return one offset classname given undefined props', () => { const props = { xsOffset: 2, smOffset: undefined, mdOffset: undefined, lgOffset: undefined, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-offset-2') }) it('should return empty when offset is set to false', () => { const actual = sizeClassNames({}, { Offsets: false }) expect(actual).to.equal('') }) }) }) })
Add sizeClassNames Given Props & Offset Tests
Add sizeClassNames Given Props & Offset Tests
JavaScript
mit
frig-js/frigging-bootstrap,frig-js/frigging-bootstrap
31ee8ce20659751cb45fc1fc7c78167ce9171e1a
client/views/home/activities/trend/trend.js
client/views/home/activities/trend/trend.js
Template.homeResidentActivityLevelTrend.rendered = function () { // Get reference to template instance var instance = this; instance.autorun(function () { // Get reference to Route var router = Router.current(); // Get current Home ID var homeId = router.params.homeId; // Get data for trend line chart var data = ReactiveMethod.call("getHomeActivityCountTrend", homeId); if (data) { MG.data_graphic({ title: "Count of residents per activity level for each of last seven days", description: "Daily count of residents with inactive, semi-active, and active status.", data: [data[0], data[1], data[2]], x_axis: false, interpolate: 'basic', full_width: true, height: 200, right: 40, target: '#trend-chart', legend: ['Inactive','Semi-active','Active'], legend_target: '.legend', colors: ['red', 'gold', 'green'], aggregate_rollover: true }); } }); }
Template.homeResidentActivityLevelTrend.rendered = function () { // Get reference to template instance var instance = this; instance.autorun(function () { // Get reference to Route var router = Router.current(); // Get current Home ID var homeId = router.params.homeId; // Get data for trend line chart var data = ReactiveMethod.call("getHomeActivityCountTrend", homeId); if (data) { MG.data_graphic({ title: "Count of residents per activity level for each of last seven days", description: "Daily count of residents with inactive, semi-active, and active status.", data: data, x_axis: true, y_accessor: ['inactive', 'semiActive', 'active'], interpolate: 'basic', full_width: true, height: 333, right: 49, target: '#trend-chart', legend: ['Inactive','Semi-active','Active'], colors: ['red', 'gold', 'green'], aggregate_rollover: true }); } }); }
Use object attributes; adjust appearance
Use object attributes; adjust appearance
JavaScript
agpl-3.0
GeriLife/wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing
2d105c1489e2648a4a5036bce8a4d0059da3eb82
resources/public/js/rx.ontrail.pager.js
resources/public/js/rx.ontrail.pager.js
(function(){ // todo: remove depsu to elementBottomIsAlmostVisible var nextPage = function(elem) { var e = ($.isFunction(elem)) ? elem() : elem return Rx.Observable.interval(200).where(function() { return elementBottomIsAlmostVisible(e, 100) }) } var pager = function(ajaxSearch, page, next) { return ajaxSearch(page).selectMany(function(res) { if (res.length === 0) { _.map(["#content-spinner-content", "#content-spinner-latest"], function(elem) { $(elem).html("Ei enempää suorituksia") }) return rx.empty() } else { return rx.returnValue(res).concat(next.take(1).selectMany(function() { return pager(ajaxSearch, page+1, next) })) } }) } var Pager = function() {} Pager.prototype.create = function(ajaxQuery, elem) { return pager(ajaxQuery, 1, nextPage(elem)) } OnTrail.pager = new Pager() Rx.Observable.prototype.scrollWith = function(action, element, visibleElem) { return this.distinctUntilChanged().doAction(function() { element.html("") }) .selectArgs(function() { var partialAppliedArgs = [action].concat(_.argsToArray(arguments)) return OnTrail.pager.create(_.partial.apply(_.partial, partialAppliedArgs), visibleElem || element) }).switchLatest() } })()
(function(){ var timer = Rx.Observable.interval(100).publish() timer.connect() // todo: remove depsu to elementBottomIsAlmostVisible var nextPage = function(elem) { var e = ($.isFunction(elem)) ? elem() : elem return timer.where(function() { return elementBottomIsAlmostVisible(e, 100) }) } var pager = function(ajaxSearch, page, next) { return ajaxSearch(page).selectMany(function(res) { if (res.length === 0) { _.map(["#content-spinner-content", "#content-spinner-latest"], function(elem) { $(elem).html("Ei enempää suorituksia") }) return rx.empty() } else { return rx.returnValue(res).concat(next.take(1).selectMany(function() { return pager(ajaxSearch, page+1, next) })) } }) } var Pager = function() {} Pager.prototype.create = function(ajaxQuery, elem) { return pager(ajaxQuery, 1, nextPage(elem)) } OnTrail.pager = new Pager() Rx.Observable.prototype.scrollWith = function(action, element, visibleElem) { return this.distinctUntilChanged().doAction(function() { element.html("") }) .selectArgs(function() { var partialAppliedArgs = [action].concat(_.argsToArray(arguments)) return OnTrail.pager.create(_.partial.apply(_.partial, partialAppliedArgs), visibleElem || element) }).switchLatest() } })()
Use single hot observable as timed event stream.
Use single hot observable as timed event stream.
JavaScript
mit
jrosti/ontrail,jrosti/ontrail,jrosti/ontrail,jrosti/ontrail,jrosti/ontrail
ab5f7faeb6b09693c6804b011113ebe6bb8e9cd1
src/components/LandingCanvas/index.js
src/components/LandingCanvas/index.js
import React from 'react'; import Helmet from 'react-helmet'; import styles from './styles'; function calculateViewportFromWindow() { if (window.innerWidth >= 544) return 'sm'; if (window.innerWidth >= 768) return 'md'; if (window.innerWidth >= 992) return 'lg'; if (window.innerWidth >= 1200) return 'xl'; return'xs'; } function renderAugmentedChildren(props) { return React.Children.map(props.children, (child) => { if (!child) return null; return React.cloneElement(child, { viewport: props.viewport }); }); } const LandingCanvas = (props) => { const s = styles(props); let { viewport } = props; viewport = viewport || calculateViewportFromWindow(); return ( <div style={ s.wrapper }> <Helmet link={[ { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato' }, { rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css' } ]} /> { renderAugmentedChildren(props) } </div> ); } export default LandingCanvas;
import React from 'react'; import Helmet from 'react-helmet'; import styles from './styles'; function calculateViewportFromWindow() { if (typeof window !== 'undefined') { if (window.innerWidth >= 544) return 'sm'; if (window.innerWidth >= 768) return 'md'; if (window.innerWidth >= 992) return 'lg'; if (window.innerWidth >= 1200) return 'xl'; return'xs'; } else { return null; } } function renderAugmentedChildren(props) { return React.Children.map(props.children, (child) => { if (!child) return null; return React.cloneElement(child, { viewport: props.viewport }); }); } const LandingCanvas = (props) => { const s = styles(props); let { viewport } = props; viewport = viewport || calculateViewportFromWindow(); return ( <div style={ s.wrapper }> <Helmet link={[ { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato' }, { rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css' } ]} /> { renderAugmentedChildren(props) } </div> ); } export default LandingCanvas;
Disable viewport calculation in case of server side render
Disable viewport calculation in case of server side render
JavaScript
mit
line64/landricks-components
f43bcef83577cbc4ef82098ee9bae8fdf709b559
ui/src/stores/photos/index.js
ui/src/stores/photos/index.js
const SET_PHOTOS = 'SET_PHOTOS' const initialState = { photos: [], photosDetail: [] } const photos = (state = initialState, action = {}) => { switch (action.type) { case SET_PHOTOS: return {...state, photos: action.payload.ids, photosDetail:action.payload.photoList} default: return state } } export default photos
const SET_PHOTOS = 'SET_PHOTOS' const initialState = { photos: [], photosDetail: [] } const photos = (state = initialState, action = {}) => { switch (action.type) { case SET_PHOTOS: let index = state.photosDetail.filter((el) => { return action.payload.photoList.findIndex( (node) => el.node.id == node.node.id) }); return {...state, photos: Array.from(new Set([...state.photos, ...action.payload.ids])), photosDetail:[...state.photosDetail, ...action.payload.photoList]} default: return state } } export default photos
Add conditions to remove duplicates.
Add conditions to remove duplicates.
JavaScript
agpl-3.0
damianmoore/photo-manager,damianmoore/photo-manager,damianmoore/photo-manager,damianmoore/photo-manager
a73508bdc6301e616eb15a7f3ee88a5eb982e466
lib/registration.js
lib/registration.js
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('./service-worker.js', {scope: './'}) .catch(function(error) { alert('Error registering service worker:'+error); }); } else { alert('service worker not supported'); }
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('./service-worker.js', {scope: './'}) .catch(function(error) { console.error('Error registering service worker:'+error); }); } else { console.log('service worker not supported'); }
Use console.error and console.log instead of alert
Use console.error and console.log instead of alert
JavaScript
mit
marco-c/broccoli-serviceworker,jkleinsc/broccoli-serviceworker
1ebfe684c986124dd8fbf7a951b1c8e8ae94f371
lib/socketServer.js
lib/socketServer.js
const socketio = require('socket.io') const data = require('../data/tasks') let counter = 0 exports.listen = function (server) { io = socketio.listen(server) io.sockets.on('connection', function (socket) { console.log('Connection created') createTask(socket) displayAllTask(socket) }) const createTask = (socket) => { socket.on('createTask', (data) => { console.log('DB call-->', data.title, data.description, data.assignedTo, data.dueDate) //++counter let counter = ++data.seq console.log('Counter = ', counter) data['tasks'][counter] = { title: data.title, desc: data.description, status: 'new', assgnBy: 'current', assgnTo: data.assignedTo, createdOn: new Date().toISOString(), dueDate: data.dueDate } io.emit('updateTaskList', data) }) } const displayAllTask = (socket) => { socket.on('populateAllTask', (data) => { socket.emit('displayAllTask', data) }) } }
const socketio = require('socket.io') const data = require('../data/tasks') exports.listen = function (server) { io = socketio.listen(server) io.sockets.on('connection', function (socket) { console.log('Connection created') createTask(socket) displayAllTask(socket) }) const createTask = (socket) => { socket.on('createTask', (task) => { let counter = ++(data.seq) data['tasks'][counter] = { title: task.title, desc: task.description, status: 'new', assgnBy: 'current', assgnTo: task.assignedTo, createdOn: new Date().toISOString(), dueDate: task.dueDate } io.emit('updateTaskList', {task: task, status: 'new'}) }) } const displayAllTask = (socket) => { socket.on('populateAllTask', (data) => { socket.emit('displayAllTask', data) }) } }
Add createTask on and emit event with mock data
[SocketServer.js] Add createTask on and emit event with mock data
JavaScript
mit
geekskool/taskMaster,geekskool/taskMaster
3cebd82a19df42814f79725c8ab168ca50ff2b2e
routes/updateUserProfile.js
routes/updateUserProfile.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const insecurity = require('../lib/insecurity') const utils = require('../lib/utils') const cache = require('../data/datacache') const challenges = cache.challenges module.exports = function updateUserProfile () { return (req, res, next) => { const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token) if (loggedInUser) { models.User.findByPk(loggedInUser.data.id).then(user => { utils.solveIf(challenges.csrfChallenge, () => { return ((req.headers.origin && req.headers.origin.includes('://htmledit.squarefree.com')) || (req.headers.referrer && req.headers.referrer.includes('://htmledit.squarefree.com'))) && req.body.username !== user.username }) return user.update({ username: req.body.username }) }).catch(error => { next(error) }) } else { next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress)) } res.location(process.env.BASE_PATH + '/profile') res.redirect(process.env.BASE_PATH + '/profile') } }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const insecurity = require('../lib/insecurity') const utils = require('../lib/utils') const cache = require('../data/datacache') const challenges = cache.challenges module.exports = function updateUserProfile () { return (req, res, next) => { const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token) if (loggedInUser) { models.User.findByPk(loggedInUser.data.id).then(user => { utils.solveIf(challenges.csrfChallenge, () => { return ((req.headers.origin && req.headers.origin.includes('://htmledit.squarefree.com')) || (req.headers.referer && req.headers.referer.includes('://htmledit.squarefree.com'))) && req.body.username !== user.username }) return user.update({ username: req.body.username }) }).catch(error => { next(error) }) } else { next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress)) } res.location(process.env.BASE_PATH + '/profile') res.redirect(process.env.BASE_PATH + '/profile') } }
Fix spelling of HTTP referer header
Fix spelling of HTTP referer header
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
5cf61c9fb5cb120e1531ac636e12727aee3768a6
lib/rsautl.js
lib/rsautl.js
var fs = require('fs'); var run = require('./runner'); var defaults = { opensslPath : '/usr/bin/openssl', padding : 'pkcs' }; function verifyOptions (options) { if (!fs.existsSync(options.opensslPath)) { throw new Error(options.opensslPath + ': No such file or directory'); } if (options.padding !== 'pkcs' && options.padding !== 'raw') { throw new Error('Unsupported padding: ' + options.padding); } } function operation (data, key, callback, options) { var options = options || {}; for (var attr in defaults) { if (!options[attr]) options[attr] = defaults[attr]; } options.operation = operation.caller.name; try { verifyOptions(options); run(options, data, key, callback); } catch (err) { return callback(err); } } exports.encrypt = function encrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.decrypt = function decrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.sign = function sign (data, key, callback, options) { operation(data, key, callback, options); }; exports.verify = function verify (data, key, callback, options) { operation(data, key, callback, options); };
var fs = require('fs'); var run = require('./runner'); var defaults = { opensslPath : '/usr/bin/openssl', padding : 'pkcs' }; function verifyOptions (options) { if (fs.existsSync !== undefined && !fs.existsSync(options.opensslPath)) { throw new Error(options.opensslPath + ': No such file or directory'); } if (options.padding !== 'pkcs' && options.padding !== 'raw') { throw new Error('Unsupported padding: ' + options.padding); } } function operation (data, key, callback, options) { var options = options || {}; for (var attr in defaults) { if (!options[attr]) options[attr] = defaults[attr]; } options.operation = operation.caller.name; try { verifyOptions(options); run(options, data, key, callback); } catch (err) { return callback(err); } } exports.encrypt = function encrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.decrypt = function decrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.sign = function sign (data, key, callback, options) { operation(data, key, callback, options); }; exports.verify = function verify (data, key, callback, options) { operation(data, key, callback, options); };
Handle Meteor's stripping out methods from the fs core API.
Handle Meteor's stripping out methods from the fs core API.
JavaScript
bsd-2-clause
ragnar-johannsson/rsautl
43590c27a485c93298bd89be4a1fe84e32aae30b
rollup.config.js
rollup.config.js
import resolve from 'rollup-plugin-node-resolve'; import eslint from 'rollup-plugin-eslint'; import babel from 'rollup-plugin-babel'; import commonjs from 'rollup-plugin-commonjs'; import replace from 'rollup-plugin-replace'; import pkg from './package.json'; export default [ { input: 'src/index.js', external: ['react', 'react-dom'], output: [ { file: pkg.main, format: 'umd', name: 'reactAccessibleAccordion' }, { file: pkg['jsnext:main'], format: 'es' }, ], name: 'reactAccessibleAccordion', plugins: [ resolve({ jsnext: true, main: true, browser: true, }), eslint(), babel(), commonjs(), replace({ exclude: 'node_modules/**', ENV: JSON.stringify(process.env.NODE_ENV || 'development'), }), ], }, ];
import resolve from 'rollup-plugin-node-resolve'; import eslint from 'rollup-plugin-eslint'; import babel from 'rollup-plugin-babel'; import commonjs from 'rollup-plugin-commonjs'; import replace from 'rollup-plugin-replace'; import pkg from './package.json'; export default [ { input: 'src/index.js', external: ['react', 'react-dom'], output: [ { file: pkg.main, format: 'umd', name: 'reactAccessibleAccordion' }, { file: pkg['jsnext:main'], format: 'es' }, ], name: 'reactAccessibleAccordion', plugins: [ replace({ 'process.env.NODE_ENV': JSON.stringify('production'), }), resolve({ jsnext: true, main: true, browser: true, }), eslint(), babel(), commonjs(), ], }, ];
Fix 'rollup-plugin-replace' order and variable name
Fix 'rollup-plugin-replace' order and variable name
JavaScript
mit
springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion
206175481008af3ad074840a80f41816dcc2991c
public/app/components/chooseLanguage/chooseLanguage.js
public/app/components/chooseLanguage/chooseLanguage.js
product .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'components/chooseLanguage/chooseLanguage.tpl.html' ,controller: 'ChooseLanguageCtrl' ,resolve: { LanguageService: 'LanguageService', languages: function(LanguageService){ // This line is updated to return the promise //return LanguageService.query().$promise; } } }) .otherwise({ redirectTo: '/whatever' }); } ) .controller("ChooseLanguageCtrl", ['$scope','$http', '$q', '$location', 'LanguageService', ChooseLanguageCtrl]); function ChooseLanguageCtrl($scope, $http, $q, $location, LanguageService) { $scope.languages = LanguageService.query().$promise; $scope.languages.then(function (data) {$scope.languages= data;}); //Methods $scope.getCityWeather = function () { var data = LanguageService.get({city: $scope.select_city}).$promise; data.then(function(data) { $scope.information = data; }); }; } ;
product .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'components/chooseLanguage/chooseLanguage.tpl.html' ,resolve: { $b: ["$q", "LanguageService", function ($q, LanguageService) { return $q.all({ languages: LanguageService.query().$promise }); }] } ,controller: 'ChooseLanguageCtrl' }) .otherwise({ redirectTo: '/whatever' }); } ) .controller("ChooseLanguageCtrl", ['$scope','$http', '$q', '$location', '$b', 'LanguageService', ChooseLanguageCtrl]); function ChooseLanguageCtrl($scope, $http, $q, $location, $b, LanguageService) { angular.extend($scope, $b); //$scope.languages = LanguageService.query().$promise; //$scope.languages.then(function (data) {$scope.languages= data;}); //Methods $scope.getCityWeather = function () { var data = LanguageService.get({city: $scope.select_city}).$promise; data.then(function(data) { $scope.information = data; }); }; } ;
Fix change to resolve promise before controller
Fix change to resolve promise before controller
JavaScript
mit
stevenrojasv21/product-list-steven-rojas,stevenrojasv21/product-list-steven-rojas,stevenrojasv21/product-list-steven-rojas
4817ef6d6d10db74bc67a3f07c8db75bb2e3dd6e
common/predictive-text/unit_tests/headless/default-word-breaker.js
common/predictive-text/unit_tests/headless/default-word-breaker.js
/** * Smoke-test the default */ var assert = require('chai').assert; var breakWords = require('../../build/intermediate').wordBreakers['uax29']; const SHY = '\u00AD'; describe('The default word breaker', function () { it('should break multilingual text', function () { let breaks = breakWords( `ᑖᓂᓯ᙮ рабочий — after working on ka${SHY}wen${SHY}non:${SHY}nis let's eat phở! 🥣` ); let words = breaks.map(span => span.text); assert.deepEqual(words, [ 'ᑖᓂᓯ', '᙮', 'рабочий', '—', 'after', 'working', 'on', `ka${SHY}wen${SHY}non:${SHY}nis`, "let's", 'eat', 'phở', '!', '🥣' ]); }); });
/** * Smoke-test the default */ var assert = require('chai').assert; var breakWords = require('../../build/intermediate').wordBreakers['uax29']; const SHY = '\u00AD'; describe('The default word breaker', function () { it('should break multilingual text', function () { let breaks = breakWords( `Добрый день! ᑕᐻ᙮ — after working on ka${SHY}wen${SHY}non:${SHY}nis, let's eat phở! 🥣` ); let words = breaks.map(span => span.text); assert.deepEqual(words, [ 'Добрый', 'день', '!', 'ᑕᐻ', '᙮', '—', 'after', 'working', 'on', `ka${SHY}wen${SHY}non:${SHY}nis`, ',', "let's", 'eat', 'phở', '!', '🥣' ]); }); });
Make unit test slightly less weird.
Make unit test slightly less weird.
JavaScript
apache-2.0
tavultesoft/keymanweb,tavultesoft/keymanweb
5f079cbed8904f50c273aa5a017172081d91021f
js/projects.js
js/projects.js
/** * Created by sujithkatakam on 3/15/16. */ function pagination() { var monkeyList = new List('test-list', { valueNames: ['name'], page: 4, innerWindow: 4, plugins: [ ListPagination({}) ] }); } window.onload = function() { pagination(); getMonthsCount('experience', new Date(2014, 10, 15)); };
/** * Created by sujithkatakam on 3/15/16. */ function pagination() { var monkeyList = new List('test-list', { valueNames: ['name'], page: 4, innerWindow: 4, plugins: [ ListPagination({}) ] }); } window.onload = function() { pagination(); getMonthsCount('experience', new Date(2014, 10, 15), new Date(2016, 03, 15)); };
Work ex fix in summary
Work ex fix in summary
JavaScript
apache-2.0
sujithktkm/sujithktkm.github.io,sujithktkm/sujithktkm.github.io
c91d95333da23c09b5f9df9e5a591b2d007ea531
server/auth/craftenforum.js
server/auth/craftenforum.js
"use strict"; const passport = require('passport'); const BdApiStrategy = require('passport-bdapi').Strategy; module.exports = (config, app, passport, models) => { passport.use(new BdApiStrategy({ apiURL: config.apiUrl, clientID: config.clientId, clientSecret: config.clientSecret, callbackURL: config.callbackUrl }, (accessToken, refreshToken, profile, done) => { models.User.findOne({oauthId: `cf-${profile.user_id}`}, (err, user) => { if (user) { user.username = profile.username; user.save(err => done(err, user)); } else { models.User.create({ oauthId: "cf-#{profile.user_id}", username: profile.username }) .then(user => done(null, user)) .then(null, err => done(err, null)); } }); })); app.get('/auth/craftenforum', passport.authenticate('oauth2', {scope: 'read'}) ); app.get('/auth/craftenforum/callback', passport.authenticate('oauth2', {failureRedirect: '/'}), (req, res) => res.redirect('/') ); };
"use strict"; const passport = require('passport'); const BdApiStrategy = require('passport-bdapi').Strategy; module.exports = (config, app, passport, models) => { passport.use(new BdApiStrategy({ apiURL: config.apiUrl, clientID: config.clientId, clientSecret: config.clientSecret, callbackURL: config.callbackUrl }, (accessToken, refreshToken, profile, done) => { models.User.findOne({oauthId: `cf-${profile.user_id}`}, (err, user) => { if (user) { user.username = profile.username; user.save(err => done(err, user)); } else { models.User.create({ oauthId: `cf-${profile.user_id}`, username: profile.username }) .then(user => done(null, user)) .then(null, err => done(err, null)); } }); })); app.get('/auth/craftenforum', passport.authenticate('oauth2', {scope: 'read'}) ); app.get('/auth/craftenforum/callback', passport.authenticate('oauth2', {failureRedirect: '/'}), (req, res) => res.redirect('/') ); };
Fix wrong oauthId when creating users.
Fix wrong oauthId when creating users.
JavaScript
mit
leMaik/EduCraft-Editor,leMaik/EduCraft-Editor,leMaik/EduCraft-Editor,leMaik/EduCraft-Editor
1eeb1d49f7214732754b359bea00025d11395e4b
server/game/cards/02.2-FHaG/RaiseTheAlarm.js
server/game/cards/02.2-FHaG/RaiseTheAlarm.js
const DrawCard = require('../../drawcard.js'); class RaiseTheAlarm extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Flip a dynasty card', condition: context => this.game.isDuringConflict('military') && context.player.isDefendingPlayer(), cannotBeMirrored: true, effect: 'flip the card in the conflict province faceup', gameAction: ability.actions.flipDynasty(context => ({ target: context.player.controller.getDynastyCardInProvince(this.game.currentConflict.conflictProvince.location) })), then: context => ({ handler: () => { let card = context.player.controller.getDynastyCardInProvince(this.game.currentConflict.conflictProvince.location); if(card.type === 'character' && card.allowGameAction('putIntoConflict', context)) { this.game.addMessage('{0} is revealed and brought into the conflict!', card); ability.actions.putIntoConflict().resolve(card, context); } else { this.game.addMessage('{0} is revealed but cannot be brought into the conflict!', card); } } }) }); } } RaiseTheAlarm.id = 'raise-the-alarm'; module.exports = RaiseTheAlarm;
const DrawCard = require('../../drawcard.js'); class RaiseTheAlarm extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Flip a dynasty card', condition: context => this.game.isDuringConflict('military') && context.player.isDefendingPlayer(), cannotBeMirrored: true, effect: 'flip the card in the conflict province faceup', gameAction: ability.actions.flipDynasty(context => ({ target: context.player.getDynastyCardInProvince(this.game.currentConflict.conflictProvince.location) })), then: context => ({ handler: () => { let card = context.player.controller.getDynastyCardInProvince(this.game.currentConflict.conflictProvince.location); if(card.type === 'character' && card.allowGameAction('putIntoConflict', context)) { this.game.addMessage('{0} is revealed and brought into the conflict!', card); ability.actions.putIntoConflict().resolve(card, context); } else { this.game.addMessage('{0} is revealed but cannot be brought into the conflict!', card); } } }) }); } } RaiseTheAlarm.id = 'raise-the-alarm'; module.exports = RaiseTheAlarm;
Fix Raise the Alarm bug
Fix Raise the Alarm bug
JavaScript
mit
gryffon/ringteki,jeremylarner/ringteki,gryffon/ringteki,gryffon/ringteki,jeremylarner/ringteki,jeremylarner/ringteki
51be095bab5e4c8b34b8e2dda0bd56a565d43bad
app.js
app.js
/** * @module App Main Application Module */ 'use strict'; const express = require('express'); const app = express(); const api = require('./api/api.router'); app.use('/', express.static('public')); app.use('/api', api); module.exports = app;
/** * @module App Main Application Module */ 'use strict'; const express = require('express'); const app = express(); app.set('trust proxy', true); const api = require('./api/api.router'); app.use('/', express.static('public')); app.use('/api', api); module.exports = app;
Set trust proxy to true
Set trust proxy to true
JavaScript
mit
agroupp/test-api,agroupp/test-api
55a86b726335b4dbc2fa45b43e82c6245fdfed82
src/routes/Home/components/HomeView.js
src/routes/Home/components/HomeView.js
import React, { Component } from 'react' import { connect } from 'react-redux' import PropTypes from 'prop-types' import Sidebar from '../../../components/Sidebar' import TopicList from '../../../components/TopicList' import './HomeView.scss' class HomeView extends Component { static propTypes = { topics: PropTypes.object } transformTopicsToArray (obj) { const ids = Object.keys(obj) let arr = ids.map(id => { return { id: id, name: obj[id].name, point: obj[id].point } }) return arr } render () { return ( <div> <div className='column column--main'> <TopicList topics={this.transformTopicsToArray(this.props.topics)} /> </div> <div className='column column--side'> <Sidebar /> </div> </div> ) } } const mapStateToProps = state => { return { topics: state.topic.topics } } export default connect(mapStateToProps, null)(HomeView)
import React, { Component } from 'react' import { connect } from 'react-redux' import PropTypes from 'prop-types' import Sidebar from '../../../components/Sidebar' import TopicList from '../../../components/TopicList' import './HomeView.scss' class HomeView extends Component { static propTypes = { topics: PropTypes.object } constructor (props) { super(props) this.preprocessTopics = this.preprocessTopics.bind(this) } transformTopicsToArray (obj) { const ids = Object.keys(obj) let arr = ids.map(id => { return { id: id, name: obj[id].name, point: obj[id].point } }) return arr } sortTopicsByPoint (topics) { return topics.sort((a, b) => b.point - a.point) } preprocessTopics (topics) { let newTopics = this.transformTopicsToArray(topics) return this.sortTopicsByPoint(newTopics) } render () { return ( <div> <div className='column column--main'> <TopicList topics={this.preprocessTopics(this.props.topics)} /> </div> <div className='column column--side'> <Sidebar /> </div> </div> ) } } const mapStateToProps = state => { return { topics: state.topic.topics } } export default connect(mapStateToProps, null)(HomeView)
Sort topics by the number of upvotes/downvotes
Sort topics by the number of upvotes/downvotes
JavaScript
mit
AdrielLimanthie/carousell-reddit,AdrielLimanthie/carousell-reddit
a9817a7d8b33fa27072d5f5a55cfc49e00eada71
webpack.development.config.js
webpack.development.config.js
//extend webpack.config.js var config = require('./webpack.config'); var path = require('path'); //for more info, look into webpack.config.js //this will add a new object into default settings // config.entry = [ // 'webpack/hot/dev-server', // 'webpack-dev-server/client?http://localhost:8080', // ]; config.entry.app.push('webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080'); config.output = { path: path.resolve('dist'), filename: 'app.js', publicPath: '/' }; config.devtool = 'source-map'; config.devServer = { contentBase: 'src', stats: { colors: true }, hot: true }; module.exports = config;
//extend webpack.config.js var config = require('./webpack.config'); var path = require('path'); //for more info, look into webpack.config.js //this will add a new object into default settings // config.entry = [ // 'webpack/hot/dev-server', // 'webpack-dev-server/client?http://localhost:8080', // ]; config.entry.app.push('webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080'); config.output = { path: path.resolve('dist'), filename: 'app.js', publicPath: '/' }; config.devtool = 'source-map'; config.devServer = { contentBase: 'src', stats: { colors: true }, host: '0.0.0.0', hot: true, //UNCOMMENT THIS if you need to call you backend server // proxy: { // '/api/**': { // target: 'http://localhost:3000', // secure: false // } // } }; module.exports = config;
Allow server to be accessed via IP
Allow server to be accessed via IP
JavaScript
isc
terryx/react-webpack,terryx/react-webpack
c1439e9e07786a46290a550304f3c9014a1b3d06
src/app/projects/controller/project_list_controller.js
src/app/projects/controller/project_list_controller.js
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * 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. */ /** * The project list controller handles discovery for all projects, including * search. Note that it is assumed that we implemented a search (inclusive), * rather than a browse (exclusive) approach. */ angular.module('sb.projects').controller('ProjectListController', function ($scope) { 'use strict'; // search results must be of type "project" $scope.resourceTypes = ['Project']; // Projects have no default criteria $scope.defaultCriteria = []; });
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * 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. */ /** * The project list controller handles discovery for all projects, including * search. Note that it is assumed that we implemented a search (inclusive), * rather than a browse (exclusive) approach. */ angular.module('sb.projects').controller('ProjectListController', function ($scope, isSuperuser) { 'use strict'; // inject superuser flag to properly adjust UI. $scope.is_superuser = isSuperuser; // search results must be of type "project" $scope.resourceTypes = ['Project']; // Projects have no default criteria $scope.defaultCriteria = []; });
Tweak for Superuser UI in projects.
Tweak for Superuser UI in projects. This will properly align the create-project button for superadmin. Change-Id: Id79c7daa66b7db559bda5a41e494f17d519cf6a3
JavaScript
apache-2.0
ColdrickSotK/storyboard-webclient,ColdrickSotK/storyboard-webclient,ColdrickSotK/storyboard-webclient
dbf22af2728160fbe45245c9a779dec2f634cbe4
app/assets/javascripts/tests/helpers/common.js
app/assets/javascripts/tests/helpers/common.js
const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); // Require and load .env vars require('./dotenv'); // Configure chai to use Sinon-Chai chai.should(); chai.use(sinonChai); global.expect = chai.expect; global.sinon = sinon;
/** * This file is globally included on every testcase instance. It is useful to * load constants such as `chai`, `sinon` or any setup phase that we need. In * our case, we need to setup sinon-chai, avoiding repeating a chunk of code * across our test files. */ const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); // Require and load .env vars require('./dotenv'); // Configure chai to use Sinon-Chai chai.should(); chai.use(sinonChai); global.expect = chai.expect; global.sinon = sinon;
Add docs on global test file
Add docs on global test file
JavaScript
bsd-3-clause
kriansa/amelia,kriansa/amelia,kriansa/amelia,kriansa/amelia
b260f27e0176f2615236e78e06c8af045f5b0680
scripts/build.js
scripts/build.js
const buildBaseCss = require(`./_build-base-css.js`); const buildBaseHtml = require(`./_build-base-html.js`); const buildPackageCss = require(`./_build-package-css.js`); const buildPackageHtml = require(`./_build-package-html.js`); const getDirectories = require(`./_get-directories.js`); const packages = getDirectories(`avalanche/packages`); const data = {}; buildBaseHtml({}); buildBaseCss(); packages.forEach((packageName) => { data.title = packageName; data.css = `<link rel="stylesheet" href="css/index.css">`; data.scripts = ``; buildPackageHtml(packageName, data); buildPackageCss(packageName); });
const buildBaseCss = require(`./_build-base-css.js`); const buildBaseHtml = require(`./_build-base-html.js`); const buildPackageCss = require(`./_build-package-css.js`); const buildPackageHtml = require(`./_build-package-html.js`); const getDirectories = require(`./_get-directories.js`); const packages = getDirectories(`avalanche/packages`); const data = { css: `<link rel="stylesheet" href="/base/css/global.css">` }; buildBaseHtml(data); buildBaseCss(); packages.forEach((packageName) => { data.title = packageName; data.css += `<link rel="stylesheet" href="css/index.css">`; data.scripts = ``; buildPackageHtml(packageName, data); buildPackageCss(packageName); });
Add global.css file to pages by default
Add global.css file to pages by default
JavaScript
mit
avalanchesass/avalanche-website,avalanchesass/avalanche-website
c8a608cf64c5fb9ce0f24beee53b7acccfc4cd03
packages/custom/icu/public/components/data/context/context.service.js
packages/custom/icu/public/components/data/context/context.service.js
'use strict'; angular.module('mean.icu').service('context', function ($injector, $q) { var mainMap = { task: 'tasks', user: 'people', project: 'projects', discussion: 'discussions', officeDocument:'officeDocuments', office: 'offices', templateDoc: 'templateDocs', folder: 'folders' }; return { entity: null, entityName: '', entityId: '', main: '', setMain: function (main) { this.main = mainMap[main]; }, getContextFromState: function(state) { var parts = state.name.split('.'); if (parts[0] === 'main') { var reverseMainMap = _(mainMap).invert(); var main = 'task'; if (parts[1] !== 'search') { main = reverseMainMap[parts[1]]; } var params = state.params; var entityName = params.entity; if (!entityName && parts[2] === 'all') { entityName = 'all'; } if (!entityName && parts[2] === 'byassign') { entityName = 'my'; } if (!entityName && parts[2] === 'byparent') { entityName = main; } return { main: main, entityName: entityName, entityId: params.entityId }; } } }; });
'use strict'; angular.module('mean.icu').service('context', function ($injector, $q) { var mainMap = { task: 'tasks', user: 'people', project: 'projects', discussion: 'discussions', officeDocument:'officeDocuments', office: 'offices', templateDoc: 'templateDocs', folder: 'folders' }; return { entity: null, entityName: '', entityId: '', main: '', setMain: function (main) { this.main = mainMap[main]; }, getContextFromState: function(state) { var parts = state.name.split('.'); if (parts[0] === 'main') { var reverseMainMap = _(mainMap).invert(); var main = 'task'; if (parts[1] !== 'search') { main = reverseMainMap[parts[1]]; } // When in context of search, the entity you selected is in parts[2] if (parts[1] == 'search') { main = reverseMainMap[parts[2]]; } var params = state.params; var entityName = params.entity; if (!entityName && parts[2] === 'all') { entityName = 'all'; } if (!entityName && parts[2] === 'byassign') { entityName = 'my'; } if (!entityName && parts[2] === 'byparent') { entityName = main; } return { main: main, entityName: entityName, entityId: params.entityId }; } } }; });
Make correct context when select entity in search
Make correct context when select entity in search
JavaScript
mit
linnovate/icu,linnovate/icu,linnovate/icu
e5985521ee1fd0960dcc6af004e5dd831857685d
app/props/clickable.js
app/props/clickable.js
import Prop from 'props/prop'; import canvas from 'canvas'; import mouse from 'lib/mouse'; // http://stackoverflow.com/questions/16628184/add-onclick-and-onmouseover-to-canvas-element export default class Clickable extends Prop { constructor(x, y, width, height, fn) { super(x, y, width, height); this.fn = fn; this.onClick = this.onClick.bind(this); } onClick(event) { const coords = mouse.getCoordinates(event); if (this.isPointInside(coords.x, coords.y)) { this.fn(); this.destroy(); } } render() { canvas.addEventListener('click', this.onClick); // @TODO: Remove this debug when complete. super.render(null, null, 'rgba(50, 50, 50, 1)'); } destroy() { canvas.removeEventListener('click', this.onClick); } isPointInside(x, y) { return (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height); } }
import Prop from 'props/prop'; import canvas from 'canvas'; import mouse from 'lib/mouse'; // http://stackoverflow.com/questions/16628184/add-onclick-and-onmouseover-to-canvas-element export default class Clickable extends Prop { constructor(x, y, width, height, fn) { super(x, y, width, height); this.fn = fn; this.onClick = this.onClick.bind(this); } onClick(event) { const coords = mouse.getCoordinates(event); if (this.isPointInside(coords.x, coords.y)) { this.fn(); this.destroy(); } } render() { canvas.addEventListener('click', this.onClick); } destroy() { canvas.removeEventListener('click', this.onClick); } isPointInside(x, y) { return (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height); } }
Remove rendering for debugging click handlers
Remove rendering for debugging click handlers
JavaScript
mit
oliverbenns/pong,oliverbenns/pong
2a8cd200a67562a32fcce6dd01e253985e94d18a
05/jjhampton-ch5-every-some.js
05/jjhampton-ch5-every-some.js
// Arrays also come with the standard methods every and some. Both take a predicate function that, when called with an array element as argument, returns true or false. Just like && returns a true value only when the expressions on both sides are true, every returns true only when the predicate returns true for all elements of the array. Similarly, some returns true as soon as the predicate returns true for any of the elements. They do not process more elements than necessary—for example, if some finds that the predicate holds for the first element of the array, it will not look at the values after that. // Write two functions, every and some, that behave like these methods, except that they take the array as their first argument rather than being a method. function every(array, action) { let conditional = true; for (let i = 0; i < array.length; i++) { if (!action(array[i])) conditional = false; } return conditional; } function some(array, action) { let conditional = false; for (let i = 0; i < array.length; i++) { if (action(array[i])) conditional = true; } return conditional; } console.log(every([NaN, NaN, NaN], isNaN)); console.log(every([NaN, NaN, 4], isNaN)); console.log(some([NaN, 3, 4], isNaN)); console.log(some([2, 3, 4], isNaN));
// Arrays also come with the standard methods every and some. Both take a predicate function that, when called with an array element as argument, returns true or false. Just like && returns a true value only when the expressions on both sides are true, every returns true only when the predicate returns true for all elements of the array. Similarly, some returns true as soon as the predicate returns true for any of the elements. They do not process more elements than necessary—for example, if some finds that the predicate holds for the first element of the array, it will not look at the values after that. // Write two functions, every and some, that behave like these methods, except that they take the array as their first argument rather than being a method. function every(array, action) { for (let i = 0; i < array.length; i++) { if (!action(array[i])) return false; } return true; } function some(array, action) { for (let i = 0; i < array.length; i++) { if (action(array[i])) return true; } return false; } console.log(every([NaN, NaN, NaN], isNaN)); console.log(every([NaN, NaN, 4], isNaN)); console.log(some([NaN, 3, 4], isNaN)); console.log(some([2, 3, 4], isNaN));
Enable every/some methods to return early to prevent iterating over entire array
Enable every/some methods to return early to prevent iterating over entire array
JavaScript
mit
OperationCode/eloquent-js
35ead74f1fcb0b20d83be28cc9e187cdfe115373
servers/index.js
servers/index.js
require('coffee-script').register(); var argv = require('minimist')(process.argv); // require('./lib/source-server') module.exports = require('./lib/server');
require('coffee-script').register(); // require('./lib/source-server') module.exports = require('./lib/server');
Remove unused command line options parsing code
Remove unused command line options parsing code Signed-off-by: Sonmez Kartal <[email protected]>
JavaScript
agpl-3.0
usirin/koding,gokmen/koding,acbodine/koding,alex-ionochkin/koding,mertaytore/koding,kwagdy/koding-1,kwagdy/koding-1,gokmen/koding,jack89129/koding,szkl/koding,drewsetski/koding,andrewjcasal/koding,szkl/koding,usirin/koding,rjeczalik/koding,koding/koding,drewsetski/koding,jack89129/koding,kwagdy/koding-1,rjeczalik/koding,andrewjcasal/koding,usirin/koding,acbodine/koding,sinan/koding,szkl/koding,kwagdy/koding-1,sinan/koding,kwagdy/koding-1,andrewjcasal/koding,mertaytore/koding,koding/koding,szkl/koding,sinan/koding,szkl/koding,rjeczalik/koding,koding/koding,drewsetski/koding,cihangir/koding,kwagdy/koding-1,jack89129/koding,mertaytore/koding,usirin/koding,usirin/koding,koding/koding,sinan/koding,szkl/koding,jack89129/koding,kwagdy/koding-1,sinan/koding,sinan/koding,alex-ionochkin/koding,andrewjcasal/koding,andrewjcasal/koding,acbodine/koding,drewsetski/koding,alex-ionochkin/koding,mertaytore/koding,drewsetski/koding,andrewjcasal/koding,jack89129/koding,rjeczalik/koding,alex-ionochkin/koding,usirin/koding,cihangir/koding,acbodine/koding,gokmen/koding,jack89129/koding,drewsetski/koding,koding/koding,jack89129/koding,usirin/koding,andrewjcasal/koding,acbodine/koding,cihangir/koding,koding/koding,gokmen/koding,sinan/koding,cihangir/koding,cihangir/koding,mertaytore/koding,mertaytore/koding,szkl/koding,alex-ionochkin/koding,szkl/koding,drewsetski/koding,gokmen/koding,koding/koding,jack89129/koding,drewsetski/koding,cihangir/koding,cihangir/koding,acbodine/koding,kwagdy/koding-1,gokmen/koding,alex-ionochkin/koding,gokmen/koding,rjeczalik/koding,andrewjcasal/koding,sinan/koding,mertaytore/koding,gokmen/koding,alex-ionochkin/koding,rjeczalik/koding,usirin/koding,acbodine/koding,cihangir/koding,acbodine/koding,koding/koding,mertaytore/koding,rjeczalik/koding,rjeczalik/koding,alex-ionochkin/koding
376fda5bcdd5e0d4511ab08cd5c7125d72905e8b
lib/feature.js
lib/feature.js
var debug = require('debug')('rose'); var mongoose = require('mongoose'); var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/mydb'; debug('Connecting to MongoDB at ' + mongoURI + '...'); mongoose.connect(mongoURI); var featureSchema = new mongoose.Schema({ name: { type: String, required: true }, examples: { type: [{ technology: { type: String, required: true }, snippets: { type: [String], required: true } }], required: true } }); featureSchema.statics.search = function (query) { return this.find({ $or: [ { name: new RegExp(query, 'i') }, { examples: { $elemMatch: { $or: [ { technology: new RegExp(query, 'i') }, { snippets: new RegExp(query, 'i') } ] }}}, ]}) .lean() .select('-__v -_id -examples._id') .exec(); }; module.exports = mongoose.model('Feature', featureSchema);
var debug = require('debug')('rose'); var mongoose = require('mongoose'); var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/rose'; debug('Connecting to MongoDB at ' + mongoURI + '...'); mongoose.connect(mongoURI); var featureSchema = new mongoose.Schema({ name: { type: String, required: true }, examples: { type: [{ technology: { type: String, required: true }, snippets: { type: [String], required: true } }], required: true } }); featureSchema.statics.search = function (query) { return this.find({ $or: [ { name: new RegExp(query, 'i') }, { examples: { $elemMatch: { $or: [ { technology: new RegExp(query, 'i') }, { snippets: new RegExp(query, 'i') } ] }}}, ]}) .lean() .select('-__v -_id -examples._id') .exec(); }; module.exports = mongoose.model('Feature', featureSchema);
Rename the DB from mydb to rose
Rename the DB from mydb to rose
JavaScript
mit
nickmccurdy/rose,nickmccurdy/rose,nicolasmccurdy/rose,nicolasmccurdy/rose
59ae7095d382380d0a14871a1a571fb7c99b31f6
examples/hello-world/app.js
examples/hello-world/app.js
var app = module.exports = require('appjs').createApp({CachePath: '/Users/dbartlett/.cache1'}); app.serveFilesFrom(__dirname + '/content'); var window = app.createWindow({ width : 640, height : 460, icons : __dirname + '/content/icons' }); window.on('create', function(){ console.log("Window Created"); window.frame.show(); window.frame.center(); }); window.on('ready', function(){ console.log("Window Ready"); window.require = require; window.process = process; window.module = module; function F12(e){ return e.keyIdentifier === 'F12' } function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey } window.addEventListener('keydown', function(e){ if (F12(e) || Command_Option_J(e)) { window.frame.openDevTools(); } }); }); window.on('close', function(){ console.log("Window Closed"); });
var app = module.exports = require('appjs').createApp(); app.serveFilesFrom(__dirname + '/content'); var window = app.createWindow({ width : 640, height : 460, icons : __dirname + '/content/icons' }); window.on('create', function(){ console.log("Window Created"); window.frame.show(); window.frame.center(); }); window.on('ready', function(){ console.log("Window Ready"); window.require = require; window.process = process; window.module = module; function F12(e){ return e.keyIdentifier === 'F12' } function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey } window.addEventListener('keydown', function(e){ if (F12(e) || Command_Option_J(e)) { window.frame.openDevTools(); } }); }); window.on('close', function(){ console.log("Window Closed"); });
Remove testing CachePath from example.
Remove testing CachePath from example.
JavaScript
mit
tempbottle/appjs,SaravananRajaraman/appjs,yuhangwang/appjs,appjs/appjs,appjs/appjs,imshibaji/appjs,tempbottle/appjs,yuhangwang/appjs,modulexcite/appjs,yuhangwang/appjs,SaravananRajaraman/appjs,eric-seekas/appjs,eric-seekas/appjs,eric-seekas/appjs,SaravananRajaraman/appjs,appjs/appjs,SaravananRajaraman/appjs,modulexcite/appjs,eric-seekas/appjs,tempbottle/appjs,SaravananRajaraman/appjs,tempbottle/appjs,SaravananRajaraman/appjs,imshibaji/appjs,yuhangwang/appjs,appjs/appjs,imshibaji/appjs,modulexcite/appjs,imshibaji/appjs,modulexcite/appjs
01e2d7f7a2a533d6eebd750096ccb542e5c524ae
web/lib/socket.js
web/lib/socket.js
import log from './lib/log'; let socket = root.io.connect(''); socket.on('connect', () => { log.debug('socket.io: connected'); }); socket.on('error', () => { log.error('socket.io: error'); socket.destroy(); }); socket.on('close', () => { log.debug('socket.io: closed'); }); export default socket;
import log from './log'; let socket = root.io.connect(''); socket.on('connect', () => { log.debug('socket.io: connected'); }); socket.on('error', () => { log.error('socket.io: error'); socket.destroy(); }); socket.on('close', () => { log.debug('socket.io: closed'); }); export default socket;
Change the import path for log
Change the import path for log
JavaScript
mit
cheton/cnc.js,cheton/cnc,cncjs/cncjs,cheton/cnc,cncjs/cncjs,cheton/piduino-grbl,cheton/cnc,cheton/cnc.js,cheton/cnc.js,cheton/piduino-grbl,cncjs/cncjs,cheton/piduino-grbl
dd6f17e4f57e799a6200dec3f339f5ccba75de8d
webpack.config.js
webpack.config.js
var webpack = require('webpack'); var BrowserSyncPlugin = require('browser-sync-webpack-plugin'); module.exports = { context: __dirname, entry: './src/whoami.js', output: { path: './dist', filename: 'whoami.min.js', libraryTarget: 'var', library: 'whoami' }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, plugins: [ new BrowserSyncPlugin({ host: 'localhost', port: 3000, server: { baseDir: ['dist'] } }), new webpack.optimize.UglifyJsPlugin({ minimize: true }) ], resolve: { extensions: ['', '.js'] } }
var webpack = require('webpack'); var BrowserSyncPlugin = require('browser-sync-webpack-plugin'); module.exports = { context: __dirname, entry: './src/whoami.js', output: { path: './dist', filename: 'whoami.min.js', libraryTarget: 'var', library: 'whoami' }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, plugins: [ new BrowserSyncPlugin({ host: 'localhost', port: 3000, files: 'dist/*.*', server: { baseDir: ['dist'] } }), new webpack.optimize.UglifyJsPlugin({ minimize: true }) ], resolve: { extensions: ['', '.js'] } }
Watch dist files on browsersync
Watch dist files on browsersync
JavaScript
mit
andersonba/whoami.js
1ab999034c53389d359ab2161492a70e82c1ab47
src/wirecloud/fiware/static/js/WirecloudAPI/NGSIAPI.js
src/wirecloud/fiware/static/js/WirecloudAPI/NGSIAPI.js
(function () { "use strict"; var key, manager = window.parent.NGSIManager, NGSIAPI = {}; NGSIAPI.Connection = function Connection(url, options) { manager.Connection.call(this, 'operator', MashupPlatform.operator.id, url, options); }; NGSIAPI.Connection.prototype = window.parent.NGSIManager.Connection.prototype; Object.freeze(NGSIAPI); window.NGSI = NGSIAPI; })();
(function () { "use strict"; var key, manager = window.parent.NGSIManager, NGSIAPI = {}; if (MashupPlatform.operator != null) { NGSIAPI.Connection = function Connection(url, options) { manager.Connection.call(this, 'operator', MashupPlatform.operator.id, url, options); }; } else if (MashupPlatform.widget != null) { NGSIAPI.Connection = function Connection(url, options) { manager.Connection.call(this, 'widget', MashupPlatform.widget.id, url, options); }; } else { throw new Error('Unknown resource type'); } NGSIAPI.Connection.prototype = window.parent.NGSIManager.Connection.prototype; Object.freeze(NGSIAPI); window.NGSI = NGSIAPI; })();
Fix bug: export NGSI API also for widgets
Fix bug: export NGSI API also for widgets
JavaScript
agpl-3.0
jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud
1dcc6eab08d4df0e01427402503c5e26808e58ca
test/utils/to-date-time-in-time-zone.js
test/utils/to-date-time-in-time-zone.js
'use strict'; module.exports = function (t, a) { var mayanEndOfTheWorld = new Date(2012, 11, 21, 1, 1); a.deep(t(mayanEndOfTheWorld, 'America/Guatemala').valueOf(), new Date(2012, 11, 20, 18, 1).valueOf()); a.deep(t(mayanEndOfTheWorld, 'Europe/Warsaw').valueOf(), new Date(2012, 11, 21, 1, 1).valueOf()); };
'use strict'; module.exports = function (t, a) { var mayanEndOfTheWorld = new Date(Date.UTC(2012, 11, 21, 1, 1)); a.deep(t(mayanEndOfTheWorld, 'America/Guatemala').valueOf(), new Date(2012, 11, 20, 19, 1).valueOf()); a.deep(t(mayanEndOfTheWorld, 'Europe/Warsaw').valueOf(), new Date(2012, 11, 21, 2, 1).valueOf()); };
Fix test so is timezone independent
Fix test so is timezone independent
JavaScript
mit
egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations
10c19dabd1178de4f561327e348c3c114b54ea67
Web/Application.js
Web/Application.js
var express = require('express'); var app = express(); var CurrentUser = require('../Architecture/CurrentUser').CurrentUser; var WebService = require('../Architecture/WebService').WebService; var MongoAdapter = require('../Adapters/Mongo').MongoAdapter; var RedisAdapter = require('../Adapters/Redis').RedisAdapter; var webServiceInit = new WebService(new CurrentUser()); var runService = webServiceInit.runWrapper(); // Database adapters. var mongodb = new MongoAdapter(); var redis = new RedisAdapter(); app.use(mongodb.connect()); app.use(redis.connect()); app.use(function (req, res, next) { // Add things to dependencies in everything service. webServiceInit.addDependency('mongo', mongodb); webServiceInit.addDependency('redis', redis); next(); }); app.use(function (req, res, next) { webServiceInit.runRef = webServiceInit.run.bind(webServiceInit); next(); }); app.use(express.static('Resources')); // ### Routing ### app.get('/login', runService('loginGet', [0, 1, 2, 3], { param1: 'value1', param2: 'value2' })); app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' })); app.listen(process.argv[2]); console.log('Server listening on port ' + process.argv[2] + '.');
var express = require('express'); var app = express(); var CurrentUser = require('../Architecture/CurrentUser').CurrentUser; var WebService = require('../Architecture/WebService').WebService; var MongoAdapter = require('../Adapters/Mongo').MongoAdapter; var RedisAdapter = require('../Adapters/Redis').RedisAdapter; var webServiceInit = new WebService(new CurrentUser()); var runService = webServiceInit.runWrapper(); // Database adapters. var mongodb = new MongoAdapter(); var redis = new RedisAdapter(); app.use(mongodb.connect()); app.use(redis.connect()); app.use(function (req, res, next) { // Add things to dependencies in everything service. webServiceInit.addDependency('mongo', mongodb); webServiceInit.addDependency('redis', redis); next(); }); app.use(function (req, res, next) { webServiceInit.runRef = webServiceInit.run.bind(webServiceInit); next(); }); app.use(express.static('Resources')); // ### Routing ### app.get('/login', runService('loginGet', [0, 1, 2, 3])); app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' })); app.listen(process.argv[2]); console.log('Server listening on port ' + process.argv[2] + '.');
Remove params from login route.
Remove params from login route.
JavaScript
mit
rootsher/server-side-portal-framework
d7983d0ed5f18fb64e046fb4aefa718c7cdd2a8b
src/bot/index.js
src/bot/index.js
import 'babel-polyfill'; import { existsSync } from 'fs'; import { resolve } from 'path'; import merge from 'lodash.merge'; import TipsBot from './Tipsbot'; const tokenPath = resolve(__dirname, '..', '..', 'token.js'); const defaultToken = existsSync(tokenPath) ? require(tokenPath) : null; const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; const defaultSchedule = '0 9 * * 1,2,3,4,5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = ''; export const create = (options = {}) => { let defaults = { token: process.env.BOT_API_KEY || defaultToken, name: process.env.BOT_NAME || defaultName, filePath: process.env.BOT_FILE_PATH || defaultTips, channel: process.env.BOT_CHANNEL || defaultChannel, schedule: process.env.BOT_SCHEDULE || defaultSchedule, startIndex: process.env.BOT_START_INDEX || defaultStartIndex, iconURL: process.env.BOT_ICON_URL || defaultIconURL, }; return new TipsBot(merge(defaults, options)); }
import 'babel-polyfill'; import { existsSync } from 'fs'; import { resolve } from 'path'; import merge from 'lodash.merge'; import TipsBot from './Tipsbot'; const tokenPath = resolve(__dirname, '..', '..', 'token.js'); const defaultToken = existsSync(tokenPath) ? require(tokenPath) : ''; const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; const defaultSchedule = '0 9 * * 1,2,3,4,5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = ''; export const create = (options = {}) => { let defaults = { token: process.env.BOT_API_KEY || defaultToken, name: process.env.BOT_NAME || defaultName, filePath: process.env.BOT_FILE_PATH || defaultTips, channel: process.env.BOT_CHANNEL || defaultChannel, schedule: process.env.BOT_SCHEDULE || defaultSchedule, startIndex: process.env.BOT_START_INDEX || defaultStartIndex, iconURL: process.env.BOT_ICON_URL || defaultIconURL, }; return new TipsBot(merge(defaults, options)); }
Set default token to empty string insted of null
Set default token to empty string insted of null
JavaScript
mit
simon-johansson/tipsbot
61d51a215bed8e447a528c8a65a9d2ba92453790
js/memberlist.js
js/memberlist.js
//Memberlist JavaScript function hookUpMemberlistControls() { $("#orderBy,#order,#sex,#power").change(function(e) { refreshMemberlist(); }); $("#submitQuery").click(function() { refreshMemberlist(); }); refreshMemberlist(); } function refreshMemberlist(page) { var orderBy = document.getElementById("orderBy").value; var order = document.getElementById( "order").value; var sex = document.getElementById( "sex").value; var power = document.getElementById( "power").value; var query = document.getElementById( "query").value; if (typeof page == "undefined") page = 0; $.get("./?page=memberlist", { listing: true, dir: order, sort: orderBy, sex: sex, pow: power, from: page, query: query}, function(data) { $("#memberlist").html(data); }); } $(document).ready(function() { hookUpMemberlistControls(); });
//Memberlist JavaScript function hookUpMemberlistControls() { $("#orderBy,#order,#sex,#power").change(function(e) { refreshMemberlist(); }); $("#submitQuery").click(function() { refreshMemberlist(); }); refreshMemberlist(); } function refreshMemberlist(page) { var orderBy = $("#orderBy").val(); var order = $( "#order").val(); var sex = $( "#sex").val(); var power = $( "#power").val(); var query = $( "#query").val(); if (typeof page == "undefined") page = 0; $.get("./?page=memberlist", { listing: true, dir: order, sort: orderBy, sex: sex, pow: power, from: page, query: query}, function(data) { $("#memberlist").html(data); }); } $(document).ready(function() { hookUpMemberlistControls(); });
Use jQuery instead of document.getElementById.
Use jQuery instead of document.getElementById.
JavaScript
bsd-2-clause
Jceggbert5/ABXD,ABXD/ABXD,carlosfortes/ABXD,carlosfortes/ABXD,carlosfortes/ABXD,Jceggbert5/ABXD,Jceggbert5/ABXD,ABXD/ABXD,ABXD/ABXD
b6d411f8cd7a895394227ec6b1b3e226a69bb5e6
lib/chlg-init.js
lib/chlg-init.js
'use strict'; var fs = require('fs'); var program = require('commander'); program .option('-f, --file [filename]', 'Changelog filename', 'CHANGELOG.md') .parse(process.argv); function chlgInit(file, callback) { file = file || program.file; fs.stat(file, function (err) { if (!err || err.code !== 'ENOENT') { return callback(new Error('cannot create file ‘' + file + '’: File exists')); } fs.writeFile(file, [ '# Change Log', 'All notable changes to this project will be documented in this file.', 'This project adheres to [Semantic Versioning](http://semver.org/).', '', '## [Unreleased][unreleased]', '' ].join('\n'), {encoding: 'utf8'}, function (error) { return callback(error ? new Error('cannot create file ‘' + file + '’: ' + error.message) : null); }); }); } if (require.main === module) { chlgInit(function (err) { if (err) { console.error('chlg-init: ' + err.message); process.exit(1); } }); } else { module.exports = chlgInit; }
'use strict'; var fs = require('fs'); var program = require('commander'); program .option('-f, --file [filename]', 'Changelog filename', 'CHANGELOG.md') .parse(process.argv); function chlgInit(file, callback) { file = file || program.file; fs.stat(file, function (err) { if (!err || err.code !== 'ENOENT') { return callback(new Error('cannot create file ‘' + file + '’: File exists')); } fs.writeFile(file, [ '# Change Log', 'All notable changes to this project will be documented in this file.', 'This project adheres to [Semantic Versioning](http://semver.org/).', '', '## [Unreleased][unreleased]', '' ].join('\n'), {encoding: 'utf8'}, function (error) { return callback(error ? new Error('cannot create file ‘' + file + '’: ' + error.message) : null); }); }); } if (require.main === module) { chlgInit(program.file, function (err) { if (err) { console.error('chlg-init: ' + err.message); process.exit(1); } }); } else { module.exports = chlgInit; }
Fix chld-show command line usage
Fix chld-show command line usage
JavaScript
mit
fldubois/changelog-cli
599c023798d96766d4552ad3619b95f5e84f8ed3
lib/form-data.js
lib/form-data.js
/*global window*/ var isBrowser = typeof window !== 'undefined' && typeof window.FormData !== 'undefined'; // use native FormData in a browser var FD = isBrowser? window.FormData : require('form-data'); module.exports = FormData; module.exports.isBrowser = isBrowser; function FormData() { this.fd = new FD(); } FormData.prototype.append = function (name, data, opt) { if (isBrowser) { if (opt && opt.filename) { return this.fd.append(name, data, opt.filename); } return this.fd.append(name, data); } return this.fd.append.apply(this.fd, arguments); }; FormData.prototype.pipe = function (to) { if (isBrowser && to.end) { return to.end(this.fd); } return this.fd.pipe(to); }; FormData.prototype.getHeaders = function () { if (isBrowser) { return {}; } return this.fd.getHeaders(); };
/*global window*/ var isBrowser = typeof window !== 'undefined' && typeof window.FormData !== 'undefined'; // use native FormData in a browser var FD = isBrowser? window.FormData : require('form-data'); module.exports = FormData; module.exports.isBrowser = isBrowser; function FormData() { this.fd = new FD(); } FormData.prototype.append = function (name, data, opt) { if (isBrowser) { // data must be converted to Blob if it's an arraybuffer if (data instanceof window.ArrayBuffer) { data = new window.Blob([ data ]); } if (opt && opt.filename) { return this.fd.append(name, data, opt.filename); } return this.fd.append(name, data); } return this.fd.append.apply(this.fd, arguments); }; FormData.prototype.pipe = function (to) { if (isBrowser && to.end) { return to.end(this.fd); } return this.fd.pipe(to); }; FormData.prototype.getHeaders = function () { if (isBrowser) { return {}; } return this.fd.getHeaders(); };
Convert ArrayBuffer to Blob in FormData
Convert ArrayBuffer to Blob in FormData
JavaScript
mit
lakenen/node-box-view
9d214f96490ae3ac6eeea2f24e970e12e91a677e
client/app/components/fileUploadModal/index.js
client/app/components/fileUploadModal/index.js
import React from 'react'; import style from './style.css'; import Modal from 'react-modal'; import H1 from '../h1'; import ControllButton from '../controllButton'; import SelectedPrinters from '../selectedPrinters'; let fileInput; function extractFileNameFromPath(path) {{ } return path.match(/[^\/\\]+$/); } function confirmButtonstate() { if (fileInput) { if (fileInput.value) { return false; } } return true; } function onUploadButtonClick(confirm) { if (fileInput && fileInput.value) { confirm(fileInput.files); } } const FileUploadModal = ({ isOpen, children, close, confirm, isUploadingFile, selectedPrinters }) => ( <Modal isOpen={isOpen} className={style.modal} overlayClassName={style.modalOverlay} onRequestClose={() => { close(); }}> <H1>File upload</H1> { isUploadingFile && <span>this is a loading spinner for now</span> } <SelectedPrinters selectedPrinters={selectedPrinters} /> <span className={style.fileName}>{fileInput && extractFileNameFromPath(fileInput.value)}</span> <ControllButton onClick={() => { fileInput.click(); }}>Load file</ControllButton> <input type="file" hidden open ref={(input) => { fileInput = input; }} accept=".gcode"/> <ControllButton disabled={confirmButtonstate()} onClick={() => { onUploadButtonClick(confirm); }}>Upload</ControllButton> </Modal> ); export default FileUploadModal;
import React from 'react'; import style from './style.css'; import Modal from 'react-modal'; import H1 from '../h1'; import ControllButton from '../controllButton'; import SelectedPrinters from '../selectedPrinters'; let fileInput; function extractFileNameFromPath(path) {{ } return path.match(/[^\/\\]+$/); } function confirmButtonstate() { if (fileInput) { if (fileInput.value) { return false; } } return true; } function onUploadButtonClick(confirm) { if (fileInput && fileInput.value) { confirm(fileInput.files); } } const FileUploadModal = ({ isOpen, children, close, confirm, isUploadingFile, selectedPrinters }) => ( <Modal isOpen={isOpen} className={style.modal} overlayClassName={style.modalOverlay} onRequestClose={() => { close(); }}> <H1>File upload</H1> { isUploadingFile && <span>this is a loading spinner for now</span> } <SelectedPrinters selectedPrinters={selectedPrinters} /> <span className={style.fileName}>{fileInput && extractFileNameFromPath(fileInput.value)}</span> <ControllButton onClick={() => { fileInput.click(); }}>Load file</ControllButton> <input type="file" hidden open ref={(input) => { fileInput = input; }} accept=".gco"/> <ControllButton disabled={confirmButtonstate()} onClick={() => { onUploadButtonClick(confirm); }}>Upload</ControllButton> </Modal> ); export default FileUploadModal;
Fix file extension in file input
Fix file extension in file input
JavaScript
agpl-3.0
MakersLab/farm-client,MakersLab/farm-client
daa7c07dc6eaaad441c35c9da540ef4863f2bee3
client/views/activities/latest/latestByType.js
client/views/activities/latest/latestByType.js
Template.latestActivitiesByType.created = function () { // Create 'instance' variable for use througout template logic var instance = this; // Subscribe to all activity types instance.subscribe('allActivityTypes'); // Create variable to hold activity type selection instance.activityTypeSelection = new ReactiveVar(); }; Template.latestActivitiesByType.helpers({ 'activityTypeOptions': function () { // Get all activity types activityTypes = ActivityTypes.find().fetch(); return activityTypes; } });
Template.latestActivitiesByType.created = function () { // Create 'instance' variable for use througout template logic var instance = this; // Subscribe to all activity types instance.subscribe('allActivityTypes'); // Create variable to hold activity type selection instance.activityTypeSelection = new ReactiveVar(); }; Template.latestActivitiesByType.helpers({ 'activityTypeOptions': function () { // Get all activity types activityTypes = ActivityTypes.find().fetch(); return activityTypes; } }); Template.latestActivitiesByType.events({ 'change #activity-type-select': function (event, template) { // Create instance variable for consistency var instance = Template.instance(); var selectedActivityType = event.target.value; instance.activityTypeSelection.set(selectedActivityType); } });
Change activity type selection on change event
Change activity type selection on change event
JavaScript
agpl-3.0
brylie/juhani-wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,GeriLife/wellbeing
4b765f32e63599995bef123d47fd9ddd39bdb235
pages/books/read.js
pages/books/read.js
// @flow /** * Part of GDL gdl-frontend. * Copyright (C) 2017 GDL * * See LICENSE */ import * as React from 'react'; import { fetchBook } from '../../fetch'; import type { BookDetails, Context } from '../../types'; import defaultPage from '../../hocs/defaultPage'; import Head from '../../components/Head'; import Reader from '../../components/Reader'; type Props = { book: BookDetails, url: { query: { chapter?: string } } }; class Read extends React.Component<Props> { static async getInitialProps({ query }: Context) { const bookRes = await fetchBook(query.id, query.lang); if (!bookRes.isOk) { return { statusCode: bookRes.statusCode }; } const book = bookRes.data; // Make sure the chapters are sorted by the chapter numbers // Cause further down we rely on the array indexes book.chapters.sort((a, b) => a.seqNo - b.seqNo); return { book }; } render() { let { book, url } = this.props; return ( <React.Fragment> <Head title={book.title} isBookType description={book.description} imageUrl={book.coverPhoto ? book.coverPhoto.large : null} /> <Reader book={book} initialChapter={url.query.chapter} /> </React.Fragment> ); } } export default defaultPage(Read);
// @flow /** * Part of GDL gdl-frontend. * Copyright (C) 2017 GDL * * See LICENSE */ import * as React from 'react'; import { fetchBook } from '../../fetch'; import type { BookDetails, Context } from '../../types'; import defaultPage from '../../hocs/defaultPage'; import errorPage from '../../hocs/errorPage'; import Head from '../../components/Head'; import Reader from '../../components/Reader'; type Props = { book: BookDetails, url: { query: { chapter?: string } } }; class Read extends React.Component<Props> { static async getInitialProps({ query }: Context) { const bookRes = await fetchBook(query.id, query.lang); if (!bookRes.isOk) { return { statusCode: bookRes.statusCode }; } const book = bookRes.data; // Make sure the chapters are sorted by the chapter numbers // Cause further down we rely on the array indexes book.chapters.sort((a, b) => a.seqNo - b.seqNo); return { book }; } render() { let { book, url } = this.props; return ( <React.Fragment> <Head title={book.title} isBookType description={book.description} imageUrl={book.coverPhoto ? book.coverPhoto.large : null} /> <Reader book={book} initialChapter={url.query.chapter} /> </React.Fragment> ); } } export default defaultPage(errorPage(Read));
Add error handling to Read book page
Add error handling to Read book page
JavaScript
apache-2.0
GlobalDigitalLibraryio/gdl-frontend,GlobalDigitalLibraryio/gdl-frontend
56583e9cb09dfbcea6da93af4d10268b51b232e9
js/casper.js
js/casper.js
var fs = require('fs'); var links; function getLinks() { // Scrape the links from primary nav of the website var links = document.querySelectorAll('.nav-link.t-nav-link'); return Array.prototype.map.call(links, function (e) { return e.getAttribute('href') }); } casper.start('http://192.168.13.37/index.php', function() { fs.write('tests/validation/html_output/index.html', this.getPageContent(), 'w'); }); casper.then(function () { links = this.evaluate(getLinks); for(var i in links) { console.log(i,' Outer:', links[i]); casper.start(links[i], function() { console.log(i, ' Inner:', links[i]); fs.write('tests/validation/html_output/page-' + i + '.html', this.getPageContent(), 'w'); }); } }); casper.run(function() { this.exit(); })
var fs = require('fs'); var links; function getLinks() { var links = document.querySelectorAll('.nav-link.t-nav-link'); return Array.prototype.map.call(links, function (e) { return e.getAttribute('href') }); } casper.start('http://192.168.13.37/index.php', function() { fs.write('tests/validation/html_output/homepage.html', this.getPageContent(), 'w'); }); casper.then(function () { var links = this.evaluate(getLinks); var current = 1; var end = links.length; for (;current < end;) { //console.log(current,' Outer:', current); (function(cntr) { casper.thenOpen(links[cntr], function() { console.log(cntr, ' Inner:', links[cntr]); fs.write('tests/validation/html_output/_' + cntr + '.html', this.getPageContent(), 'w'); }); })(current); current++; } }); casper.run(function() { this.exit(); })
Fix For Loop to Iterate Every Link in Primary Nav
Fix For Loop to Iterate Every Link in Primary Nav
JavaScript
mit
jadu/pulsar,jadu/pulsar,jadu/pulsar
626e52c243ee1e82988d4650cbb22d3d8c304ed6
js/modals.js
js/modals.js
/* ======================================================================== * Ratchet: modals.js v2.0.2 * http://goratchet.com/components#modals * ======================================================================== * Copyright 2015 Connor Sears * Licensed under MIT (https://github.com/twbs/ratchet/blob/master/LICENSE) * ======================================================================== */ !(function () { 'use strict'; var findModals = function (target) { var i; var modals = document.querySelectorAll('a'); for (; target && target !== document; target = target.parentNode) { for (i = modals.length; i--;) { if (modals[i] === target) { return target; } } } }; var getModal = function (event) { var modalToggle = findModals(event.target); if (modalToggle && modalToggle.hash) { return document.querySelector(modalToggle.hash); } }; window.addEventListener('touchend', function (event) { var modal = getModal(event); if (modal) { if (modal && modal.classList.contains('modal')) { modal.classList.toggle('active'); } event.preventDefault(); // prevents rewriting url (apps can still use hash values in url) } }); }());
/* ======================================================================== * Ratchet: modals.js v2.0.2 * http://goratchet.com/components#modals * ======================================================================== * Copyright 2015 Connor Sears * Licensed under MIT (https://github.com/twbs/ratchet/blob/master/LICENSE) * ======================================================================== */ !(function () { 'use strict'; var eventModalOpen = new CustomEvent('modalOpen', { bubbles: true, cancelable: true }); var eventModalClose = new CustomEvent('modalClose', { bubbles: true, cancelable: true }); var findModals = function (target) { var i; var modals = document.querySelectorAll('a'); for (; target && target !== document; target = target.parentNode) { for (i = modals.length; i--;) { if (modals[i] === target) { return target; } } } }; var getModal = function (event) { var modalToggle = findModals(event.target); if (modalToggle && modalToggle.hash) { return document.querySelector(modalToggle.hash); } }; window.addEventListener('touchend', function (event) { var modal = getModal(event); if (modal && modal.classList.contains('modal')) { var eventToDispatch = eventModalOpen; if (modal.classList.contains('active')) { eventToDispatch = eventModalClose; } modal.dispatchEvent(eventToDispatch); modal.classList.toggle('active'); } event.preventDefault(); // prevents rewriting url (apps can still use hash values in url) }); }());
Create modalOpen and modalClose events.
Create modalOpen and modalClose events.
JavaScript
mit
jackyzonewen/ratchet,hashg/ratchet,AndBicScadMedia/ratchet,mazong1123/ratchet-pro,Joozo/ratchet,calvintychan/ratchet,asonni/ratchet,aisakeniudun/ratchet,youprofit/ratchet,Diaosir/ratchet,wallynm/ratchet,vebin/ratchet,mbowie5/playground2,arnoo/ratchet,AladdinSonni/ratchet,youzaiyouzai666/ratchet,ctkjose/ratchet-1,liangxiaojuan/ratchet,Samda/ratchet,tranc99/ratchet,guohuadeng/ratchet,jamesrom/ratchet,Artea/ratchet,twbs/ratchet,isathish/ratchet,cslgjiangjinjian/ratchet,twbs/ratchet,kkirsche/ratchet,Holism/ratchet,coderstudy/ratchet,mazong1123/ratchet-pro,jimjin/ratchet,leplatrem/ratchet
65a9b66c2d9f30bad14a06b0646737ec86799f39
src/matchNode.js
src/matchNode.js
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object|Function} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { if (typeof needle === 'function') { return needle(haystack); } var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object|Function} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { if (typeof needle === 'function') { return needle(haystack); } var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && needle[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
Fix fatal when matching null values in needle
Fix fatal when matching null values in needle
JavaScript
mit
facebook/jscodeshift,fkling/jscodeshift
a69af39c3d2f4b1ec80a08bd6abe70e2a431b083
packages/staplegun/test/fixtures/good-plugins/threepack/three.js
packages/staplegun/test/fixtures/good-plugins/threepack/three.js
const R = require('ramda') export default async () => { console.log('1...2...3...') return R.range(1, 4) // return [1, 2, 3] }
const R = require('ramda') export default async () => { return R.range(1, 4) }
Remove the console log from a fixture.
Remove the console log from a fixture.
JavaScript
mit
infinitered/gluegun,infinitered/gluegun,infinitered/gluegun
eef93ee29ecec1f150dc8af0e9277709a39daaed
dotjs.js
dotjs.js
var hostname = location.hostname.replace(/^www\./, ''); var style = document.createElement('link'); style.rel = 'stylesheet'; style.href = chrome.extension.getURL('styles/' + hostname + '.css'); document.documentElement.insertBefore(style); var defaultStyle = document.createElement('link'); defaultStyle.rel = 'stylesheet'; defaultStyle.href = chrome.extension.getURL('styles/default.css'); document.documentElement.insertBefore(defaultStyle); var script = document.createElement('script'); script.src = chrome.extension.getURL('scripts/' + hostname + '.js'); document.documentElement.insertBefore(script); var defaultScript = document.createElement('script'); defaultScript.src = chrome.extension.getURL('scripts/default.js'); document.documentElement.insertBefore(defaultScript);
var hostname = location.hostname.replace(/^www\./, ''); var style = document.createElement('link'); style.rel = 'stylesheet'; style.href = chrome.extension.getURL('styles/' + hostname + '.css'); document.documentElement.appendChild(style); var defaultStyle = document.createElement('link'); defaultStyle.rel = 'stylesheet'; defaultStyle.href = chrome.extension.getURL('styles/default.css'); document.documentElement.appendChild(defaultStyle); var script = document.createElement('script'); script.src = chrome.extension.getURL('scripts/' + hostname + '.js'); document.documentElement.appendChild(script); var defaultScript = document.createElement('script'); defaultScript.src = chrome.extension.getURL('scripts/default.js'); document.documentElement.appendChild(defaultScript);
Use appendChild instead of insertBefore for a small perfomance boost
Use appendChild instead of insertBefore for a small perfomance boost - Fixes #11
JavaScript
mit
p3lim/dotjs-universal,p3lim/dotjs-universal
d0b8c473fa886a208dcdfa4fd8bc97fc4c1b6770
lib/graph.js
lib/graph.js
import _ from 'lodash'; import {Graph, alg} from 'graphlib'; const dijkstra = alg.dijkstra; export function setupGraph(relationships) { let graph = new Graph({ directed: true }); _.each(relationships, function (relationship) { graph.setEdge(relationship.from, relationship.to, relationship.method); }); return graph; } export function getPath(graph, source, destination, path) { let map = dijkstra(graph, source); let predecessor = map[destination].predecessor; if (_.isEqual(predecessor, source)) { path.push(graph.edge(predecessor, destination)); return path.reverse(); } else { path.push(graph.edge(predecessor, destination)); return getPath(graph, source, predecessor, path); } }
import _ from 'lodash'; import {Graph, alg} from 'graphlib'; _.memoize.Cache = WeakMap; let dijkstra = _.memoize(alg.dijkstra); export function setupGraph(pairs) { let graph = new Graph({ directed: true }); _.each(pairs, ({from, to, method}) => graph.setEdge(from, to, method)); return graph; } export function getPath(graph, source, destination, path) { let map = dijkstra(graph, source); let predecessor = map[destination].predecessor; if (_.isEqual(predecessor, source)) { path.push(graph.edge(predecessor, destination)); return path.reverse(); } else { path.push(graph.edge(predecessor, destination)); return getPath(graph, source, predecessor, path); } }
Use ES2015 destructuring and add memoization to dijkstra
Use ES2015 destructuring and add memoization to dijkstra
JavaScript
mit
siddharthkchatterjee/graph-resolver
b20135c356901cd16f8fd94f3ac05af4ab464005
lib/index.js
lib/index.js
import constant from './constant'; import freeze from './freeze'; import is from './is'; import _if from './if'; import ifElse from './ifElse'; import map from './map'; import omit from './omit'; import reject from './reject'; import update from './update'; import updateIn from './updateIn'; import withDefault from './withDefault'; import { _ } from './util/curry'; const u = update; u._ = _; u.constant = constant; u.if = _if; u.ifElse = ifElse; u.is = is; u.freeze = freeze; u.map = map; u.omit = omit; u.reject = reject; u.update = update; u.updateIn = updateIn; u.withDefault = withDefault; export default u;
import constant from './constant'; import freeze from './freeze'; import is from './is'; import _if from './if'; import ifElse from './ifElse'; import map from './map'; import omit from './omit'; import reject from './reject'; import update from './update'; import updateIn from './updateIn'; import withDefault from './withDefault'; import { _ } from './util/curry'; const u = update; u._ = _; u.constant = constant; u.if = _if; u.ifElse = ifElse; u.is = is; u.freeze = freeze; u.map = map; u.omit = omit; u.reject = reject; u.update = update; u.updateIn = updateIn; u.withDefault = withDefault; module.exports = u;
Allow updeep to be require()’d from CommonJS
Allow updeep to be require()’d from CommonJS
JavaScript
mit
substantial/updeep,substantial/updeep
f3735c9b214ea8bbe2cf3619409952fedb1eb7ac
lib/index.js
lib/index.js
'use strict'; var path = require('path'); var BinWrapper = require('bin-wrapper'); var pkg = require('../package.json'); var url = 'https://raw.githubusercontent.com/jihchi/giflossy-bin/v' + pkg.version + '/vendor/'; module.exports = new BinWrapper() .src(url + 'macos/giflossy', 'darwin') .src(url + 'linux/x86/giflossy', 'linux', 'x86') .src(url + 'linux/x64/giflossy', 'linux', 'x64') .src(url + 'freebsd/x86/giflossy', 'freebsd', 'x86') .src(url + 'freebsd/x64/giflossy', 'freebsd', 'x64') .src(url + 'win/x86/giflossy.exe', 'win32', 'x86') .src(url + 'win/x64/giflossy.exe', 'win32', 'x64') .dest(path.join(__dirname, '../vendor')) .use(process.platform === 'win32' ? 'giflossy.exe' : 'giflossy');
'use strict'; var path = require('path'); var BinWrapper = require('bin-wrapper'); var pkg = require('../package.json'); var url = 'https://raw.githubusercontent.com/jihchi/giflossy-bin/v' + pkg.version + '/vendor/'; module.exports = new BinWrapper() .src(url + 'macos/gifsicle', 'darwin') .src(url + 'linux/x86/gifsicle', 'linux', 'x86') .src(url + 'linux/x64/gifsicle', 'linux', 'x64') .src(url + 'freebsd/x86/gifsicle', 'freebsd', 'x86') .src(url + 'freebsd/x64/gifsicle', 'freebsd', 'x64') .src(url + 'win/x86/gifsicle.exe', 'win32', 'x86') .src(url + 'win/x64/gifsicle.exe', 'win32', 'x64') .dest(path.join(__dirname, '../vendor')) .use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');
Rename binary filename to gifsicle
Rename binary filename to gifsicle
JavaScript
mit
jihchi/giflossy-bin
fec0c1ca4048c3590396cd5609cb3085e6c61bf5
lib/index.js
lib/index.js
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[a-z1-9]+(\s+[a-z]+=["'](.*)["'])*\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(document.data.html === undefined) { changes.data.html = document.metadata.text; } else if(document.metadata.text === undefined) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators_html.some(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); return true; } return false; }); } if(changes.metadata.text === document.metadata.text) { config.separators_text.some(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; return true; } return false; }); } finalCb(null, changes); };
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(document.data.html === undefined) { changes.data.html = document.metadata.text; } else if(document.metadata.text === undefined) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators_html.some(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); return true; } return false; }); } if(changes.metadata.text === document.metadata.text) { config.separators_text.some(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; return true; } return false; }); } finalCb(null, changes); };
Update regexp for HTML strip
Update regexp for HTML strip
JavaScript
mit
AnyFetch/embedmail-hydrater.anyfetch.com
7ca1d708a9a9c22e596e9c4a64db74115994d54a
koans/AboutExpects.js
koans/AboutExpects.js
describe("About Expects", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(false).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); //Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); //Sometimes you need to be really exact about what you "type". it("should assert equality with ===", function () { var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); //Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(FILL_ME_IN); }); });
describe("About Expects", function() { // We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(false).toBeTruthy(); // This should be true }); // To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); // Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); // Sometimes you need to be precise about what you "type". it("should assert equality with ===", function () { var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); // Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(FILL_ME_IN); }); });
Correct spacing and language in comments
Correct spacing and language in comments
JavaScript
mit
DhiMalo/javascript-koans,GMatias93/javascript-koans,JosephSun/javascript-koans,existenzial/javascript-koans,GMatias93/javascript-koans,darrylnu/javascript-koans,JosephSun/javascript-koans,DhiMalo/javascript-koans,existenzial/javascript-koans,GMatias93/javascript-koans,darrylnu/javascript-koans,darrylnu/javascript-koans,JosephSun/javascript-koans,existenzial/javascript-koans,DhiMalo/javascript-koans
f6b82baae39560c733160d292dcbcec043b5edb3
Packages/ohif-viewerbase/client/lib/classes/plugins/OHIFPlugin.js
Packages/ohif-viewerbase/client/lib/classes/plugins/OHIFPlugin.js
export class OHIFPlugin { // TODO: this class is still under development and will // likely change in the near future constructor () { this.name = "Unnamed plugin"; this.description = "No description available"; } // load an individual script URL static loadScript(scriptURL) { const script = document.createElement("script"); script.src = scriptURL; script.type = "text/javascript"; script.async = false; const head = document.getElementsByTagName("head")[0]; head.appendChild(script); head.removeChild(script); return script; } // reload all the dependency scripts and also // the main plugin script url. static reloadPlugin(plugin) { console.warn(`reloadPlugin: ${plugin.name}`); if (plugin.scriptURLs && plugin.scriptURLs.length) { plugin.scriptURLs.forEach(scriptURL => { this.loadScript(scriptURL).onload = function() {} }); } let scriptURL = plugin.url; if (plugin.allowCaching === false) { scriptURL += "?" + performance.now(); } this.loadScript(scriptURL).onload = function() { const entryPointFunction = OHIF.plugins.entryPoints[plugin.name]; if (entryPointFunction) { entryPointFunction(); } } } }
export class OHIFPlugin { // TODO: this class is still under development and will // likely change in the near future constructor () { this.name = "Unnamed plugin"; this.description = "No description available"; } // load an individual script URL static loadScript(scriptURL, type = "text/javascript") { const script = document.createElement("script"); script.src = scriptURL; script.type = type; script.async = false; const head = document.getElementsByTagName("head")[0]; head.appendChild(script); head.removeChild(script); return script; } // reload all the dependency scripts and also // the main plugin script url. static reloadPlugin(plugin) { if (plugin.scriptURLs && plugin.scriptURLs.length) { plugin.scriptURLs.forEach(scriptURL => { this.loadScript(scriptURL).onload = function() {} }); } // TODO: Later we should probably merge script and module URLs if (plugin.moduleURLs && plugin.moduleURLs.length) { plugin.moduleURLs.forEach(moduleURLs => { this.loadScript(moduleURLs, "module").onload = function() {} }); } let scriptURL = plugin.url; if (plugin.allowCaching === false) { scriptURL += "?" + performance.now(); } this.loadScript(scriptURL).onload = function() { const entryPointFunction = OHIF.plugins.entryPoints[plugin.name]; if (entryPointFunction) { entryPointFunction(); } } } }
Add moduleURLs in addition to scriptURLs
feat(plugins): Add moduleURLs in addition to scriptURLs
JavaScript
mit
OHIF/Viewers,OHIF/Viewers,OHIF/Viewers
6eea14a4d3291b3d6e1088a6cd4eacda056ce56a
tests/dummy/mirage/factories/pledge.js
tests/dummy/mirage/factories/pledge.js
import { Factory, faker } from 'ember-cli-mirage'; export default Factory.extend({ fund: () => faker.random.arrayElement(["WNYC", "WQXR", "Radiolab"]), orderPrice: () => faker.random.arrayElement([60, 72, 120, 12, 90, 100]), orderDate: faker.date.past, orderCode: () => faker.random.arrayElement([1234567,2345678,3456789]), orderType: () => faker.random.arrayElement(["onetime", "sustainer"]), orderKey: () => faker.random.uuid(), premium: () => faker.random.arrayElement(['Brian Lehrer Animated Series', 'BL Mug', 'WNYC Hoodie', '']), creditCardType: 'VISA', creditCardLast4Digits: '0302', isActiveMember: faker.random.boolean, isSustainer: faker.random.boolean, });
import { Factory, faker } from 'ember-cli-mirage'; export default Factory.extend({ fund: () => faker.random.arrayElement(["WNYC", "WQXR", "Radiolab", "J.Schwartz"]), orderPrice: () => faker.random.arrayElement([60, 72, 120, 12, 90, 100]), orderDate: faker.date.past, orderCode: () => faker.random.arrayElement([1234567,2345678,3456789]), orderType: () => faker.random.arrayElement(["onetime", "sustainer"]), orderKey: () => faker.random.uuid(), premium: () => faker.random.arrayElement(['Brian Lehrer Animated Series', 'BL Mug', 'WNYC Hoodie', '']), creditCardType: 'VISA', creditCardLast4Digits: '0302', isActiveMember: faker.random.boolean, isSustainer: faker.random.boolean, });
Add Jonathan Schwartz as fund in mirage factory
Add Jonathan Schwartz as fund in mirage factory
JavaScript
mit
nypublicradio/nypr-account-settings,nypublicradio/nypr-account-settings
c19fc02c3ea90da940bb39a9f59f0c9b06632175
lib/index.js
lib/index.js
var _ = require('lodash'); var path = require('path'); var exec = require('child_process').exec; var LOG_TYPES = [ "ERROR", "WARNING" ]; module.exports = function(filepath, options, callback) { if (!callback) { callback = options; options = {}; } options = _.defaults(options || {}, { epubcheck: "epubcheck" }); filepath = path.resolve(process.cwd(), filepath); var command = options.epubcheck+" "+filepath+" -q"; exec(command, function (error, stdout, stderr) { var output = stderr.toString(); var lines = stderr.split("\n"); error = null; lines = _.chain(lines) .map(function(line) { var parts = line.split(":"); if (!_.contains(LOG_TYPES, parts[0])) return null; var type = parts[0].toLowerCase(); var content = parts.slice(1).join(":"); if (type == "error") { error = new Error(content); } return { 'type': type, 'content': content }; }) .compact() .value(); callback(error, { messages: lines }); }); };
var _ = require('lodash'); var path = require('path'); var exec = require('child_process').exec; var LOG_TYPES = [ "ERROR", "WARNING" ]; module.exports = function(filepath, options, callback) { if (!callback) { callback = options; options = {}; } options = _.defaults(options || {}, { epubcheck: "epubcheck" }); filepath = path.resolve(process.cwd(), filepath); var command = options.epubcheck+" "+filepath+" -q"; exec(command, function (error, stdout, stderr) { var output = stderr.toString(); var lines = stderr.split("\n"); var err = null; lines = _.chain(lines) .map(function(line) { var parts = line.split(":"); if (!_.contains(LOG_TYPES, parts[0])) return null; var type = parts[0].toLowerCase(); var content = parts.slice(1).join(":"); if (type == "error") { err = new Error(content); } return { 'type': type, 'content': content }; }) .compact() .value(); if (error && !err) err = error; callback(err, { messages: lines }); }); };
Handle correctly error from epubcheck
Handle correctly error from epubcheck
JavaScript
apache-2.0
GitbookIO/node-epubcheck
7fbdffa0bb2c82589c2d786f9fa16863780a63db
app/assets/javascripts/download-menu.js
app/assets/javascripts/download-menu.js
function show_download_menu() { $('#download-menu').slideDown(); setTimeout(hide_download_menu, 20000); $('#download-link').html('cancel'); } function hide_download_menu() { $('#download-menu').slideUp(); $('#download-link').html('download'); } function toggle_download_menu() { if ($('#download-link').html() === 'download') { show_download_menu(); } else { hide_download_menu(); } }
function show_download_menu() { $('#download-menu').slideDown({ duration: 200 }); setTimeout(hide_download_menu, 20000); $('#download-link').html('cancel'); } function hide_download_menu() { $('#download-menu').slideUp({ duration: 200 }); $('#download-link').html('download'); } function toggle_download_menu() { if ($('#download-link').html() === 'download') { show_download_menu(); } else { hide_download_menu(); } }
Speed up the download menu appear/disappear a bit
Speed up the download menu appear/disappear a bit
JavaScript
agpl-3.0
BatedUrGonnaDie/splits-io,BatedUrGonnaDie/splits-io,glacials/splits-io,BatedUrGonnaDie/splits-io,glacials/splits-io,glacials/splits-io,BatedUrGonnaDie/splits-io,glacials/splits-io
78a75ddd6de442e9e821a1bb09192d17635ff1b6
config/default.js
config/default.js
module.exports = { Urls: { vault_base_url: '', base_url: process.env.BASE_URL || process.env.HUBOT_ROOT_URL }, Strings: { sorry_dave: 'I\'m sorry %s, I\'m afraid I can\'t do that.' }, };
module.exports = { Urls: { vault_base_url: process.env.HUBOT_VAULT_URL, base_url: process.env.BASE_URL || process.env.HUBOT_ROOT_URL }, Strings: { sorry_dave: 'I\'m sorry %s, I\'m afraid I can\'t do that.' }, };
Add vault url config environment variable
Add vault url config environment variable
JavaScript
mit
uWhisp/hubot-db-heimdall,uWhisp/hubot-db-heimdall
bd13b83b42ac2e552010f228f20fa7f5e67b896a
lib/utils.js
lib/utils.js
utils = { startsAtMomentWithOffset: function (game) { var offset = game.location.utc_offset; if (! Match.test(offset, UTCOffset)) { offset: -8; // Default to California } // UTC offsets returned by Google Places API, // which is the source of game.location.utc_offset, // differ in sign from what is expected by moment.js return moment(game.startsAt).zone(-offset); }, displayTime: function (game) { return utils.startsAtMomentWithOffset(game).format('ddd h:mma'); }, // Same-day-ness depends on the known timezone of the game, // not the timezone of the system executing this function. isToday: function (game) { var gameWhen = utils.startsAtMomentWithOffset(game); var now = utils.startsAtMomentWithOffset( // clone of game that starts now _.extend({startsAt: new Date()}, _.omit(game, 'startsAt')) ); return gameWhen.isSame(now, 'day'); }, // Markdown->HTML converter: new Showdown.converter() };
utils = { startsAtMomentWithOffset: function (game) { var offset = game.location.utc_offset; if (! Match.test(offset, UTCOffset)) { offset = -8; // Default to California } // UTC offsets returned by Google Places API, // which is the source of game.location.utc_offset, // differ in sign from what is expected by moment.js return moment(game.startsAt).zone(-offset); }, displayTime: function (game) { return utils.startsAtMomentWithOffset(game).format('ddd h:mma'); }, // Same-day-ness depends on the known timezone of the game, // not the timezone of the system executing this function. isToday: function (game) { var gameWhen = utils.startsAtMomentWithOffset(game); var now = utils.startsAtMomentWithOffset( // clone of game that starts now _.extend({startsAt: new Date()}, _.omit(game, 'startsAt')) ); return gameWhen.isSame(now, 'day'); }, // Markdown->HTML converter: new Showdown.converter() };
Fix typo in setting default time zone for game
Fix typo in setting default time zone for game Close #110
JavaScript
mit
pushpickup/pushpickup,pushpickup/pushpickup,pushpickup/pushpickup
3691387bdf33e6c02899371de63497baea3ab807
app/routes.js
app/routes.js
// @flow import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './containers/App'; import VerticalTree from './containers/VerticalTree'; export default ( <Route path="/" component={App}> <IndexRoute component={VerticalTree} /> </Route> );
// @flow import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './containers/App'; import Menu from './components/Menu'; import VerticalTree from './containers/VerticalTree'; import AVLTree from './containers/AVLTree'; export default ( <Route path="/" component={App}> <IndexRoute component={Menu} /> <Route path="usertree" component={VerticalTree} /> <Route path="treeExamples" component={AVLTree} /> </Route> );
Add route for example structures, and home page
Add route for example structures, and home page
JavaScript
mit
ivtpz/brancher,ivtpz/brancher
2ed2947f05c86d25e47928fa3eedbca0e84b92d8
LayoutTests/http/tests/notifications/resources/update-event-test.js
LayoutTests/http/tests/notifications/resources/update-event-test.js
if (self.importScripts) { importScripts('/resources/testharness.js'); importScripts('worker-helpers.js'); } async_test(function(test) { if (Notification.permission != 'granted') { assert_unreached('No permission has been granted for displaying notifications.'); return; } var notification = new Notification('My Notification', { tag: 'notification-test' }); notification.addEventListener('show', function() { var updatedNotification = new Notification('Second Notification', { tag: 'notification-test' }); updatedNotification.addEventListener('show', function() { test.done(); }); }); // FIXME: Replacing a notification should fire the close event on the // notification that's being replaced. notification.addEventListener('error', function() { assert_unreached('The error event should not be thrown.'); }); }, 'Replacing a notification will discard the previous notification.'); if (isDedicatedOrSharedWorker()) done();
if (self.importScripts) { importScripts('/resources/testharness.js'); importScripts('worker-helpers.js'); } async_test(function(test) { if (Notification.permission != 'granted') { assert_unreached('No permission has been granted for displaying notifications.'); return; } // We require two asynchronous events to happen when a notification gets updated, (1) // the old instance should receive the "close" event, and (2) the new notification // should receive the "show" event, but only after (1) has happened. var closedOriginalNotification = false; var notification = new Notification('My Notification', { tag: 'notification-test' }); notification.addEventListener('show', function() { var updatedNotification = new Notification('Second Notification', { tag: 'notification-test' }); updatedNotification.addEventListener('show', function() { assert_true(closedOriginalNotification); test.done(); }); }); notification.addEventListener('close', function() { closedOriginalNotification = true; }); notification.addEventListener('error', function() { assert_unreached('The error event should not be thrown.'); }); }, 'Replacing a notification will discard the previous notification.'); if (isDedicatedOrSharedWorker()) done();
Verify in a layout test that replacing a notification closes the old one.
Verify in a layout test that replacing a notification closes the old one. We do this by listening to the "close" event on the old notification as well. This test passes with or without the Chrome-sided fix because it's properly implemented in the LayoutTestNotificationManager, but is a good way of verifying the fix manually. BUG=366098 Review URL: https://codereview.chromium.org/750563005 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@186033 bbb929c8-8fbe-4397-9dbb-9b2b20218538
JavaScript
bsd-3-clause
Bysmyyr/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,modulexcite/blink,Pluto-tv/blink-crosswalk,jtg-gg/blink,nwjs/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,kurli/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,modulexcite/blink,modulexcite/blink,Pluto-tv/blink-crosswalk,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,XiaosongWei/blink-crosswalk,modulexcite/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,jtg-gg/blink,Bysmyyr/blink-crosswalk,nwjs/blink,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,smishenk/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,smishenk/blink-crosswalk,smishenk/blink-crosswalk,smishenk/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,jtg-gg/blink,PeterWangIntel/blink-crosswalk,modulexcite/blink,nwjs/blink,nwjs/blink,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,nwjs/blink,smishenk/blink-crosswalk,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,modulexcite/blink,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,XiaosongWei/blink-crosswalk,nwjs/blink,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,jtg-gg/blink,nwjs/blink,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,kurli/blink-crosswalk
750402603dd7060bec89b98704be75597c6634bd
bin/oust.js
bin/oust.js
#!/usr/bin/env node var oust = require('../index'); var pkg = require('../package.json'); var fs = require('fs'); var argv = require('minimist')((process.argv.slice(2))) var printHelp = function() { console.log('oust'); console.log(pkg.description); console.log(''); console.log('Usage:'); console.log(' $ oust --file <filename> --selector <selector>'); }; if(argv.h || argv.help) { printHelp(); return; } if(argv.v || argv.version) { console.log(pkg.version); return; } var file = argv.f || argv.file; var selector = argv.s || argv.selector; fs.readFile(file, function(err, data) { if(err) { console.log('Error opening file:', err.code); return; } var res = oust(data, selector); console.log(res.join("\n")); });
#!/usr/bin/env node var oust = require('../index'); var pkg = require('../package.json'); var fs = require('fs'); var argv = require('minimist')((process.argv.slice(2))) var printHelp = function() { console.log('oust'); console.log(pkg.description); console.log(''); console.log('Usage:'); console.log(' $ oust <filename> <selector>'); }; if(argv.h || argv.help) { printHelp(); return; } if(argv.v || argv.version) { console.log(pkg.version); return; } var file = argv._[0]; var selector = argv._[1]; fs.readFile(file, function(err, data) { if(err) { console.error('Error opening file:', err.message); process.exit(1); } var res = oust(data, selector); console.log(res.join("\n")); });
Update CLI based on @sindresorhus feedback
Update CLI based on @sindresorhus feedback * don't use flagged args for file and selector * exit properly if error opening file
JavaScript
apache-2.0
addyosmani/oust,addyosmani/oust,actmd/oust,actmd/oust
fdee590648c6fdad1d6b19ef83bb9ce4b33fb0dc
src/merge-request-schema.js
src/merge-request-schema.js
const mongoose = require('mongoose'); const Schema = mongoose.Schema; module.exports = new Schema({ merge_request: { id: Number, url: String, target_branch: String, source_branch: String, created_at: String, updated_at: String, title: String, description: String, status: String, work_in_progress: Boolean }, last_commit: { id: Number, message: String, timestamp: String, url: String, author: { name: String, email: String } }, project: { name: String, namespace: String }, author: { name: String, username: String }, assignee: { claimed_on_slack: Boolean, name: String, username: String } });
const mongoose = require('mongoose'); const Schema = mongoose.Schema; module.exports = { name: 'MergeRequest', schema: new Schema({ merge_request: { id: Number, url: String, target_branch: String, source_branch: String, created_at: String, updated_at: String, title: String, description: String, status: String, work_in_progress: Boolean }, last_commit: { id: Number, message: String, timestamp: String, url: String, author: { name: String, email: String } }, project: { name: String, namespace: String }, author: { name: String, username: String }, assignee: { claimed_on_slack: Boolean, name: String, username: String } }) }
Merge request now exports its desired collection name
refactor: Merge request now exports its desired collection name
JavaScript
mit
NSAppsTeam/nickel-bot
26aca19bd633c7c876099d39b8d688d51bb7e773
spec/specs.js
spec/specs.js
describe('pingPongOutput', function() { it("is the number for most input numbers", function() { expect(pingPongOutput(2)).to.equal(2); }); it("is 'ping' for numbers divisible by 3", function() { expect(pingPongOutput(6)).to.equal("ping"); }); });
describe('pingPongOutput', function() { it("is the number for most input numbers", function() { expect(pingPongOutput(2)).to.equal(2); }); it("is 'ping' for numbers divisible by 3", function() { expect(pingPongOutput(6)).to.equal("ping"); }); it("is 'pong' for numbers divisible by 5", function() { expect(pingPongOutput(5)).to.equal("pong"); }); });
Add spec for numbers divisible by 5
Add spec for numbers divisible by 5
JavaScript
mit
JeffreyRuder/ping-pong-app,JeffreyRuder/ping-pong-app
a00605eaf01b7ebe50aea57981b85faa3b406d4a
app/js/arethusa.sg/directives/sg_context_menu_selector.js
app/js/arethusa.sg/directives/sg_context_menu_selector.js
"use strict"; angular.module('arethusa.sg').directive('sgContextMenuSelector', [ 'sg', function(sg) { return { restrict: 'A', scope: { obj: '=' }, link: function(scope, element, attrs) { scope.sg = sg; function ancestorChain(chain) { arethusaUtil.map(chain, function(el) { return el.short; }).join(' > '); } scope.$watchCollection('obj.ancestors', function(newVal, oldVal) { scope.heading = (newVal.length === 0) ? 'Select Smyth Categories' : ancestorChain(newVal); }); }, templateUrl: 'templates/arethusa.sg/sg_context_menu_selector.html' }; } ]);
"use strict"; angular.module('arethusa.sg').directive('sgContextMenuSelector', [ 'sg', function(sg) { return { restrict: 'A', scope: { obj: '=' }, link: function(scope, element, attrs) { scope.sg = sg; function ancestorChain(chain) { return arethusaUtil.map(chain, function(el) { return el.short; }).join(' > '); } scope.$watchCollection('obj.ancestors', function(newVal, oldVal) { scope.heading = (newVal.length === 0) ? 'Select Smyth Categories' : ancestorChain(newVal); }); }, templateUrl: 'templates/arethusa.sg/sg_context_menu_selector.html' }; } ]);
Fix typo in sg context menu selector
Fix typo in sg context menu selector
JavaScript
mit
fbaumgardt/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,latin-language-toolkit/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa
da15d3de4dca28bb7ade0818b8dc0b97967c067d
lib/widgets/KeyBar.js
lib/widgets/KeyBar.js
'use strict'; const CLI = require('clui'); const clc = require('cli-color'); const gauge = CLI.Gauge; const Line = CLI.Line; module.exports = function (tactile, max) { if (!tactile) { return new Line(); } let name = tactile.label; if (tactile.name) { name += ` (${tactile.name.toUpperCase()})`; } return new Line() .padding(2) .column(name, 15, [clc.cyan]) .column(gauge(tactile.percentHolding * 100, max, 20, 60), 25) .column(gauge(tactile.percentReleasing * 100, max, 20, 60), 25) .column((tactile.action) ? '▼' : '▲', 2, [(tactile.action) ? clc.green : clc.red]) .fill(); };
'use strict'; const CLI = require('clui'); const clc = require('cli-color'); const gauge = CLI.Gauge; const Line = CLI.Line; module.exports = function (tactile, maxIdLength, max) { if (!tactile) { return new Line(); } let id = Array(maxIdLength - tactile.id.toString().length).join(0) + tactile.id.toString(); let name = tactile.label; if (tactile.name) { name += ` (${tactile.name.toUpperCase()})`; } return new Line() .padding(2) .column(id, 5, [clc.magenta]) .column(name, 15, [clc.cyan]) .column(gauge(tactile.percentHolding * 100, max, 20, 60), 25) .column(gauge(tactile.percentReleasing * 100, max, 20, 60), 25) .column((tactile.action) ? '▼' : '▲', 2, [(tactile.action) ? clc.green : clc.red]) .fill(); };
Add tactile id to output
Add tactile id to output
JavaScript
mit
ProbablePrime/interactive-keyboard,ProbablePrime/beam-keyboard