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
a244849572e671865cfa28171d567a15d318b38d
client/src/App/index.js
client/src/App/index.js
// Import libraries import 'rxjs' import { Provider } from 'react-redux' import React, { PureComponent } from 'react' import { syncHistoryWithStore } from 'react-router-redux' import { Router, Route, browserHistory, IndexRoute } from 'react-router' // Add CSS framework import 'foundation-sites/dist/foundation.min.css' // Our modules import store from 'store' import Container from 'shared/Container' // Our pages import Home from 'Home' // Create enhanced history const history = syncHistoryWithStore(browserHistory, store, { selectLocationState (state) { return state.get('routing').toJS() } }) export default class App extends PureComponent { // App component never needs to update shouldComponentUpdate (nextProps, nextState) { return false } render () { return ( <Provider store={store}> <Router history={history}> <Route path='/' component={Container}> <IndexRoute component={Home} /> </Route> </Router> </Provider> ) } }
// Import libraries import 'rxjs' import { Provider } from 'react-redux' import React, { PureComponent } from 'react' import { syncHistoryWithStore } from 'react-router-redux' import { Router, Route, browserHistory, IndexRoute } from 'react-router' // Add CSS framework import 'foundation-sites/dist/foundation.min.css' // Our modules import store from 'store' import Container from 'shared/Container' // Our pages import Home from 'Home' import Browse from 'SOMEWHERE' import Upload from 'SOMEWHERE' import Register from 'SOMEWHERE' import Login from 'SOMEWHERE' import User from 'SOMEWHERE' // Create enhanced history const history = syncHistoryWithStore(browserHistory, store, { selectLocationState (state) { return state.get('routing').toJS() } }) export default class App extends PureComponent { // App component never needs to update shouldComponentUpdate (nextProps, nextState) { return false } render () { return ( <Provider store={store}> <Router history={history}> <Route path='/' component={Container}> <IndexRoute component={Home} /> <Route path='browse/:id' component={Browse} /> <Route path='upload' component={Upload} /> <Route path='login' component={Login} /> <Route path='register' component={Register} /> <Route path='user/:id' component={User} /> </Route> </Router> </Provider> ) } }
Add routes for Aksels further development
Add routes for Aksels further development
JavaScript
mit
Entake/acuity,Entake/acuity,Entake/acuity
5a53fd6dab930c9b3e3984c369ada0d0e9410207
app/reducers/verticalTreeReducers.js
app/reducers/verticalTreeReducers.js
import undoable from 'redux-undo-immutable'; import { fromJS } from 'immutable'; import { findPathByNodeId } from '../utils/vertTreeUtils'; const defaultState = fromJS([{ value: undefined, children: [], _id: 1000 }]); const verticalTreeData = ( state = defaultState, action ) => { let path = findPathByNodeId(action.nodeId, state); switch (action.type) { case 'UPDATE_VERT_STRUCTURE': return action.newState; case 'HIGHLIGHT_NODE': path.push('highlighted'); return state.setIn(path, true); case 'UNHIGHLIGHT_NODE': path.push('highlighted'); return state.setIn(path, false); case 'RESET_TO_DEFAULT': return defaultState; default: return state; } }; const undoableVerticalTreeData = undoable( verticalTreeData, { limit: 20 } ); export default { verticalTreeData: undoableVerticalTreeData, testableVerticalTreeData: verticalTreeData };
import undoable from 'redux-undo-immutable'; import { fromJS } from 'immutable'; import { findPathByNodeId } from '../utils/vertTreeUtils'; const defaultState = fromJS([{ value: undefined, children: [], _id: 1000 }]); const verticalTreeData = ( state = defaultState, action ) => { let path = findPathByNodeId(action.nodeId, state); if (path) { path.push('highlighted'); } switch (action.type) { case 'UPDATE_VERT_STRUCTURE': return action.newState; case 'HIGHLIGHT_NODE': return path ? state.setIn(path, true) : state; case 'UNHIGHLIGHT_NODE': return path ? state.setIn(path, false) : state; case 'RESET_TO_DEFAULT': return defaultState; default: return state; } }; const undoableVerticalTreeData = undoable( verticalTreeData, { limit: 20 } ); export default { verticalTreeData: undoableVerticalTreeData, testableVerticalTreeData: verticalTreeData };
Move path logic out of switch statements
Move path logic out of switch statements
JavaScript
mit
ivtpz/brancher,ivtpz/brancher
8cf72e8a622aef28778487738de8fa03c4023014
jquery.externalLinkWarning.js
jquery.externalLinkWarning.js
;(function($) { $.fn.externalLinkWarning = function() { $('a').on('click', function(e) { // create temporary anchor var tmpLink = document.createElement('a'); tmpLink.href = this.href; // check if anchor host matches top window host var externalLink = (tmpLink.host !== top.location.host); // if this is an external link, show confirmation dialog if (externalLink) { return confirm('This link will take you to an external website. Proceed with caution.'); } // if we're here just return true to allow propagation as normal return true; }); }; })(jQuery);
;(function($) { $.fn.externalLinkWarning = function() { $('a').on('click', function(e) { // create temporary anchor var tmpLink = document.createElement('a'); tmpLink.href = this.href; // check if anchor host matches top window host var externalLink = (tmpLink.hostname !== top.location.hostname); // if this is an external link, show confirmation dialog if (externalLink) { return confirm('This link will take you to an external website. Proceed with caution.'); } // if we're here just return true to allow propagation as normal return true; }); }; })(jQuery);
Change host to hostname for IE compatibility
Change host to hostname for IE compatibility
JavaScript
mit
martinbean/external-link-warning
bcaa28358534bee8f5e0bfe40f33e05ac09fcd6f
lib/id_token.js
lib/id_token.js
module.exports = (provider, body, session) => { if (!/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/.test(body.id_token)) { return {error: 'Grant: OpenID Connect invalid id_token format'} } var [header, payload, signature] = body.id_token.split('.') try { header = JSON.parse(Buffer.from(header, 'base64').toString('binary')) payload = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')) } catch (err) { return {error: 'Grant: OpenID Connect error decoding id_token'} } if (payload.aud !== provider.key) { return {error: 'Grant: OpenID Connect invalid id_token audience'} } else if ((payload.nonce && session.nonce) && (payload.nonce !== session.nonce)) { return {error: 'Grant: OpenID Connect nonce mismatch'} } return {header, payload, signature} }
const isAudienceValid = (aud, key) => (Array.isArray(aud) && aud.indexOf(key) !== -1) || aud === key; module.exports = (provider, body, session) => { if (!/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/.test(body.id_token)) { return {error: 'Grant: OpenID Connect invalid id_token format'} } var [header, payload, signature] = body.id_token.split('.') try { header = JSON.parse(Buffer.from(header, 'base64').toString('binary')) payload = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')) } catch (err) { return {error: 'Grant: OpenID Connect error decoding id_token'} } if (!isAudienceValid(payload.aud, provider.key)) { return {error: 'Grant: OpenID Connect invalid id_token audience'} } else if ((payload.nonce && session.nonce) && (payload.nonce !== session.nonce)) { return {error: 'Grant: OpenID Connect nonce mismatch'} } return {header, payload, signature} }
Handle audience as an array
Handle audience as an array According to RFC7519, `aud` claim is an array of strings; only in case there's one audience, `aud` can be a string. See https://tools.ietf.org/html/rfc7519#page-9 This fix allows for audience claim to be both string and array of strings.
JavaScript
mit
simov/grant
ec95831e70ae13816a6ad88cb5113f31a87b525f
server/app/models/barman.js
server/app/models/barman.js
const { DataTypes, Model } = require('sequelize'); /** * This class represents a barman. */ class Barman extends Model { /** * Initialization function. * * @param sequelize * @returns {Model} */ static init(sequelize) { return super.init({ id: { type: DataTypes.INTEGER, primaryKey: true }, firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING, allowNull: false }, nickname: { type: DataTypes.STRING, allowNull: false }, facebook: { type: DataTypes.STRING }, dateOfBirth: { type: DataTypes.DATEONLY, allowNull: false }, flow: { type: DataTypes.TEXT }, }, { sequelize, // Do not delete row, even when the user delete is account paranoid: true }); } /** * Set associations for the model. * * @param models */ static associate(models) { this.belongsToMany(models.Kommission, { through: models.KommissionWrapper }); this.belongsToMany(models.Role, { through: models.RoleWrapper }); this.belongsToMany(models.Service, { through: models.ServiceWrapper }); this.hasOne(Barman, { as: 'godFather' }); this.hasOne(models.ConnectionInformation, { as: 'connection' }); } } module.exports = { Barman };
const { DataTypes, Model } = require('sequelize'); /** * This class represents a barman. */ class Barman extends Model { /** * Initialization function. * * @param sequelize * @returns {Model} */ static init(sequelize) { return super.init({ id: { type: DataTypes.INTEGER, primaryKey: true }, firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING, allowNull: false }, nickname: { type: DataTypes.STRING, allowNull: false }, facebook: { type: DataTypes.STRING }, dateOfBirth: { type: DataTypes.DATEONLY, allowNull: false }, flow: { type: DataTypes.TEXT }, active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true } }, { sequelize, // Do not delete row, even when the user delete is account paranoid: true }); } /** * Set associations for the model. * * @param models */ static associate(models) { this.belongsToMany(models.Kommission, { through: models.KommissionWrapper }); this.belongsToMany(models.Role, { through: models.RoleWrapper }); this.belongsToMany(models.Service, { through: models.ServiceWrapper }); this.hasOne(Barman, { as: 'godFather' }); this.hasOne(models.ConnectionInformation, { as: 'connection' }); } } module.exports = { Barman };
Add field `active` for Barman
Add field `active` for Barman
JavaScript
apache-2.0
K-Fet/K-App,K-Fet/K-App,K-Fet/K-App,K-Fet/K-App
8325ecf62128b33ca43fd188fcefe524e17c38f3
ycomments.js
ycomments.js
(function ($) { var settings = {}, defaults = { api: "http://api.ihackernews.com/post/%s?format=jsonp", }; $.fn.ycomments = function (options) { $.extend(settings, defaults, options); return this.each(init); }; init = function () { var $this = $(this), url = settings.api.replace("%s", settings.id); $.ajax({url: url, dataType: "jsonp"}) .success(showcomments); }; showcomments = function (data) { }; })(jQuery);
(function ($) { var settings = {}, defaults = { api: "http://api.ihackernews.com/post/%s?format=jsonp", apidatatype: "jsonp", }; $.fn.ycomments = function (options) { $.extend(settings, defaults, options); return this.each(init); }; init = function () { var $this = $(this), url = settings.api.replace("%s", settings.id); $.ajax({url: url, dataType: settings.apidatatype}) .success(showcomments); }; showcomments = function (data) { }; })(jQuery);
Make API data type configurable.
Make API data type configurable.
JavaScript
isc
whilp/ycomments
5eca351cf8a562dcd00f671db68b80ea64265131
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, contentSecurityPolicy: { "script-src": "'self' 'unsafe-inline'", "font-src": "'self'", "style-src": "'self' 'unsafe-inline'", "img-src": "'self' data:" } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/gloit-component'; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, contentSecurityPolicy: { "script-src": "'self' 'unsafe-inline'", "font-src": "'self'", "style-src": "'self' 'unsafe-inline'", "img-src": "'self' data:" } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; ENV.baseURL = ''; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/gloit-component'; } return ENV; };
Set the baseURL for development
Set the baseURL for development
JavaScript
mit
gloit/gloit-component,gloit/gloit-component
9fcc31c97cdc01ce38e7ac5f5151837fa5ea1b18
lib/facebook-setup.js
lib/facebook-setup.js
(function () { var _fb = false; var _pc = false; var _inst = null; var app = null; window.fbAsyncInit = function() { FB.init({ appId : '1238816002812487', xfbml : true, version : 'v2.5' }); _fb = true; if (_fb && app) { app.fire("fb:init"); } }; app = pc.Application.getApplication(); app.on("start", function () { if (_fb) { app.fire("fb:init"); } }); (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }());
(function () { var _fb = false; var _pc = false; var _inst = null; var app = null; window.fbAsyncInit = function() { FB.init({ appId : '1238816002812487', xfbml : true, version : 'v2.5' }); _fb = true; if (_fb && app) { app.fire("fb:init"); } }; app = pc.Application.getApplication(); app.on("initialize", function () { if (_fb) { app.fire("fb:init"); } }); (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }());
Use `initialize` event to start up
Use `initialize` event to start up Initialize event is fired after other scripts have initialized. Which means they can listen for fb:init event.
JavaScript
mit
playcanvas/playcanvas-facebook
7a89eb48c8486235cd9d197fc2ad7c84ef0201a6
tests/specs/misc/on-error/main.js
tests/specs/misc/on-error/main.js
define(function(require) { var test = require('../../../test') var n = 0 // 404 var a = require('./a') test.assert(a === null, '404 a') // exec error setTimeout(function() { var b = require('./b') }, 0) require.async('./c', function(c) { test.assert(c === null, '404 c') done() }) require.async('./e', function(e) { test.assert(e === null, 'exec error e') done() }) seajs.use('./d', function(d) { test.assert(d === null, '404 d') done() }) // 404 css //require('./f.css') function done() { if (++n === 3) { test.assert(w_errors.length > 0, w_errors.length) test.assert(s_errors.length === 3, s_errors.length) test.next() } } })
define(function(require) { var test = require('../../../test') var n = 0 // 404 var a = require('./a') test.assert(a === null, '404 a') // exec error setTimeout(function() { var b = require('./b') }, 0) require.async('./c', function(c) { test.assert(c === null, '404 c') done() }) require.async('./e', function(e) { test.assert(e === null, 'exec error e') done() }) seajs.use('./d', function(d) { test.assert(d === null, '404 d') done() }) // 404 css //require('./f.css') function done() { if (++n === 3) { test.assert(w_errors.length > 0, w_errors.length) // 0 for IE6-8 test.assert(s_errors.length === 0 || s_errors.length === 3, s_errors.length) test.next() } } })
Fix test spec for old browsers
Fix test spec for old browsers
JavaScript
mit
yuhualingfeng/seajs,judastree/seajs,LzhElite/seajs,mosoft521/seajs,ysxlinux/seajs,sheldonzf/seajs,jishichang/seajs,jishichang/seajs,chinakids/seajs,yern/seajs,longze/seajs,imcys/seajs,mosoft521/seajs,mosoft521/seajs,zaoli/seajs,LzhElite/seajs,Lyfme/seajs,AlvinWei1024/seajs,moccen/seajs,twoubt/seajs,seajs/seajs,chinakids/seajs,kuier/seajs,PUSEN/seajs,lovelykobe/seajs,hbdrawn/seajs,MrZhengliang/seajs,ysxlinux/seajs,PUSEN/seajs,kuier/seajs,zwh6611/seajs,tonny-zhang/seajs,moccen/seajs,JeffLi1993/seajs,AlvinWei1024/seajs,longze/seajs,FrankElean/SeaJS,sheldonzf/seajs,yern/seajs,yuhualingfeng/seajs,coolyhx/seajs,Lyfme/seajs,judastree/seajs,lianggaolin/seajs,angelLYK/seajs,imcys/seajs,treejames/seajs,kuier/seajs,tonny-zhang/seajs,miusuncle/seajs,121595113/seajs,kaijiemo/seajs,eleanors/SeaJS,judastree/seajs,FrankElean/SeaJS,lee-my/seajs,lianggaolin/seajs,Lyfme/seajs,twoubt/seajs,JeffLi1993/seajs,yuhualingfeng/seajs,lovelykobe/seajs,evilemon/seajs,angelLYK/seajs,evilemon/seajs,wenber/seajs,kaijiemo/seajs,uestcNaldo/seajs,uestcNaldo/seajs,Gatsbyy/seajs,treejames/seajs,lovelykobe/seajs,AlvinWei1024/seajs,121595113/seajs,moccen/seajs,twoubt/seajs,yern/seajs,imcys/seajs,kaijiemo/seajs,lee-my/seajs,wenber/seajs,lianggaolin/seajs,zaoli/seajs,longze/seajs,MrZhengliang/seajs,evilemon/seajs,seajs/seajs,JeffLi1993/seajs,miusuncle/seajs,zaoli/seajs,miusuncle/seajs,PUSEN/seajs,MrZhengliang/seajs,LzhElite/seajs,hbdrawn/seajs,coolyhx/seajs,liupeng110112/seajs,lee-my/seajs,angelLYK/seajs,treejames/seajs,baiduoduo/seajs,sheldonzf/seajs,uestcNaldo/seajs,baiduoduo/seajs,wenber/seajs,baiduoduo/seajs,zwh6611/seajs,13693100472/seajs,zwh6611/seajs,seajs/seajs,ysxlinux/seajs,liupeng110112/seajs,FrankElean/SeaJS,liupeng110112/seajs,coolyhx/seajs,Gatsbyy/seajs,tonny-zhang/seajs,jishichang/seajs,eleanors/SeaJS,eleanors/SeaJS,13693100472/seajs,Gatsbyy/seajs
71ddf05f43903a0549ec74e46e71a59e57c88ccd
karma.local.conf.js
karma.local.conf.js
"use strict"; module.exports = function(config) { config.set({ frameworks: [ "mocha" ], files: [ "dist/jsonapi-client-test.js" ], reporters: [ "spec" ], plugins: [ "karma-mocha", "karma-firefox-launcher", "karma-spec-reporter" ], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: [ "Firefox"/*, "PhantomJS"*/ ], singleRun: true, concurrency: 1, client: { captureConsole: true } }); };
"use strict"; module.exports = function(config) { config.set({ frameworks: [ "mocha" ], files: [ "dist/jsonapi-client-test.js" ], reporters: [ "spec" ], plugins: [ "karma-mocha", "karma-firefox-launcher", "karma-spec-reporter" ], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: [ "Firefox"/*, "PhantomJS"*/ ], singleRun: true, concurrency: 1, client: { captureConsole: true, timeout: 10000 } }); };
Extend timeout on travis Mocha tests
Extend timeout on travis Mocha tests
JavaScript
mit
holidayextras/jsonapi-client
473ec082e5f0bcb8279a4e6c2c16bec7f11cd592
js/main.js
js/main.js
var questions = [ Q1 = { question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What does CSS means?", answer: "Cascading Style Sheet" }, Q3 = { question: "Why the \"C\" in CSS, is called Cascading?", answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; var question = document.getElementById('question'); var questionNum = 0, answeredQA = []; // Generate random number to display random QA set function createNum() { questionNum = Math.floor(Math.random() * 3); // Recursively create random questionNum so that last QA set will not be repeated if (answeredQA.indexOf(questionNum) !== -1) { createNum(); } question.innerHTML = questions[questionNum].question; answeredQA.push(questionNum); } createNum(); var revealBtn = document.getElementById('reveal-answer'); function revealAns() { question.innerHTML = questions[questionNum].answer; } function nextSet() { createNum(); question.innerHTML = questions[questionNum].question; } revealBtn.onclick = revealAns;
var questions = [ Q1 = { question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What does CSS means?", answer: "Cascading Style Sheet" }, Q3 = { question: "Why the \"C\" in CSS, is called Cascading?", answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; var question = document.getElementById('question'); var questionNum = 0, answeredQA = []; // Generate random number to display random QA set function createNum() { questionNum = Math.floor(Math.random() * 3); // Recursively create random questionNum so that last QA set will not be repeated if (answeredQA.indexOf(questionNum) !== -1) { createNum(); } question.innerHTML = questions[questionNum].question; answeredQA.push(questionNum); } createNum(); var revealBtn = document.getElementById('reveal-answer'); function revealAns() { question.innerHTML = questions[questionNum].answer; revealBtn.value = "NEXT"; } function nextSet() { createNum(); question.innerHTML = questions[questionNum].question; } revealBtn.onclick = revealAns;
Change the value of revealBtn when clicked
Change the value of revealBtn when clicked
JavaScript
mit
vinescarlan/FlashCards,vinescarlan/FlashCards
177405e72f0057fe6953833325e8342e8a2b1dca
test/issues/issue-beta-352.js
test/issues/issue-beta-352.js
console.log('1..4'); console.log([1,2,3].join() == '1,2,3' ? 'ok' : 'not ok'); console.log([1,2,3].join('###') == '1###2###3' ? 'ok' : 'not ok'); console.log([1,2,3].join(1) == '11213' ? 'ok' : 'not ok'); console.log([1,2,3].join(null) == '1,2,3' ? 'ok' : 'not ok');
console.log('1..4'); console.log([1,2,3].join() == '1,2,3' ? 'ok' : 'not ok'); console.log([1,2,3].join('###') == '1###2###3' ? 'ok' : 'not ok'); console.log([1,2,3].join(1) == '11213' ? 'ok' : 'not ok'); console.log([1,2,3].join(null) == '1null2null3' ? 'ok' : 'not ok');
Fix Tim's dumbass broken test
Fix Tim's dumbass broken test
JavaScript
apache-2.0
tessel/t1-runtime,tessel/t1-runtime,tessel/t1-runtime,tessel/t1-runtime,tessel/t1-runtime
7f444a4bc172e88fe0e0466d4103189c4b8d32dc
js/main.js
js/main.js
var tabs = document.querySelectorAll('.tab'); var allPanels = document.querySelectorAll(".schedule"); function activateTab(tab) { //remove active de todas as outras tabs tabs.forEach(function(tab) { tab.classList.remove('active'); }); //adiciona active em t tab.classList.add('active'); } function openCourse(item, day) { for(var i=0;i<allPanels.length;i++){ allPanels[i].style.display = 'none'; } document.getElementById(day).style.display = 'block'; activateTab(item); } function initMap() { var myLatlng = {lat: -23.482069, lng: -47.425131}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: myLatlng, scrollwheel: false, }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: 'Click to zoom' }); map.addListener('center_changed', function() { // 3 seconds after the center of the map has changed, pan back to the // marker. window.setTimeout(function() { map.panTo(marker.getPosition()); }, 3000); }); marker.addListener('click', function() { map.setZoom(8); map.setCenter(marker.getPosition()); }); }
var tabs = document.querySelectorAll('.tab'); var allPanels = document.querySelectorAll(".schedule"); function activateTab(tab) { //remove active de todas as outras tabs for (i = 0; i < tabs.length; ++i) { tabs[i].classList.remove('active'); } //adiciona active em t tab.classList.add('active'); } function openCourse(item, day) { for(var i=0;i<allPanels.length;i++){ allPanels[i].style.display = 'none'; } document.getElementById(day).style.display = 'block'; activateTab(item); } function initMap() { var myLatlng = {lat: -23.482069, lng: -47.425131}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: myLatlng, scrollwheel: false, }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: 'Click to zoom' }); map.addListener('center_changed', function() { // 3 seconds after the center of the map has changed, pan back to the // marker. window.setTimeout(function() { map.panTo(marker.getPosition()); }, 3000); }); marker.addListener('click', function() { map.setZoom(8); map.setCenter(marker.getPosition()); }); }
Fix timeline tabs to work on mozilla (for instead of forEach to nodelist)
Fix timeline tabs to work on mozilla (for instead of forEach to nodelist)
JavaScript
cc0-1.0
FatecSorocaba/semana-da-tecnologia,FatecSorocaba/semana-da-tecnologia
e7c19ff1ab2ceefea9968c5587487fa10f539ab5
src/lib/logger.js
src/lib/logger.js
var config = require('./config') var logStack = [] module.exports = { getLogStack: function () { return logStack }, log: function (message, data) { var isDebugMode = config.get('debug') == 'true' var hasConsole = window.console logStack.push({ msg: message, data: data }) if (isDebugMode && hasConsole) { window.console.log(message, data) } } }
var config = require('./config') var logStack = [] module.exports = { getLogStack: function () { return logStack }, log: function (message, data) { var isDebugMode = config.get('debug') === true || config.get('debug') === 'true' var hasConsole = window.console logStack.push({ msg: message, data: data }) if (isDebugMode && hasConsole) { window.console.log(message, data) } } }
Handle of the case of debug-config being a bool
Handle of the case of debug-config being a bool
JavaScript
mit
opbeat/opbeat-angular,opbeat/opbeat-js-core,opbeat/opbeat-angular,opbeat/opbeat-react,opbeat/opbeat-react,jahtalab/opbeat-js,opbeat/opbeat-js-core,jahtalab/opbeat-js,opbeat/opbeat-react,opbeat/opbeat-angular,jahtalab/opbeat-js
9f1604e38dfeb88a9c327a0c0096b7712738da5a
tests/helpers/start-app.js
tests/helpers/start-app.js
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp(attrs) { let application; // use defaults, but you can override let attributes = Ember.assign({}, config.APP, attrs); Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; const merge = Ember.assign || Ember.merge; export default function startApp(attrs) { let application; let attributes = merge({}, config.APP); attributes = merge(attributes, attrs); // use defaults, but you can override Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
Fix startApp for older ember versions
Fix startApp for older ember versions
JavaScript
mit
jkusa/ember-cli-clipboard,jkusa/ember-cli-clipboard
d9f8fc7a8edea40b3ef244f5f4ab19403d9a14a0
js/classes/Message.js
js/classes/Message.js
// Show message // --------------------------------------------------------------------- class Message { show(msg, timing, animations, new_game_btn, field) { if (new_game_btn === undefined) { new_game_btn = false; } $('#msg_new_game').off('click'); var msg_box = $('#message_box'); msg_box.hide(); var msg_div = $('<div>').attr('id', "message_text").html(msg); msg_box.html(msg_div); if (new_game_btn) { $('#message_text').append('<input type="button" id="msg_new_game" value="New Game">'); $('#msg_new_game').on('click', function() { field.initialize(field); }); } if (animations) { $('#mineblaster').css({filter: 'blur(5px)'}); msg_box.fadeIn(timing); } else { msg_box.show(); } } // Hide message box // --------------------------------------------------------------------- hide(animations) { // Remove end message, if present if (animations) { $('#mineblaster').css('filter', 'none'); $("#message_box").fadeOut(); } else { $("#message_box").hide(); } } }
// Show message // --------------------------------------------------------------------- class Message { show(msg, timing, animations, new_game_btn, field) { if (new_game_btn === undefined) { new_game_btn = false; } $('#msg_new_game').off('click'); var msg_box = $('#message_box'); msg_box.hide(); var msg_div = $('<div>').attr('id', "message_text").html(msg); msg_box.html(msg_div); if (new_game_btn) { $('#message_text').append('<input type="button" id="msg_new_game" value="New Game">'); $('#msg_new_game').on('click', function() { field.initialize(field); }); } if (animations) { $('#message_box').css({backdropFilter: 'blur(5px)'}); msg_box.fadeIn(timing); } else { msg_box.show(); } } // Hide message box // --------------------------------------------------------------------- hide(animations) { // Remove end message, if present if (animations) { $('#mineblaster').css('filter', 'none'); $("#message_box").fadeOut(); } else { $("#message_box").hide(); } } }
Switch from filter to backdrop-filter to blur background
Switch from filter to backdrop-filter to blur background
JavaScript
lgpl-2.1
blazeag/js-mineblaster,blazeag/js-mineblaster
95876f17f96cf06542e050643c12f93731837ae1
test.js
test.js
'use strict'; var assert = require('assert'), Selector = require('./'); describe('Selector', function () { it('should return an object', function () { var selector = new Selector('body', [ 0, 0, 0, 1 ]); console.log(selector); assert(selector); assert.equal(selector.text, 'body'); assert.deepEqual(selector.spec, [ 0, 0, 0, 1 ]); }); }); describe('Selector.parsed', function () { it('should get parsed selector', function () { var selector = new Selector('body'); console.log(selector.parsed()); assert(selector.parsed()); assert.equal(selector.parsed()['0'].tag, 'body'); assert.equal(selector.parsed().length, 1); }); }); describe('Selector.specificity', function () { it('should get specificity', function () { var selector = new Selector('body'); console.log(selector.specificity()); assert.deepEqual(selector.specificity(), [ 0, 0, 0, 1 ]); }); });
/* global describe, it */ 'use strict'; var assert = require('assert'), Selector = require('./'); describe('Selector', function () { it('should return an object', function () { var selector = new Selector('body', [ 0, 0, 0, 1 ]); assert(selector); assert.equal(selector.text, 'body'); assert.deepEqual(selector.spec, [ 0, 0, 0, 1 ]); }); }); describe('Selector.parsed', function () { it('should get parsed selector', function () { var selector = new Selector('body'); assert(selector.parsed()); assert.equal(selector.parsed()['0'].tag, 'body'); assert.equal(selector.parsed().length, 1); }); }); describe('Selector.specificity', function () { it('should get specificity', function () { var selector = new Selector('body'); assert.deepEqual(selector.specificity(), [ 0, 0, 0, 1 ]); }); });
Remove logging and add globals for jshint.
Remove logging and add globals for jshint.
JavaScript
mit
jonkemp/style-selector
9db45c50489d852c0a40167f59dee4720712c78c
assets/lib/js/sb-admin-2.min.js
assets/lib/js/sb-admin-2.min.js
$(function(){$("#side-menu").metisMenu()}),$(function(){$(window).bind("load resize",function(){topOffset=50,width=this.window.innerWidth>0?this.window.innerWidth:this.screen.width,768>width?($("div.navbar-collapse").addClass("collapse"),topOffset=100):$("div.navbar-collapse").removeClass("collapse"),height=(this.window.innerHeight>0?this.window.innerHeight:this.screen.height)-1,height-=topOffset,1>height&&(height=1),height>topOffset&&$("#page-wrapper").css("min-height",height+"px")});var i=window.location,e=$("ul.nav a").filter(function(){return this.href==i||0==i.href.indexOf(this.href)}).addClass("active").parent().parent().addClass("in").parent();e.is("li")&&e.addClass("active")});
$(function(){$("#side-menu").metisMenu()}),$(function(){$(window).bind("load resize",function(){topOffset=50,width=this.window.innerWidth>0?this.window.innerWidth:this.screen.width,768>width?($("div.navbar-collapse").addClass("collapse"),topOffset=100):$("div.navbar-collapse").removeClass("collapse"),height=(this.window.innerHeight>0?this.window.innerHeight:this.screen.height)-1,height-=topOffset,1>height&&(height=1),height>topOffset&&$("#page-wrapper").css("min-height",height+"px")});var i=window.location,e=$("ul.nav a").filter(function(){return this.href==i||0==i.href.split('#')[0].indexOf(this.href)}).addClass("active").parent().parent().addClass("in").parent();e.is("li")&&e.addClass("active")});
Fix for active nav links when URL has hash
Fix for active nav links when URL has hash
JavaScript
mit
p2made/yii2-sb-admin-theme,p2made/yii2-sb-admin-theme,p2made/yii2-sb-admin-theme
57edac53919b5d94ac9d32a6689efe6ba393dab9
src/hooks/query-with-current-user.js
src/hooks/query-with-current-user.js
const defaults = { idField: '_id', as: 'userId' }; export default function(options = {}) { return function(hook) { if (hook.type !== 'before') { throw new Error(`The 'associateCurrentUser' hook should only be used as a 'before' hook.`); } if (!hook.params.user) { throw new Error('There is no current user to associate.'); } options = Object.assign({}, defaults, hook.app.get('auth'), options); const id = hook.params.user[options.idField]; if (id === undefined) { throw new Error(`Current user is missing '${options.idField}' field.`); } hook.params.query[options.as] = id; }; }
const defaults = { idField: '_id', as: 'userId' }; export default function(options = {}) { return function(hook) { if (hook.type !== 'before') { throw new Error(`The 'queryWithCurrentUser' hook should only be used as a 'before' hook.`); } if (!hook.params.user) { throw new Error('There is no current user to associate.'); } options = Object.assign({}, defaults, hook.app.get('auth'), options); const id = hook.params.user[options.idField]; if (id === undefined) { throw new Error(`Current user is missing '${options.idField}' field.`); } hook.params.query[options.as] = id; }; }
Fix copy paste typo in queryWithCurrentUser hook.
Fix copy paste typo in queryWithCurrentUser hook.
JavaScript
mit
m1ch3lcl/feathers-authentication,eblin/feathers-authentication,eblin/feathers-authentication,feathersjs/feathers-authentication,feathersjs/feathers-passport-jwt,feathersjs/feathers-passport-jwt,m1ch3lcl/feathers-authentication
fc66fd3761ba8231e49a7045cd5290b619dfc0e0
lib/node/nodes/weighted-centroid.js
lib/node/nodes/weighted-centroid.js
'use strict'; var Node = require('../node'); var dot = require('dot'); var TYPE = 'weighted-centroid'; var PARAMS = { source : Node.PARAM.NODE(Node.GEOMETRY.POINT), weight_column : Node.PARAM.STRING, category_column : Node.PARAM.STRING }; var WeightedCentroid = Node.create(TYPE, PARAMS, {cache: true}); module.exports = WeightedCentroid; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; var weightedCentroidTemplate = dot.template([ 'SELECT the_geom , class', 'FROM cdb_crankshaft.CDB_WeightedMean($weightedmean_query${{=it.query}}$weightedmean_query$,\'{{=it.weight_column}}\',\'{{=it.category_column}}\')' ].join('\n')); function query(it) { return weightedCentroidTemplate(it); } WeightedCentroid.prototype.sql = function(){ return query({ query : this.source.getQuery(), weight_column : this.weight_column, category_column : this.category_column }); };
'use strict'; var Node = require('../node'); var dot = require('dot'); var TYPE = 'weighted-centroid'; var PARAMS = { source : Node.PARAM.NODE(Node.GEOMETRY.POINT), weight_column : Node.PARAM.STRING, category_column : Node.PARAM.STRING }; var WeightedCentroid = Node.create(TYPE, PARAMS, {cache: true}); module.exports = WeightedCentroid; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; var weightedCentroidTemplate = dot.template([ 'SELECT the_geom, class', 'FROM cdb_crankshaft.CDB_WeightedMean(', ' $weightedmean_query${{=it.query}}$weightedmean_query$,', ' \'{{=it.weight_column}}\',', ' \'{{=it.category_column}}\'', ')' ].join('\n')); function query(it) { return weightedCentroidTemplate(it); } WeightedCentroid.prototype.sql = function(){ return query({ query : this.source.getQuery(), weight_column : this.weight_column, category_column : this.category_column }); };
Fix too long line issue
Fix too long line issue
JavaScript
bsd-3-clause
CartoDB/camshaft
63fd3aa92c0d659e577cee39db72914951b5d9fa
ui/src/actions/documentActions.js
ui/src/actions/documentActions.js
import { endpoint } from 'app/api'; import asyncActionCreator from './asyncActionCreator'; export const ingestDocument = asyncActionCreator( (collectionId, metadata, file, onUploadProgress, cancelToken) => async () => { const formData = new FormData(); if (file) { formData.append('file', file); } formData.append('meta', JSON.stringify(metadata)); const config = { onUploadProgress, headers: { 'content-type': 'multipart/form-data', }, params: { sync: true }, cancelToken, }; const response = await endpoint.post( `collections/${collectionId}/ingest`, formData, config ); return { ...response.data }; }, { name: 'INGEST_DOCUMENT' } );
import { endpoint } from 'app/api'; import asyncActionCreator from './asyncActionCreator'; export const ingestDocument = asyncActionCreator( (collectionId, metadata, file, onUploadProgress, cancelToken) => async () => { const formData = { meta: JSON.stringify(metadata), file: file, }; const config = { onUploadProgress, params: { sync: true }, cancelToken, }; const response = await endpoint.postForm( `collections/${collectionId}/ingest`, formData, config ); return { ...response.data }; }, { name: 'INGEST_DOCUMENT' } );
Use automatic form data serialization
Use automatic form data serialization Starting from 0.27.0, axios supports automatic serialization to the form data format for requests with a `multipart/form-data` content type.
JavaScript
mit
alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph
8823acb41f9810e07f09ea9fe660deebc657f451
lib/menus/contextMenu.js
lib/menus/contextMenu.js
'use babel'; const init = () => { const copyEnabled = () => atom.config.get('remote-ftp.context.enableCopyFilename'); const contextMenu = { '.remote-ftp-view .entries.list-tree:not(.multi-select) .directory .header': { enabled: copyEnabled(), command: [{ label: 'Copy name', command: 'remote-ftp:copy-name', }, { type: 'separator', }], }, '.remote-ftp-view .entries.list-tree:not(.multi-select) .file': { enabled: copyEnabled(), command: [{ label: 'Copy filename', command: 'remote-ftp:copy-name', }, { type: 'separator', }], }, }; return contextMenu; }; export default init;
'use babel'; const init = () => { const contextMenu = { '.remote-ftp-view .entries.list-tree:not(.multi-select) .directory': { enabled: atom.config.get('remote-ftp.context.enableCopyFilename'), command: [{ label: 'Copy name', command: 'remote-ftp:copy-name', }, { type: 'separator', }], }, '.remote-ftp-view .entries.list-tree:not(.multi-select) .file': { enabled: atom.config.get('remote-ftp.context.enableCopyFilename'), command: [{ label: 'Copy filename', command: 'remote-ftp:copy-name', }, { type: 'separator', }], }, }; return contextMenu; }; export default init;
Fix directory "Copy name" function
Fix directory "Copy name" function
JavaScript
mit
mgrenier/remote-ftp,icetee/remote-ftp
95c874d1a0f53bc15bba2c3e141560e20fc8ee3b
src/nzServices.js
src/nzServices.js
(function (angular) { "use strict"; var module = angular.module('net.enzey.services', []); module.service('nzService', function ($document, $timeout) { // position flyout var getChildElems = function(elem) { var childElems = []; elem = angular.element(elem); var children = elem.children(); for (var i=0; i < children.length; i++) { getChildElems(children[i]).forEach(function(childElem) { childElems.push(childElem); }); } childElems.push(elem[0]); return childElems; }; this.registerClickAwayAction = function(contextElem, clickAwayAction) { var wrappedClickAwayAction = null; wrappedClickAwayAction = function(event) { if (getChildElems(contextElem).indexOf(event.target) === -1) { $document.off('click', wrappedClickAwayAction); clickAwayAction(event); } }; $timeout(function() { $document.on('click', wrappedClickAwayAction); }); }; }); })(angular);
(function (angular) { "use strict"; var module = angular.module('net.enzey.services', []); module.service('nzService', function ($document, $timeout) { // position flyout var getChildElems = function(elem) { var childElems = []; elem = angular.element(elem); var children = elem.children(); for (var i=0; i < children.length; i++) { getChildElems(children[i]).forEach(function(childElem) { childElems.push(childElem); }); } childElems.push(elem[0]); return childElems; }; this.registerClickAwayAction = function(clickAwayAction) { var wrappedClickAwayAction = null; var parentElems = []; for (var i = 1; i < arguments.length; i++) { parentElems.push(arguments[i]); } wrappedClickAwayAction = function(event) { var allElements = []; parentElems.forEach(function(parentElem) { getChildElems(parentElem).forEach(function (elem) { allElements.push(elem); }); }); if (allElements.indexOf(event.target) === -1) { $document.off('click', wrappedClickAwayAction); clickAwayAction(event); } }; $timeout(function() { $document.on('click', wrappedClickAwayAction); }); }; }); })(angular);
Allow multiple elements, and their children, to be watched to determine if the clickAwayAction should be called.
Allow multiple elements, and their children, to be watched to determine if the clickAwayAction should be called.
JavaScript
apache-2.0
EnzeyNet/Services
bd565f9c1131a432028da2de89646c80b2420aa3
lib/update-license.js
lib/update-license.js
module.exports = function (licenseContent, done) { var thisYear = (new Date()).getFullYear(); var latestYear, originalYearInfo, updatedYearInfo, match, updatedLicenseContent; match = licenseContent.match(/Copyright \(c\) (\d{4})\s*[~-]\s*(\d{4})/); if (match) { latestYear = match[2]; if (parseInt(latestYear) < thisYear) { originalYearInfo = match[0]; updatedYearInfo = originalYearInfo.replace(latestYear, thisYear); updatedLicenseContent = licenseContent .replace(originalYearInfo, updatedYearInfo); done(null, updatedLicenseContent, originalYearInfo, updatedYearInfo); return; } } else { match = licenseContent.match(/Copyright \(c\) (\d{4})/); latestYear = match[1]; if (parseInt(latestYear) < thisYear) { originalYearInfo = match[0]; updatedYearInfo = originalYearInfo + '-' + thisYear; updatedLicenseContent = licenseContent .replace(originalYearInfo, updatedYearInfo); done(null, updatedLicenseContent, originalYearInfo, updatedYearInfo); return; } } // Otherwise update is not needed done(); };
module.exports = function (licenseContent, done) { var thisYear = (new Date()).getFullYear(); var latestYear, originalYearInfo, updatedYearInfo, match, updatedLicenseContent; match = licenseContent.match(/Copyright \(c\) (\d{4})\s*[~-]\s*(\d{4})/); if (match) { latestYear = match[2]; if (parseInt(latestYear) < thisYear) { originalYearInfo = match[0]; updatedYearInfo = originalYearInfo.replace(latestYear, thisYear); updatedLicenseContent = licenseContent .replace(originalYearInfo, updatedYearInfo); done(null, updatedLicenseContent, originalYearInfo, updatedYearInfo); return; } } else { match = licenseContent.match(/Copyright \(c\) (\d{4})/); if (match) { latestYear = match[1]; if (parseInt(latestYear) < thisYear) { originalYearInfo = match[0]; updatedYearInfo = originalYearInfo + '-' + thisYear; updatedLicenseContent = licenseContent .replace(originalYearInfo, updatedYearInfo); done(null, updatedLicenseContent, originalYearInfo, updatedYearInfo); return; } } } // Otherwise update is not needed done(); };
Check match exists before extracting latestYear
Check match exists before extracting latestYear
JavaScript
mit
sungwoncho/license-up
116724c9e7dfdbd528f98cf435abe6d1a2255c94
app/scripts/controllers/navbar.js
app/scripts/controllers/navbar.js
'use strict'; /** * @ngdoc function * @name dockstore.ui.controller:NavbarCtrl * @description * # NavbarCtrl * Controller of the dockstore.ui */ angular.module('dockstore.ui') .controller('NavbarCtrl', [ '$scope', '$rootScope', '$auth', '$location', 'UserService', 'NotificationService', function ($scope, $rootScope, $auth, $location, UserService, NtfnService) { $scope.userObj = UserService.getUserObj(); $scope.isAuthenticated = function() { return $auth.isAuthenticated(); }; $scope.isHomePage = function() { return ($location.url() === '/'); }; $scope.logout = function() { UserService.logout(); }; $scope.$watch('searchQuery', function(newValue, oldValue) { $rootScope.searchQuery = newValue; }); $scope.$on('$routeChangeStart', function(event, next, current) { if ($location.url().indexOf('/search') === -1) { $scope.searchQuery = ''; } }); }]).filter('shortenString', function() { return function (string, scope) { if (string.length > 10) { return string.substring(0,9) + '...'; } else { return string; } }; });
'use strict'; /** * @ngdoc function * @name dockstore.ui.controller:NavbarCtrl * @description * # NavbarCtrl * Controller of the dockstore.ui */ angular.module('dockstore.ui') .controller('NavbarCtrl', [ '$scope', '$rootScope', '$auth', '$location', 'UserService', 'NotificationService', function ($scope, $rootScope, $auth, $location, UserService, NtfnService) { $scope.userObj = UserService.getUserObj(); $scope.isAuthenticated = function() { return $auth.isAuthenticated(); }; $scope.isHomePage = function() { return ($location.url() === '/'); }; $scope.logout = function() { UserService.logout(); }; $scope.$watch('searchQuery', function(newValue, oldValue) { $rootScope.searchQuery = newValue; }); $scope.$on('$routeChangeStart', function(event, next, current) { if ($location.url().indexOf('/search') === -1) { $scope.searchQuery = ''; } }); }]).filter('shortenString', function() { return function (string, scope) { if (string != null && string.length > 10) { return string.substring(0,9) + '...'; } else { return string; } }; });
Handle error case for username shortening
Handle error case for username shortening
JavaScript
apache-2.0
ga4gh/dockstore-ui,ga4gh/dockstore-ui,ga4gh/dockstore-ui
e986b21056f79b7632f6854d31f0f2dd352ae1d1
src/arrow.js
src/arrow.js
import {Table} from 'apache-arrow'; const RowIndex = Symbol('rowIndex'); export default function arrow(data) { const table = Table.from(Array.isArray(data) ? data : [data]), proxy = rowProxy(table), rows = Array(table.length); table.scan(i => rows[i] = proxy(i)); return rows; } arrow.responseType = 'arrayBuffer'; function rowProxy(table) { const fields = table.schema.fields.map(d => d.name), Row = function(index) { this[RowIndex] = index; }, proto = Row.prototype; fields.forEach(name => { const column = table.getColumn(name); // skip columns with duplicate names if (proto.hasOwnProperty(name)) return; Object.defineProperty(proto, name, { get: function() { return column.get(this[RowIndex]); }, set: function() { throw Error('Can not overwrite Arrow data field values.'); }, enumerable: true }); }); return i => new Row(i); }
import {Table} from 'apache-arrow'; const RowIndex = Symbol('rowIndex'); export default function arrow(data) { const table = Table.from(Array.isArray(data) ? data : [data]), proxy = rowProxy(table), rows = Array(table.length); table.scan(i => rows[i] = proxy(i)); return rows; } arrow.responseType = 'arrayBuffer'; function rowProxy(table) { const fields = table.schema.fields.map(d => d.name), Row = function(index) { this[RowIndex] = index; }, proto = Row.prototype; fields.forEach((name, index) => { const column = table.getColumnAt(index); // skip columns with duplicate names if (proto.hasOwnProperty(name)) return; Object.defineProperty(proto, name, { get: function() { return column.get(this[RowIndex]); }, set: function() { throw Error('Arrow field values can not be overwritten.'); }, enumerable: true }); }); return i => new Row(i); }
Use indices for faster column lookup.
Use indices for faster column lookup.
JavaScript
bsd-3-clause
vega/vega-loader-arrow
07f15715639416099e8f58462a96e14874dd70d7
Gruntfile.js
Gruntfile.js
/* jshint node:true */ 'use strict'; module.exports = function (grunt) { var config = { pkg: grunt.file.readJSON('package.json'), srcDir: 'src', destDir: 'dist', tempDir: 'tmp', }; // load plugins require('load-grunt-tasks')(grunt); // load task definitions grunt.loadTasks('tasks'); // Utility function to load plugin configurations into an object function loadConfig(path) { var object = {}; require('glob').sync('*', {cwd: path}).forEach(function(option) { object[option.replace(/\.js$/,'')] = require(path + option)(config); }); return object; } // Merge that object with what with whatever we have here grunt.util._.extend(config, loadConfig('./tasks/options/')); // pass the config to grunt grunt.initConfig(config); };
/* jshint node:true */ 'use strict'; module.exports = function (grunt) { var config = { pkg: grunt.file.readJSON('package.json'), srcDir: 'src', destDir: 'dist', tempDir: 'tmp', }; // load plugins require('load-grunt-tasks')(grunt); // load task definitions grunt.loadTasks('tasks'); // Utility function to load plugin settings into config function loadConfig(config,path) { require('glob').sync('*', {cwd: path}).forEach(function(option) { var key = option.replace(/\.js$/,''); // If key already exists, extend it. It is your responsibility to avoid naming collisions config[key] = config[key] || {}; grunt.util._.extend(config[key], require(path + option)(config)); }); // technically not required return config; } // Merge that object with what with whatever we have here loadConfig(config,'./tasks/options/'); // pass the config to grunt grunt.initConfig(config); };
Update loadConfig to allow duplicates
Update loadConfig to allow duplicates
JavaScript
agpl-3.0
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
aca17ece6baa27b604a46116a8aaeb034d042286
src/WebInterface.js
src/WebInterface.js
const util = require('util'); const express = require('express'); const app = express(); const router = express.Router(); const Config = require('./Config'); class WebInterface { constructor(state) { this.state = state; this.port = Config.get('webPort') || 9000; } init() { router.get('/', (req, res) => res.json(this.state)); app.use('/api', router); app.listen(this.port); util.log(`WEB: Web API activated and running on port ${this.port}.`); } } module.exports = WebInterface;
const util = require('util'); const express = require('express'); const app = express(); const router = express.Router(); const Config = require('./Config'); class WebInterface { constructor(state) { this.state = state; this.port = Config.get('webPort') || 9000; } init() { // Routes for the API's GET response. router.get('/', (req, res) => res.json(this.state)); router.get('/npcs', (req, res) => res.json(this.state.MobFactory.npcs)); router.get('/players', (req, res) => res.json(this.state.PlayerManager.players)); router.get('/items', (req, res) => res.json(this.state.ItemManager.items)); router.get('/rooms', (req, res) => res.json(this.state.RoomManager.rooms)); router.get('/help', (req, res) => res.json(this.state.HelpManager.helps)); app.use('/api', router); app.listen(this.port); util.log(`WEB: Web API activated and running on port ${this.port}.`); } } module.exports = WebInterface;
Add routes for various get responses.
Add routes for various get responses.
JavaScript
mit
shawncplus/ranviermud,seanohue/ranviermud,seanohue/ranviermud
e735a093caade4c4106307935e25a42d7361c49a
semaphore.js
semaphore.js
(function (context) { var _SEMAPOHRES = {}; var Semaphore = function (key) { this.key = key; if (_SEMAPOHRES[this.key] == undefined) _SEMAPOHRES[this.key] = false; return this; }; Semaphore.prototype.isLocked = function() { return _SEMAPOHRES[this.key]; }; Semaphore.prototype.lock = function() { _SEMAPOHRES[this.key] = true; return this; }; Semaphore.prototype.unlock = function() { _SEMAPOHRES[this.key] = false; return this; }; Semaphore.wrap = function (key, callback) { var semaphore = new this(key); if (!semaphore.isLocked()) { semaphore.lock() callback(semaphore); } }; Semaphore.wrap = function (key, callback) { var semaphore = new this(key); if (!semaphore.isLocked()) { semaphore.lock() callback(semaphore); } }; var conflictingSemaphore = context.Semaphore; Semaphore.noConflict = function () { context.Semaphore = conflictingSemaphore; return Semaphore; }; context.Semaphore = Semaphore; });
(function (context) { var _SEMAPOHRES = {}; var Semaphore = function (key) { this.key = key; if (_SEMAPOHRES[this.key] == undefined) _SEMAPOHRES[this.key] = false; return this; }; Semaphore.prototype.isLocked = function() { return _SEMAPOHRES[this.key]; }; Semaphore.prototype.lock = function() { _SEMAPOHRES[this.key] = true; return this; }; Semaphore.prototype.unlock = function() { _SEMAPOHRES[this.key] = false; return this; }; Semaphore.wrap = function (key, callback) { var semaphore = new this(key); if (!semaphore.isLocked()) { semaphore.lock() callback(semaphore); } }; var conflictingSemaphore = context.Semaphore; Semaphore.noConflict = function () { context.Semaphore = conflictingSemaphore; return Semaphore; }; context.Semaphore = Semaphore; })(this);
Remove second Semaphore.wrap and pass in this.
Remove second Semaphore.wrap and pass in this.
JavaScript
mit
RyanMcG/semaphore-js
dae676daebaca628db83a769ca6cba03f3b8727b
blueprints/ember-cli-react/index.js
blueprints/ember-cli-react/index.js
/*jshint node:true*/ var RSVP = require('rsvp'); module.exports = { description: 'Install ember-cli-react dependencies into your app.', normalizeEntityName: function() {}, // Install react into host app afterInstall: function() { return RSVP.all([ this.addPackageToProject("ember-browserify", "^1.1.7"), this.addPackageToProject("react", "^0.14.7"), this.addPackageToProject("react-dom", "^0.14.7") ]); } };
/*jshint node:true*/ var RSVP = require('rsvp'); var pkg = require('../../package.json'); function getDependencyVersion(packageJson, name) { var dependencies = packageJson.dependencies; var devDependencies = packageJson.devDependencies; return dependencies[name] || devDependencies[name]; } module.exports = { description: 'Install ember-cli-react dependencies into your app.', normalizeEntityName: function() {}, // Install react into host app afterInstall: function() { return RSVP.all([ this.addPackageToProject("ember-browserify", getDependencyVersion(pkg, "ember-browserify")), this.addPackageToProject("react", getDependencyVersion(pkg, "react")), this.addPackageToProject("react-dom", getDependencyVersion(pkg, "react-dom")) ]); } };
Synchronize packages version in blueprint
Synchronize packages version in blueprint
JavaScript
mit
pswai/ember-cli-react,pswai/ember-cli-react
2aa678272232db394988884c2eabbeba50f84f36
src/components/Panels.js
src/components/Panels.js
import React, { Component, PropTypes } from 'react'; import Panel from './Panel'; import idSafeName from '../helpers/idSafeName'; class Panels extends Component { render () { const { data, selectedIndex } = this.props; if (!data.length) { return null; } return ( <div> {data.map((panel, index) => { const id = idSafeName(panel.label, index); return ( <Panel key={id} className="tabs__panels" content={panel.content} id={id} index={index} selectedIndex={selectedIndex} /> ); })} </div> ); } } Panels.propTypes = { data: PropTypes.array, selectedIndex: PropTypes.number }; export default Panels;
import React, { Component, PropTypes } from 'react'; import Panel from './Panel'; import idSafeName from '../helpers/idSafeName'; class Panels extends Component { render () { const { data, selectedIndex } = this.props; if (!data.length) { return null; } return ( <div className="tabs__panels"> {data.map((panel, index) => { const id = idSafeName(panel.label, index); return ( <Panel key={id} content={panel.content} id={id} index={index} selectedIndex={selectedIndex} /> ); })} </div> ); } } Panels.propTypes = { data: PropTypes.array, selectedIndex: PropTypes.number }; export default Panels;
Put .tabs__panels on correct element
Put .tabs__panels on correct element
JavaScript
mit
stowball/react-accessible-tabs
da16e7386042b77c942924fcab6114116bc52ec8
src/index.js
src/index.js
import {Configure} from './configure'; export function configure(aurelia, configCallback) { var instance = aurelia.container.get(Configure); // Do we have a callback function? if (configCallback !== undefined && typeof(configCallback) === 'function') { configCallback(instance); } return new Promise((resolve, reject) => { instance.loadConfig().then(data => { instance.setAll(data); resolve(); }); }).catch(() => { reject(new Error('Configuration file could not be loaded')); }); } export {Configure};
import {Configure} from './configure'; export function configure(aurelia, configCallback) { var instance = aurelia.container.get(Configure); // Do we have a callback function? if (configCallback !== undefined && typeof(configCallback) === 'function') { configCallback(instance); } return new Promise((resolve, reject) => { instance.loadConfig().then(data => { instance.setAll(data); // Gets the current pathName to determine dynamic environments (if defined) instance.check(); resolve(); }); }).catch(() => { reject(new Error('Configuration file could not be loaded')); }); } export {Configure};
Call the check function during configuration phase
Call the check function during configuration phase
JavaScript
mit
Vheissu/Aurelia-Configuration,JeroenVinke/Aurelia-Configuration,JoshMcCullough/Aurelia-Configuration,Vheissu/Aurelia-Configuration
490db713beee28b626237aab95fd70ead87a6ac5
src/index.js
src/index.js
import Component from './class/Component'; import render from './core/render'; import renderToString from './core/renderToString'; import unmountComponentAtNode from './core/unmountComponentAtNode'; import FragmentValueTypes from './enum/fragmentValueTypes'; import TemplateTypes from './enum/templateTypes'; import createFragment from './core/createFragment'; import createTemplate from './core/createTemplate'; import clearDomElement from './core/clearDomElement'; import createRef from './core/createRef'; import registerAttributes from './template/registerAttributeHandlers'; import { registerSetupHooks } from './events/hooks/createListenerArguments'; import { registerEventHooks } from './events/hooks/listenerSetup'; module.exports = { Component, render, renderToString, createFragment, createTemplate, unmountComponentAtNode, FragmentValueTypes, TemplateTypes, clearDomElement, createRef, /** * 3rd party */ registerAttributes, registerSetupHooks, registerEventHooks };
export { default as Component } from './class/Component'; export { default as render } from './core/render'; export { default as renderToString } from './core/renderToString'; export { default as unmountComponentAtNode } from './core/unmountComponentAtNode'; export { default as FragmentValueTypes } from './enum/fragmentValueTypes'; export { default as TemplateTypes } from './enum/templateTypes'; export { default as createFragment } from './core/createFragment'; export { default as createTemplate } from './core/createTemplate'; export { default as clearDomElement } from './core/clearDomElement'; export { default as createRef } from './core/createRef'; export { default as registerAttributes } from './template/registerAttributeHandlers'; export { registerSetupHooks } from './events/hooks/createListenerArguments'; export { registerEventHooks } from './events/hooks/listenerSetup';
Use ES6 export instead of CJS
Use ES6 export instead of CJS
JavaScript
mit
trueadm/inferno,infernojs/inferno,trueadm/inferno,infernojs/inferno
ab2c01ed76f5e55b82736eb5cf7314c6524fd05d
src/order.js
src/order.js
import { polygonCentroid, distance } from "./math.js"; // With 8 or fewer shapes, find the best permutation // Skip if array is huge (9+ shapes) export default function(start, end) { let distances = start.map(p1 => end.map(p2 => squaredDistance(p1, p2))), order = bestOrder(start, end, distances); if (start.length > 8) { return start.map((d, i) => i); } return bestOrder(start, end, distances); } export function bestOrder(start, end, distances) { let min = Infinity, best = start.map((d, i) => i); function permute(arr, order = [], sum = 0) { for (let i = 0; i < arr.length; i++) { let cur = arr.splice(i, 1), dist = distances[cur[0]][order.length]; if (sum + dist < min) { if (arr.length) { permute(arr.slice(), order.concat(cur), sum + dist); } else { min = sum + dist; best = order.concat(cur); } } if (arr.length) { arr.splice(i, 0, cur[0]); } } } permute(best); return best; } function squaredDistance(p1, p2) { let d = distance(polygonCentroid(p1), polygonCentroid(p2)); return d * d; }
import { polygonCentroid, distance } from "./math.js"; // With 8 or fewer shapes, find the best permutation // Skip if array is huge (9+ shapes) export default function(start, end) { let distances = start.map(p1 => end.map(p2 => squaredDistance(p1, p2))); if (start.length > 8) { return start.map((d, i) => i); } return bestOrder(start, end, distances); } export function bestOrder(start, end, distances) { let min = Infinity, best = start.map((d, i) => i); function permute(arr, order = [], sum = 0) { for (let i = 0; i < arr.length; i++) { let cur = arr.splice(i, 1), dist = distances[cur[0]][order.length]; if (sum + dist < min) { if (arr.length) { permute(arr.slice(), order.concat(cur), sum + dist); } else { min = sum + dist; best = order.concat(cur); } } if (arr.length) { arr.splice(i, 0, cur[0]); } } } permute(best); return best; } function squaredDistance(p1, p2) { let d = distance(polygonCentroid(p1), polygonCentroid(p2)); return d * d; }
Remove unused call to 'bestOrder'
Remove unused call to 'bestOrder'
JavaScript
mit
veltman/flubber
c879f1c7b35af059ca97d05b57ef1ee41da7ca60
api/tests/features/events/index.unit.spec.js
api/tests/features/events/index.unit.spec.js
require('rootpath')(); const Hapi = require('hapi'); const { describe, it, expect, sinon, before, after, beforeEach, afterEach } = require('tests/helper'); const route = require('app/features/events'); const eventHandler = require('app/features/events/eventHandler'); describe('Unit | Route | Event Index ', function() { let server; beforeEach(() => { server = require('server').BootStrapTestHelper('events'); }); afterEach(() => { server.stop(); }); describe('Server', () => { it('should have an object, version, and name attribute', () => { // then expect(route.register.attributes).to.exist; expect(route.register.attributes).to.be.an('object'); expect(route.register.attributes.name).to.equal('events-api'); expect(route.register.attributes).to.have.property('version'); }); }); describe('Route POST /api/events', () => { before(() => { sinon.stub(eventHandler, 'create').callsFake((request, reply) => reply('ok')); }); after(() => { eventHandler.create.restore(); }); it('should exist', () => { // when return server.inject({ method: 'POST', url: '/api/events', payload: { username: 'Flo' } }).then((res) => { // then expect(res.statusCode).to.equal(200); }); }); }); });
require('rootpath')(); const Hapi = require('hapi'); const { describe, it, expect, sinon, before, after, beforeEach, afterEach } = require('tests/helper'); const route = require('app/features/events'); const eventHandler = require('app/features/events/eventHandler'); describe('Unit | Route | Event Index ', function() { let server; beforeEach(() => { server = require('server').BootStrapTestHelper('events'); }); afterEach(() => { server.stop(); }); describe('Server', () => { it('should have an object, version, and name attribute', () => { // then expect(route.register.attributes).to.exist; expect(route.register.attributes).to.be.an('object'); expect(route.register.attributes.name).to.equal('events-api'); expect(route.register.attributes).to.have.property('version'); }); }); describe('Route POST /api/events', () => { before(() => { sinon.stub(eventHandler, 'create').callsFake((request, reply) => reply('ok')); }); after(() => { eventHandler.create.restore(); }); it('should exist', () => { // when return server.inject({ method: 'POST', url: '/api/events', payload: { host: {}, event: {} } }).then((res) => { // then expect(res.statusCode).to.equal(200); }); }); }); });
Add test when error is unknown
Add test when error is unknown
JavaScript
agpl-3.0
Hypernikao/who-brings-what
cc6b9e82123d9a9f75075ed0e843227ea9c74e4d
src/timer.js
src/timer.js
var Timer = (function(Util) { 'use strict'; // Internal constants for the various timer states. var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Delay = 4; var state = Waiting; var startTime = undefined, endTime = undefined, solveTime = undefined; var intervalID = undefined; function isWaiting() { return state == Waiting; } function isReady() { return state == Ready; } function isRunning() { return state == Running; } function runningEmitter() { Event.emit("timer/running"); } function trigger() { if (isWaiting()) { state = Ready; } else if (isReady()) { state = Running; startTime = Util.getMilli(); intervalID = setInterval(runningEmitter, 100); } else if (isRunning()) { state = Waiting; endTime = Util.getMilli(); clearInterval(intervalID); } } function getCurrent() { return Util.getMill() - startTime; } return { trigger: trigger, getCurrent: getCurrent }; });
var Timer = (function(Util) { 'use strict'; // Internal constants for the various timer states. var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Delay = 4; var state = Waiting; var startTime = undefined, endTime = undefined, solveTime = undefined; var intervalID = undefined; function isWaiting() { return state === Waiting; } function isReady() { return state === Ready; } function isRunning() { return state === Running; } function onWaiting() { endTime = Util.getMilli(); clearInterval(intervalID); } function onRunning() { startTime = Util.getMilli(); intervalID = setInterval(runningEmitter, 100); } function setState(new_state) { state = new_state; switch(state) { case Waiting: onWaiting(); break; case Running: onRunning(); break; } } function runningEmitter() { Event.emit("timer/running"); } function trigger() { if (isWaiting()) { setState(Ready); } else if (isReady()) { setState(Running); } else if (isRunning()) { setState(Waiting); } } function getCurrent() { return Util.getMill() - startTime; } return { trigger: trigger, getCurrent: getCurrent }; });
Move the functionality out of trigger(), to make it do as little as possible. Also, use '===' instead of '=='.
Move the functionality out of trigger(), to make it do as little as possible. Also, use '===' instead of '=='.
JavaScript
mit
jjtimer/jjtimer-core
8b5307e97bf54da9b97f1fbe610daf6ca3ebf7aa
src/server/app.js
src/server/app.js
import upload from './upload'; import express from 'express'; import logger from 'winston'; const app = express(); export default app; app.set('port', process.env.PORT || 3000); logger.remove(logger.transports.Console); logger.add(logger.transports.Console, {'timestamp':true,}); app.use((req, res, next) => { // eslint-disable-line no-unused-vars res.header('Access-Control-Allow-Origin', 'angeleandgus.com'); res.header('Access-Control-Allow-Headers', 'Content-Type'); }); app.use('/upload', upload); app.use((err, req, res, next) => { const status = err.statusCode || err.status || 500; res.status(status); const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; logger.error(`ip: ${ip} err: ${err}`); res.end(`Error ${status}: ${err.shortMessage}`); next(err); }); app.listen(app.get('port'), () => { logger.info(`Server started: http://localhost:${app.get('port')}/`); });
import upload from './upload'; import express from 'express'; import logger from 'winston'; const app = express(); export default app; app.set('port', process.env.PORT || 3000); logger.remove(logger.transports.Console); logger.add(logger.transports.Console, {'timestamp':true,}); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'angeleandgus.com'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); app.use('/upload', upload); app.use((err, req, res, next) => { const status = err.statusCode || err.status || 500; res.status(status); const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; logger.error(`ip: ${ip} err: ${err}`); res.end(`Error ${status}: ${err.shortMessage}`); next(err); }); app.listen(app.get('port'), () => { logger.info(`Server started: http://localhost:${app.get('port')}/`); });
Fix endless loop in server
Fix endless loop in server
JavaScript
agpl-3.0
gusmonod/aag,gusmonod/aag
6a6df1b256978c460ec823ee019c2028806d5bd1
sashimi-webapp/src/database/storage.js
sashimi-webapp/src/database/storage.js
/* * CS3283/4 storage.js * This is a facade class for other components */
/** * * CS3283/4 storage.js * This class acts as a facade for other developers to access to the database. * The implementation is a non-SQL local storage to support the WebApp. * */ const entitiesCreator = require('./create/entitiesCreator'); class Storage { static constructor() {} static initializeDatabase() { entitiesCreator.createUserTable(); entitiesCreator.createOrganizationTable(); entitiesCreator.createFolderTable(); entitiesCreator.createFileManagerTable(); entitiesCreator.clearDatabase(); } } Storage.initializeDatabase();
Add initializeDatabase function facade class
Add initializeDatabase function facade class
JavaScript
mit
nus-mtp/sashimi-note,nus-mtp/sashimi-note,nus-mtp/sashimi-note
60bd0a8274ec5e922bdaaba82c8c9e1054cea5f5
backend/src/routes/users/index.js
backend/src/routes/users/index.js
const express = require('express') const ERRORS = require('../../errors') const User = require('../../models/User') const utils = require('../../utils') const router = express.Router() router.post('/', register) function register(req, res, next) { const { body: { username, password } } = req if (!username || !password) { next(ERRORS.MISSING_PARAMETERS(['username', 'password'])) } else { User.register(username, password) .then(user => ({ id: user.id, username: user.username, token: utils.genToken(user.id) })) .then(data => { res.status(201) res.json(data) }) .catch(err => next(ERRORS.REGISTRATION_FAILED(err))) } } module.exports = router
const express = require('express') const ERRORS = require('../../errors') const User = require('../../models/User') const utils = require('../../utils') const router = express.Router() router.post('/', register) function register(req, res, next) { const { body: { username, password } } = req if (!username || !password) { next(ERRORS.MISSING_PARAMETERS(['username', 'password'])) } else { User.register(username, password) .then(user => ({ id: user.id, username: user.username, token: utils.genToken(user.id), createdAt: user.createdAt })) .then(data => { res.status(201) res.json(data) }) .catch(err => next(ERRORS.REGISTRATION_FAILED(err))) } } module.exports = router
Fix missing parameter to pass tests
Fix missing parameter to pass tests
JavaScript
mit
14Plumes/Hexode,14Plumes/Hexode,KtorZ/Hexode,14Plumes/Hexode,KtorZ/Hexode,KtorZ/Hexode
c98265f61bae81b9de01ac423f7a2b57a7f83e0f
tests/CoreSpec.js
tests/CoreSpec.js
describe("Core Bliss", function () { "use strict"; before(function() { fixture.setBase('tests/fixtures'); }); beforeEach(function () { this.fixture = fixture.load('core.html'); document.body.innerHTML += this.fixture[0]; }); // testing setup it("has the fixture on the dom", function () { expect($('#fixture-container')).to.not.be.null; }); it("has global methods and aliases", function() { expect(Bliss).to.exist; expect($).to.exist; expect($$).to.exist; expect($).to.equal(Bliss); expect($$).to.equal($.$); }); });
describe("Core Bliss", function () { "use strict"; before(function() { fixture.setBase('tests/fixtures'); }); beforeEach(function () { this.fixture = fixture.load('core.html'); }); // testing setup it("has the fixture on the dom", function () { expect($('#fixture-container')).to.not.be.null; }); it("has global methods and aliases", function() { expect(Bliss).to.exist; expect($).to.exist; expect($$).to.exist; expect($).to.equal(Bliss); expect($$).to.equal($.$); }); });
Remove appending of fixture to dom
Remove appending of fixture to dom This is not needed as far as I can tell, the test below works without it, and loading other fixtures elsewhere doesn't seem to work with this here.
JavaScript
mit
zdfs/bliss,zdfs/bliss,LeaVerou/bliss,dperrymorrow/bliss,LeaVerou/bliss,dperrymorrow/bliss
3f85aa402425340b7476aba9873af2bb3bc3534e
next/pages/index.js
next/pages/index.js
// This is the Link API import Link from 'next/link' const Index = () => ( <div> <Link href="/about"> <a>About Page</a> </Link> <p>Hello Next.js</p> </div> ) export default Index
// This is the Link API import Link from 'next/link' const Index = () => ( <div> <Link href="/about"> <a style={{fontSize: 20}}>About Page</a> </Link> <p>Hello Next.js</p> </div> ) export default Index
Add style to anchor link
Add style to anchor link
JavaScript
mit
yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program
2ad2196880708ceaf1870c89a5080f65efb66e8b
example/hoppfile.js
example/hoppfile.js
import hopp from 'hopp' export const css = hopp([ 'src/css/*.css' ]) .dest('dist/css') export const js = hopp([ 'src/js/*.js' ]) // create fs streams // .babel() // pipe to (create babel stream) .dest('dist/js') // pipe to (create dest stream) export default [ 'js', 'css' ]
import hopp from 'hopp' export const css = hopp([ 'src/css/*.css' ]) .dest('dist/css') export const js = hopp([ 'src/js/*.js' ]) .dest('dist/js') export const watch = hopp.watch([ 'js', 'css' ]) export default [ 'js', 'css' ]
Add sample watch task to example
Add sample watch task to example
JavaScript
mit
hoppjs/hopp
ab13702e08dd3daa943b08bb4a2cc014128b0ee0
wolf.js
wolf.js
var irc = require('irc'); // IRC Client require('js-yaml'); // JavaScript YAML parser (for settings) // Import settings file var settings = require('./config/bot.yaml'); var client = new irc.Client(settings.server, settings.nick, { userName: settings.username, realName: settings.realname, port: settings.port, channels: [settings.channel], }); // Original IRC output to console (for debugging) client.addListener('raw', function (message) { if (message.server) { console.log(':' + message.server + ' ' + message.command + ' ' + message.args.join(' :') ); } else { console.log(':' + message.nick + '!' + message.user + '@' + message.host + ' ' + message.command + ' ' + message.args.join(' :') ); } });
var irc = require('irc'); // IRC Client require('js-yaml'); // JavaScript YAML parser (for settings) // Gr__dirnameab configuration files var settings = require(__dirname + '/config/bot.yaml'); var werewolf = require(__dirname + '/config/werewolf.yaml'); var client = new irc.Client(settings.server, settings.nick, { userName: settings.username, realName: settings.realname, port: settings.port, channels: [settings.channel], }); // Original IRC output to console (for debugging) client.addListener('raw', function (message) { if (message.server) { console.log(':' + message.server + ' ' + message.command + ' ' + message.args.join(' :') ); } else { console.log(':' + message.nick + '!' + message.user + '@' + message.host + ' ' + message.command + ' ' + message.args.join(' :') ); } }); // The Locale handler var Locale = require(__dirname + '/components/locale.js'); var locale = Locale.createInstance(__dirname + '/locales', '.yaml'); locale.setLanguage(settings.language); setTimeout(function() { console.log(locale.languages); }, 100);
Use the new locale handler
Use the new locale handler
JavaScript
mpl-2.0
gluxon/wolf.js
b1030675d9b6432dfaf2bd76b395c28491bc32a8
src/main/server/Stats.js
src/main/server/Stats.js
import bunyan from 'bunyan'; import Promise from 'bluebird'; import SDC from 'statsd-client'; const logger = bunyan.createLogger({name: 'Stats'}); export default class Stats { constructor(config) { const stats = config.statsd; logger.info('Starting StatsD client.'); this._statsd = new SDC({ host: stats.host }); } /** * Get the underlying stats client. * You should not rely on the type of this, only that it can be used * as a middleware for express. **/ get client() { return this._statsd; } close() { this._statsd.close(); } counter(name, value = 1) { logger.info('Updating counter %s by %s.', name, value); this._statsd.counter(name, value); } gauge(name, value) { logger.info('Gauging %s at %s.', name, value); this._statsd.gauge(name, value); } }
import bunyan from 'bunyan'; import Promise from 'bluebird'; import SDC from 'statsd-client'; const logger = bunyan.createLogger({name: 'Stats'}); export default class Stats { constructor(config) { const stats = config.statsd; logger.info('Starting StatsD client.'); this._statsd = new SDC({ host: stats.host }); } /** * Get the underlying stats client. * You should not rely on the type of this, only that it can be used * as a middleware for express. **/ get client() { return this._statsd; } close() { this._statsd.close(); } counter(name, value = 1) { logger.debug('Updating counter %s by %s.', name, value); this._statsd.counter(name, value); } gauge(name, value) { logger.debug('Gauging %s at %s.', name, value); this._statsd.gauge(name, value); } }
Make stats quieter in logs.
Make stats quieter in logs.
JavaScript
mit
ssube/eveningdriver,ssube/eveningdriver
b268879770a80c260b68e7a5925f988b713bea09
src/components/FormInput.js
src/components/FormInput.js
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Form, Label, Input } from 'semantic-ui-react'; class FormInput extends Component { componentWillReceiveProps(nextProps) { const { input: { value, onChange }, meta: { visited }, defaultValue } = nextProps; if (!value && !visited && defaultValue) onChange(defaultValue); } render() { const { input, meta: { error, touched }, readOnly, width, label, defaultValue, required, errorPosition, inline, ...rest } = this.props; const hasError = touched && Boolean(error); if (readOnly) { return ( <span className="read-only"> {input && input.value && input.value.toLocaleString()} </span> ); } return ( <Form.Field error={hasError} width={width} required={required} style={{ position: 'relative' }} inline={inline} > {label && <label>{label}</label>} <Input {...input} {...rest} value={input.value || ''} error={hasError} /> {hasError && ( <Label pointing={inline ? 'left' : true}> {error} </Label> )} </Form.Field> ); } } export default FormInput;
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Form, Label, Input } from 'semantic-ui-react'; class FormInput extends Component { componentWillReceiveProps(nextProps) { const { input: { value, onChange }, meta: { visited }, defaultValue } = nextProps; if (!value && !visited && defaultValue) onChange(defaultValue); } render() { const { input, meta: { error, touched }, readOnly, width, label, defaultValue, required, inline, errorMessageStyle, ...rest } = this.props; const hasError = touched && Boolean(error); if (readOnly) { return ( <span className="read-only"> {input && input.value && input.value.toLocaleString()} </span> ); } return ( <Form.Field error={hasError} width={width} required={required} inline={inline} > {label && <label>{label}</label>} <Input {...input} {...rest} value={input.value || ''} error={hasError} /> {hasError && ( <Label className="error-message" pointing={inline ? 'left' : true} style={errorMessageStyle}> {error} </Label> )} </Form.Field> ); } } export default FormInput;
Add ability to customize error message styles
Add ability to customize error message styles
JavaScript
mit
mariusespejo/semantic-redux-form-fields
e3a8c773cc63a8263f8fe9bb98be8326671bbdcc
src/components/posts_new.js
src/components/posts_new.js
import React from 'react'; class PostsNew extends React.Component { render() { return ( <div className='posts-new'> Posts new </div> ); } } export default PostsNew;
import React from 'react'; import { Field, reduxForm } from 'redux-form'; class PostsNew extends React.Component { render() { return ( <form className='posts-new'> <Field name='title' component={} /> </form> ); } } export default reduxForm({ form: 'PostsNewForm' })(PostsNew);
Add initial posts new form elements
Add initial posts new form elements
JavaScript
mit
monsteronfire/redux-learning-blog,monsteronfire/redux-learning-blog
6874f190611009228ea9d6901fcdd6b951c66198
tests/unit/tooltip/tooltip_common.js
tests/unit/tooltip/tooltip_common.js
TestHelpers.commonWidgetTests( "tooltip", { defaults: { content: function() {}, disabled: false, hide: true, items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flipfit" }, show: true, tooltipClass: null, track: false, // callbacks close: null, create: null, open: null } });
TestHelpers.commonWidgetTests( "tooltip", { defaults: { content: function() {}, disabled: false, hide: true, items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flip" }, show: true, tooltipClass: null, track: false, // callbacks close: null, create: null, open: null } });
Fix default for position option, follow-up to 1d9eab1.
Tooltip: Fix default for position option, follow-up to 1d9eab1.
JavaScript
mit
GrayYoung/jQuery.UI.Extension,GrayYoung/jQuery.UI.Extension
4fce90c61e7b0c363261866d4d47268403c634ba
lib/models/relatedResource.js
lib/models/relatedResource.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.Types.ObjectId; var ORIGIN_TYPES = [ 'srv:coupledResource', 'gmd:onLine' ]; var RESOURCE_TYPES = [ 'feature-type', 'link', 'atom-feed' ]; var RelatedResourceSchema = new Schema({ type: { type: String, required: true, index: true, enum: RESOURCE_TYPES }, updatedAt: { type: Date, required: true, index: true }, // touchedAt: { type: Date, required: true }, name: { type: String }, /* Origin */ originType: { type: String, enum: ORIGIN_TYPES, required: true, index: true }, originId: { type: ObjectId, required: true, index: true }, originCatalog: { type: ObjectId, ref: 'Service', index: true, sparse: true }, /* Record */ record: { type: String, required: true, index: true }, /* FeatureType */ featureType: { candidateName: { type: String }, candidateLocation: { type: String }, matchingName: { type: String, index: true, sparse: true }, matchingService: { type: ObjectId, index: true, sparse: true } } /* */ }); mongoose.model('RelatedResource', RelatedResourceSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.Types.ObjectId; var ORIGIN_TYPES = [ 'srv:coupledResource', 'gmd:onLine' ]; var RESOURCE_TYPES = [ 'feature-type', 'link', 'atom-feed' ]; var RelatedResourceSchema = new Schema({ type: { type: String, required: true, index: true, enum: RESOURCE_TYPES }, updatedAt: { type: Date, required: true, index: true }, checking: { type: Boolean, index: true, sparse: true }, name: { type: String }, /* Origin */ originType: { type: String, enum: ORIGIN_TYPES, required: true, index: true }, originId: { type: ObjectId, required: true, index: true }, originCatalog: { type: ObjectId, ref: 'Service', index: true, sparse: true }, /* Record */ record: { type: String, required: true, index: true }, /* FeatureType */ featureType: { candidateName: { type: String }, candidateLocation: { type: String }, matchingName: { type: String, index: true, sparse: true }, matchingService: { type: ObjectId, index: true, sparse: true } } }); /* ** Statics */ RelatedResourceSchema.statics = { markAsChecking: function (query, done) { this.update(query, { $set: { checking: true } }, { multi: true }, done); } }; mongoose.model('RelatedResource', RelatedResourceSchema);
Add checking flag to RelatedResource model
Add checking flag to RelatedResource model
JavaScript
agpl-3.0
jdesboeufs/geogw,inspireteam/geogw
20f511a5e77972396b3ba9496283900bcbb6cbf6
webpack.common.js
webpack.common.js
var path = require('path'); module.exports = { /** * Path from which all relative webpack paths will be resolved. */ context: path.resolve(__dirname), /** * Entry point to the application, webpack will bundle all imported modules. */ entry: './src/index.ts', /** * Rule for which files should be transpiled via typescript loader. */ module: { rules: [ { test: /\.ts$/, use: [{ loader: 'ts-loader' }] } ] }, resolve: { /** * Resolve the following extensions when requiring/importing modules. */ extensions: ['.ts', '.js'] }, /** * Specify output as an UMD library. */ output: { path: 'build/dist', filename: 'baasic-sdk-javascript.js', library: 'baasicSdkJavaScript', libraryTarget: 'umd' } }
var path = require('path'); var rootDir = path.resolve(__dirname); function getRootPath(args) { args = Array.prototype.slice.call(arguments, 0); return path.join.apply(path, [rootDir].concat(args)); } module.exports = { /** * Path from which all relative webpack paths will be resolved. */ context: path.resolve(__dirname), /** * Entry point to the application, webpack will bundle all imported modules. */ entry: './src/index.ts', /** * Rule for which files should be transpiled via typescript loader. */ module: { rules: [ { test: /\.ts$/, use: [{ loader: 'ts-loader' }] } ] }, resolve: { /** * Resolve the following extensions when requiring/importing modules. */ extensions: ['.ts', '.js'], /** * Resolve modules using following folders. */ modules: [getRootPath('src'), getRootPath('node_modules')] }, /** * Specify output as an UMD library. */ output: { path: 'build/dist', filename: 'baasic-sdk-javascript.js', library: 'baasicSdkJavaScript', libraryTarget: 'umd' } }
Add module loading from src to webpack configuration.
Add module loading from src to webpack configuration.
JavaScript
mit
Baasic/baasic-sdk-javascript,Baasic/baasic-sdk-javascript
b8a2c85d3191879b74520499dbe768ddf487adc0
src/frontend/container/Resources/SwitchResource.js
src/frontend/container/Resources/SwitchResource.js
import React from 'react'; import PropTypes from 'prop-types'; import * as action from '../../action/'; import Switch from '@material-ui/core/Switch'; import Typography from '@material-ui/core/Typography'; import { connect } from 'react-redux'; class SwitchResource extends React.Component { handleChange = (field, value) => { if (this.props.isWriteable === true) { this.props.toggleSwitch(this.props.objectID, this.props.instanceID, this.props.resource.resourceID, value); } }; render () { return ( <div> <Typography variant='subheading' align='center'>{this.props.resource.name}</Typography> <Switch checked={this.props.currentValue} onChange={this.handleChange.bind(this, 'switch')} /> </div> ); } } SwitchResource.propTypes = { currentValue: PropTypes.any, instanceID: PropTypes.number, isWriteable: PropTypes.bool, objectID: PropTypes.number, resource: PropTypes.object, toggleSwitch: PropTypes.func.isRequired }; const mapStateToProps = (state) => { return { }; }; const mapDispatchToProps = (dispatch) => { return { toggleSwitch: (objectID, instanceID, resourceID, value) => dispatch(action.sendRequest(objectID, instanceID, resourceID, value)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(SwitchResource);
import React from 'react'; import PropTypes from 'prop-types'; import * as action from '../../action/'; import Switch from '@material-ui/core/Switch'; import Typography from '@material-ui/core/Typography'; import { connect } from 'react-redux'; class SwitchResource extends React.Component { handleChange = (field, value) => { if (this.props.isWriteable === true) { this.props.toggleSwitch(this.props.objectID, this.props.instanceID, this.props.resource.resourceID, this.props.currentValue); } }; render () { return ( <div> <Typography variant='subheading' align='center'>{this.props.resource.name}</Typography> <Switch checked={this.props.currentValue} onChange={this.handleChange.bind(this, 'switch')} /> </div> ); } } SwitchResource.propTypes = { currentValue: PropTypes.any, instanceID: PropTypes.number, isWriteable: PropTypes.bool, objectID: PropTypes.number, resource: PropTypes.object, toggleSwitch: PropTypes.func.isRequired }; const mapStateToProps = (state) => { return { }; }; const mapDispatchToProps = (dispatch) => { return { toggleSwitch: (objectID, instanceID, resourceID, value) => dispatch(action.sendRequest(objectID, instanceID, resourceID, !value)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(SwitchResource);
Fix bug with unresponsive switch due to new framework
Fix bug with unresponsive switch due to new framework
JavaScript
apache-2.0
doemski/cblocks,doemski/cblocks
06b3319ea0b7add2e69eecc473927034521bd7e5
lib/languages/rust.js
lib/languages/rust.js
var DocsParser = require("../docsparser"); var xregexp = require('../xregexp').XRegExp; function RustParser(settings) { DocsParser.call(this, settings); } RustParser.prototype = Object.create(DocsParser.prototype); RustParser.prototype.setup_settings = function() { this.settings = { 'curlyTypes': false, 'typeInfo': false, 'typeTag': false, 'varIdentifier': '.*', 'fnIdentifier': '.*', 'fnOpener': '^\\s*fn', 'commentCloser': ' */', 'bool': 'Boolean', 'function': 'Function' }; }; RustParser.prototype.parse_function = function(line) { var regex = xregexp('\\s*fn\\s+(?P<name>\\S+)'); var matches = xregexp.exec(line, regex); if(matches === null) return null; var name = matches.name || ''; return [ name, []]; }; RustParser.prototype.parse_var = function(line) { return null; }; RustParser.prototype.format_function = function(name, args) { return name; }; module.exports = RustParser;
var DocsParser = require("../docsparser"); var xregexp = require('../xregexp').XRegExp; function RustParser(settings) { DocsParser.call(this, settings); } RustParser.prototype = Object.create(DocsParser.prototype); RustParser.prototype.setup_settings = function() { this.settings = { 'curlyTypes': false, 'typeInfo': false, 'typeTag': false, 'varIdentifier': '.*', 'fnIdentifier': '[a-zA-Z_][a-zA-Z_0-9]*', 'fnOpener': '^\\s*fn', 'commentCloser': ' */', 'bool': 'Boolean', 'function': 'Function' }; }; RustParser.prototype.parse_function = function(line) { // TODO: add regexp for closures syntax // TODO: parse params var regex = xregexp('\\s*fn\\s+(?P<name>' + this.settings.fnIdentifier + ')'); var matches = xregexp.exec(line, regex); if(matches === null || matches.name === undefined) { return null; } var name = matches.name; return [name, null]; }; RustParser.prototype.parse_var = function(line) { return null; }; RustParser.prototype.format_function = function(name, args) { return name; }; module.exports = RustParser;
Improve Rust function parser (Use correct identifier)
Improve Rust function parser (Use correct identifier)
JavaScript
mit
NikhilKalige/docblockr
8c7a1ff64829876ee7d3815a7dd2bc32c6d7ec44
lib/testExecutions.js
lib/testExecutions.js
"use strict"; const file = require("./file"); module.exports = function testExecutions(data, formatForSonar56 = false) { const aTestExecution = [{ _attr: { version: "1" } }]; const testResults = data.testResults.map(file); return formatForSonar56 ? { unitTest: aTestExecution.concat(testResults) } : { testExecutions: aTestExecution.concat(testResults) }; };
'use strict' const file = require('./file') module.exports = function testExecutions(data, formatForSonar56 = false) { const aTestExecution = [{_attr: {version: '1'}}] const testResults = data.testResults.map(file) return formatForSonar56 ? { unitTest: aTestExecution.concat(testResults) } : { testExecutions: aTestExecution.concat(testResults) }; };
Undo changes done by prettier
Undo changes done by prettier old habbits die hard! Ran the prettier on Atom on the whole file, this commit undoes it.
JavaScript
mit
3dmind/jest-sonar-reporter,3dmind/jest-sonar-reporter
fe71f0ef2c920712e3b33f5002a18ab87ff52544
src/index.js
src/index.js
export function onConnect(respond, connections = {}, tab, error) { chrome.runtime.onConnect.addListener(function(port) { function extensionListener(message) { if (message.name === 'init') { connections[message.tabId] = port; if (tab && message.tabId !== tab.id) { error(port); return; } connections[message.tabId].postMessage(respond()); } } port.onMessage.addListener(extensionListener); port.onDisconnect.addListener(function(portDiscon) { portDiscon.onMessage.removeListener(extensionListener); Object.keys(connections).forEach(function(id) { if (connections[id] === portDiscon) { delete connections[id]; } }); }); }); } export const connect = chrome.runtime.connect; export function onMessage(messaging) { if (chrome.runtime.onMessage) chrome.runtime.onMessage.addListener(messaging); } export const sendToBg = chrome.runtime.sendMessage; export function sendToTab(...args) { chrome.tabs.sendMessage(...args); }
export function onConnect(respond, connections = {}, tab, error) { chrome.runtime.onConnect.addListener(function(port) { function extensionListener(message) { if (message.name === 'init') { connections[message.tabId || port.sender.tab.id] = port; if (tab && message.tabId !== tab.id) { error(port); return; } port.postMessage(respond()); } } port.onMessage.addListener(extensionListener); port.onDisconnect.addListener(function(portDiscon) { portDiscon.onMessage.removeListener(extensionListener); Object.keys(connections).forEach(function(id) { if (connections[id] === portDiscon) { delete connections[id]; } }); }); }); } export const connect = chrome.runtime.connect; export function onMessage(messaging) { if (chrome.runtime.onMessage) chrome.runtime.onMessage.addListener(messaging); } export const sendToBg = chrome.runtime.sendMessage; export function sendToTab(...args) { chrome.tabs.sendMessage(...args); }
Allow not to specify sender tab id. Detect it implicitly
Allow not to specify sender tab id. Detect it implicitly
JavaScript
mit
zalmoxisus/crossmessaging
e2925bec159f6fc40317b40b3036cd669a23ddfb
app/Artist.js
app/Artist.js
const https = require("https"); const fs = require("fs"); module.exports = class Artist { constructor(artistObject) { this.id = artistObject.id; this.name = artistObject.name; this.tracks = []; this.artistObject = artistObject; this.artId = artistObject.picture; } async updateTracks(tidalApi) { this.tracks = await tidalApi.getArtistTopTracks(this); } updateArt(tidalApi) { return new Promise((resolve, reject) => { this.mkdirSync("/tmp/tidal-cli-client"); this.artURL = tidalApi.getArtURL(this.artId, 750, 750); this.artSrc = "/tmp/tidal-cli-client/" + this.artId + ".jpg"; let artFile = fs.createWriteStream(this.artSrc); https.get(this.artURL, response => { response.pipe(artFile); resolve(); }); }); } mkdirSync(dirPath) { try { fs.mkdirSync(dirPath) } catch (err) { if (err.code !== "EXIST") throw err; } } };
const https = require("https"); const fs = require("fs"); module.exports = class Artist { constructor(artistObject) { this.id = artistObject.id; this.name = artistObject.name; this.tracks = []; this.artistObject = artistObject; this.artId = artistObject.picture; } async updateTracks(tidalApi) { this.tracks = await tidalApi.getArtistTopTracks(this); } updateArt(tidalApi) { return new Promise((resolve, reject) => { this.mkdirSync("/tmp/tidal-cli-client"); this.artURL = tidalApi.getArtURL(this.artId, 750, 750); this.artSrc = "/tmp/tidal-cli-client/" + this.artId + ".jpg"; let artFile = fs.createWriteStream(this.artSrc); https.get(this.artURL, response => { response.pipe(artFile); resolve(); }); }); } mkdirSync(dirPath) { if(!fs.existsSync(dirPath)) { try { fs.mkdirSync(dirPath) } catch (err) { if (err.code !== "EEXIST") throw err; } } } };
Check if directory exists before creating
Check if directory exists before creating
JavaScript
mit
okonek/tidal-cli-client,okonek/tidal-cli-client
128f6c14cc4562a43bd929080691a4c764cb9b8d
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); gulp.task('compile', function () { return gulp.src('./scss/*.scss') .pipe(gulp.dest('./dist/')); }); gulp.task('watch', function () { gulp.watch('./scss/*.scss', ['compile']); });
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); gulp.task('compile', function () { return gulp.src('./scss/*.scss') .pipe(sass()) .pipe(gulp.dest('./dist/')); }); gulp.task('watch', function () { gulp.watch('./scss/*.scss', ['compile']); });
Add sass compilation back to gulp file, tweaked output
Add sass compilation back to gulp file, tweaked output
JavaScript
mit
MikeBallan/Amazium,aoimedia/Amazium,aoimedia/Amazium,catchamonkey/amazium,OwlyStuff/Amazium,OwlyStuff/Amazium
13526036cd2f742c1ef744cbd87debdcea70e1ea
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var minifycss = require('gulp-minify-css'); var autoprefixer = require('gulp-autoprefixer'); var sourcemaps = require('gulp-sourcemaps'); var paths = { sass: 'wye/static/sass/*.scss', css: 'wye/static/css' }; gulp.task('css', function() { return gulp.src(paths.sass) .pipe(sourcemaps.init()) .pipe(sass() .on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['> 1%'] })) .pipe(minifycss({ debug: true })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(paths.css)); }); gulp.task('watch', function() { gulp.watch(paths.sass, ['css']); }); gulp.task('default', ['watch']);
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var minifycss = require('gulp-minify-css'); var autoprefixer = require('gulp-autoprefixer'); var sourcemaps = require('gulp-sourcemaps'); var paths = { sass: 'wye/static/sass/**/*.scss', css: 'wye/static/css' }; gulp.task('css', function() { return gulp.src(paths.sass) .pipe(sourcemaps.init()) .pipe(sass() .on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['> 1%'] })) .pipe(minifycss({ debug: true })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(paths.css)); }); gulp.task('watch', function() { gulp.watch(paths.sass, ['css']); }); gulp.task('default', ['watch']);
Include all sass dirs to compile
Include all sass dirs to compile
JavaScript
mit
pythonindia/wye,pythonindia/wye,pythonindia/wye,pythonindia/wye
0f21e31f84a1fececa6b8220eb2049651630e58e
gulpfile.js
gulpfile.js
var gulp = require('gulp'), gulpCopy = require('gulp-file-copy'); gulp.task('copy', function() { gulp.src('./bower_components/jquery/jquery.min.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./jquery-mobile/jquery.mobile-1.4.5.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./bower_components/moment/min/moment-with-locales.min.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./bower_components/local-storage/src/LocalStorage.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./jquery-mobile/jquery.mobile-1.4.5.css') .pipe(gulp.dest('./css/lib/')); });
var gulp = require('gulp'), gulpCopy = require('gulp-file-copy'); gulp.task('copy', function() { gulp.src('./bower_components/jquery/jquery.min.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./jquery-mobile/jquery.mobile-1.4.5.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./bower_components/moment/min/moment-with-locales.min.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./bower_components/local-storage/src/LocalStorage.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./jquery-mobile/jquery.mobile-1.4.5.css') .pipe(gulp.dest('./css/lib/')); gulp.src('./jquery-mobile/images/ajax-loader.gif') .pipe(gulp.dest('./js/lib/images/')); });
Add copy image in gulp
Add copy image in gulp
JavaScript
mit
jeremy5189/payWhichClient,jeremy5189/payWhichClient
80469cdd650849ad6775f5d0a2bfad6a1cb445db
desktop/app/shared/database/parse.js
desktop/app/shared/database/parse.js
/** * Parse task and return task info if * the task is valid, otherwise throw * error. * @param {string} query Enetered task * @return {object} Task info containing * task text, start time * and dealine */ function parse(query) { /** * Day, week or month coefficient * @type {Object} */ const dwm = { d: 1, '': 1, w: 7, m: 30, }; const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); let start = Date.now(); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; } const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]); const importance = regexResult[6].length + 1; const status = 0; return { text: text.trim(), start, end, importance, status, }; } module.exports = parse;
/** * Parse task and return task info if * the task is valid, otherwise throw * error. * @param {string} query Enetered task * @return {object} Task info containing * task text, start time * and dealine */ function parse(query) { /** * Day, week or month coefficient * @type {Object} */ const dwm = { d: 1, '': 1, w: 7, m: 30, }; const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); let start = Date.now() - ((Date.now() % 86400000) + (new Date().getTimezoneOffset() * 60000)); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; } const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]); const importance = regexResult[6].length + 1; const status = 0; return { text: text.trim(), start, end, importance, status, }; } module.exports = parse;
Move task starting and ending points to start of days
Move task starting and ending points to start of days
JavaScript
mit
mkermani144/wanna,mkermani144/wanna
f9089bd10a8283fb2cd9f9914c39dc61f5c670fa
tasks/css_flip.js
tasks/css_flip.js
/* * grunt-css-flip * https://github.com/twbs/grunt-css-flip * * Copyright (c) 2014 Chris Rebert * Licensed under the MIT License. */ 'use strict'; var flip = require('css-flip'); module.exports = function(grunt) { grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () { var options = this.options({}); this.files.forEach(function (f) { var originalCss = grunt.file.read(f.src); var flippedCss = null; try { flippedCss = flip(originalCss, options); } catch (err) { grunt.fail.warn(err); } grunt.file.write(f.dest, flippedCss); grunt.log.writeln('File "' + f.dest.cyan + '" created.'); }); }); };
/* * grunt-css-flip * https://github.com/twbs/grunt-css-flip * * Copyright (c) 2014 Chris Rebert * Licensed under the MIT License. */ 'use strict'; var flip = require('css-flip'); module.exports = function (grunt) { grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () { var options = this.options({}); this.files.forEach(function (f) { var originalCss = grunt.file.read(f.src); var flippedCss = null; try { flippedCss = flip(originalCss, options); } catch (err) { grunt.fail.warn(err); } grunt.file.write(f.dest, flippedCss); grunt.log.writeln('File "' + f.dest.cyan + '" created.'); }); }); };
Add missing space before paren
Add missing space before paren
JavaScript
mit
twbs/grunt-css-flip
286b7f561655fdf75e0fe53d888d95082605ef3f
src/index.js
src/index.js
export default function({ types }) { return { visitor: { Function: function parseFunctionPath(path) { (path.get('params') || []).reverse().forEach(function(param) { const decorators = param.node.decorators.reverse(); if (param.node && Array.isArray(decorators)) { let currentDecorator; decorators.forEach(function(decorator) { /** * TODO: Validate the name of the decorator is not * the same as any of the passed params */ const callNode = types.callExpression( decorator.expression, [ currentDecorator || types.Identifier(`_${param.node.name}`) ] ); currentDecorator = callNode; }); param.parentPath.get('body').unshiftContainer( 'body', types.variableDeclaration('var', [ types.variableDeclarator( types.Identifier(param.node.name), currentDecorator ) ]) ); param.replaceWith( types.Identifier(`_${param.node.name}`) ); } }); } } }; }
export default function({ types }) { return { visitor: { Function: function parseFunctionPath(path) { (path.get('params') || []).reverse().forEach(function(param) { let currentDecorator; (param.node.decorators || []).reverse() .forEach(function(decorator) { /** * TODO: Validate the name of the decorator is not * the same as any of the passed params */ currentDecorator = types.callExpression( decorator.expression, [ currentDecorator || types.Identifier(`_${param.node.name}`) ] ); }); param.parentPath.get('body').unshiftContainer( 'body', types.variableDeclaration('var', [ types.variableDeclarator( types.Identifier(param.node.name), currentDecorator ) ]) ); param.replaceWith( types.Identifier(`_${param.node.name}`) ); }); } } }; }
Fix issue with the existence of the decorators array introduced by syntax changes
Fix issue with the existence of the decorators array introduced by syntax changes
JavaScript
mit
benderTheCrime/babel-plugin-transform-function-parameter-decorators
45263d5abdd81c9ce15c52835d98b4998ccbe337
src/index.js
src/index.js
import Promise from 'bluebird'; import process from 'process'; import util from 'util'; import { withRetries } from 'killrvideo-nodejs-common'; import { Scheduler } from './scheduler'; import * as availableTasks from './tasks'; import { initCassandraAsync } from './utils/cassandra'; import { initializeSampleDataAsync } from './sample-data/initialize'; // Allow promise cancellation Promise.config({ cancellation: true }); /** * Async start the application. */ async function startAsync() { let scheduler = null; try { // Make sure C* is ready to go await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false); // Initialize sample data await initializeSampleDataAsync(); // Start scheduled tasks scheduler = new Scheduler(availableTasks); scheduler.start(); return scheduler; } catch (err) { if (scheduler !== null) scheduler.stop(); console.error('Unable to start Sample Data Generator'); console.error(err); process.exitCode = 1; } } // Start the app let startPromise = startAsync(); // Handler for attempting to gracefully shutdown function onStop() { console.log('Attempting to shutdown'); if (startPromise.isFulfilled()) { let s = startPromise.value(); s.stop(); } else { startPromise.cancel(); } process.exit(0); } // Attempt to shutdown on SIGINT process.on('SIGINT', onStop);
import Promise from 'bluebird'; import process from 'process'; import util from 'util'; import { withRetries } from 'killrvideo-nodejs-common'; import { Scheduler } from './scheduler'; import * as availableTasks from './tasks'; import { initCassandraAsync } from './utils/cassandra'; import { initializeSampleDataAsync } from './sample-data/initialize'; // Allow promise cancellation Promise.config({ cancellation: true }); /** * Async start the application. */ async function startAsync() { let scheduler = null; try { // Make sure C* is ready to go await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false); // Initialize sample data await initializeSampleDataAsync(); // Start scheduled tasks scheduler = new Scheduler(availableTasks); scheduler.start(); return scheduler; } catch (err) { if (scheduler !== null) scheduler.stop(); console.error('Unable to start Sample Data Generator'); console.error(err); process.exit(1); } } // Start the app let startPromise = startAsync(); // Handler for attempting to gracefully shutdown function onStop() { console.log('Attempting to shutdown'); if (startPromise.isFulfilled()) { let s = startPromise.value(); s.stop(); } else { startPromise.cancel(); } process.exit(0); } // Attempt to shutdown on SIGINT process.on('SIGINT', onStop);
Make sure we actually exit when we fail on startup
Make sure we actually exit when we fail on startup
JavaScript
apache-2.0
KillrVideo/killrvideo-generator,KillrVideo/killrvideo-generator
11086bca7cb8b43fb099e70ab70fc548bcba9683
src/index.js
src/index.js
/** * @copyright 2015, Prometheus Research, LLC */ import {createValue} from './Value'; export Fieldset from './Fieldset'; export Field from './Field'; export {createValue}; export WithFormValue from './WithFormValue'; export * as Schema from './Schema'; export Input from './Input'; export ErrorList from './ErrorList'; export function Value(schema, value, onChange, params, errorList) { console.error("`import {Value} from 'react-forms'` is deprecated, \ change it to 'import {createvalue} from `'react-forms'`"); return createValue({schema, value, onChange, params, errorList}); }
/** * @copyright 2015, Prometheus Research, LLC */ import {createValue} from './Value'; export Fieldset from './Fieldset'; export Field from './Field'; export {createValue}; export WithFormValue from './WithFormValue'; export * as Schema from './Schema'; export Input from './Input'; export ErrorList from './ErrorList'; export function Value(schema, value, onChange, params, errorList) { console.error("`import {Value} from 'react-forms'` is deprecated, \ change it to 'import {createValue} from `'react-forms'`"); return createValue({schema, value, onChange, params, errorList}); }
Fix typo: createvalue -> createValue
Fix typo: createvalue -> createValue
JavaScript
mit
prometheusresearch/react-forms
b394877b0b152d43656c5dfc18e667111273668e
src/utils.js
src/utils.js
/** * Create a copy of an object, omitting provided keys. * @param {Object} obj Object to copy * @param {Array} arr Keys to omit * @returns {Object} */ export const omit = (obj, arr) => Object.keys(obj).reduce((res, key) => { if (arr.indexOf(key) === -1) { res[key] = obj[key] } return res }, {}) export const getQueryStringValue = (key) => { return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1')) } /** * Get key value from location hash * @param {string} key Key to get value from * @returns {string|null} */ export const getHashValue = (key) => { const matches = window.location.hash.match(new RegExp(`${key}=([^&]*)`)) return matches ? matches[1] : null }
/** * Create a copy of an object, omitting provided keys. * @param {Object} obj Object to copy * @param {Array} arr Keys to omit * @returns {Object} */ export const omit = (obj, arr) => Object.keys(obj).reduce((res, key) => { if (arr.indexOf(key) === -1) { res[key] = obj[key] } return res }, {}) /** * Get key value from url query strings * @param {string} key Key to get value from * @returns {string} */ export const getQueryStringValue = (key) => { return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1')) } /** * Get key value from location hash * @param {string} key Key to get value from * @returns {string|null} */ export const getHashValue = (key) => { const matches = window.location.hash.match(new RegExp(`${key}=([^&]*)`)) return matches ? matches[1] : null } export const responseTextToObject = (text, key) => { const keyValuePairs = text.split('&') if (!keyValuePairs || keyValuePairs.length === 0) { return {} } return keyValuePairs.reduce((result, pair) => { const [key, value] = pair.split('=') result[key] = decodeURIComponent(value) return result }, {}) }
Add util to parse response from GitHub access token request
Add util to parse response from GitHub access token request
JavaScript
mit
nicolas-goudry/react-social-login,deepakaggarwal7/react-social-login,deepakaggarwal7/react-social-login,nicolas-goudry/react-social-login,deepakaggarwal7/react-social-login,nicolas-goudry/react-social-login
61328d83b9671c066913c301bc4bc449ea427eb7
src/utils.js
src/utils.js
export function getInterfaceLanguage() { if (!!navigator && !!navigator.language) { return navigator.language; } else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) { return navigator.languages[0]; } else if (!!navigator && !!navigator.userLanguage) { return navigator.userLanguage; } else if (!!navigator && !!navigator.browserLanguage) { return navigator.browserLanguage; } return 'en-US'; } export function validateProps(props) { const reservedNames = [ '_interfaceLanguage', '_language', '_defaultLanguage', '_defaultLanguageFirstLevelKeys', '_props', ]; Object.keys(props).forEach(key => { if (reservedNames.indexOf(key)>=0) throw new Error(`${key} cannot be used as a key. It is a reserved word.`) }); }
export function getInterfaceLanguage() { if (!!navigator && !!navigator.language) { return navigator.language; } else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) { return navigator.languages[0]; } else if (!!navigator && !!navigator.userLanguage) { return navigator.userLanguage; } else if (!!navigator && !!navigator.browserLanguage) { return navigator.browserLanguage; } return 'en-US'; } export function validateProps(props) { const reservedNames = [ '_interfaceLanguage', '_language', '_defaultLanguage', '_defaultLanguageFirstLevelKeys', '_props', ]; Object.keys(props).forEach(key => { if (reservedNames.includes(key)) throw new Error(`${key} cannot be used as a key. It is a reserved word.`) }); }
Use includes to make code simplier
Use includes to make code simplier
JavaScript
mit
stefalda/react-localization
b44c58ba61808077ae22d1e4e3030d0aeb84c97a
face-read.js
face-read.js
'use strict'; var fs = require('fs'); /* * read *.<type> files at given `path', * return array of files and their * textual content */ exports.read = function (path, type, callback) { var textFiles = {}; var regex = new RegExp("\\." + type); fs.readdir(path, function (error, files) { if (error) throw new Error("Error reading from path: " + path); for (var file = 0; file < files.length; file++) { if (files[file].match(regex)) { textFiles[files[file] .slice(0, (type.length * -1) - 1 )] = fs.readFileSync(path + '/' + files[file] , 'utf8'); } } if (typeof callback === 'function') { callback(textFiles); } }); }
'use strict'; var fs = require('fs'); /* * read *.<type> files at given `path', * return array of files and their * textual content */ exports.read = function (path, type, callback) { var textFiles = {}; var regex = new RegExp("\\." + type); var typeLen = (type.length * -1) -1; fs.readdir(path, function (error, files) { if (error) throw new Error("Error reading from path: " + path); for (var file = 0; file < files.length; file++) { if (files[file].match(regex)) { // load textFiles with content textFiles[files[file] .slice(0, typeLen] = fs.readFileSync(path + '/' + files[file] , 'utf8'); } } if (typeof callback === 'function') { callback(textFiles); } }); }
Split up assignment logic and add elucidating comment
Split up assignment logic and add elucidating comment This is the first in a line of commit intended to make this module more useable
JavaScript
mit
jm-janzen/EC2-facer,jm-janzen/EC2-facer,jm-janzen/EC2-facer
db859ac95909fe575ffeab45892c67b4f910f6c4
config/_constant.js
config/_constant.js
/** * @author {{{author}}} * @since {{{date}}} */ (function () { 'use strict'; angular .module({{{moduleName}}}) .constant({{{elementName}}}, // Add your values here ); }); })();
/** * @author {{{author}}} * @since {{{date}}} */ (function () { 'use strict'; angular .module('{{{moduleName}}}') .constant('{{{elementName}}}', // Add your values here ); }); })();
Add missing quotes to template
Add missing quotes to template
JavaScript
mit
natete/angular-file-templates,natete/angular-file-templates
edc62580aaa114c7b87938a2e275acdef3562981
tests/js/index.js
tests/js/index.js
/*global mocha, mochaPhantomJS, sinon:true, window */ 'use strict'; var $ = require('jquery'), chai = require('chai'), sinon = require('sinon'), sinonChai = require('sinon-chai'), toggles; // Expose jQuery globals window.$ = window.jQuery = $; toggles = require('../../libs/jquery-toggles/toggles.min'); // Load Sinon-Chai chai.use(sinonChai); mocha.timeout(2000); // Expose tools in the global scope window.chai = chai; window.describe = describe; window.expect = chai.expect; window.it = it; window.sinon = sinon; <<<<<<< HEAD ======= require('./tabbedLayoutTest'); require('./ButtonComponentTest.js'); require('./FlashMessageComponentTest.js'); require('./PulsarFormComponentTest.js'); require('./HelpTextComponentTest.js'); require('./PulsarUIComponentTest.js'); // require('./signinTest'); //require('./MasterSwitchComponentTest'); if (typeof mochaPhantomJS !== 'undefined') { mochaPhantomJS.run(); } else { mocha.run(); } >>>>>>> develop
/*global mocha, mochaPhantomJS, sinon:true, window */ 'use strict'; var $ = require('jquery'), chai = require('chai'), sinon = require('sinon'), sinonChai = require('sinon-chai'), toggles; // Expose jQuery globals window.$ = window.jQuery = $; toggles = require('../../libs/jquery-toggles/toggles.min'); // Load Sinon-Chai chai.use(sinonChai); mocha.timeout(2000); // Expose tools in the global scope window.chai = chai; window.describe = describe; window.expect = chai.expect; window.it = it; window.sinon = sinon; require('./tabbedLayoutTest'); require('./ButtonComponentTest.js'); require('./FlashMessageComponentTest.js'); require('./PulsarFormComponentTest.js'); require('./HelpTextComponentTest.js'); require('./PulsarUIComponentTest.js'); if (typeof mochaPhantomJS !== 'undefined') { mochaPhantomJS.run(); } else { mocha.run(); }
Fix merge conflict in js tests
Fix merge conflict in js tests
JavaScript
mit
jadu/pulsar,jadu/pulsar,jadu/pulsar
12cfd7069c6513186bffdc073c1fd5264d077754
app/js/arethusa.core/conf_url.js
app/js/arethusa.core/conf_url.js
'use strict'; // Handles params concerning configuration files in the $routeProvider phase angular.module('arethusa.core').factory('confUrl', [ 'CONF_PATH', '$route', function (CONF_PATH, $route) { return function (useDefault) { var params = $route.current.params; var confPath = CONF_PATH + '/'; // Fall back to default and wrong paths to conf files // need to be handled separately eventually if (params.conf) { return confPath + params.conf + '.json'; } else if (params.conf_file) { return params.conf_file; } else { if (useDefault) { return confPath + 'default.json'; } } }; } ]);
'use strict'; // Handles params concerning configuration files in the $routeProvider phase angular.module('arethusa.core').factory('confUrl', [ 'CONF_PATH', '$route', function (CONF_PATH, $route) { // The default route is deprectated and can be refactored away return function (useDefault) { var params = $route.current.params; var confPath = CONF_PATH + '/'; // Fall back to default and wrong paths to conf files // need to be handled separately eventually if (params.conf) { return confPath + params.conf + '.json'; } else if (params.conf_file) { return params.conf_file; } else { if (useDefault) { return confPath + 'default.json'; } } }; } ]);
Add comment about future work in confUrl
Add comment about future work in confUrl
JavaScript
mit
Masoumeh/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa
1378fbb1df3684e9674a2fb9836d8516b624e7a4
grunt/css.js
grunt/css.js
module.exports = function(grunt) { //grunt-sass grunt.config('sass', { options: { outputStyle: 'expanded', imagePath: '../<%= config.image.dir %>' }, dist: { files: { '<%= config.css.dir %>/<%= config.css.file %>': '<%= config.scss.dir %>/<%= config.scss.file %>' } } }); //grunt-autoprefixer grunt.config('autoprefixer', { options: { browsers: ['> 1%', 'last 2 versions', 'ie 8', 'ie 9', 'ie 10'] }, dist: { files: { '<%= config.css.dir %>/<%= config.css.file %>': '<%= config.css.dir %>/<%= config.css.file %>' } } }); //grunt-contrib-cssmin grunt.config('cssmin', { target: { src: '<%= config.css.dir %>/<%= config.css.file %>', dest: '<%= config.css.dir %>/<%= config.css.file %>' } }); //grunt-contrib-csslint grunt.config('csslint', { options: { csslintrc: 'grunt/.csslintrc' }, strict: { src: ['<%= config.css.dir %>/*.css'] } }); };
module.exports = function(grunt) { //grunt-sass grunt.config('sass', { options: { outputStyle: 'expanded', //includePaths: ['<%= config.scss.includePaths %>'], imagePath: '../<%= config.image.dir %>' }, dist: { files: { '<%= config.css.dir %>/<%= config.css.file %>': '<%= config.scss.dir %>/<%= config.scss.file %>' } } }); //grunt-autoprefixer grunt.config('autoprefixer', { options: { browsers: ['> 1%', 'last 2 versions', 'ie 8', 'ie 9', 'ie 10'] }, dist: { files: { '<%= config.css.dir %>/<%= config.css.file %>': '<%= config.css.dir %>/<%= config.css.file %>' } } }); //grunt-contrib-cssmin grunt.config('cssmin', { target: { src: '<%= config.css.dir %>/<%= config.css.file %>', dest: '<%= config.css.dir %>/<%= config.css.file %>' } }); //grunt-contrib-csslint grunt.config('csslint', { options: { csslintrc: 'grunt/.csslintrc' }, strict: { src: ['<%= config.css.dir %>/*.css'] } }); };
Add commented includePaths parameters for grunt-sass in case of Foundation usage
Add commented includePaths parameters for grunt-sass in case of Foundation usage
JavaScript
mit
SnceGroup/grunt-config-for-websites,SnceGroup/grunt-config-for-websites
79ddea43a8e7217f974dc183e4f9bdb6732d2d11
controllers/users/collection.js
controllers/users/collection.js
module.exports = (function(){ // GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME> return function* collection(id) { // Twitter Requests var TwitterManager = require('../media/twitter'); var twitterGranuals = yield TwitterManager.search(this.request.url) var InstagramManager = require('../media/instagram'); var instagramGranuals = yield InstagramManager.search(this.request.url) // Flickr Requests // var FlickrManager = require('../media/flickr'); // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { "user_id": id, "latitude": require('../../helpers').paramsForUrl(this.request.url).lat, "longitude": require('../../helpers').paramsForUrl(this.request.url).lng, "timestamp": require('../../helpers').paramsForUrl(this.request.url).time, "data": [] } capsul.data.push(instagramGranuals); capsul.data.push(twitterGranuals); delete instagramGranuals; delete twitterGranuals; this.body = yield capsul; } })();
module.exports = (function(){ // GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME> return function* collection(id) { // Twitter Requests var twitterDef = require('q').defer() var TwitterManager = require('../media/twitter'); var twitterGranuals = twitterDef.promise.then(TwitterManager.search); // var twitterDef = require('q').defer() // var instagramDef = require('q').defer() var InstagramManager = require('../media/instagram'); // var instagramGranuals = instagramDef.promise.then(InstagramManager.search); var instagramGranuals = InstagramManager.search(this.request.url); // Flickr Requests // var FlickrManager = require('../media/flickr'); // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { "user_id": id, "latitude": require('../../helpers').paramsForUrl(this.request.url).lat, "longitude": require('../../helpers').paramsForUrl(this.request.url).lng, "timestamp": require('../../helpers').paramsForUrl(this.request.url).time, "data": [] } // def.resolve(this.request.url) // var instaGranuals = def.promise.then(InstagramManager.search); // capsul.data.push(instagramGranuals) twitterDef.resolve(this.request.url) // instagramDef.resolve(this.request.url) capsul.data.push(twitterGranuals); capsul.data.push(instagramGranuals) this.body = yield capsul; } })();
Refactor the twitter manager search methods with promises.
Refactor the twitter manager search methods with promises.
JavaScript
mit
capsul/capsul-api
3dd759f1b7756e34f94a66ae361c44c6a2781c8d
client/js/directives/give-focus-directive.js
client/js/directives/give-focus-directive.js
"use strict"; angular.module("hikeio"). directive("giveFocus", function() { return { link: function(scope, element, attributes) { scope.$watch(attributes.giveFocus, function(value) { if (value) { setTimeout(function() { element.focus(); }); } }); } }; });
"use strict"; angular.module("hikeio"). directive("giveFocus", ["$timeout", function($timeout) { return { link: function(scope, element, attributes) { scope.$watch(attributes.giveFocus, function(value) { if (value) { $timeout(function() { element.focus(); }); } }); } }; }]);
Use angular timeout directive instead of setTimeout.
Use angular timeout directive instead of setTimeout.
JavaScript
mit
zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io
13b62a9096c0e81efeaabfe7f603051a246fd22d
tasks/defaults.js
tasks/defaults.js
/******************************* Default Paths *******************************/ module.exports = { base : '', theme : './src/theme.config', docs : { source : '../docs/server/files/release/', output : '../docs/release/' }, // files cleaned after install setupFiles: [ './src/theme.config.example', './semantic.json.example', './src/_site' ], // modified to create configs templates: { config : './semantic.json.example', site : './src/_site', theme : './src/theme.config.example' }, regExp: { themeRoot: /.*\/themes\/.*?\//mg }, // folder pathsr folders: { config : './', site : './src/site', theme : './src/' }, // file paths files: { composer : 'composer.json', config : './semantic.json', npm : './package.json', site : './src/site', theme : './src/theme.config' }, // same as semantic.json.example paths: { source: { config : 'src/theme.config', definitions : 'src/definitions/', site : 'src/site/', themes : 'src/themes/' }, output: { packaged : 'dist/', uncompressed : 'dist/components/', compressed : 'dist/components/', themes : 'dist/themes/' }, clean : 'dist/' } };
/******************************* Default Paths *******************************/ module.exports = { base : '', theme : './src/theme.config', docs : { source : '../docs/server/files/release/', output : '../docs/release/' }, // files cleaned after install setupFiles: [ './src/theme.config.example', './semantic.json.example', './src/_site' ], // modified to create configs templates: { config : './semantic.json.example', site : './src/_site', theme : './src/theme.config.example' }, regExp: { themePath: /.*\/themes\/.*?\//mg }, // folder pathsr folders: { config : './', site : './src/site', theme : './src/' }, // file paths files: { composer : 'composer.json', config : './semantic.json', npm : './package.json', site : './src/site', theme : './src/theme.config' }, // same as semantic.json.example paths: { source: { config : 'src/theme.config', definitions : 'src/definitions/', site : 'src/site/', themes : 'src/themes/' }, output: { packaged : 'dist/', uncompressed : 'dist/components/', compressed : 'dist/components/', themes : 'dist/themes/' }, clean : 'dist/' } };
Fix regexp for theme changes
Fix regexp for theme changes
JavaScript
mit
lucienevans/Semantic-UI,avorio/Semantic-UI,Dineshs91/Semantic-UI,CapeSepias/Semantic-UI,bradbird1990/Semantic-UI,techpool/Semantic-UI,vibhatha/Semantic-UI,dhj2020/Semantic-UI,Keystion/Semantic-UI,nik4152/Semantic-UI,raoenhui/Semantic-UI-DIV,zcodes/Semantic-UI,CapsuleHealth/Semantic-UI,davialexandre/Semantic-UI,86yankai/Semantic-UI,Semantic-Org/Semantic-UI,Jiasm/Semantic-UI,lucienevans/Semantic-UI,androidesk/Semantic-UI,Illyism/Semantic-UI,JonathanRamier/Semantic-UI,Chrismarcel/Semantic-UI,tarvos21/Semantic-UI,kevinrodbe/Semantic-UI,jcdc21/Semantic-UI,abbasmhd/Semantic-UI,MathB/Semantic-UI,raphaelfruneaux/Semantic-UI,gangeshwark/Semantic-UI,imtapps-dev/imt-semantic-ui,SeanOceanHu/Semantic-UI,newsiberian/Semantic-UI,imtapps-dev/imt-semantic-ui,sunseth/Semantic-UI,Azzurrio/Semantic-UI,Pyrotoxin/Semantic-UI,guiquanz/Semantic-UI,Semantic-Org/Semantic-UI,zcodes/Semantic-UI,snwfog/hamijia-semantic,jcdc21/Semantic-UI,techpool/Semantic-UI,chrismoulton/Semantic-UI,not001praween001/Semantic-UI,openbizgit/Semantic-UI,listepo/Semantic-UI,kk9599/Semantic-UI,TangereJs/Semantic-UI,wang508x102/Semantic-UI,rwoll/Semantic-UI,AlbertoBarrago/Semantic-UI,liangxiaojuan/Semantic-UI,r14r-work/fork_javascript_semantic_ui,m2lan/Semantic-UI,86yankai/Semantic-UI,antyang/Semantic-UI,sudhakar/Semantic-UI,codeRuth/Semantic-UI,akinsella/Semantic-UI,artemkaint/Semantic-UI,akinsella/Semantic-UI,ShanghaitechGeekPie/Semantic-UI,yangyitao/Semantic-UI,schmiddd/Semantic-UI,ListnPlay/Semantic-UI,mnquintana/Semantic-UI,xiwc/semantic-ui.src,codeRuth/Semantic-UI,guodong/Semantic-UI,shengwenming/Semantic-UI,CapsuleHealth/Semantic-UI,leguian/SUI-Less,avorio/Semantic-UI,FlyingWHR/Semantic-UI,gextech/Semantic-UI,martindale/Semantic-UI,BobJavascript/Semantic-UI,Chrismarcel/Semantic-UI,jahnaviancha/Semantic-UI,Sweetymeow/Semantic-UI,teefresh/Semantic-UI,IveWong/Semantic-UI,taihuoniao/Semantic-UI-V2,marciovicente/Semantic-UI,flashadicts/Semantic-UI,Faisalawanisee/Semantic-UI,ryancanhelpyou/Semantic-UI,abbasmhd/Semantic-UI,raoenhui/Semantic-UI-DIV,sunseth/Semantic-UI,maher17/Semantic-UI,elliottisonfire/Semantic-UI,neomadara/Semantic-UI,wildKids/Semantic-UI,youprofit/Semantic-UI,jayphelps/Semantic-UI,eyethereal/archer-Semantic-UI,IveWong/Semantic-UI,manukall/Semantic-UI,m4tx/egielda-Semantic-UI,zanjs/Semantic-UI,1246419375/git-ui,CapeSepias/Semantic-UI,AlbertoBarrago/Semantic-UI,dieface/Semantic-UI,MichelSpanholi/Semantic-UI,eyethereal/archer-Semantic-UI,johnschult/Semantic-UI,exicon/Semantic-UI,MichelSpanholi/Semantic-UI,kongdw/Semantic-UI,edumucelli/Semantic-UI,jahnaviancha/Semantic-UI,anyroadcom/Semantic-UI,kongdw/Semantic-UI,snwfog/hamijia-semantic,r14r/fork_javascript_semantic_ui,bandzoogle/Semantic-UI,marciovicente/Semantic-UI,TangereJs/Semantic-UI,m2lan/Semantic-UI,Pro4People/Semantic-UI,SungDiYen/Semantic-UI,ilovezy/Semantic-UI,Acceptd/Semantic-UI,TangereJs/Semantic-UI,elliottisonfire/Semantic-UI,Centiq/semantic-ui,Jiasm/Semantic-UI,wlzc/semantic-ui.src,Illyism/Semantic-UI,Neaox/Semantic-UI,sudhakar/Semantic-UI,vibhatha/Semantic-UI,gsls1817/Semantic-UI,davialexandre/Semantic-UI,taihuoniao/Semantic-UI-V2,TagNewk/Semantic-UI,MrFusion42/Semantic-UI,tareq-s/Semantic-UI,napalmdev/Semantic-UI,1246419375/git-ui,shengwenming/Semantic-UI,flashadicts/Semantic-UI,FlyingWHR/Semantic-UI,larsbo/Semantic-UI,johnschult/Semantic-UI,r14r/fork_javascript_semantic_ui,BobJavascript/Semantic-UI,dominicwong617/Semantic-UI,rwoll/Semantic-UI,kk9599/Semantic-UI,Pyrotoxin/Semantic-UI,jayphelps/Semantic-UI,maher17/Semantic-UI,edumucelli/Semantic-UI,rockmandew/Semantic-UI,orlaqp/Semantic-UI,codedogfish/Semantic-UI,chrismoulton/Semantic-UI,chlorm-forks/Semantic-UI,ListnPlay/Semantic-UI,ikhakoo/Semantic-UI,champagne-randy/Semantic-UI,zanjs/Semantic-UI,FernandoMueller/Semantic-UI,tamdao/Semantic-UI,JonathanRamier/Semantic-UI,kevinrodbe/Semantic-UI,chlorm-forks/Semantic-UI,FernandoMueller/Semantic-UI,not001praween001/Semantic-UI,bandzoogle/Semantic-UI,guodong/Semantic-UI,anyroadcom/Semantic-UI,wlzc/semantic-ui.src,Dineshs91/Semantic-UI,kushal-likhi/bower-semantic-ui-1.0,anyroadcom/Semantic-UI,orlaqp/Semantic-UI,antyang/Semantic-UI,MrFusion42/Semantic-UI,gangeshwark/Semantic-UI,neomadara/Semantic-UI,youprofit/Semantic-UI,raphaelfruneaux/Semantic-UI,exicon/Semantic-UI,champagne-randy/Semantic-UI,ShanghaitechGeekPie/Semantic-UI,teefresh/Semantic-UI,newsiberian/Semantic-UI,Eynaliyev/Semantic-UI,Acceptd/Semantic-UI,wildKids/Semantic-UI,mnquintana/Semantic-UI,Centiq/semantic-ui,r14r-work/fork_javascript_semantic_ui,tamdao/Semantic-UI,Azzurrio/Semantic-UI,gextech/Semantic-UI,yangyitao/Semantic-UI,codedogfish/Semantic-UI,SungDiYen/Semantic-UI,TagNewk/Semantic-UI,Eynaliyev/Semantic-UI,ordepdev/Semantic-UI,openbizgit/Semantic-UI,leguian/SUI-Less,manukall/Semantic-UI,liangxiaojuan/Semantic-UI,m4tx/egielda-Semantic-UI,dhj2020/Semantic-UI,xiwc/semantic-ui.src,tarvos21/Semantic-UI,SeanOceanHu/Semantic-UI,wang508x102/Semantic-UI,warjiang/Semantic-UI,nik4152/Semantic-UI,eyethereal/archer-Semantic-UI,dieface/Semantic-UI,Pro4People/Semantic-UI,tareq-s/Semantic-UI,warjiang/Semantic-UI,guiquanz/Semantic-UI,listepo/Semantic-UI,larsbo/Semantic-UI,rockmandew/Semantic-UI,Faisalawanisee/Semantic-UI,bradbird1990/Semantic-UI,artemkaint/Semantic-UI,besrabasant/Semantic-UI,Neaox/Semantic-UI,androidesk/Semantic-UI,MathB/Semantic-UI,Sweetymeow/Semantic-UI,ikhakoo/Semantic-UI,martindale/Semantic-UI,ilovezy/Semantic-UI,ryancanhelpyou/Semantic-UI,dominicwong617/Semantic-UI,besrabasant/Semantic-UI,tarvos21/Semantic-UI,gsls1817/Semantic-UI
63875316d9df4983c477600dac427f1bed899ae2
common/app/Router/redux/add-lang-enhancer.js
common/app/Router/redux/add-lang-enhancer.js
import { langSelector } from './'; // This enhancers sole purpose is to add the lang prop to route actions so that // they do not need to be explicitally added when using a RFR route action. export default function addLangToRouteEnhancer(routesMap) { return createStore => (...args) => { const store = createStore(...args); return { ...store, dispatch(action) { if ( routesMap[action.type] && (action && action.payload && !action.payload.lang) ) { action = { ...action, payload: { ...action.payload, lang: langSelector(store.getState()) || 'en' } }; } return store.dispatch(action); } }; }; }
import { langSelector } from './'; // This enhancers sole purpose is to add the lang prop to route actions so that // they do not need to be explicitly added when using a RFR route action. export default function addLangToRouteEnhancer(routesMap) { return createStore => (...args) => { const store = createStore(...args); return { ...store, dispatch(action) { if ( routesMap[action.type] && (!action.payload || !action.payload.lang) ) { action = { ...action, payload: { ...action.payload, lang: langSelector(store.getState()) || 'en' } }; } return store.dispatch(action); } }; }; }
Add lang to payload if payload doesn't exist
fix(Router): Add lang to payload if payload doesn't exist closes #16134
JavaScript
bsd-3-clause
MiloATH/FreeCodeCamp,HKuz/FreeCodeCamp,Munsterberg/freecodecamp,jonathanihm/freeCodeCamp,FreeCodeCampQuito/FreeCodeCamp,BhaveshSGupta/FreeCodeCamp,no-stack-dub-sack/freeCodeCamp,matthew-t-smith/freeCodeCamp,FreeCodeCamp/FreeCodeCamp,raisedadead/FreeCodeCamp,BerkeleyTrue/FreeCodeCamp,raisedadead/FreeCodeCamp,otavioarc/freeCodeCamp,jonathanihm/freeCodeCamp,HKuz/FreeCodeCamp,systimotic/FreeCodeCamp,BerkeleyTrue/FreeCodeCamp,pahosler/freecodecamp,matthew-t-smith/freeCodeCamp,MiloATH/FreeCodeCamp,FreeCodeCampQuito/FreeCodeCamp,no-stack-dub-sack/freeCodeCamp,Munsterberg/freecodecamp,otavioarc/freeCodeCamp,BhaveshSGupta/FreeCodeCamp,BhaveshSGupta/FreeCodeCamp,systimotic/FreeCodeCamp,pahosler/freecodecamp,FreeCodeCamp/FreeCodeCamp
1b36979ac15068f7072fb1cc4d36318fdc805a44
test/view.sendmessage.js
test/view.sendmessage.js
'use strict'; var express = require('express'); var supertest = require('supertest'); var logger = require('log4js').getLogger('Unit-Test'); var nconf = require('nconf'); nconf.argv() .env() .file({ file: 'config.json' }); var request = supertest(app); exports['Check view health'] = function(test){ request.get('/sendmessage').end(function(err,res)){ test.equal(err,null,'It should not had any error!'); test.equal(res,200,'It should return 200!'); test.done(); } } exports['Test send message'] = { 'Test send message success':function(test){ request.post('/sendmessage'), .send({'receiver':'','text':'Hello World'!}) .end(function(err,res)){ test.equal(err,null,'It should not had any error!') test.equal(res,201,'It should return 201!'); } } }
'use strict'; var express = require('express'); var supertest = require('supertest'); var logger = require('log4js').getLogger('Unit-Test'); var nconf = require('nconf'); nconf.argv() .env() .file({ file: 'config.json' }); var request = supertest(app); exports['Check view health'] = function(test){ request.get('/message').end(function(err,res)){ test.equal(err,null,'It should not had any error!'); test.equal(res,200,'It should return 200!'); test.done(); } } exports['Test send message'] = { 'Test send message success':function(test){ request.post('/message'), .send({'receiver':'','text':'Hello World'!}) .end(function(err,res)){ test.equal(err,null,'It should not had any error!') test.equal(res,201,'It should return 201!'); } } }
Fix the url of message
Fix the url of message
JavaScript
apache-2.0
dollars0427/ATMessager,dollars0427/ATMessager
7ec505fba9972b109a3aea2e70c103f5b8c09286
src/browser-runner/platform-dummy/sagas/server-command-handlers.js
src/browser-runner/platform-dummy/sagas/server-command-handlers.js
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { takeEvery } from 'redux-saga/effects'; import opn from 'opn'; import SharedActions from '../../../shared/actions/shared-actions'; function create({ payload: { url } }) { console.log(`Chrome frontend hosted at ${url}`); // eslint-disable-line no-console opn(url); } export default function* () { yield [ takeEvery(SharedActions.commands.fromServer.toRunner.app.window.create, create), ]; }
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { takeEvery } from 'redux-saga/effects'; import opn from 'opn'; import logger from '../../logger'; import SharedActions from '../../../shared/actions/shared-actions'; function create({ payload: { url } }) { logger.log(`Chrome frontend hosted at ${url}`); opn(url); } export default function* () { yield [ takeEvery(SharedActions.commands.fromServer.toRunner.app.window.create, create), ]; }
Use logger module instead of console for the dummy browser runner sagas
Use logger module instead of console for the dummy browser runner sagas Signed-off-by: Victor Porof <4f672cb979ca45495d0cccc37abaefc8713fcc24@gmail.com>
JavaScript
apache-2.0
victorporof/tofino,victorporof/tofino
1c4c3c036aa2d88db4d1c078d009eb2d0875b136
packages/babel-preset-expo/index.js
packages/babel-preset-expo/index.js
module.exports = function() { return { presets: ['module:metro-react-native-babel-preset'], plugins: [ [ 'babel-plugin-module-resolver', { alias: { 'react-native-vector-icons': '@expo/vector-icons', }, }, ], ['@babel/plugin-proposal-decorators', { legacy: true }], ], }; };
module.exports = function(api) { const isWeb = api.caller(isTargetWeb); return { presets: ['module:metro-react-native-babel-preset'], plugins: [ [ 'babel-plugin-module-resolver', { alias: { 'react-native-vector-icons': '@expo/vector-icons', }, }, ], ['@babel/plugin-proposal-decorators', { legacy: true }], ], }; }; function isTargetWeb(caller) { return caller && caller.name === 'babel-loader'; }
Update preset to be able to detect if it's run from Webpack's babel-loader
[babel] Update preset to be able to detect if it's run from Webpack's babel-loader
JavaScript
bsd-3-clause
exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent
8acde49dee699c4055d930eb4bfb9916e884026f
app/events/model.js
app/events/model.js
var mongoose = require('mongoose'); var schema = require('validate'); var Event = mongoose.model('Event', { name: String, start: Date, end: Date, group: String, notify: Boolean }); var validate = function (event) { var test = schema({ name: { type: 'string', required: true, message: 'You must provide a name for the event.' }, start: { type: 'date', required: true, message: 'You must provide a start time.' }, end: { type: 'date', required: true, message: 'You must provide an end time.' }, group: { type: 'string', required: false }, notify: { type: 'boolean', required: false } }, {typecast: true}); return test.validate(event); }; module.exports = Event; module.exports.validate = validate;
var mongoose = require('mongoose'); var schema = require('validate'); var Event = mongoose.model('Event', { name: String, start: Date, end: Date, group: {type: String, enum: ['attendee', 'staff', 'admin'], default: 'attendee'}, notify: {type: Boolean, default: true} }); var validate = function (event) { var test = schema({ name: { type: 'string', required: true, message: 'You must provide a name for the event.' }, start: { type: 'date', required: true, message: 'You must provide a start time.' }, end: { type: 'date', required: true, message: 'You must provide an end time.' }, group: { type: 'string' }, notify: { type: 'boolean' } }, {typecast: true}); return test.validate(event); }; module.exports = Event; module.exports.validate = validate;
Fix validation issue on events
Fix validation issue on events
JavaScript
mit
hacksu/kenthackenough,hacksu/kenthackenough
db599cb4fdaa27d68a45f0d5198d2e8a6a70201b
server/auth/local/passport.js
server/auth/local/passport.js
'use strict'; import passport from 'passport'; import {Strategy as LocalStrategy} from 'passport-local'; function localAuthenticate(User, email, password, done) { User.findOneAsync({ email: email.toLowerCase() }) .then(user => { if (!user) { return done(null, false, { message: 'This email is not registered.' }); } user.authenticate(password, function(authError, authenticated) { if (authError) { return done(authError); } if (!authenticated) { return done(null, false, { message: 'This password is not correct.' }); } else { return done(null, user); } }); }) .catch(err => done(err)); } export function setup(User, config) { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' // this is the virtual field on the model }, function(email, password, done) { return localAuthenticate(User, email, password, done); })); }
'use strict'; import passport from 'passport'; import {Strategy as LocalStrategy} from 'passport-local'; function localAuthenticate(User, email, password, done) { User.findOne({ email: email.toLowerCase() }) .then(user => { if (!user) { return done(null, false, { message: 'This email is not registered.' }); } user.authenticate(password, function(authError, authenticated) { if (authError) { return done(authError); } if (!authenticated) { return done(null, false, { message: 'This password is not correct.' }); } else { return done(null, user); } }); }) .catch(err => done(err)); } export function setup(User, config) { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' // this is the virtual field on the model }, function(email, password, done) { return localAuthenticate(User, email, password, done); })); }
Remove async from mongosoe query
Remove async from mongosoe query
JavaScript
mit
Klemensas/ffempire,Klemensas/ffempire
a6e68f4688fa2f527b118f175d46e1dadba27472
server/publications/groups.js
server/publications/groups.js
Meteor.publish('allGroups', function () { return Groups.find(); });
Meteor.publish('allGroups', function () { // Publish all groups return Groups.find(); }); Meteor.publish('singleGroup', function (groupId) { // Publish only one group, specified as groupId return Groups.find(groupId); });
Add singleGroup publication, clarifying comments
Add singleGroup publication, clarifying comments
JavaScript
agpl-3.0
GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing
5cd96c419d81f5365121064bfb8a0762c3004984
test/libraries.js
test/libraries.js
var fs = require('fs'), Libraries = require('../lib/libraries'), should = require('should'); describe('Libraries', function() { describe('#bowerLibraries', function() { var readdirSync = fs.readdirSync, statSync = fs.statSync, context = { event: {emit: function() {}} }; before(function() { fs.statSync = function(path) { if (/bar\//.test(path)) { throw new Error(); } }; }); after(function() { fs.readdirSync = readdirSync; fs.statSync = statSync; }); it('should return all modules in bower directory', function() { fs.readdirSync = function(path) { return ['foo', 'bar', 'baz']; }; var library = new Libraries(); library.bowerLibraries(context).should.eql(['bower_components/foo', 'bower_components/baz']); }); it('should not error on fs error', function() { fs.readdirSync = function(path) { throw new Error(); }; var library = new Libraries(); should.not.exist(library.bowerLibraries(context)); }); }); });
var fs = require('fs'), Libraries = require('../lib/libraries'), should = require('should'); describe('Libraries', function() { describe('#bowerLibraries', function() { beforeEach(function() { require('bower').config.directory = 'bower_components'; }); var readdirSync = fs.readdirSync, statSync = fs.statSync, context = { event: {emit: function() {}} }; before(function() { fs.statSync = function(path) { if (/bar\//.test(path)) { throw new Error(); } }; }); after(function() { fs.readdirSync = readdirSync; fs.statSync = statSync; }); it('should return all modules in bower directory', function() { fs.readdirSync = function(path) { return ['foo', 'bar', 'baz']; }; var library = new Libraries(); library.bowerLibraries(context).should.eql(['bower_components/foo', 'bower_components/baz']); }); it('should not error on fs error', function() { fs.readdirSync = function(path) { throw new Error(); }; var library = new Libraries(); should.not.exist(library.bowerLibraries(context)); }); }); });
Fix bower config value for tests
Fix bower config value for tests
JavaScript
mit
walmartlabs/lumbar
30caeb00644a2f7e3740b49b39790f96a796bee5
test/init.js
test/init.js
require('ts-node').register({ fast: true, compilerOptions: { target: 'es2015', } }) require('source-map-support/register') require('jsdom-global/register') require('raf').polyfill(global) const enzyme = require('enzyme') const chai = require('chai') const chaiEnzyme = require('chai-enzyme') const sinonChai = require('sinon-chai') const EnzymeAdapter = require('enzyme-adapter-react-16') const chaiAsPromised = require("chai-as-promised") enzyme.configure({ adapter: new EnzymeAdapter() }) console.error = () => {} chai.use(chaiEnzyme()) chai.use(sinonChai) chai.use(chaiAsPromised)
require('ts-node').register({ fast: true, compilerOptions: { target: 'es2015' } }) require('source-map-support').install({ hookRequire: true }) require('jsdom-global/register') require('raf').polyfill(global) const enzyme = require('enzyme') const chai = require('chai') const chaiEnzyme = require('chai-enzyme') const sinonChai = require('sinon-chai') const EnzymeAdapter = require('enzyme-adapter-react-16') const chaiAsPromised = require("chai-as-promised") enzyme.configure({ adapter: new EnzymeAdapter() }) console.error = () => {} console.warn = () => {} chai.use(chaiEnzyme()) chai.use(sinonChai) chai.use(chaiAsPromised)
Fix testcase source maps and hide console.warn messages
Fix testcase source maps and hide console.warn messages
JavaScript
mit
brightinteractive/bright-js-framework,brightinteractive/bright-js-framework,brightinteractive/bright-js-framework
4718270e280fb258aacf942ed6d33cb3e6c39ae3
test/select-test.js
test/select-test.js
var chai = require('chai'), expect = chai.expect, sql = require('../psql'); describe('select', function() { it('should generate a select statement with an asterisk with no arguments', function() { expect(sql.select().from('users').toQuery().text).to.equal('select * from users'); }); it('should generate a select statement with a single column name', function() { expect(sql.select('id').from('users').toQuery().text).to.equal('select id from users'); }) it('should generate a select statement with column names', function() { expect(sql.select('id', 'email').from('users').toQuery().text).to.equal('select id, email from users'); }); });
var chai = require('chai'), expect = chai.expect, sql = require('../psql'); describe('select', function() { it('should generate a select statement with an asterisk with no arguments', function() { expect(sql.select().from('users').toQuery().text).to.equal('select * from users'); }); it('should generate a select statement with a single column name', function() { expect(sql.select('id').from('users').toQuery().text).to.equal('select id from users'); }) it('should generate a select statement with column names', function() { expect(sql.select('id', 'email').from('users').toQuery().text).to.equal('select id, email from users'); }); it('should handle json columns', function() { expect(sql.select('id', "data->>'name' as name").from('users').toQuery().text).to.equal("select id, data->>'name' as name from users") }); //SELECT id, data->'author'->>'first_name' as author_first_name FROM books; it('should handle json column nesting', function() { expect(sql.select('id', "data->'author'->>'first_name' as author_first_name").from('books').toQuery().text) .to.equal("select id, data->'author'->>'first_name' as author_first_name from books") }); });
Add select test for json columns
Add select test for json columns
JavaScript
mit
swlkr/psqljs
0e16b3547b7134e032885053ddac97cb85cb7ee2
tests/karma.conf.js
tests/karma.conf.js
var path = require('path'); var webpack = require('./webpack.config'); process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '.', frameworks: ['mocha'], reporters: ['mocha'], client: { captureConsole: true, mocha: { timeout : 10000, // 10 seconds - upped from 2 seconds retries: 3 // Allow for slow server on CI. } }, files: [ {pattern: path.resolve('./build/injector.js'), watched: false}, {pattern: process.env.KARMA_FILE_PATTERN, watched: false} ], preprocessors: { 'build/injector.js': ['webpack'], 'src/*.spec.ts': ['webpack', 'sourcemap'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, webpack: webpack, webpackMiddleware: { noInfo: true, stats: 'errors-only' }, browserNoActivityTimeout: 31000, // 31 seconds - upped from 10 seconds browserDisconnectTimeout: 31000, // 31 seconds - upped from 2 seconds browserDisconnectTolerance: 2, port: 9876, colors: true, singleRun: true, logLevel: config.LOG_INFO }); };
var path = require('path'); var webpack = require('./webpack.config'); process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '.', frameworks: ['mocha'], reporters: ['mocha'], client: { captureConsole: true, }, files: [ {pattern: path.resolve('./build/injector.js'), watched: false}, {pattern: process.env.KARMA_FILE_PATTERN, watched: false} ], preprocessors: { 'build/injector.js': ['webpack'], 'src/*.spec.ts': ['webpack', 'sourcemap'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, webpack: webpack, webpackMiddleware: { noInfo: true, stats: 'errors-only' }, port: 9876, colors: true, singleRun: true, logLevel: config.LOG_INFO }); };
Decrease high timeout in ci
Decrease high timeout in ci
JavaScript
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
ce1c01c9c1802296c4ff319f71a60a079b758cbb
examples/dir/counter/index.js
examples/dir/counter/index.js
import { app, html } from "flea" const model = 0 const view = (model, dispatch) => html` <div> <h1>${model}</h1> <button onclick=${_ => dispatch("INCREMENT")}>+</button> <button onclick=${_ => dispatch("DECREMENT")}>-</button> </div>` const update = { INCREMENT: model => model + 2, DECREMENT: model => model - 1 } app(model, view, update)
import { app, html } from "flea" const model = 0 const view = (model, dispatch) => html` <div> <button onclick=${_ => dispatch("INCREMENT")}>+</button> <p>${model}</p> <button onclick=${_ => dispatch("DECREMENT")} disabled=${model <= 0}>-</button> </div>` const update = { INCREMENT: model => model + 1, DECREMENT: model => model - 1 } app(model, view, update)
Increment by one. Show how to use disabled attribute with boolean var.
Increment by one. Show how to use disabled attribute with boolean var.
JavaScript
mit
Mytrill/hyperapp,tzellman/hyperapp,Mytrill/hyperapp
7d1c8097ef9ead4935f94e7f69dcbe5e8e5f2330
test/spec/json.js
test/spec/json.js
'use strict'; var JsonExtension = require('../../src/json'); var expect = require('chai').expect; describe('JsonExtension', function () { var ext; beforeEach(function() { ext = new JsonExtension(); }); describe('extension applicability', function() { it('should apply when application/json content type', function() { expect(ext.applies({}, { 'content-type': 'application/json' })).to.be.true; }); it('should apply to application/json content type with params', function() { expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true; }); }); describe('data parser', function() { it('should return the data', function() { var data = ext.dataParser({ name: 'John Doe' }, {}); expect(data).to.eql({ name: 'John Doe' }); }); }); it('should have application/json media types', function() { expect(ext.mediaTypes).to.eql(['application/json']); }); });
'use strict'; var JsonExtension = require('../../src/json'); var expect = require('chai').expect; describe('JsonExtension', function () { var ext; beforeEach(function() { ext = new JsonExtension(); }); describe('extension applicability', function() { it('should apply when application/json content type', function() { expect(ext.applies({}, { 'content-type': 'application/json' })).to.be.true; }); it('should apply to application/json content type with params', function() { expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true; }); it('should not apply when no content type at all (e.g. 204 response)', function() { expect(ext.applies({}, {}, 204)).to.be.false; }); }); describe('data parser', function() { it('should return the data', function() { var data = ext.dataParser({ name: 'John Doe' }, {}); expect(data).to.eql({ name: 'John Doe' }); }); }); it('should have application/json media types', function() { expect(ext.mediaTypes).to.eql(['application/json']); }); });
Test JSON extension deoes not apply for 204 status responses.
Test JSON extension deoes not apply for 204 status responses.
JavaScript
mit
petejohanson/hy-res
6a25939169dde7cb31093f3ebf7298a658ed0ab4
lib/repl.js
lib/repl.js
const {VM} = require('vm2') const exec = require('child_process').exec module.exports = { js: code => { const vm = new VM() try { return vm.run(code).toString() } catch (e) { return e.toString(); } }, rb: code => { return new Promise((resolve, reject) => { const unsafe = new RegExp(/(`|%x|system|exec|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found') } else { exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => { if(err){ reject(err) } resolve(stdout) }) } }) } }
const {VM} = require('vm2') const exec = require('child_process').exec module.exports = { js: code => { const vm = new VM() try { return vm.run(code).toString() } catch (e) { return e.toString(); } }, rb: code => { return new Promise((resolve, reject) => { const unsafe = new RegExp(/(`|%x|system|exec|method|call|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found') } else { exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => { if(err){ reject(err) } resolve(stdout) }) } }) } }
Add more keywords to ruby sandbox
Add more keywords to ruby sandbox
JavaScript
mit
josephrexme/sia
4b37bc34f49b3cdc59b2960dd97b4083995f72a4
webpack.config.js
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { entry: { main: __dirname + "/src/DragRange.jsx", viewer: __dirname + "/src/index.js", }, output: { filename: "[name].js", path: __dirname + "/dist", }, devtool: "source-map", module: { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], use: { loader: "babel-loader", } }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true }, } ] }, ], }, plugins: [ new HtmlWebPackPlugin({ template: __dirname + "/src/index.html", filename: __dirname + "/index.html", }) ], }
const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { entry: { main: __dirname + "/src/DragRange.jsx", viewer: __dirname + "/src/index.js", }, output: { filename: "[name].js", path: __dirname + "/dist", }, devtool: "source-map", module: { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], use: { loader: "babel-loader", } }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true }, } ] }, ], }, plugins: [ new HtmlWebPackPlugin({ template: "./src/index.html", filename: "./index.html", }) ], }
Use relative path for html plugin
Use relative path for html plugin
JavaScript
mit
Radivarig/react-drag-range,Radivarig/react-drag-range
a49d464a2ba55c3d0c3600f14c85f8c003c785cd
webpack.config.js
webpack.config.js
const path = require("path") const PATHS = { app: path.join(__dirname, 'src/index.tsx'), } module.exports = { entry: { app: PATHS.app, }, output: { path: __dirname + '/dist', filename: 'bundle.js', publicPath: "http://localhost:8080/" }, mode: 'development', module: { rules: [ { test: /\.(js|jsx|tsx)$/, loader: 'babel-loader', exclude: /node_modules/, include: /src/ }, { test: /\.jsx?$/, use: 'react-hot-loader/webpack', include: /node_modules/, } ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, devServer: { index: 'index.html', headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization" } }, devtool: 'inline-source-map' }
const path = require("path") const PATHS = { app: path.join(__dirname, 'src/index.tsx'), } module.exports = { entry: { app: PATHS.app, }, output: { path: __dirname + '/dist', filename: 'bundle.js', publicPath: "http://localhost:8080/" }, mode: 'development', module: { rules: [ { test: /\.(js|jsx|ts|tsx)$/, loader: 'babel-loader', exclude: /node_modules/, include: /src/ }, { test: /\.jsx?$/, use: 'react-hot-loader/webpack', include: /node_modules/, } ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, devServer: { index: 'index.html', headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization" } }, devtool: 'inline-source-map' }
Add .ts files to loader
Add .ts files to loader
JavaScript
mit
looker-open-source/extension-template-react,looker-open-source/extension-template-react
f011989558edaea5df62e28155cd904942ed743f
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ path.resolve(__dirname, "src", "r3test.js"), "webpack/hot/dev-server", "webpack-dev-server/client?http://localhost:8081" ], output: { path: path.resolve(__dirname, "scripts"), publicPath: "/scripts/", filename: "r3test.js" }, plugins: [ new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/, include: path.join(__dirname, 'src') } ] } }
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ path.resolve(__dirname, "src", "r3test.js"), "webpack/hot/dev-server", "webpack-dev-server/client?http://localhost:8081" ], output: { path: path.resolve(__dirname, "scripts"), publicPath: "/scripts/", filename: "r3test.js" }, plugins: [ new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.js$/, loader: 'babel', exclude: /node_modules/, include: path.join(__dirname, 'src'), query: { presets: ['es2015', 'stage-2', 'react'], plugins: ['transform-runtime'] } } ] } }
Switch to new babel/react-transform build pipeline
Switch to new babel/react-transform build pipeline
JavaScript
apache-2.0
Izzimach/r3test,Izzimach/r3test
0fb79bc1c55db7e13eb4ce987256b87f751d3d01
src/index.js
src/index.js
require('core-js'); // es2015 polyfill var path = require('path'); var plopBase = require('./modules/plop-base'); var generatorRunner = require('./modules/generator-runner'); /** * Main node-plop module * * @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with * @returns {object} the node-plop API for the plopfile requested */ module.exports = function (plopfilePath) { const plop = plopBase(); const runner = generatorRunner(plop); plopfilePath = path.resolve(plopfilePath); plop.setPlopfilePath(plopfilePath); require(plopfilePath)(plop); ///// // external API for node-plop // return { getGeneratorList: plop.getGeneratorList, getGenerator: function (genName) { const genObject = plop.getGenerator(genName); return Object.assign(genObject, { runActions: (data) => runner.runGeneratorActions(genObject, data), runPrompts: () => runner.runGeneratorPrompts(genObject) }); }, runActions: runner.runGeneratorActions, runPrompts: runner.runGeneratorPrompts }; };
require('core-js'); // es2015 polyfill var path = require('path'); var plopBase = require('./modules/plop-base'); var generatorRunner = require('./modules/generator-runner'); /** * Main node-plop module * * @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with * @returns {object} the node-plop API for the plopfile requested */ module.exports = function (plopfilePath) { const plop = plopBase(); const runner = generatorRunner(plop); if (plopfilePath) { plopfilePath = path.resolve(plopfilePath); plop.setPlopfilePath(plopfilePath); require(plopfilePath)(plop); } ///// // external API for node-plop // return { getGeneratorList: plop.getGeneratorList, getGenerator: function (genName) { const genObject = plop.getGenerator(genName); return Object.assign(genObject, { runActions: (data) => runner.runGeneratorActions(genObject, data), runPrompts: () => runner.runGeneratorPrompts(genObject) }); }, setGenerator: plop.setGenerator, runActions: runner.runGeneratorActions, runPrompts: runner.runGeneratorPrompts }; };
Make plop file optional, and expose plop.setGenerator() function to allow dynamic creation of generator configs.
Make plop file optional, and expose plop.setGenerator() function to allow dynamic creation of generator configs.
JavaScript
mit
amwmedia/node-plop,amwmedia/node-plop,amwmedia/node-plop
ebbffa2dde972b267f70677adc60a21c89c07b8e
src/index.js
src/index.js
import React from 'react' import { render } from 'react-dom' import './index.css' import '../semantic/dist/semantic.min.css'; import Exame from './Exame.js' import Result from './Result.js' import { Route, BrowserRouter } from 'react-router-dom' let TO_ANSWER_GROUPS = require('.//GROUP_DEFINITION.json') render( <BrowserRouter> <div> <Route exact path="/" component={() => <Exame groups={TO_ANSWER_GROUPS}></Exame>}/> <Route path="/result" component={Result}/> </div> </BrowserRouter>, document.getElementById('root') )
import React from 'react' import { render } from 'react-dom' import './index.css' import '../semantic/dist/semantic.min.css'; import Exame from './Exame.js' import Result from './Result.js' import { Route, HashRouter } from 'react-router-dom' let TO_ANSWER_GROUPS = require('.//GROUP_DEFINITION.json') render( <HashRouter> <div> <Route exact path="/" component={() => <Exame groups={TO_ANSWER_GROUPS}></Exame>}/> <Route path="/result" component={Result}/> </div> </HashRouter>, document.getElementById('root') )
Use HashRouter for fix gh-page routing.
Use HashRouter for fix gh-page routing.
JavaScript
mit
wallat/little-test,wallat/little-test
bc24c5e0a2abc2f89c98f66ea19b632d3248c64b
frontend/app/components/bar-graph.js
frontend/app/components/bar-graph.js
import Ember from 'ember'; export default Ember.Component.extend({ didInsertElement() { Chart.defaults.global.responsive = true; Chart.defaults.global.legend.display =false }, didRender() { let data = this.get('data'); let toGraph = { labels: [], datasets: [{ data: [] }] } data.forEach(item => { toGraph.labels.push(item.get('name')); toGraph.datasets[0].data.push(item.get('value')); }); let options = { type: 'bar', data: toGraph, options: { scales: { yAxes: [ { ticks: {beginAtZero: true} } ] } } } console.log(this.elementId); let ctx = this.$().children(".bar-chart").first();//.getContext('2d'); let statsChart = new Chart(ctx, options); } });
import Ember from 'ember'; export default Ember.Component.extend({ didInsertElement() { Chart.defaults.global.responsive = true; Chart.defaults.global.legend.display =false }, didRender() { let data = this.get('data'); let toGraph = { labels: [], datasets: [{ data: [] }] } data.forEach(item => { toGraph.labels.push(item.get('name')); toGraph.datasets[0].data.push(item.get('value')); }); let options = { type: 'bar', data: toGraph, options: { scales: { yAxes: [ { ticks: {beginAtZero: true} } ] } } } let ctx = this.$().children(".bar-chart").first();//.getContext('2d'); let statsChart = new Chart(ctx, options); } });
Remove console logging from figuring out graphjs.
Remove console logging from figuring out graphjs.
JavaScript
mit
ThreeDRadio/playlists,ThreeDRadio/playlists,ThreeDRadio/playlists
d5e55241a66d37f45b0404be3d4e1d0f85715573
src/store.js
src/store.js
/** @babel */ import { applyMiddleware, createStore } from 'redux' import createLogger from 'redux-logger' import createSagaMiddleware from 'redux-saga' import reducers, { initialState } from './reducers' import rootSaga from './sagas' import { isAtomInDebugMode } from './debug' const saga = createSagaMiddleware() let middlewares = [saga] if (isAtomInDebugMode) { const logger = createLogger({ collapsed: true }) middlewares.push(logger) } export const store = createStore( reducers, applyMiddleware(...middlewares) ) saga.run(rootSaga, initialState)
/** @babel */ import { applyMiddleware, createStore } from 'redux' import createLogger from 'redux-logger' import createSagaMiddleware from 'redux-saga' import reducers, { initialState } from './reducers' import rootSaga from './sagas' import { isAtomInDebugMode } from './debug' const saga = createSagaMiddleware() let middlewares = [saga] if (isAtomInDebugMode()) { const logger = createLogger({ collapsed: true }) middlewares.push(logger) } export const store = createStore( reducers, applyMiddleware(...middlewares) ) saga.run(rootSaga, initialState)
Use loggin on debug mode
Improve(debug): Use loggin on debug mode
JavaScript
mit
sanack/atom-jq
d8fff58a630c053f4a5706a7022ab2f3589200f6
app/routes.js
app/routes.js
var express = require('express'); var router = express.Router(); var TaxonPresenter = require('./presenters/taxon-presenter.js'); router.get('/', function (req, res) { res.render('index'); }); router.get('/tabbed/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/mvp/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/tabless/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'base'); presenter.curatedContent = presenter.allContent.slice(4); presenter.latestContent = presenter.allContent.slice(-3).reverse(); res.render(presenter.viewTemplateName, presenter); }); module.exports = router;
var express = require('express'); var router = express.Router(); var TaxonPresenter = require('./presenters/taxon-presenter.js'); router.get('/', function (req, res) { res.render('index'); }); router.get('/tabbed/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/mvp/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/tabless/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'base'); presenter.curatedContent = presenter.allContent.slice(0,3); presenter.latestContent = presenter.allContent.slice(-3).reverse(); res.render(presenter.viewTemplateName, presenter); }); module.exports = router;
Fix item list length bug when rendering tabless design
Fix item list length bug when rendering tabless design
JavaScript
mit
alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype
825828d319b65a1027f18b42bac80c7d0a89869f
src/index.js
src/index.js
import React, { Component } from 'react' import PropTypes from 'prop-types' export const getContextualizer = (propTypes, targetProp) => { class ContextProps extends Component { getChildContext () { const props = Object.keys(this.props).reduce((x, key) => { if (key !== 'children') { x[key] = this.props[key] } return x }, {}) return targetProp ? { [targetProp]: props } : props } render () { return <span>{this.props.children}</span> } } ContextProps.displayName = 'ContextProps' ContextProps.childContextTypes = targetProp ? { [targetProp]: PropTypes.shape(propTypes) } : propTypes return ContextProps } export const withPropsFromContext = propList => Target => { class WithPropsFromContext extends Component { render () { const props = { ...propList.reduce((x, prop) => { x[prop] = this.context[prop] return x }, {}), ...this.props } return <Target {...props} /> } } WithPropsFromContext.contextTypes = propList.reduce((x, prop) => { x[prop] = PropTypes.any return x }, {}) WithPropsFromContext.displayName = Target.displayName || Target.name return WithPropsFromContext }
import React, { Component } from 'react' import PropTypes from 'prop-types' export const getContextualizer = (propTypes, targetProp) => { class ContextProps extends Component { getChildContext () { const props = Object.keys(this.props).reduce((x, key) => { if (key !== 'children') { x[key] = this.props[key] } return x }, {}) return targetProp ? { [targetProp]: props } : props } render () { return <span>{this.props.children}</span> } } ContextProps.displayName = 'ContextProps' ContextProps.childContextTypes = targetProp ? { [targetProp]: PropTypes.shape(propTypes) } : propTypes return ContextProps } export const withPropsFromContext = propList => Target => { class WithPropsFromContext extends Component { render () { const props = { ...propList.reduce((x, prop) => { x[prop] = this.context[prop] return x }, {}), ...this.props } return <Target {...props} /> } } WithPropsFromContext.contextTypes = propList.reduce((x, prop) => { x[prop] = PropTypes.any return x }, {}) WithPropsFromContext.displayName = `withPropsFromContext(${Target.displayName || Target.name})` return WithPropsFromContext }
Update displayName of wrapped component to include HoC name
Update displayName of wrapped component to include HoC name
JavaScript
unlicense
xaviervia/react-context-props,xaviervia/react-context-props
987768c4c78761ed5b827131f10b4a9d6e79fc12
src/index.js
src/index.js
const { createLogger, LEVELS: { INFO } } = require('./loggers') const logFunctionConsole = require('./loggers/console') const Cluster = require('./cluster') const createProducer = require('./producer') const createConsumer = require('./consumer') module.exports = class Client { constructor({ brokers, ssl, sasl, clientId, connectionTimeout, retry, logLevel = INFO, logFunction = logFunctionConsole, }) { this.logger = createLogger({ level: logLevel, logFunction }) this.cluster = new Cluster({ logger: this.logger, brokers, ssl, sasl, clientId, connectionTimeout, retry, }) } producer({ createPartitioner, retry } = {}) { return createProducer({ cluster: this.cluster, logger: this.logger, createPartitioner, retry, }) } consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) { return createConsumer({ cluster: this.cluster, logger: this.logger, groupId, createPartitionAssigner, sessionTimeout, retry, }) } }
const { createLogger, LEVELS: { INFO } } = require('./loggers') const logFunctionConsole = require('./loggers/console') const Cluster = require('./cluster') const createProducer = require('./producer') const createConsumer = require('./consumer') module.exports = class Client { constructor({ brokers, ssl, sasl, clientId, connectionTimeout, retry, logLevel = INFO, logFunction = logFunctionConsole, }) { this.logger = createLogger({ level: logLevel, logFunction }) this.createCluster = () => new Cluster({ logger: this.logger, brokers, ssl, sasl, clientId, connectionTimeout, retry, }) } /** * @public */ producer({ createPartitioner, retry } = {}) { return createProducer({ cluster: this.createCluster(), logger: this.logger, createPartitioner, retry, }) } /** * @public */ consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) { return createConsumer({ cluster: this.createCluster(), logger: this.logger, groupId, createPartitionAssigner, sessionTimeout, retry, }) } }
Create different instances of the cluster for producers and consumers
Create different instances of the cluster for producers and consumers
JavaScript
mit
tulios/kafkajs,tulios/kafkajs,tulios/kafkajs,tulios/kafkajs
d6a2545ab672c59f66b13570a7d809483cd7e78e
src/index.js
src/index.js
/** * Returns a very important number. * * @returns {number} - The number. */ export default function theDefaultExport() { return 40; } /** * Value that can be incremented. * * @type {number} */ export let value = 0; /** * Increments the value by one. */ export function incrementValue() { value++; } /** * Returns a cool value. * * @returns {string} The cool value. */ export function feature() { return 'cool'; } /** * Returns something. * * @returns {string} - Something. */ export function something() { return 'something'; }
/** * Returns a very important number. * * @returns {number} - The number. */ export default function theDefaultExport() { return 42; } /** * Value that can be incremented. * * @type {number} */ export let value = 0; /** * Increments the value by one. */ export function incrementValue() { value++; } /** * Returns a cool value. * * @returns {string} The cool value. */ export function feature() { return 'cool'; } /** * Returns something. * * @returns {string} - Something. */ export function something() { return 'something'; }
Revert "test: make test fail"
Revert "test: make test fail" This reverts commit 6e23d7e72ae9379a18b756d609985065a840b3d7.
JavaScript
mit
cheminfo-js/test
ab9f0b13f4a8e07d4e255a856fcc2ae2c0e4a456
src/index.js
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; // Create a new component to produce some html const App = function () { // const means that this is the final value. Here we are making a component. return <div>Hello!</div>; // This is JSX, which gets transpiled to javascript. // Test here: http://babeljs.io/repl } // Put the component HTML into the DOM ReactDOM.render(<App />, document.querySelector('.container')); // To make an instance of the App class, we wrap it in a JSX tag
import React from 'react'; import ReactDOM from 'react-dom'; // Create a new component to produce some html const App = () => { // const means that this is the final value. Here we are making a component. return <div>Hello!</div>; // This is JSX, which gets transpiled to javascript. // Test here: http://babeljs.io/repl } // Put the component HTML into the DOM ReactDOM.render(<App />, document.querySelector('.container')); // To make an instance of the App class, we wrap it in a JSX tag
Use ES6 syntax fat arrow instead of using 'function'
Use ES6 syntax fat arrow instead of using 'function'
JavaScript
mit
phirefly/react-redux-starter,phirefly/react-redux-starter
d86544c4df922080939dc057f7b682298b13a6d6
src/index.js
src/index.js
import h from 'snabbdom/h' import extend from 'extend' const sanitizeProps = (props) => { props = props === null ? {} : props Object.keys(props).map((prop) => { const keysRiver = prop.split('-').reverse() if(keysRiver.length > 1) { let newObject = keysRiver.reduce( (object, key) => ({ [key]: object }), props[prop] ) extend(true, props, newObject) delete props[prop] } else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) { extend(true, props, {props: { [prop]: props[prop] } }) delete props[prop] } }) return props } const sanitizeChilds = (children) => { return children.length === 1 && typeof children[0] === 'string' ? children[0] : children } export const createElement = (type, props, ...children) => { return h(type, sanitizeProps(props), sanitizeChilds(children)) } export default { createElement }
import h from 'snabbdom/h' import extend from 'extend' const sanitizeProps = (props) => { props = props === null ? {} : props Object.keys(props).map((prop) => { const keysRiver = prop.split('-').reverse() if(keysRiver.length > 1) { let newObject = keysRiver.reduce( (object, key) => ({ [key]: object }), props[prop] ) extend(true, props, newObject) delete props[prop] } else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) { extend(true, props, {props: { [prop]: props[prop] } }) delete props[prop] } }) return props } const sanitizeChilds = (children) => { return children.length === 1 && typeof children[0] === 'string' ? children[0] : children } export const createElement = (type, props, ...children) => { return (typeof type === 'function') ? type(props, children) : h(type, sanitizeProps(props), sanitizeChilds(children)) } export default { createElement }
Add component as function support
Add component as function support
JavaScript
mit
Swizz/snabbdom-pragma
069158e6356e3a58a8c41191a5d00f2afeac0bba
src/index.js
src/index.js
import { createFilter } from 'rollup-pluginutils'; import { resolve as resolveSourceMap } from 'source-map-resolve'; import { readFile } from 'fs'; export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { name: 'sourcemaps', load(id) { if (!filter(id)) { return null; } return new Promise(resolve => { readFile(id, 'utf8', (err, code) => { if (err) { // Failed reading file, let the next plugin deal with it resolve(null); } else { resolveSourceMap(code, id, readFile, (err, sourceMap) => { if (err || sourceMap === null) { // Either something went wrong, or there was no source map resolve(code); } else { const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; resolve({ code, map }); } }); } }); }); }, }; }
import { createFilter } from 'rollup-pluginutils'; import { resolve as resolveSourceMap } from 'source-map-resolve'; import * as fs from 'fs'; export default function sourcemaps({ include, exclude, readFile = fs.readFile } = {}) { const filter = createFilter(include, exclude); return { name: 'sourcemaps', load(id) { if (!filter(id)) { return null; } return new Promise(resolve => { readFile(id, 'utf8', (err, code) => { if (err) { // Failed reading file, let the next plugin deal with it resolve(null); } else { resolveSourceMap(code, id, readFile, (err, sourceMap) => { if (err || sourceMap === null) { // Either something went wrong, or there was no source map resolve(code); } else { const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; resolve({ code, map }); } }); } }); }); }, }; }
Add the ability to override the readFile function
Add the ability to override the readFile function
JavaScript
mit
maxdavidson/rollup-plugin-sourcemaps,maxdavidson/rollup-plugin-sourcemaps