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
|
---|---|---|---|---|---|---|---|---|---|
28e666a0419b17cfa85a8e340927fd9cd691d045 | index.js | index.js | module.exports = function (path) {
var req = require;
return function (module_name) {
try {
return req(module_name);
} catch (err) {
var resolve = null;
req.main.paths.some(function (item) {
if (resolve) return true;
item = item.replace('node_modules', path);
try {
var main = req(item + '/' + module_name + '/package.json').main;
main = item + '/' + module_name + '/' + main;
req(main);
resolve = main;
} catch (e) {} // do nothing
});
if (!resolve) throw err;
return req(resolve)
}
};
};
| var path = require('path');
module.exports = function (pathname) {
var req = require;
return function (module_name) {
try {
return req(module_name);
} catch (err) {
var resolve = null;
req.main.paths.some(function (item) {
if (resolve) return true;
item = item.replace('node_modules', pathname);
try {
var main = path.join(item, module_name, 'package.json');
main = req(main).main;
main = path.join(item, module_name, main);
req(main);
resolve = main;
} catch (e) {} // do nothing
});
if (!resolve) throw err;
return req(resolve)
}
};
};
| Add path for supporting Windows | Add path for supporting Windows
| JavaScript | mit | watilde/graceful-require |
955c5abe4bc2843df9c88124776207e83292d157 | index.js | index.js | import bluebird from 'bluebird'
import consoleStamp from 'console-stamp'
import 'newrelic';
import { getSingleton as initApp } from './app/app'
global.Promise = bluebird
global.Promise.onPossiblyUnhandledRejection((e) => { throw e; });
consoleStamp(console, 'yyyy/mm/dd HH:MM:ss.l')
initApp()
.then((app) => {
app.logger.info(`Server initialization is complete`)
})
.catch((e) => {
process.stderr.write(`FATAL ERROR\n`)
process.stderr.write(`${e.message}\n`)
process.stderr.write(`${e.stack}\n`)
process.exit(1)
})
| import { statSync } from 'fs';
import bluebird from 'bluebird'
import consoleStamp from 'console-stamp'
import { getSingleton as initApp } from './app/app'
try {
statSync(`${__dirname}/newrelic.js`);
require('newrelic');
} catch (e) {
// No newrelic's config found. Won't report stats to them
}
global.Promise = bluebird
global.Promise.onPossiblyUnhandledRejection((e) => { throw e; });
consoleStamp(console, 'yyyy/mm/dd HH:MM:ss.l')
initApp()
.then((app) => {
app.logger.info(`Server initialization is complete`)
})
.catch((e) => {
process.stderr.write(`FATAL ERROR\n`)
process.stderr.write(`${e.message}\n`)
process.stderr.write(`${e.stack}\n`)
process.exit(1)
})
| Enable newrelic only if config exists | Enable newrelic only if config exists
| JavaScript | mit | FreeFeed/freefeed-server,SiTLar/freefeed-server,SiTLar/freefeed-server,golozubov/freefeed-server,golozubov/freefeed-server,FreeFeed/freefeed-server |
346b58a0e4693f9bb25ca4271e7518a3a027983d | index.js | index.js | var loaderUtils = require('loader-utils');
var postcss = require('postcss');
module.exports = function (source) {
if ( this.cacheable ) this.cacheable();
var file = loaderUtils.getRemainingRequest(this);
var params = loaderUtils.parseQuery(this.query);
var opts = { from: file, to: file };
if ( params.safe ) opts.safe = true;
var processors = this.options.postcss;
if ( params.pack ) {
processors = processors[params.pack];
} else if ( !Array.isArray(processors) ) {
processors = processors.defaults;
}
var processed = postcss.apply(postcss, processors).process(source, opts);
this.callback(null, processed.css, processed.map);
};
| var loaderUtils = require('loader-utils');
var postcss = require('postcss');
module.exports = function (source, map) {
if ( this.cacheable ) this.cacheable();
var file = loaderUtils.getRemainingRequest(this);
var params = loaderUtils.parseQuery(this.query);
var opts = { from: file, to: file, map: { prev: map, inline: false } };
if ( params.safe ) opts.safe = true;
var processors = this.options.postcss;
if ( params.pack ) {
processors = processors[params.pack];
} else if ( !Array.isArray(processors) ) {
processors = processors.defaults;
}
var processed = postcss.apply(postcss, processors).process(source, opts);
this.callback(null, processed.css, processed.map);
};
| Use previous source map and don't inline the source maps. | Use previous source map and don't inline the source maps.
This fixes source mapping when used with sass-loader.
Also, we don't want to map to the postcss generated source, we want to map to the pre-postcss source.
| JavaScript | mit | mokevnin/postcss-loader |
2b8f476de5049d3d0933ca1712f1c22190a250cf | index.js | index.js | var toc = require('markdown-toc');
module.exports = {
book: {},
hooks: {
"page:before": function (page) {
page.content = toc.insert(page.content, {
slugify: function (str) {
return encodeURI(str.toLowerCase()).replace(/%20/g, '-').replace(/[\.,\-\(\)]/g,'');
}
});
if (this.options.pluginsConfig.atoc.addClass) {
var className = this.options.pluginsConfig.atoc.className || 'atoc';
page.content = page.content + '\n\n\n<script type="text/javascript">var targetUl = document.getElementsByClassName(\'page-inner\')[0].getElementsByTagName(\'ul\')[0];if(targetUl&&targetUl.getElementsByTagName(\'a\').length>0){targetUl.className=\'' + className + '\';}</script>';
}
return page;
}
}
};
| var toc = require('markdown-toc');
module.exports = {
book: {},
hooks: {
"page:before": function (page) {
page.content = toc.insert(page.content, {
slugify: function (str) {
return encodeURI(str.toLowerCase().replace(/[\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-]/g,'')).replace(/%20/g, '-');
}
});
if (this.options.pluginsConfig.atoc.addClass) {
var className = this.options.pluginsConfig.atoc.className || 'atoc';
page.content = page.content + '\n\n\n<script type="text/javascript">var targetUl = document.getElementsByClassName(\'page-inner\')[0].getElementsByTagName(\'ul\')[0];if(targetUl&&targetUl.getElementsByTagName(\'a\').length>0){targetUl.className=\'' + className + '\';}</script>';
}
return page;
}
}
};
| Fix every case a special character is suppressed | Fix every case a special character is suppressed
I refer to https://github.com/jonschlinkert/remarkable/blob/dev/lib/common/utils.js#L45 for regex writing. | JavaScript | mit | willin/gitbook-plugin-atoc |
f681c2e21fe5b84d97d22a909103ddd64db5b1e1 | index.js | index.js | const createUrl = require('./lib/create-url');
const downloadAndSave = require('./lib/download-and-save');
const parsePage = require('./lib/parse-page');
module.exports = save;
/**
* @param {string} urlOrMediaId
* @return {Promise}
*/
function save(urlOrMediaId, dir) {
return new Promise((resolve, reject) => {
const url = createUrl(urlOrMediaId);
parsePage(url)
.then(post => {
const downloadUrl = post.downloadUrl;
const filename = post.filename;
const isVideo = post.isVideo;
const mimeType = post.mimeType;
const file = `${dir}/${filename}`;
downloadAndSave(downloadUrl, filename).then(() => {
return resolve({
file,
mimeType,
url,
label: isVideo ? 'video' : 'photo',
source: downloadUrl
});
});
})
.catch(err => {
return reject({
url,
error: err,
message: `Download failed`
});
});
});
}
| const createUrl = require('./lib/create-url');
const downloadAndSave = require('./lib/download-and-save');
const parsePage = require('./lib/parse-page');
module.exports = save;
/**
* @param {string} urlOrMediaId
* @return {Promise}
*/
function save(urlOrMediaId, dir) {
return new Promise((resolve, reject) => {
const url = createUrl(urlOrMediaId);
parsePage(url)
.then(post => {
const downloadUrl = post.downloadUrl;
const filename = post.filename;
const isVideo = post.isVideo;
const mimeType = post.mimeType;
const file = `${dir}/${filename}`;
downloadAndSave(downloadUrl, file).then(() => {
return resolve({
file,
mimeType,
url,
label: isVideo ? 'video' : 'photo',
source: downloadUrl
});
});
})
.catch(err => {
return reject({
url,
error: err,
message: `Download failed`
});
});
});
}
| Fix for dir being ignored when supplied and files always saved to cwd. | Fix for dir being ignored when supplied and files always saved to cwd.
| JavaScript | mit | ericnishio/instagram-save |
9fc664fcacbd8149b06a6b80e62f7a1d4e8609e4 | index.js | index.js | var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
var objectAssign = require('object-assign');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var queryOptions = loaderUtils.parseQuery(this.query);
var options;
if (queryOptions) {
options = objectAssign({}, queryOptions);
}
var creator = new DtsCreator(options);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
// Emit the created content as well
this.emitFile(this.resourcePath + '.d.ts', content.contents || ['']);
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
var objectAssign = require('object-assign');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var queryOptions = loaderUtils.parseQuery(this.query);
var options;
if (queryOptions) {
options = objectAssign({}, queryOptions);
}
var creator = new DtsCreator(options);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
// Emit the created content as well
this.emitFile(content.outputFilePath, content.contents || [''], map);
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| Use content.outputFilePath and use pass sourcemap | Use content.outputFilePath and use pass sourcemap | JavaScript | mit | olegstepura/typed-css-modules-loader |
185c90d862bccb2061f00bf2f4e6858cbb0eb660 | index.js | index.js | 'use strict'
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
config = require('./libs/config'),
email = require('./libs/email')
app.use(bodyParser.json())
app.post('/subscribe', email.subscribe)
app.listen(config.port)
| 'use strict'
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
config = require('./libs/config'),
email = require('./libs/email')
app.use(bodyParser.json())
app.post('/subscribe', email.subscribe)
app.listen(process.env.PORT || config.port)
| Allow PORT to be set from cli | Allow PORT to be set from cli | JavaScript | mit | MakerFaireOrlando/mfo-server |
0d62962e33a670ae3459d936ea7b95d2782eb340 | index.js | index.js | /* Uses the slack button feature to offer a real time bot to multiple teams */
var Botkit = require('botkit');
if (!process.env.TOKEN || !process.env.PORT) {
console.log('Error: Specify token and port in environment');
process.exit(1);
}
var config = {}
if(process.env.MONGOLAB_URI) {
var BotkitStorage = require('botkit-storage-mongo');
config = {
storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
};
} else {
config = {
json_file_store: './db_slackbutton_bot/',
};
}
var controller = Botkit.slackbot(config);
controller.spawn({
token: process.env.TOKEN
}).startRTM(function(err) {
if (err) {
throw new Error(err);
}
});
// BEGIN EDITING HERE!
controller.hears('hello','direct_message',function(bot,message) {
bot.reply(message,'Hello!');
});
controller.hears('^stop','direct_message',function(bot,message) {
bot.reply(message,'Goodbye');
bot.rtm.close();
});
controller.on('direct_message,mention,direct_mention',function(bot,message) {
bot.api.reactions.add({
timestamp: message.ts,
channel: message.channel,
name: 'robot_face',
},function(err) {
if (err) { console.log(err) }
bot.reply(message,'I heard you loud and clear boss.');
});
});
| /* Uses the slack button feature to offer a real time bot to multiple teams */
var Botkit = require('botkit');
if (!process.env.TOKEN) {
console.log('Error: Missing environment variable TOKEN. Please Specify your Slack token in environment');
process.exit(1);
}
var config = {}
if(process.env.MONGOLAB_URI) {
var BotkitStorage = require('botkit-storage-mongo');
config = {
storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
};
} else {
config = {
json_file_store: './db_slackbutton_bot/',
};
}
var controller = Botkit.slackbot(config);
controller.spawn({
token: process.env.TOKEN
}).startRTM(function(err) {
if (err) {
throw new Error(err);
}
});
// BEGIN EDITING HERE!
controller.hears('hello','direct_message',function(bot,message) {
bot.reply(message,'Hello!');
});
// An example of what could be...
//
//controller.on('direct_message,mention,direct_mention',function(bot,message) {
// bot.api.reactions.add({
// timestamp: message.ts,
// channel: message.channel,
// name: 'robot_face',
// },function(err) {
// if (err) { console.log(err) }
// bot.reply(message,'I heard you loud and clear boss.');
// });
//});
| Tidy things up, remove requirement for PORT env var | Tidy things up, remove requirement for PORT env var
| JavaScript | mit | slackhq/easy-peasy-bot-custom-integration |
172ffddb3645f508093fac4e6d2d355c0c3e7d5a | index.js | index.js | var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var yaml = require('js-yaml');
// const s3EnvVars = require('s3-env-vars');
// var doc = s3EnvVars("mybucketname", "folderpathinbucket", "filename", function(err, data) {
// if(err) console.log(err);
// else console.log(data);
// });
module.exports = function(bucket, path, filename, callback) {
var s3Params = {
Bucket: bucket,
Key: path + "/" + filename
};
s3.getObject(s3Params, function(err, data) {
if (err) callback(err, err.stack); // an error occurred
else {
try {
console.log('info: ', "Retrieved s3 object.");
var doc = yaml.safeLoad(data.Body);
console.log('data: ', "yml file contents: ", doc);
callback(null, data);
} catch (e) {
callback(err, err.stack); // an error occurred reading the yml file
}
}
});
}; | var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var yaml = require('js-yaml');
// const s3EnvVars = require('s3-env-vars');
// var doc = s3EnvVars("mybucketname", "folderpathinbucket", "filename", function(err, data) {
// if(err) console.log(err);
// else console.log(data);
// });
module.exports = function(bucket, path, filename, callback) {
var s3Params = {
Bucket: bucket,
Key: path + "/" + filename
};
s3.getObject(s3Params, function(err, data) {
if (err) callback(err, err.stack); // an error occurred
else {
try {
console.log('info: ', "Retrieved s3 object.");
var doc = yaml.safeLoad(data.Body);
console.log('data: ', "yml file contents: ", doc);
callback(null, doc);
} catch (e) {
callback(err, err.stack); // an error occurred reading the yml file
}
}
});
}; | Send back the doc not the s3 object | Send back the doc not the s3 object
| JavaScript | mit | Referly/lambda-s3-yml |
8b2da192dbc26d7354ec1db9d101ae4c927b1bc6 | src/state/middleware.js | src/state/middleware.js | import dataComplete from './actions/dataComplete';
import preprocessData from './actions/preprocessData';
import readFile from '../functions/file/readFile';
import preprocessFile from '../functions/file/preprocessFile';
import { PREPROCESSDATA, READDATA } from './constants';
const middleware = store => next => action => {
const state = store.getState();
switch (action.type) {
case READDATA:
if (!state.coordIn || !state.fileIn) {
console.error('Input fields not filled properly!');
break;
}
next(action);
readFile(state.fileInList)
.then(data => {
store.dispatch(preprocessData(data));
}).catch(error => {
console.error(error.message);
});
break;
case PREPROCESSDATA:
preprocessFile(action.payload)
.then(data => {
store.dispatch(dataComplete(data));
}).catch(error => {
console.error(error.message);
});
break;
default:
next(action);
}
};
export default middleware;
| import dataComplete from './actions/dataComplete';
import preprocessData from './actions/preprocessData';
import readFile from '../functions/file/readFile';
import preprocessFile from '../functions/file/preprocessFile';
import parseCoordinates from '../functions/parseCoordinates';
import issetCoordinates from '../functions/issetCoordinates';
import { PREPROCESSDATA, READDATA } from './constants';
const checkCoordinates = coordinates => issetCoordinates(parseCoordinates(coordinates));
const middleware = store => next => action => {
const state = store.getState();
switch (action.type) {
case READDATA:
if (!state.coordIn || !state.fileIn || !checkCoordinates(state.coordIn)) {
console.error('Input fields not filled properly!');
break;
}
next(action);
readFile(state.fileInList)
.then(data => {
store.dispatch(preprocessData(data));
}).catch(error => {
console.error(error.message);
});
break;
case PREPROCESSDATA:
preprocessFile(action.payload)
.then(data => {
store.dispatch(dataComplete(data));
}).catch(error => {
console.error(error.message);
});
break;
default:
next(action);
}
};
export default middleware;
| Check passed coordinates to be correct | Check passed coordinates to be correct
| JavaScript | mit | krajvy/nearest-coordinates,krajvy/nearest-coordinates,krajvy/nearest-coordinates |
c2c4730b4554357f394c3ecb9bae3e465cc4a154 | lib/middleware/campaign-keyword.js | lib/middleware/campaign-keyword.js | 'use strict';
const Campaigns = require('../../app/models/Campaign');
module.exports = function getCampaignForKeyword() {
return (req, res, next) => {
if (req.reply.template) {
return next();
}
return Campaigns.findByKeyword(req.userCommand)
.then((campaign) => {
if (! campaign) {
return next();
}
req.campaign = campaign;
req.keyword = req.userCommand;
return next();
});
};
};
| 'use strict';
const Campaigns = require('../../app/models/Campaign');
module.exports = function getCampaignForKeyword() {
return (req, res, next) => {
if (req.reply.template) {
return next();
}
// Did User send a Campaign keyword?
return Campaigns.findByKeyword(req.userCommand)
.then((campaign) => {
if (! campaign) {
return next();
}
req.campaign = campaign;
req.keyword = req.userCommand;
// Gambit to handle the Confirmation/Continue reply.
req.reply.template = 'gambit';
return next();
});
};
};
| Fix Campaign keyword, send Gambit reply | Fix Campaign keyword, send Gambit reply
| JavaScript | mit | DoSomething/gambit,DoSomething/gambit |
823ecb6eb0f78d51b950fbe382b73769c8502c58 | build-prod.js | build-prod.js | ({
mainConfigFile: './requirejs.conf.js',
paths: {
jquery: 'lib/jquery/jquery.min',
almond: 'lib/almond/almond'
},
baseUrl: '.',
name: "streamhub-map",
exclude: ['streamhub-sdk', 'almond'],
stubModules: ['text', 'hgn', 'json'],
out: "./dist/streamhub-map.min.js",
namespace: 'Livefyre',
pragmasOnSave: {
excludeHogan: true
},
optimize: "uglify2",
uglify2: {
compress: {
unsafe: true
},
mangle: true
},
onBuildRead: function(moduleName, path, contents) {
if (moduleName == "jquery") {
contents = "define([], function(require, exports, module) {" + contents + "});";
}
return contents;
}
})
| ({
mainConfigFile: './requirejs.conf.js',
paths: {
jquery: 'lib/jquery/jquery.min',
almond: 'lib/almond/almond'
},
baseUrl: '.',
name: "streamhub-map",
exclude: ['streamhub-sdk', 'almond'],
stubModules: ['text', 'hgn', 'json'],
out: "./dist/streamhub-map.min.js",
namespace: 'Livefyre',
pragmasOnSave: {
excludeHogan: true
},
cjsTranslate: true,
optimize: "uglify2",
uglify2: {
compress: {
unsafe: true
},
mangle: true
},
onBuildRead: function(moduleName, path, contents) {
if (moduleName == "jquery") {
contents = "define([], function(require, exports, module) {" + contents + "});";
}
return contents;
}
})
| Add 'cjsTranslate' config option to build profile | Add 'cjsTranslate' config option to build profile
| JavaScript | mit | cheung31/streamhub-map,Livefyre/streamhub-map,Livefyre/streamhub-map |
af0c5f7cbbfb29a962477160976f8a048eb493d1 | cache-bust.js | cache-bust.js | /** @license MIT License (c) copyright 2014 original authors */
/** @author Brian Cavalier */
/** @author John Hann */
define(['curl/_privileged'], function (priv) {
var loadScript = priv['core'].loadScript;
priv['core'].loadScript = function (def, success, failure) {
var urlArgs = priv['config']()['urlArgs'];
if (urlArgs) {
def.url += (def.url.indexOf('?') >= 0 ? '&' : '?') + urlArgs;
}
return loadScript(def, success, failure);
};
});
| /** @license MIT License (c) copyright 2014 original authors */
/** @author John Hann */
define(/*==='curl-cache-bust/cache-bust',===*/ ['curl/_privileged'], function (priv) {
var loadScript = priv['core'].loadScript;
priv['core'].loadScript = function (def, success, failure) {
var urlArgs = priv['config']()['urlArgs'];
if (urlArgs) {
def.url += (def.url.indexOf('?') >= 0 ? '&' : '?') + urlArgs;
}
return loadScript(def, success, failure);
};
});
| Add replaceable module id for curl's make utility. | Add replaceable module id for curl's make utility.
| JavaScript | mit | unscriptable/curl-cache-bust |
9493463612fae494ee5f1f644e379b876b8c5655 | app/routes.js | app/routes.js | import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import store from 'lib/store';
import App from 'components/app';
import AdminDashboard from 'components/admin-dashboard';
import ImportPanel from 'components/import';
import ExportPanel from 'components/export';
import LoggedIn from 'components/logged-in';
export default (
<Provider store={ store }>
<Router history={ browserHistory }>
<Route path="/" component={ App }>
<IndexRoute component={ LoggedIn } />
<Route path="/admin" component={ AdminDashboard } />
<Route path="/import" component={ ImportPanel } />
<Route path="/export" component={ ExportPanel } />
</Route>
</Router>
</Provider>
);
| import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import store from 'lib/store';
import App from 'components/app';
import ImportPanel from 'components/import';
import ExportPanel from 'components/export';
import LoggedIn from 'components/logged-in';
export default (
<Provider store={ store }>
<Router history={ browserHistory }>
<Route path="/" component={ App }>
<IndexRoute component={ LoggedIn } />
<Route path="/import" component={ ImportPanel } />
<Route path="/export" component={ ExportPanel } />
</Route>
</Router>
</Provider>
);
| Remove admin dashboard for now | Remove admin dashboard for now
| JavaScript | mit | sirbrillig/voyageur-js-client,sirbrillig/voyageur-js-client |
91266e20e67cb920c86c014202a906af55b387bd | src/renderer/reducers/connections.js | src/renderer/reducers/connections.js | import * as types from '../actions/connections';
export default function(state = {}, action) {
switch (action.type) {
case types.CONNECTION_REQUEST: {
const { server, database } = action;
return { connected: false, connecting: true, server, database };
}
case types.CONNECTION_SUCCESS: {
if (!_isSameConnection(state, action)) return state;
return { ...state, connected: true, connecting: false };
}
case types.CONNECTION_FAILURE: {
if (!_isSameConnection(state, action)) return state;
return { ...state, connected: false, connecting: false, error: action.error };
}
default : return state;
}
}
function _isSameConnection (state, action) {
return state.server === action.server
&& state.database === action.database;
}
| import * as types from '../actions/connections';
const INITIAL_STATE = {};
export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case types.CONNECTION_REQUEST: {
const { server, database } = action;
return { connected: false, connecting: true, server, database };
}
case types.CONNECTION_SUCCESS: {
if (!_isSameConnection(state, action)) return state;
return { ...state, connected: true, connecting: false };
}
case types.CONNECTION_FAILURE: {
if (!_isSameConnection(state, action)) return state;
return { ...state, connected: false, connecting: false, error: action.error };
}
default : return state;
}
}
function _isSameConnection (state, action) {
return state.server === action.server
&& state.database === action.database;
}
| Move connection initial state to variable | Move connection initial state to variable | JavaScript | mit | sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui |
5c3cc5bce58b5c5b0dd7861b993b25d865e95aee | src/scripts/common/utils/platform.js | src/scripts/common/utils/platform.js | export default {
isDarwin: process.platform === 'darwin',
isNonDarwin: process.platform !== 'darwin',
isWindows: process.platform === 'win32',
isLinux: process.platform === 'linux',
isWindows7: process.platform === 'win32' &&
navigator && !!navigator.userAgent.match(/(Windows 7|Windows NT 6\.1)/)
};
| export default {
isDarwin: process.platform === 'darwin',
isNonDarwin: process.platform !== 'darwin',
isWindows: process.platform === 'win32',
isLinux: process.platform === 'linux',
isWindows7: process.platform === 'win32' && window.navigator &&
!!window.navigator.userAgent.match(/(Windows 7|Windows NT 6\.1)/)
};
| Fix detection of Windows 7 | Fix detection of Windows 7
| JavaScript | mit | Aluxian/Messenger-for-Desktop,Aluxian/Messenger-for-Desktop,rafael-neri/whatsapp-webapp,Aluxian/Facebook-Messenger-Desktop,rafael-neri/whatsapp-webapp,Aluxian/Facebook-Messenger-Desktop,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,rafael-neri/whatsapp-webapp |
f841fdaa19aeb5e35251af3c709f9893fc83cc68 | routes2/api/auth.js | routes2/api/auth.js | const _ = require("lodash");
const express = require("express");
const router = express.Router();
const session = require("express-session");
const connect = require("../../utils/database.js");
const restrict = require("../../utils/middlewares/restrict.js");
const auth = require("../../utils/auth.js");
const jwt = require('jsonwebtoken');
const CharError = require("../../utils/charError.js");
const Promise = require("bluebird");
Promise.promisifyAll(jwt);
require('dotenv').config();
const secret = "secret_key_PLEASE_CHANGE";
// Catch all for authentication (temporary)
router.use(function(req, res, next){
// Anonymous access to API
if(typeof req.token == "undefined" && process.env.ALLOW_ANNONYMOUS_TOKENS == "true"){
req.user = {
username: "Anonymous",
role: "anonymous"
};
next();
return;
}
// Authenticate here and also set the logged in users role accordingly
// Verify auth token
jwt.verifyAsync(req.token, secret).then(function(payload){
req.user = {
username: payload.username,
role: payload.role
};
next();
}).catch(function(err){
next(new CharError("Auth Token Invalid", err.message, 403));
});
});
module.exports = router; | const _ = require("lodash");
const express = require("express");
const router = express.Router();
const session = require("express-session");
const connect = require("../../utils/database.js");
const restrict = require("../../utils/middlewares/restrict.js");
const auth = require("../../utils/auth.js");
const jwt = require('jsonwebtoken');
const CharError = require("../../utils/charError.js");
const Promise = require("bluebird");
Promise.promisifyAll(jwt);
require('dotenv').config();
const secret = process.env.JWT_SECRET;
// Catch all for authentication (temporary)
router.use(function(req, res, next){
// Anonymous access to API
if(typeof req.token == "undefined" && process.env.ALLOW_ANNONYMOUS_TOKENS == "true"){
req.user = {
username: "Anonymous",
role: "anonymous"
};
next();
return;
}
// Authenticate here and also set the logged in users role accordingly
// Verify auth token
jwt.verifyAsync(req.token, secret).then(function(payload){
req.user = {
username: payload.username,
role: payload.role
};
next();
}).catch(function(err){
next(new CharError("Auth Token Invalid", err.message, 403));
});
});
module.exports = router; | Use .env to store secret | Use .env to store secret
| JavaScript | bsd-3-clause | limzykenneth/char,limzykenneth/char |
3735ae8afefd31831fa5d8d8445412b0f55ac41a | packages/razzle/config/paths.js | packages/razzle/config/paths.js | 'use strict';
const path = require('path');
const fs = require('fs');
const nodePaths = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter(Boolean)
.filter(folder => !path.isAbsolute(folder))
.map(resolveApp);
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
function resolveApp(relativePath) {
return path.resolve(fs.realpathSync(process.cwd()), relativePath);
}
function resolveOwn(relativePath) {
return path.resolve(__dirname, '..', relativePath);
}
module.exports = {
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appBuildPublic: resolveApp('build/public'),
appManifest: resolveApp('build/assets.json'),
appPublic: resolveApp('public'),
appNodeModules: resolveApp('node_modules'),
appSrc: resolveApp('src'),
appServerIndexJs: resolveApp('src/index.js'),
appClientIndexJs: resolveApp('src/client'),
appBabelRc: resolveApp('.babelrc'),
appRazzleConfig: resolveApp('razzle.config.js'),
nodePaths: nodePaths,
ownPath: resolveOwn('.'),
ownNodeModules: resolveOwn('node_modules'),
};
| 'use strict';
const path = require('path');
const fs = require('fs');
const nodePaths = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter(Boolean)
.filter(folder => !path.isAbsolute(folder))
.map(resolveApp);
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
function resolveApp(relativePath) {
return path.resolve(fs.realpathSync(process.cwd()), relativePath);
}
function resolveOwn(relativePath) {
return path.resolve(__dirname, '..', relativePath);
}
module.exports = {
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appBuildPublic: resolveApp('build/public'),
appManifest: resolveApp('build/assets.json'),
appPublic: resolveApp('public'),
appNodeModules: resolveApp('node_modules'),
appSrc: resolveApp('src'),
appServerIndexJs: resolveApp('src'),
appClientIndexJs: resolveApp('src/client'),
appBabelRc: resolveApp('.babelrc'),
appRazzleConfig: resolveApp('razzle.config.js'),
nodePaths: nodePaths,
ownPath: resolveOwn('.'),
ownNodeModules: resolveOwn('node_modules'),
};
| Make path to server more TS friendly by removing strict file type | Make path to server more TS friendly by removing strict file type
| JavaScript | mit | jaredpalmer/razzle,jaredpalmer/razzle,jaredpalmer/react-production-starter |
3f463786c52254f353e5bb9c22155441146f8eef | docs/src/app/components/pages/components/RaisedButton/ExampleComplex.js | docs/src/app/components/pages/components/RaisedButton/ExampleComplex.js | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import FontIcon from 'material-ui/FontIcon';
const styles = {
button: {
margin: 12,
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
const RaisedButtonExampleComplex = () => (
<div>
<RaisedButton
label="Choose an Image"
labelPosition="before"
style={styles.button}
>
<input type="file" style={styles.exampleImageInput} />
</RaisedButton>
<RaisedButton
label="Label before"
labelPosition="before"
primary={true}
icon={<ActionAndroid />}
style={styles.button}
/>
<RaisedButton
label="Github Link"
href="https://github.com/callemall/material-ui"
secondary={true}
style={styles.button}
icon={<FontIcon className="muidocs-icon-custom-github" />}
/>
</div>
);
export default RaisedButtonExampleComplex;
| import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import FontIcon from 'material-ui/FontIcon';
const styles = {
button: {
margin: 12,
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
const RaisedButtonExampleComplex = () => (
<div>
<RaisedButton
label="Choose an Image"
labelPosition="before"
style={styles.button}
containerElement="label"
>
<input type="file" style={styles.exampleImageInput} />
</RaisedButton>
<RaisedButton
label="Label before"
labelPosition="before"
primary={true}
icon={<ActionAndroid />}
style={styles.button}
/>
<RaisedButton
label="Github Link"
href="https://github.com/callemall/material-ui"
secondary={true}
style={styles.button}
icon={<FontIcon className="muidocs-icon-custom-github" />}
/>
</div>
);
export default RaisedButtonExampleComplex;
| Update file input RaisedButton example | Update file input RaisedButton example
This shows how to correctly embed a file input file into a RaisedButton ensuring that the file input remains clickable cross browser #3689 #4983 #1178 | JavaScript | mit | janmarsicek/material-ui,mit-cml/iot-website-source,hwo411/material-ui,ichiohta/material-ui,w01fgang/material-ui,igorbt/material-ui,hwo411/material-ui,mtsandeep/material-ui,pancho111203/material-ui,manchesergit/material-ui,lawrence-yu/material-ui,frnk94/material-ui,ichiohta/material-ui,hai-cea/material-ui,mtsandeep/material-ui,ArcanisCz/material-ui,mmrtnz/material-ui,ArcanisCz/material-ui,janmarsicek/material-ui,pancho111203/material-ui,frnk94/material-ui,kittyjumbalaya/material-components-web,mmrtnz/material-ui,manchesergit/material-ui,janmarsicek/material-ui,janmarsicek/material-ui,lawrence-yu/material-ui,w01fgang/material-ui,igorbt/material-ui,hai-cea/material-ui,mit-cml/iot-website-source,verdan/material-ui,verdan/material-ui,mit-cml/iot-website-source,kittyjumbalaya/material-components-web |
915acf8a0b9012f04825846b91c68c1ac0ed9df1 | packages/storybook/jest.config.js | packages/storybook/jest.config.js | module.exports = {
collectCoverageFrom: [
"**/src/**/*.{js,jsx}",
"!**/index.js",
],
coverageDirectory: "<rootDir>/packages/storybook/coverage",
coveragePathIgnorePatterns: [
"node_modules",
"packages\/vanilla",
"src\/playground",
"examples\/redux",
"__stories__",
"__gemini__"
],
coverageThreshold: {
global: {
branches: 60,
functions: 60,
lines: 60,
statements: 60
}
},
moduleNameMapper: {
"\\.(css|scss|svg)$": "<rootDir>/packages/storybook/support/jest/fileMock.js"
},
modulePaths: ["node_modules"],
moduleFileExtensions: ["js", "jsx", "json"],
rootDir: "../../",
setupFiles: ["raf/polyfill"],
setupTestFrameworkScriptFile: "<rootDir>/packages/storybook/support/jest/setupTests.js",
testPathIgnorePatterns: ["<rootDir>/packages/vanilla"],
unmockedModulePathPatterns: ["node_modules"]
};
| module.exports = {
collectCoverageFrom: [
"**/src/**/*.{js,jsx}"
],
coverageDirectory: "<rootDir>/packages/storybook/coverage",
coveragePathIgnorePatterns: [
"node_modules",
"packages\/vanilla",
"src\/playground",
"examples\/redux",
"__stories__",
"__gemini__"
],
coverageThreshold: {
global: {
branches: 60,
functions: 60,
lines: 60,
statements: 60
}
},
moduleNameMapper: {
"\\.(css|scss|svg)$": "<rootDir>/packages/storybook/support/jest/fileMock.js"
},
modulePaths: ["node_modules"],
moduleFileExtensions: ["js", "jsx", "json"],
rootDir: "../../",
setupFiles: ["raf/polyfill"],
setupTestFrameworkScriptFile: "<rootDir>/packages/storybook/support/jest/setupTests.js",
testPathIgnorePatterns: ["<rootDir>/packages/vanilla"],
unmockedModulePathPatterns: ["node_modules"]
};
| Include coverage for index files | Include coverage for index files
| JavaScript | apache-2.0 | Autodesk/hig,Autodesk/hig,Autodesk/hig |
94ae410220b3006290526484c25ae18405cb5f1e | frontend/src/state/store.js | frontend/src/state/store.js | const createLogger = require('redux-logger');
const enableBatching = require('redux-batched-actions').enableBatching;
const promiseMiddleware = require('redux-promise-middleware').default;
const redux = require('redux');
const thunk = require('redux-thunk').default;
const createReducer = require('@state/reducers');
const {
createStore,
compose,
applyMiddleware
} = redux;
module.exports = (state = Object.freeze({})) => {
return createStore(
enableBatching(createReducer()),
state,
compose(
applyMiddleware(
createLogger(),
promiseMiddleware(),
thunk
)
)
);
};
| const createLogger = require('redux-logger');
const enableBatching = require('redux-batched-actions').enableBatching;
const promiseMiddleware = require('redux-promise-middleware').default;
const redux = require('redux');
const thunk = require('redux-thunk').default;
const createReducer = require('@state/reducers');
const {
createStore,
compose,
applyMiddleware
} = redux;
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
module.exports = (state = Object.freeze({})) => {
return createStore(
enableBatching(createReducer()),
state,
composeEnhancers(
applyMiddleware(
createLogger(),
promiseMiddleware(),
thunk
)
)
);
};
| Add Redux devtool extension connection - will need to only be available in dev in the future | Add Redux devtool extension connection - will need to only be available in dev in the future
| JavaScript | mpl-2.0 | yldio/joyent-portal,yldio/copilot,geek/joyent-portal,yldio/copilot,yldio/joyent-portal,yldio/copilot,geek/joyent-portal |
b7af36180873e1bb8bf201ae3dd7a2d765519ce0 | dev/app/components/main/projects/projects.controller.js | dev/app/components/main/projects/projects.controller.js | ProjectsController.$inject = [ 'TbUtils', 'projects', '$rootScope' ];
function ProjectsController(TbUtils, projects, $rootScope) {
const vm = this;
vm.searchObj = term => { return { Name: term }; };
vm.searchResults = [];
vm.pageSize = 9;
vm.get = projects.getProjectsWithPagination;
vm.getAll = projects.getProjects;
vm.hideLoadBtn = () => vm.projects.length !== vm.searchResults.length;
vm.projects = [];
vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); };
vm.goToNewProject = project => { TbUtils.go('main.addproject'); };
vm.goToEdit = project => { TbUtils.go('main.editproject', { project: JSON.stringify(project) }); };
vm.loading = true;
vm.removeProjectClicked = removeProjectClicked;
vm.toTitleCase = TbUtils.toTitleCase;
TbUtils.getAndLoad(vm.get, vm.projects, () => { vm.loading = false; }, 0, vm.pageSize);
function removeProjectClicked(project) {
TbUtils.confirm('Eliminar Proyecto', `Esta seguro de eliminar ${project.Name}?`,
resolve => {
if (resolve) {
vm.loading = true;
TbUtils.deleteAndNotify(projects.deleteProject, project, vm.projects,
() => { vm.loading = false; });
}
});
}
}
module.exports = {
name: 'ProjectsController',
ctrl: ProjectsController
}; | ProjectsController.$inject = [ 'TbUtils', 'projects', '$rootScope' ];
function ProjectsController(TbUtils, projects, $rootScope) {
const vm = this;
vm.searchObj = term => { return { Name: term }; };
vm.searchResults = [];
vm.pageSize = 9;
vm.get = projects.getProjectsWithPagination;
vm.getAll = projects.getProjects;
vm.hideLoadBtn = () => vm.projects.length !== vm.searchResults.length;
vm.projects = [];
vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); };
vm.goToNewProject = project => { TbUtils.go('main.new-project'); };
vm.goToEdit = project => { TbUtils.go('main.edit-project', { project: btoa(JSON.stringify(project)) }); };
vm.loading = true;
vm.removeProjectClicked = removeProjectClicked;
vm.toTitleCase = TbUtils.toTitleCase;
TbUtils.getAndLoad(vm.get, vm.projects, () => { vm.loading = false; }, 0, vm.pageSize);
function removeProjectClicked(project) {
TbUtils.confirm('Eliminar Proyecto', `Esta seguro de eliminar ${project.Name}?`,
resolve => {
if (resolve) {
vm.loading = true;
TbUtils.deleteAndNotify(projects.deleteProject, project, vm.projects,
() => { vm.loading = false; });
}
});
}
}
module.exports = { name: 'ProjectsController', ctrl: ProjectsController }; | Change redirects to project form | Change redirects to project form
| JavaScript | mit | Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC,Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC |
6a06c6ffcaf5d3456ffa0830aee5efbeed19f540 | server/db/config.js | server/db/config.js | var mysql = require('mysql');
exports.connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'uncovery'
});
exports.initialize = function(callback) {
exports.connection.connect();
};
| var mysql = require('mysql');
exports.connection = mysql.createConnection({
host: 'localhost',
user: 'tony',
database: 'uncovery'
});
exports.initialize = function(callback) {
exports.connection.connect();
};
| Update Schema to change userIds to userTokens | Update Schema to change userIds to userTokens
| JavaScript | mit | team-oath/uncovery,team-oath/uncovery,team-oath/uncovery,scottdixon/uncovery,scottdixon/uncovery,scottdixon/uncovery,scottdixon/uncovery,team-oath/uncovery |
3b7f243a6e663129e98d2551163e2ac01248cbf3 | public/javascripts/application.js | public/javascripts/application.js | $(document).ready(function() {
if (window.location.href.search(/query=/) == -1) {
$('#query').one('click, focus', function() {
$(this).val('');
});
}
$(document).bind('keyup', function(event) {
if ($(event.target).is(':input')) {
return;
}
if (event.which == 83) {
$('#query').focus();
}
});
$('#version_for_stats').change(function() {
window.location.href = $(this).val();
});
});
| $(document).ready(function() {
$('#version_for_stats').change(function() {
window.location.href = $(this).val();
});
});
| Remove JS that handled not-quite-placeholder. | Remove JS that handled not-quite-placeholder.
| JavaScript | mit | sonalkr132/rubygems.org,hrs113355/rubygems.org,spk/rubygems.org,polamjag/rubygems.org,farukaydin/rubygems.org,iSC-Labs/rubygems.org,polamjag/rubygems.org,jamelablack/rubygems.org,childbamboo/rubygems.org,krainboltgreene/rubygems.org,davydovanton/rubygems.org,iRoxxDotOrg/rubygems.org,spk/rubygems.org,farukaydin/rubygems.org,wallin/rubygems.org,sonalkr132/rubygems.org,iRoxxDotOrg/rubygems.org,maclover7/rubygems.org,jamelablack/rubygems.org,sonalkr132/rubygems.org,davydovanton/rubygems.org,algolia/rubygems.org,huacnlee/rubygems.org,rubygems/rubygems.org,algolia/rubygems.org,huacnlee/rubygems.org,Ch4s3/rubygems.org,kbrock/rubygems.org,andrew/rubygems.org,JuanitoFatas/rubygems.org,hrs113355/rubygems.org,childbamboo/rubygems.org,Ch4s3/rubygems.org,olivierlacan/rubygems.org,rubygems/rubygems.org,davydovanton/rubygems.org,Ch4s3/rubygems.org,rubygems/rubygems.org,krainboltgreene/rubygems.org,arthurnn/rubygems.org,spk/rubygems.org,polamjag/rubygems.org,arthurnn/rubygems.org,iRoxxDotOrg/rubygems.org,andrew/rubygems.org,Elffers/rubygems.org,olivierlacan/rubygems.org,iSC-Labs/rubygems.org,algolia/rubygems.org,wallin/rubygems.org,iRoxxDotOrg/rubygems.org,davydovanton/rubygems.org,farukaydin/rubygems.org,childbamboo/rubygems.org,polamjag/rubygems.org,jamelablack/rubygems.org,Elffers/rubygems.org,fotanus/rubygems.org,fotanus/rubygems.org,kbrock/rubygems.org,fotanus/rubygems.org,knappe/rubygems.org,JuanitoFatas/rubygems.org,krainboltgreene/rubygems.org,rubygems/rubygems.org,hrs113355/rubygems.org,huacnlee/rubygems.org,JuanitoFatas/rubygems.org,iSC-Labs/rubygems.org,iSC-Labs/rubygems.org,knappe/rubygems.org,Ch4s3/rubygems.org,andrew/rubygems.org,arthurnn/rubygems.org,Exeia/rubygems.org,JuanitoFatas/rubygems.org,spk/rubygems.org,hrs113355/rubygems.org,olivierlacan/rubygems.org,Exeia/rubygems.org,knappe/rubygems.org,childbamboo/rubygems.org,wallin/rubygems.org,wallin/rubygems.org,fotanus/rubygems.org,huacnlee/rubygems.org,jamelablack/rubygems.org,sonalkr132/rubygems.org,olivierlacan/rubygems.org,Exeia/rubygems.org,Exeia/rubygems.org,kbrock/rubygems.org,krainboltgreene/rubygems.org,knappe/rubygems.org,kbrock/rubygems.org,andrew/rubygems.org,maclover7/rubygems.org,maclover7/rubygems.org,maclover7/rubygems.org,Elffers/rubygems.org,algolia/rubygems.org,farukaydin/rubygems.org,Elffers/rubygems.org |
fbd4d6a6a34a13f7d3b506baf6e7687364707a5e | src/test/resources/positive/i205-ref-disambiguation-II.js | src/test/resources/positive/i205-ref-disambiguation-II.js | defaultScope(4);
intRange(-8, 7);
c10_Car = Clafer("c10_Car").withCard(4, 4);
c11_owner = c10_Car.addChild("c11_owner").withCard(1, 1);
c21_Person = Clafer("c21_Person").withCard(4, 4);
c11_owner.refToUnique(c21_Person);
Constraint(all([disjDecl([c1 = local("c1"), c2 = local("c2")], global(c10_Car))], notEqual(join(c1, c11_owner), join(c2, c11_owner))));
| defaultScope(4);
intRange(-8, 7);
c10_Car = Clafer("c10_Car").withCard(4, 4);
c11_owner = c10_Car.addChild("c11_owner").withCard(1, 1);
c21_Person = Clafer("c21_Person").withCard(4, 4);
c11_owner.refToUnique(c21_Person);
Constraint(all([disjDecl([c1 = local("c1"), c2 = local("c2")], global(c10_Car))], notEqual(joinRef(join(c1, c11_owner)), joinRef(join(c2, c11_owner)))));
| Add explicit refs to test case. | Add explicit refs to test case.
| JavaScript | mit | gsdlab/chocosolver,gsdlab/chocosolver |
987a064c7ee618788b74709d49ea9727a4bfa2e2 | src/views/HomeView/RoomChart.js | src/views/HomeView/RoomChart.js | import React, { PropTypes } from 'react'
import {LineChart} from 'react-d3-basic'
import classes from './RoomChart.scss'
class RoomChart extends React.Component {
static propTypes = {
data: PropTypes.object
};
render () {
const {data} = this.props
let activity = []
if (data && data.activity) {
activity = data.activity
}
const chartData = activity.map((chunk) => {
return {
timestamp: new Date(chunk[0] * 1000),
messages: chunk[1]
}
})
const width = 550
return (
<LineChart
data={chartData}
width={width}
height={300}
margins={{
top: 25,
bottom: 60,
right: 25,
left: 50
}}
chartSeries={[
{
field: 'messages',
name: 'Messages',
color: '#ff7600',
style: {
'stroke-width': 2.5
}
}
]}
x={(d) => d.timestamp}
xScale='time'
innerTickSize={20}
/>
)
}
}
export default RoomChart
| import React, { PropTypes } from 'react'
import {LineChart} from 'react-d3-basic'
class RoomChart extends React.Component {
static propTypes = {
data: PropTypes.object
};
render () {
const {data} = this.props
let activity = []
if (data && data.activity) {
activity = data.activity
}
const chartData = activity.map((chunk) => {
return {
timestamp: new Date(chunk[0] * 1000),
messages: chunk[1]
}
})
const width = 550
return (
<LineChart
data={chartData}
width={width}
height={300}
margins={{
top: 25,
bottom: 60,
right: 25,
left: 50
}}
chartSeries={[
{
field: 'messages',
name: 'Messages',
color: '#ff7600',
style: {
'stroke-width': 2.5
}
}
]}
x={(d) => d.timestamp}
xScale='time'
innerTickSize={20}
/>
)
}
}
export default RoomChart
| Remove unused var to fix lint error | Remove unused var to fix lint error
| JavaScript | mit | seriallos/hubot-stats-web,seriallos/hubot-stats-web |
5b5df02c9120d9d13616f9dcabda1a959191ee19 | packages/truffle-box/test/unbox.js | packages/truffle-box/test/unbox.js | var path = require("path");
var fs = require("fs-extra");
var assert = require("assert");
var Box = require("../");
var TRUFFLE_BOX_DEFAULT = "git@github.com:trufflesuite/truffle-init-default.git";
describe("Unbox", function() {
var destination = path.join(__dirname, ".truffle_test_tmp");
before("mkdir", function(done) {
fs.ensureDir(destination, done);
});
before("remove tmp dir", function(done) {
fs.remove(destination, done);
});
it("unboxes truffle box from github", function() {
this.timeout(5000);
return Box.unbox(TRUFFLE_BOX_DEFAULT, destination)
.then(function (truffleConfig) {
assert.ok(truffleConfig);
assert(
fs.existsSync(path.join(destination, "truffle.js")),
"Unboxed project should have truffle config."
);
});
});
});
| var path = require("path");
var fs = require("fs-extra");
var assert = require("assert");
var Box = require("../");
var TRUFFLE_BOX_DEFAULT = "git@github.com:trufflesuite/truffle-init-default.git";
describe("Unbox", function() {
var destination = path.join(__dirname, ".truffle_test_tmp");
before("mkdir", function(done) {
fs.ensureDir(destination, done);
});
after("remove tmp dir", function(done) {
fs.remove(destination, done);
});
it("unboxes truffle box from github", function() {
this.timeout(5000);
return Box.unbox(TRUFFLE_BOX_DEFAULT, destination)
.then(function (truffleConfig) {
assert.ok(truffleConfig);
assert(
fs.existsSync(path.join(destination, "truffle.js")),
"Unboxed project should have truffle config."
);
});
});
it("won't re-init if truffle.js file exists", function(done) {
this.timeout(5000);
var contracts_directory = path.join(destination, "contracts");
// Assert our precondition
assert(fs.existsSync(contracts_directory), "contracts directory should exist for this test to be meaningful");
fs.remove(contracts_directory, function(err) {
if (err) return done(err);
Box.unbox(TRUFFLE_BOX_DEFAULT, destination)
.then(function(boxConfig) {
assert(
fs.existsSync(contracts_directory) == false,
"Contracts directory got recreated when it shouldn't have"
);
done();
})
.catch(function(e) {
if (e.message.indexOf("A Truffle project already exists at the destination.") >= 0) {
done();
} else {
done(new Error("Unknown error received: " + e.stack));
}
});
});
});
});
| Add project collision test from truffle-init | Add project collision test from truffle-init
| JavaScript | mit | ConsenSys/truffle |
761c016727331da4a252f4936390c2fd11097bc0 | src/overrides/HasMany.js | src/overrides/HasMany.js | Ext.define('Densa.overrides.HasMany', {
override: 'Ext.data.association.HasMany',
/**
* Allow filters in storeConfig
*
* Original overrides filters with filter
*/
createStore: function() {
var that = this,
associatedModel = that.associatedModel,
storeName = that.storeName,
foreignKey = that.foreignKey,
primaryKey = that.primaryKey,
filterProperty = that.filterProperty,
autoLoad = that.autoLoad,
storeConfig = that.storeConfig || {};
return function() {
var me = this,
config, filter,
modelDefaults = {};
if (me[storeName] === undefined) {
if (filterProperty) {
filter = {
property : filterProperty,
value : me.get(filterProperty),
exactMatch: true
};
} else {
filter = {
property : foreignKey,
value : me.get(primaryKey),
exactMatch: true
};
}
if (!storeConfig.filters) storeConfig.filters = [];
storeConfig.filters.push(filter);
modelDefaults[foreignKey] = me.get(primaryKey);
config = Ext.apply({}, storeConfig, {
model : associatedModel,
remoteFilter : false,
modelDefaults: modelDefaults,
disableMetaChangeEvent: true
});
me[storeName] = Ext.data.AbstractStore.create(config);
if (autoLoad) {
me[storeName].load();
}
}
return me[storeName];
};
}
});
| Ext.define('Densa.overrides.HasMany', {
override: 'Ext.data.association.HasMany',
/**
* Allow filters in storeConfig
*
* Original overrides filters with filter
*/
createStore: function() {
var that = this,
associatedModel = that.associatedModel,
storeName = that.storeName,
foreignKey = that.foreignKey,
primaryKey = that.primaryKey,
filterProperty = that.filterProperty,
autoLoad = that.autoLoad,
storeConfig = that.storeConfig || {};
return function() {
var me = this,
config, filter,
modelDefaults = {};
if (me[storeName] === undefined) {
if (filterProperty) {
filter = {
property : filterProperty,
value : me.get(filterProperty),
exactMatch: true
};
} else {
filter = {
property : foreignKey,
value : me.get(primaryKey),
exactMatch: true
};
}
var localStoreConfig = Ext.clone(storeConfig);
if (!localStoreConfig.filters) localStoreConfig.filters = [];
localStoreConfig.filters.push(filter);
modelDefaults[foreignKey] = me.get(primaryKey);
config = Ext.apply({}, localStoreConfig, {
model : associatedModel,
remoteFilter : false,
modelDefaults: modelDefaults,
disableMetaChangeEvent: true
});
me[storeName] = Ext.data.AbstractStore.create(config);
if (autoLoad) {
me[storeName].load();
}
}
return me[storeName];
};
}
});
| Fix filters in storeConfig: they where shared across multiple stores | Fix filters in storeConfig: they where shared across multiple stores
Problem was that storeConfig is an object and thus modified by reference
| JavaScript | bsd-2-clause | koala-framework/densajs,Ben-Ho/densajs |
2601364bb01ba8b3bce372440c48f20e41e2c6f0 | jobs/index.js | jobs/index.js | "use strict";
var autoload = require('auto-load');
var kue = require('kue');
var async = require('async');
var debug = require('debug')('kue:boot');
var jobs = autoload(__dirname);
module.exports = function(app) {
var queue = app.get('queue');
var store = app.get('keyValueStore');
delete jobs.index;
for(var job in jobs) {
debug('wait for job type', job);
// create new job processor
queue.process(job, app.get('concurrency'), jobs[job](app));
}
queue.on('job complete', function(id, result) {
var afToken;
async.waterfall([
function getJob(cb) {
kue.Job.get(id, cb);
},
function setCursor(job, cb) {
afToken = job.anyfetchToken;
store.hset('cursor', afToken, result, cb);
},
function setLastUpdate(status, cb) {
store.hset('lastUpdate', afToken, Date.now().toString(), cb);
},
function unlockUpdate(status, cb) {
store.hdel('status', afToken, cb);
}
], function throwErrs(err) {
if(err) {
throw err;
}
});
});
};
| "use strict";
var autoload = require('auto-load');
var kue = require('kue');
var async = require('async');
var rarity = require('rarity');
var debug = require('debug')('kue:boot');
var jobs = autoload(__dirname);
module.exports = function(app) {
var queue = app.get('queue');
var store = app.get('keyValueStore');
delete jobs.index;
for(var job in jobs) {
debug('wait for job type', job);
// create new job processor
queue.process(job, app.get('concurrency'), jobs[job](app));
}
queue.on('job complete', function(id, result) {
async.waterfall([
function getJob(cb) {
kue.Job.get(id, cb);
},
function removeJob(job, cb) {
var anyfetchToken = job.data.anyfetchToken;
job.remove(rarity.carry([anyfetchToken], cb));
},
function setCursor(anyfetchToken, cb) {
if(!anyfetchToken) {
return cb(null, null, null);
}
store.hset('cursor', anyfetchToken, result, rarity.carry([anyfetchToken], cb));
},
function setLastUpdate(anyfetchToken, status, cb) {
if(!anyfetchToken) {
return cb(null, null, null);
}
store.hset('lastUpdate', anyfetchToken, Date.now().toString(), rarity.carry([anyfetchToken], cb));
},
function unlockUpdate(anyfetchToken, status, cb) {
if(!anyfetchToken) {
return cb(null, null, null);
}
store.hdel('status', anyfetchToken, cb);
}
], function throwErrs(err) {
if(err) {
throw err;
}
});
});
};
| Clean redis after succeeded jobs | Clean redis after succeeded jobs
| JavaScript | mit | AnyFetch/gdrive-provider.anyfetch.com |
bbdf0c9d323e17a31f9e2e1d6442012fd1e47fdf | lib/slack-gateway.js | lib/slack-gateway.js | var _ = require('lodash');
var logger = require('winston');
var request = require('superagent');
function SlackGateway(incomingURL, channelMapping) {
this.incomingURL = incomingURL;
this.invertedMapping = _.invert(channelMapping);
}
SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) {
var payload = {
username: author,
icon_url: 'https://github.com/identicons/' + author + '.png',
channel: this.invertedMapping[ircChannel],
text: message
};
request
.post(this.incomingURL)
.send(payload)
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) return logger.error('Couldn\'t post message to Slack', err);
logger.debug('Posted message to Slack', res.body, res.statusCode);
});
};
module.exports = SlackGateway;
| var _ = require('lodash');
var logger = require('winston');
var request = require('superagent');
function SlackGateway(incomingURL, channelMapping) {
this.incomingURL = incomingURL;
this.invertedMapping = _.invert(channelMapping);
}
SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) {
var payload = {
username: author,
icon_url: 'http://api.adorable.io/avatars/48/' + author + '.png',
channel: this.invertedMapping[ircChannel],
text: message
};
request
.post(this.incomingURL)
.send(payload)
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) return logger.error('Couldn\'t post message to Slack', err);
logger.debug('Posted message to Slack', res.body, res.statusCode);
});
};
module.exports = SlackGateway;
| Change icon_url to use adorable.io | Change icon_url to use adorable.io | JavaScript | mit | ekmartin/slack-irc,tcr/slack-irc,andreaja/slack-irc,lmtierney/slack-irc,leeopop/slack-irc,umegaya/slack-irc,zabirauf/slack-irc,php-ug/slack-irc,reactiflux/discord-irc,robertkety/slack-irc,erikdesjardins/slack-irc,xbmc/slack-irc,chipx86/slack-irc,mxm/slack-irc |
e6f6f94480582504c4ff1293e9c5b00e8b450000 | js/scripts.js | js/scripts.js | var pingPongOutput = function(inputNumber) {
if(inputNumber % 3 === 0) {
return "ping";
} else {
return inputNumber;
}
};
| var pingPongOutput = function(inputNumber) {
if(inputNumber % 3 === 0) {
return "ping";
} else if (inputNumber % 5 === 0) {
return "pong";
} else {
return inputNumber;
}
};
| Implement numbers divisible by 5 | Implement numbers divisible by 5
| JavaScript | mit | JeffreyRuder/ping-pong-app,JeffreyRuder/ping-pong-app |
84639f7c85a9ae4109dee5b042e44fecc16c02dd | js/scripts.js | js/scripts.js | var pingPong = function(i) {
if (isPingPong(i)) {
return pingPongType(i)
} else {
return false;
}
}
var pingPongType = function(i) {
if ((i % 3 === 0) && (i % 5 != 0)) {
return "ping";
} else if ((i % 5 === 0) && (i % 3 !=0)) {
return "pong";
} else if (i % 15 === 0){
return "pingpong";
}
}
var isPingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0)){
return true;
} else {
return false;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var whichPingPong = pingPongType(i)
for (var i = 1; i <= number; i += 1) {
if (pingPong(i)) {
$('#outputList').append("<li>" + whichPingPong + "</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
| var pingPongType = function(i) {
if (i % 15 === 0) {
return "pingpong";
} else if (i % 5 === 0) {
return "pong";
} else {
return "ping";
}
}
var isPingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
return pingPongType(i);
} else {
return false;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var whichPingPong = pingPongType(i)
for (var i = 1; i <= number; i += 1) {
if (isPingPong(i)) {
$('#outputList').append("<li>" + whichPingPong + "</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
| Remove code for pingPong, leaving pingPongType and isPingPong as functions | Remove code for pingPong, leaving pingPongType and isPingPong as functions
| JavaScript | mit | kcmdouglas/pingpong,kcmdouglas/pingpong |
2fadeb3eaf5c182bd29380edc7b7c5666b37177e | lib/extend.js | lib/extend.js | 'use strict';
var _ = require('underscore');
module.exports = function extend (Superclass, prototypeFragment) {
prototypeFragment = prototypeFragment || {};
var Subclass = function () {
if (_.isFunction(prototypeFragment.initialize)) {
prototypeFragment.initialize.apply(this, arguments);
} else {
Superclass.apply(this, arguments);
}
};
Subclass.prototype = Object.create(Superclass.prototype);
_.extend(Subclass.prototype, prototypeFragment);
return Subclass;
};
| 'use strict';
var _ = require('underscore');
module.exports = function extend (Superclass, prototypeFragment) {
prototypeFragment = prototypeFragment || {};
var Subclass = function () {
Superclass.apply(this, arguments);
if (_.isFunction(prototypeFragment.initialize)) {
prototypeFragment.initialize.apply(this, arguments);
}
};
Subclass.prototype = Object.create(Superclass.prototype);
_.extend(Subclass.prototype, prototypeFragment);
return Subclass;
};
| Fix the issue by calling constructor and checking for initialize | [Green] Fix the issue by calling constructor and checking for initialize
| JavaScript | mit | ImpactFlow/flow |
cb7b7847c3324bb5dbbea5b9e185cece8eaf2b96 | lib/mincer.js | lib/mincer.js | 'use strict';
// internal
var mixin = require('./mincer/common');
module.exports = {
VERSION: '0.0.0',
EngineTemplate: require('./mincer/engine_template'),
Environment: require('./mincer/environment'),
Manifest: require('./mincer/manifest')
};
mixin(module.exports, require('./mincer/engines'));
mixin(module.exports, require('./mincer/paths'));
| 'use strict';
// internal
var mixin = require('./mincer/common').mixin;
var prop = require('./mincer/common').prop;
module.exports = {
VERSION: '0.0.0',
EngineTemplate: require('./mincer/engine_template'),
Environment: require('./mincer/environment'),
Manifest: require('./mincer/manifest')
};
prop(module.exports, '__engines__', {});
mixin(module.exports, require('./mincer/engines'));
mixin(module.exports, require('./mincer/paths'));
| Add some mixins to main lib | Add some mixins to main lib
| JavaScript | mit | rhyzx/mincer,mcanthony/mincer,nodeca/mincer,inukshuk/mincer |
d968bcfd42463bcbc4cddf891ae76df85c45d6f2 | src/redux/createStore.js | src/redux/createStore.js | import { createStore as _createStore, applyMiddleware } from 'redux';
import fetchMiddleware from './middleware/fetchMiddleware';
import reducer from './modules/reducer';
export default function createStore(client, data) {
const middlewares = [fetchMiddleware(client)];
const finalCreateStore = applyMiddleware(...middlewares)(_createStore);
const store = finalCreateStore(reducer, data);
/* global module, require */
if (module.hot) {
module.hot.accept('./modules/reducer', () => {
store.replaceReducer(require('./modules/reducer'));
});
}
return store;
}
| import { createStore as _createStore, applyMiddleware } from 'redux';
import { browserHistory } from 'react-router';
import { routerMiddleware, } from 'react-router-redux';
import fetchMiddleware from './middleware/fetchMiddleware';
import reducer from './modules/reducer';
export default function createStore(client, data) {
const middlewares = [
fetchMiddleware(client),
routerMiddleware(browserHistory),
];
const finalCreateStore = applyMiddleware(...middlewares)(_createStore);
const store = finalCreateStore(reducer, data);
/* global module, require */
if (module.hot) {
module.hot.accept('./modules/reducer', () => {
store.replaceReducer(require('./modules/reducer'));
});
}
return store;
}
| Connect router history to redux. | Connect router history to redux.
| JavaScript | agpl-3.0 | ahoereth/lawly,ahoereth/lawly,ahoereth/lawly |
58dd0255dc16aea48eedc2bee64da922a9e8d394 | src/server/action/Executor.js | src/server/action/Executor.js | import ExecutorBase from '../../action/Executor';
import types from '../../action/types';
export default class Executor extends ExecutorBase {
_onAttack(action, world) {
}
} | import ExecutorBase from '../../action/Executor';
export default class Executor extends ExecutorBase {
}
| Remove empty code to prevent jslint errors | Remove empty code to prevent jslint errors
| JavaScript | mit | DirtyHairy/mayrogue-deathmatch,DirtyHairy/mayrogue-deathmatch |
571376913b7b8c9d8ea329c6865cd8869c954b25 | karma.conf.js | karma.conf.js | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false, // leave Jasmine Spec Runner output visible in browser
jasmine: {
random: false
}
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false, // leave Jasmine Spec Runner output visible in browser
jasmine: {
random: false
}
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
browserNoActivityTimeout: 30000
});
};
| Increase browser inactivity timeout for test runs. | Increase browser inactivity timeout for test runs.
| JavaScript | mpl-2.0 | thehyve/glowing-bear,thehyve/glowing-bear,thehyve/glowing-bear,thehyve/glowing-bear |
7be59a49cb351dcfa4874c885ba017277027849b | karma.conf.js | karma.conf.js | /* eslint-env node */
module.exports = function (config) {
config.set({
basePath: 'public',
browsers: ['ChromeHeadlessCustom'],
files: [
'styles/index.css',
'scripts/mithril.min.js',
'scripts/underscore-min.js',
'scripts/tinyemitter.min.js',
'scripts/sw-update-manager.js',
'scripts/socket.io.slim.js',
'scripts/clipboard.min.js',
'scripts/test.js'
],
reporters: ['dots'].concat(process.env.COVERAGE ? ['coverage'] : []),
frameworks: ['mocha', 'chai-dom', 'sinon-chai'],
preprocessors: {
'**/*.js': ['sourcemap'],
'scripts/test.js': process.env.COVERAGE ? ['coverage'] : []
},
coverageReporter: {
type: 'json',
dir: '../coverage/',
subdir: '.',
file: 'coverage-unmapped.json'
},
customLaunchers: {
ChromeHeadlessCustom: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
}
});
};
| /* eslint-env node */
module.exports = function (config) {
config.set({
basePath: 'public',
browsers: ['ChromeHeadlessCustom'],
files: [
'styles/index.css',
'scripts/mithril.min.js',
'scripts/underscore-min.js',
'scripts/tinyemitter.min.js',
'scripts/sw-update-manager.js',
'scripts/socket.io.min.js',
'scripts/clipboard.min.js',
'scripts/test.js'
],
reporters: ['dots'].concat(process.env.COVERAGE ? ['coverage'] : []),
frameworks: ['mocha', 'chai-dom', 'sinon-chai'],
preprocessors: {
'**/*.js': ['sourcemap'],
'scripts/test.js': process.env.COVERAGE ? ['coverage'] : []
},
coverageReporter: {
type: 'json',
dir: '../coverage/',
subdir: '.',
file: 'coverage-unmapped.json'
},
customLaunchers: {
ChromeHeadlessCustom: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
}
});
};
| Correct SocketIO path for Karma tests | Correct SocketIO path for Karma tests
The tests should no longer be erroring out.
| JavaScript | mit | caleb531/connect-four |
050359c7399b9e8905d114a2438fa7e374da9811 | tests/collect.test.js | tests/collect.test.js | 'use strict';
(function () {
var expect = require('chai').expect;
var collect = require('../src/collect');
describe('collect.js', function () {
it('should exist', function () {
expect(collect).to.be.ok;
expect(typeof collect).to.equal('function');
});
});
})();
| 'use strict';
(function () {
var expect = require('chai').expect;
var collect = require('../src/collect');
var Jarg = require('../src/jarg');
var Command = require('../src/command');
describe('collect.js', function () {
it('should exist', function () {
expect(collect).to.be.ok;
expect(typeof collect).to.equal('function');
});
it('should return a Jarg instance', function () {
var boundCollect = collect.bind(null, 'node', 'npm', ['install', 'jargs', '--save']);
var result = boundCollect(
Command(
'npm'
)
);
expect(result instanceof Jarg).to.be.true;
});
});
})();
| Test that collect returns a Jarg instance | Test that collect returns a Jarg instance
| JavaScript | mit | JakeSidSmith/jargs |
ebdaf4dd46279ee1650fd4fc1a5128f0c404ee79 | tests/compile/main.js | tests/compile/main.js | goog.provide('Main');
// Core
// Either require 'Blockly.requires', or just the components you use:
goog.require('Blockly');
goog.require('Blockly.FieldDropdown');
goog.require('Blockly.FieldImage');
goog.require('Blockly.FieldNumber');
goog.require('Blockly.FieldTextInput');
goog.require('Blockly.FieldVariable');
goog.require('Blockly.geras.Renderer');
// Blocks
goog.require('Blockly.Constants.Logic');
goog.require('Blockly.Constants.Loops');
goog.require('Blockly.Constants.Math');
goog.require('Blockly.Constants.Text');
goog.require('Blockly.Constants.Lists');
goog.require('Blockly.Constants.Colour');
goog.require('Blockly.Constants.Variables');
goog.require('Blockly.Constants.VariablesDynamic');
goog.require('Blockly.Blocks.procedures');
Main.init = function() {
Blockly.inject('blocklyDiv', {
'toolbox': document.getElementById('toolbox')
});
};
window.addEventListener('load', Main.init);
| goog.provide('Main');
// Core
// Either require 'Blockly.requires', or just the components you use:
goog.require('Blockly');
goog.require('Blockly.geras.Renderer');
// Blocks
goog.require('Blockly.Constants.Logic');
goog.require('Blockly.Constants.Loops');
goog.require('Blockly.Constants.Math');
goog.require('Blockly.Constants.Text');
goog.require('Blockly.Constants.Lists');
goog.require('Blockly.Constants.Colour');
goog.require('Blockly.Constants.Variables');
goog.require('Blockly.Constants.VariablesDynamic');
goog.require('Blockly.Blocks.procedures');
Main.init = function() {
Blockly.inject('blocklyDiv', {
'toolbox': document.getElementById('toolbox')
});
};
window.addEventListener('load', Main.init);
| Remove now unneeded requires from compile test. | Remove now unneeded requires from compile test.
| JavaScript | apache-2.0 | mark-friedman/blockly,picklesrus/blockly,google/blockly,picklesrus/blockly,mark-friedman/blockly,mark-friedman/blockly,google/blockly,mark-friedman/blockly,mark-friedman/blockly,mark-friedman/blockly,google/blockly,rachel-fenichel/blockly,rachel-fenichel/blockly,google/blockly,rachel-fenichel/blockly,google/blockly,rachel-fenichel/blockly,google/blockly,google/blockly,rachel-fenichel/blockly,picklesrus/blockly,rachel-fenichel/blockly,rachel-fenichel/blockly |
3c21402775b39586d62cc137f4832c3397192aac | public/javascripts/documents.js | public/javascripts/documents.js | $(document).ready(function(){
var i=0;
var $td;
var state;
function checkDocumentsStatuses(){
$.getJSON("/api/documents_states", function(data){
var $bars = $(".bar");
for(i=0;i<$bars.length;i++){
$($bars[i]).css("width", data[i] + "%");
}
});
setTimeout(checkDocumentsStatuses, 15000 );
}
$(".link a").popover();
$(".link a").click(function(event){
event.preventDefault();
var $this = $(this);
$.get($this.attr("href"),
null,
function(data){
$this.parent().siblings(".content").html(data.p);
},
'json');
});
$("#stillProcessing").alert().css("display", "block");
setTimeout(checkDocumentsStatuses, 15000 );
if($(".tablesorter").length !== 0) {
$(".tablesorter").tablesorter();
}
$(".documents tbody tr").click(function() {
$(this).siblings().removeClass("selected");
$(this).addClass("selected");
var url = "/api/" + $(this).data("id") + "/context";
var template = $("#documentContext").html();
$("#document").html("").spin();
$.getJSON(url, null, function(data) {
$("#document").html(Mustache.render(template, data));
}).error(function() {
$("#document").html(Mustache.render($("#documentContextError").html()));
});
return false;
});
});
| $(document).ready(function(){
var i=0;
var $td;
var state;
function checkDocumentsStatuses(){
$.getJSON("/api/documents_states", function(data){
var $bars = $(".bar");
for(i=0;i<$bars.length;i++){
$($bars[i]).css("width", data[i] + "%");
}
});
setTimeout(checkDocumentsStatuses, 15000 );
}
$(".link a").popover();
$(".link a").click(function(event){
event.preventDefault();
var $this = $(this);
$.get($this.attr("href"),
null,
function(data){
$this.parent().siblings(".content").html(data.p);
},
'json');
});
$("#stillProcessing").alert().css("display", "block");
setTimeout(checkDocumentsStatuses, 15000 );
if($(".tablesorter").length !== 0) {
$(".tablesorter").tablesorter();
}
$(".documents tbody tr").click(function(e) {
$(this).siblings().removeClass("selected");
$(this).addClass("selected");
var url = "/api/" + $(this).data("id") + "/context";
var template = $("#documentContext").html();
$("#document").html("").spin();
$.getJSON(url, null, function(data) {
$("#document").html(Mustache.render(template, data));
}).error(function() {
$("#document").html(Mustache.render($("#documentContextError").html()));
});
});
$(".documents .tools a").click(function(e) {
e.stopPropagation();
});
});
| Stop event bubbling when clicking on document toolbar | Stop event bubbling when clicking on document toolbar
| JavaScript | mit | analiceme/chaos |
b6988ddfadcc5636fcdfff772715cd5199954f04 | tasks/lib/sigint-hook.js | tasks/lib/sigint-hook.js | var sigintHooked = false;
module.exports = function sigintHook( fn ) {
if ( sigintHooked ) {
return;
}
sigintHooked = true;
// ctrl+c should stop this task and quit grunt gracefully
// (process.on("SIGINT", fn) doesn't behave correctly on Windows):
var rl = require( "readline" ).createInterface( {
input: process.stdin,
output: process.stdout
} );
rl.on( "SIGINT", function() {
fn();
rl.close();
} );
}; | var sigintHooked = false;
module.exports = function sigintHook( fn ) {
if ( sigintHooked ) {
return;
}
sigintHooked = true;
// ctrl+c should stop this task and quit grunt gracefully
// (process.on("SIGINT", fn) doesn't behave correctly on Windows):
var rl = require( "readline" ).createInterface( {
input: process.stdin,
output: process.stdout
} );
rl.on( "SIGINT", function() {
fn();
rl.close();
sigintHooked = false;
} );
}; | Reset sigint hook when readline closes. | Reset sigint hook when readline closes.
| JavaScript | mit | peol/grunt-surveil |
6eb0da204f11a2396f1f663675c0e5406554ca9b | declarative-shadow-dom.js | declarative-shadow-dom.js | customElements.define('declarative-shadow-dom', class extends HTMLTemplateElement {
static get observedAttributes() {
return [];
}
constructor(self) {
// assignment required by polyfill
self = super(self);
}
connectedCallback(){
this.appendToParentsShadowRoot();
}
appendToParentsShadowRoot(){
const parentElement = this.parentElement;
if(!parentElement){
throw 'declarative-shadow-dom needs a perentElement to stamp to';
}
if(!parentElement.shadowRoot){
parentElement.attachShadow({mode: 'open'});
}
let fragment = document.importNode(this.content, true);
this.stampedNodes = Array.prototype.slice.call(fragment.childNodes);
parentElement.shadowRoot.appendChild(fragment);
// debugger
ShadyCSS && ShadyCSS.styleElement(parentElement);
parentElement.dispatchEvent(new CustomEvent('declarative-shadow-dom-stamped', {detail: {stampedNodes: this.stampedNodes}}));
this.parentNode.removeChild(this);
}
}, {
extends: 'template'
});
| customElements.define('declarative-shadow-dom', class extends HTMLTemplateElement {
static get observedAttributes() {
return [];
}
constructor(self) {
// assignment required by polyfill
self = super(self);
}
connectedCallback(){
this.appendToParentsShadowRoot();
}
appendToParentsShadowRoot(){
const parentElement = this.parentElement;
if(!parentElement){
throw 'declarative-shadow-dom needs a perentElement to stamp to';
}
if(!parentElement.shadowRoot){
parentElement.attachShadow({mode: 'open'});
}
let fragment = document.importNode(this.content, true);
this.stampedNodes = Array.prototype.slice.call(fragment.childNodes);
parentElement.shadowRoot.appendChild(fragment);
// debugger
typeof ShadyCSS !== 'undefined' && ShadyCSS.styleElement(parentElement);
parentElement.dispatchEvent(new CustomEvent('declarative-shadow-dom-stamped', {detail: {stampedNodes: this.stampedNodes}}));
this.parentNode.removeChild(this);
}
}, {
extends: 'template'
});
| Fix check for ShadyCSS polyfill | Fix check for ShadyCSS polyfill
| JavaScript | mit | tomalec/declarative-shadow-dom,tomalec/declarative-shadow-dom |
bd77652a50eb0feab274d65ed45a127ddf2402c7 | src/components/chat/AddChatMessage.js | src/components/chat/AddChatMessage.js | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
} | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
this.textInput.focus()
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
} | Set focus back to textarea after button was pressed | Set focus back to textarea after button was pressed
| JavaScript | mit | axax/lunuc,axax/lunuc,axax/lunuc |
594ece2b5001d39a2cd255c2a25829a1291cb75f | test/compare-versions.js | test/compare-versions.js | import test from 'ava';
import fn from '../source/libs/compare-versions';
test('Compare versions', t => {
t.is(-1, fn('1', '2'));
t.is(-1, fn('v1', '2'));
t.is(-1, fn('1.1', '1.2'));
t.is(-1, fn('1', '1.1'));
t.is(-1, fn('1', '1.0.1'));
t.is(-1, fn('2.0', '10.0'));
t.is(-1, fn('1.2.3', '1.22.3'));
t.is(-1, fn('1.1.1.1.1', '1.1.1.1.2'));
t.is(-1, fn('r1', 'r2'));
t.is(-1, fn('1.0-beta', '1.0'));
t.is(-1, fn('v0.11-M4', 'v0.20'));
});
| import test from 'ava';
import fn from '../source/libs/compare-versions';
test('Compare versions', t => {
t.is(-1, fn('1', '2'));
t.is(-1, fn('v1', '2'));
t.is(-1, fn('1.1', '1.2'));
t.is(-1, fn('1', '1.1'));
t.is(-1, fn('1', '1.0.1'));
t.is(-1, fn('2.0', '10.0'));
t.is(-1, fn('1.2.3', '1.22.3'));
t.is(-1, fn('1.1.1.1.1', '1.1.1.1.2'));
t.is(-1, fn('r1', 'r2'));
});
test.failing('Support beta versions', t => {
t.is(-1, fn('1.0-beta', '1.0'));
t.is(-1, fn('v2.0-RC4', 'v2.0'));
});
| Add failing beta version test | Add failing beta version test
| JavaScript | mit | busches/refined-github,busches/refined-github,sindresorhus/refined-github,sindresorhus/refined-github |
ee8ab3561b9722c327bac0b1ea082ab510156977 | test/mithril.withAttr.js | test/mithril.withAttr.js | describe("m.withAttr()", function () {
"use strict"
it("calls the handler with the right value/context without callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy).call(object, {currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
it("calls the handler with the right value/context with callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy, object)({currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
})
| describe("m.withAttr()", function () {
"use strict"
it("calls the handler with the right value/context without callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy).call(object, {currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("foo")
})
it("calls the handler with the right value/context with callbackThis", function () { // eslint-disable-line
var spy = sinon.spy()
var object = {}
m.withAttr("test", spy, object)({currentTarget: {test: "foo"}})
expect(spy).to.be.calledOn(object).and.calledWith("Ofoo")
})
})
| Break a test of the new suite | Break a test of the new suite
| JavaScript | mit | MithrilJS/mithril.js,tivac/mithril.js,lhorie/mithril.js,impinball/mithril.js,barneycarroll/mithril.js,impinball/mithril.js,tivac/mithril.js,pygy/mithril.js,MithrilJS/mithril.js,pygy/mithril.js,barneycarroll/mithril.js,lhorie/mithril.js |
67b66b5568f264a9ed4b0940de406ed26797fd4e | test/specificity.test.js | test/specificity.test.js | var path = require('path'),
assert = require('assert'),
fs = require('fs');
var carto = require('../lib/carto');
var tree = require('../lib/carto').tree;
var helper = require('./support/helper');
function cleanupItem(key, value) {
if (key === 'rules') return;
else if (key === 'ruleIndex') return;
else if (key === 'elements') return value.map(function(item) { return item.value; });
else if (key === 'filters') {
var arr = [];
for (var id in value.filters) arr.push(id + value.filters[id].val);
if (arr.length) return arr;
}
else if (key === 'attachment' && value === '__default__') return;
else if (key === 'zoom') {
if (value != tree.Zoom.all) return tree.Zoom.toString(value);
}
else return value;
}
describe('Specificity', function() {
helper.files('specificity', 'mss', function(file) {
it('should handle spec correctly in ' + file, function(done) {
helper.file(file, function(content) {
var tree = (new carto.Parser({
paths: [ path.dirname(file) ],
filename: file
})).parse(content);
var mss = tree.toList({});
mss = helper.makePlain(mss, cleanupItem);
helper.compareToFile(mss, file, helper.resultFile(file));
done();
});
});
});
});
| var path = require('path'),
assert = require('assert'),
fs = require('fs');
var carto = require('../lib/carto');
var tree = require('../lib/carto').tree;
var helper = require('./support/helper');
function cleanupItem(key, value) {
if (key === 'rules') return;
else if (key === 'ruleIndex') return;
else if (key === 'elements') return value.map(function(item) { return item.value; });
else if (key === 'filters') {
var arr = [];
for (var id in value.filters) arr.push(id + value.filters[id].val);
if (arr.length) return arr;
}
else if (key === 'attachment' && value === '__default__') return;
else if (key === 'zoom') {
if (value != tree.Zoom.all) return (new tree.Zoom()).setZoom(value).toString();
}
else return value;
}
describe('Specificity', function() {
helper.files('specificity', 'mss', function(file) {
it('should handle spec correctly in ' + file, function(done) {
helper.file(file, function(content) {
var tree = (new carto.Parser({
paths: [ path.dirname(file) ],
filename: file
})).parse(content);
var mss = tree.toList({});
mss = helper.makePlain(mss, cleanupItem);
helper.compareToFile(mss, file, helper.resultFile(file));
done();
});
});
});
});
| Fix zoom interpretation in helper | Fix zoom interpretation in helper
| JavaScript | apache-2.0 | pnorman/carto,clhenrick/carto,CartoDB/carto,CartoDB/carto,gravitystorm/carto,stefanklug/carto,tomhughes/carto,whitelynx/carto,mapbox/carto,midnightcomm/carto,madeinqc/carto,1ec5/carto |
e65b54770e47356e2aba9afc46b1551fa7ece6b0 | build/tasks/dev.js | build/tasks/dev.js | import gulp from 'gulp'
import path from 'path'
import BrowserSync from 'browser-sync'
import { compiler, handleWebpackResults } from '../webpack/compiler'
const browserSync = BrowserSync.create()
const args = global.__args
const themeDir = path.resolve(__pkg._themepath)
const themeRelPath = themeDir.replace(process.cwd()+'/', '')
gulp.task('dev', ['build'], ()=> {
compiler.watch({}, handleWebpackResults(true))
gulp.watch(`${themeRelPath}/scss/**/*.scss`, ['styles'])
gulp.watch(`${themeRelPath}/images/**/*`, ['images'])
gulp.watch(`${themeRelPath}/fonts/**/*`, ['static'])
if (args.sync) {
browserSync.init({
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
`${themeRelPath}/**/*.php`
]
})
}
})
| import gulp from 'gulp'
import path from 'path'
import BrowserSync from 'browser-sync'
import { compiler, handleWebpackResults } from '../webpack/compiler'
const browserSync = BrowserSync.create()
const args = global.__args
const themeDir = path.resolve(__pkg._themepath)
const themeRelPath = themeDir.replace(process.cwd()+'/', '')
gulp.task('dev', ['build'], ()=> {
compiler.watch({}, handleWebpackResults(true))
gulp.watch(`${themeRelPath}/scss/**/*.scss`, ['styles'])
gulp.watch(`${themeRelPath}/images/**/*`, ['images'])
gulp.watch(`${themeRelPath}/fonts/**/*`, ['static'])
if (args.sync) {
browserSync.init({
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
`${themeRelPath}/assets/css/*.css`,
`${themeRelPath}/**/*.php`
]
})
}
})
| Make sure CSS files are watched | Make sure CSS files are watched
| JavaScript | mit | 3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack |
03217724b92da3636e1e8b81acd35d652a21bc57 | packages/expo/bin/commands/add-hook.js | packages/expo/bin/commands/add-hook.js | const prompts = require('prompts')
const addHook = require('../lib/add-hook')
const { onCancel } = require('../lib/utils')
const { blue, yellow } = require('kleur')
module.exports = async (argv, globalOpts) => {
const res = await prompts({
type: 'confirm',
name: 'addHook',
message: `This will modify your app.json. Is that ok?`,
initial: true
}, { onCancel })
if (res.addHook) {
console.log(blue(`> Inserting hook config into app.json`))
const msg = await addHook(globalOpts['project-root'])
if (msg) console.log(yellow(` ${msg}`))
}
}
| const prompts = require('prompts')
const addHook = require('../lib/add-hook')
const { onCancel } = require('../lib/utils')
const { blue, yellow } = require('kleur')
module.exports = async (argv, globalOpts) => {
const res = await prompts({
type: 'confirm',
name: 'addHook',
message,
initial: true
}, { onCancel })
if (res.addHook) {
console.log(blue(`> Inserting hook config into app.json`))
const msg = await addHook(globalOpts['project-root'])
if (msg) console.log(yellow(` ${msg}`))
}
}
const message = `Do you want to automatically upload source maps to Bugsnag? (this will modify your app.json)`
| Add API hook command should say what it's going to do | fix(expo-cli): Add API hook command should say what it's going to do
| JavaScript | mit | bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js |
2fbf834731d37d53d81238f58866ff90edca5cbb | src/editor/components/RefComponent.js | src/editor/components/RefComponent.js | import { NodeComponent } from 'substance'
import { renderEntity } from '../../entities/entityHelpers'
export default class RefComponent extends NodeComponent {
render($$) {
const db = this.context.pubMetaDbSession.getDocument()
const ref = this.props.node
let label = _getReferenceLabel(ref)
let entityHtml = renderEntity(_getEntity(ref, db))
// TODO: do we want to display something like this
// if so, use the label provider
entityHtml = entityHtml || '<i>Not available</i>'
return $$('div').addClass('sc-ref-component').append(
$$('div').addClass('se-label').append(label),
$$('div').addClass('se-text').html(entityHtml)
)
}
}
function _getReferenceLabel(ref) {
if (ref.state && ref.state.label) {
return ref.state.label
}
return '?'
}
function _getEntity(ref, db) {
if (ref.state && ref.state.entity) {
return ref.state.entity
}
return db.get(ref.id)
}
| import { NodeComponent } from 'substance'
import { renderEntity } from '../../entities/entityHelpers'
export default class RefComponent extends NodeComponent {
render($$) {
const db = this.context.pubMetaDbSession.getDocument()
const ref = this.props.node
let label = _getReferenceLabel(ref)
let entityHtml = renderEntity(_getEntity(ref, db))
// TODO: do we want to display something like this
// if so, use the label provider
entityHtml = entityHtml || '<i>Not available</i>'
return $$('div').addClass('sc-ref-component').append(
$$('div').addClass('se-label').append(label),
$$('div').addClass('se-text').html(entityHtml)
).attr('data-id', ref.id)
}
}
function _getReferenceLabel(ref) {
if (ref.state && ref.state.label) {
return ref.state.label
}
return '?'
}
function _getEntity(ref, db) {
if (ref.state && ref.state.entity) {
return ref.state.entity
}
return db.get(ref.id)
}
| Set data-id on ref component. | Set data-id on ref component.
| JavaScript | mit | substance/texture,substance/texture |
eb3035ffcf0d68ad7477c0b25021fa46cbe32ab1 | templates/src/scripts/main.js | templates/src/scripts/main.js | var words = 'Hello Camp JS'.split(' ');
words.forEach((word) => document.body.innerHTML += '<p>' + word + '</p>');
| var words = 'Hello Camp JS'.split(' ');
words.forEach(word => document.body.innerHTML += '<p>' + word + '</p>');
| Drop parens for arrow function | Drop parens for arrow function
| JavaScript | mit | markdalgleish/slush-campjs-gulp |
67098dc24693d31a34ac2fd78d9b145b4e8aee9a | bin/avails.js | bin/avails.js | #!/usr/bin/env node
var packageJson = require('../package.json');
var program = require('commander');
program
.version(packageJson.version)
.description(packageJson.description)
.command('convert', 'convert Avails between various formats', {
isDefault: true
})
.parse(process.argv);
| #!/usr/bin/env node
var packageJson = require('../package.json');
var program = require('commander');
program
.version(packageJson.version)
.description(packageJson.description)
.command('convert', 'convert Avails between various formats')
.command('merge', 'merge historical Avails into one')
.parse(process.argv);
| Remove default setting for Avails command | Remove default setting for Avails command
| JavaScript | mit | pivotshare/avails |
225f12f2527e9d8d7d6d4b65da642375d31ffbcc | src/javascript/binary/static_pages/video_facility.js | src/javascript/binary/static_pages/video_facility.js | const BinaryPjax = require('../base/binary_pjax');
const Client = require('../base/client');
const defaultRedirectUrl = require('../base/url').defaultRedirectUrl;
const getLoginToken = require('../common_functions/common_functions').getLoginToken;
const DeskWidget = require('../common_functions/attach_dom/desk_widget');
const BinarySocket = require('../websocket_pages/socket');
const VideoFacility = (() => {
const onLoad = () => {
BinarySocket.send({ get_account_status: 1 }).then((response) => {
if (response.error) {
$('#error_message').setVisibility(1).text(response.error.message);
} else {
const status = response.get_account_status.status;
if (/authenticated/.test(status)) {
BinaryPjax.load(defaultRedirectUrl());
} else {
DeskWidget.showDeskLink('', '#facility_content');
if (!Client.isFinancial()) {
$('#not_authenticated').setVisibility(1);
}
$('.msg_authenticate').setVisibility(1);
$('#generated_token').text(getLoginToken().slice(-4));
}
}
});
};
return {
onLoad: onLoad,
};
})();
module.exports = VideoFacility;
| const BinaryPjax = require('../base/binary_pjax');
const Client = require('../base/client');
const localize = require('../base/localize').localize;
const defaultRedirectUrl = require('../base/url').defaultRedirectUrl;
const getLoginToken = require('../common_functions/common_functions').getLoginToken;
const DeskWidget = require('../common_functions/attach_dom/desk_widget');
const BinarySocket = require('../websocket_pages/socket');
const VideoFacility = (() => {
const onLoad = () => {
if (Client.get('loginid_array').find(obj => obj.id === Client.get('loginid')).non_financial) {
$('#loading').replaceWith($('<p/>', { class: 'notice-msg center-text', text: localize('Sorry, this feature is not available in your jurisdiction.') }));
return;
}
BinarySocket.send({ get_account_status: 1 }).then((response) => {
if (response.error) {
$('#error_message').setVisibility(1).text(response.error.message);
} else {
const status = response.get_account_status.status;
if (/authenticated/.test(status)) {
BinaryPjax.load(defaultRedirectUrl());
} else {
DeskWidget.showDeskLink('', '#facility_content');
if (!Client.isFinancial()) {
$('#not_authenticated').setVisibility(1);
}
$('.msg_authenticate').setVisibility(1);
$('#generated_token').text(getLoginToken().slice(-4));
}
}
});
};
return {
onLoad: onLoad,
};
})();
module.exports = VideoFacility;
| Hide video facility contents from non-financial clients | Hide video facility contents from non-financial clients
| JavaScript | apache-2.0 | negar-binary/binary-static,binary-static-deployed/binary-static,ashkanx/binary-static,4p00rv/binary-static,ashkanx/binary-static,binary-com/binary-static,raunakkathuria/binary-static,binary-static-deployed/binary-static,kellybinary/binary-static,kellybinary/binary-static,4p00rv/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,raunakkathuria/binary-static,raunakkathuria/binary-static,negar-binary/binary-static,ashkanx/binary-static,4p00rv/binary-static,binary-com/binary-static,negar-binary/binary-static,kellybinary/binary-static |
2e4976b3515f7afda8275fe89b2ac16b3e2c4f2c | sections/faqs/when-to-use-attrs.js | sections/faqs/when-to-use-attrs.js | import md from 'components/md'
const WhenToUseAttrs = () => md`
## When to use attrs?
You can pass in attributes to styled components using \`attrs\`, but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled
component to have that prop, and pass props directly when every instance needs a
different one:
\`\`\`js
const PasswordInput = styled.input.attrs({
// Every <PasswordInput /> should be type="password"
type: 'password'
})\`\`
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
`
export default WhenToUseAttrs
| import md from 'components/md'
const WhenToUseAttrs = () => md`
## When to use attrs?
You can pass in attributes to styled components using [attrs](/docs/basics#attaching-additional-props), but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled
component to have that prop, and pass props directly when every instance needs a
different one:
\`\`\`js
const PasswordInput = styled.input.attrs({
// Every <PasswordInput /> should be type="password"
type: 'password'
})\`\`
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
`
export default WhenToUseAttrs
| Add a link to attrs in the docs | Add a link to attrs in the docs
| JavaScript | mit | styled-components/styled-components-website,styled-components/styled-components-website |
cb68c4e32710ae8963df5f1b60d0b3bda6a61404 | server/controllers/eventPreview.js | server/controllers/eventPreview.js | import {
DEFAULT_LIMIT,
DEFAULT_OFFSET,
} from './base'
import {
EventBelongsToManyImage,
EventBelongsToPlace,
EventHasManySlots,
} from '../database/associations'
import Event from '../models/event'
export default {
findAll: (req, res, next) => {
const {
limit = DEFAULT_LIMIT,
offset = DEFAULT_OFFSET,
} = req.query
return Event.findAndCountAll({
include: [
EventBelongsToManyImage,
EventHasManySlots, {
association: EventBelongsToPlace,
required: true,
where: {
isPublic: true,
},
},
],
limit,
offset,
where: {
isPublic: true,
},
order: [
[
EventHasManySlots,
'from',
'ASC',
],
],
})
.then(result => {
res.json({
data: result.rows,
limit: parseInt(limit, 10),
offset: parseInt(offset, 10),
total: result.count,
})
})
.catch(err => next(err))
},
}
| import {
DEFAULT_LIMIT,
DEFAULT_OFFSET,
} from './base'
import {
EventBelongsToManyImage,
EventBelongsToPlace,
EventHasManySlots,
} from '../database/associations'
import Event from '../models/event'
export default {
findAll: (req, res, next) => {
const {
limit = DEFAULT_LIMIT,
offset = DEFAULT_OFFSET,
} = req.query
return Event.findAndCountAll({
distinct: true,
include: [
EventBelongsToManyImage,
EventHasManySlots, {
association: EventBelongsToPlace,
required: true,
where: {
isPublic: true,
},
},
],
limit,
offset,
where: {
isPublic: true,
},
order: [
[
EventHasManySlots,
'from',
'ASC',
],
],
})
.then(result => {
res.json({
data: result.rows,
limit: parseInt(limit, 10),
offset: parseInt(offset, 10),
total: result.count,
})
})
.catch(err => next(err))
},
}
| Enable distinct results for calendar preview | Enable distinct results for calendar preview
| JavaScript | agpl-3.0 | adzialocha/hoffnung3000,adzialocha/hoffnung3000 |
69f93bb91f57900f337b6ba7c5d0602e6846cdd8 | lib/addMethod/validateRESTInput.js | lib/addMethod/validateRESTInput.js | var _ = require('lodash');
module.exports = function (methodName, config) {
// Ensure the minimum parameters have been passed
if (!methodName || !_.isString(methodName)) {
throw new Error('The first parameter passed to `addMethod` should be a string.');
}
// If a function is inputted as the `config`, then just return - there's
// really not much to validate.
if (_.isFunction(config)) {
return;
}
if (!config || !_.isObject(config)) {
throw new Error('The `config` object should be an object.');
}
// Check to see if the method has already been declared
if (!_.isUndefined(this[methodName])) {
throw new Error('Method `'+methodName+'` has already been declared.');
}
// Ensure the config parameters have been specified correctly
if (!config.url) {
throw new Error('The `url` config parameter should be declared.');
}
if (!config.method || !_.isString(config.method)) {
throw new Error('The `method` config parameter should be declared as string.');
}
var method = config.method.toLowerCase();
var allowedMethods = [ 'get', 'put', 'post', 'delete', 'head', 'patch' ];
if (allowedMethods.indexOf(method) === -1) {
throw new Error('The `method` "'+method+'" is not a valid method. Allowed methods are: '+allowedMethods.join(', '));
}
}; | var _ = require('lodash');
module.exports = function (methodName, config) {
// Ensure the minimum parameters have been passed
if (!methodName || !_.isString(methodName)) {
throw new Error('The first parameter passed to `addMethod` should be a string.');
}
// If a function is inputted as the `config`, then just return - there's
// really not much to validate.
if (_.isFunction(config)) {
return;
}
if (!config || !_.isObject(config)) {
throw new Error('The `config` object should be an object.');
}
// Check to see if the method has already been declared
if (!_.isUndefined(this[methodName])) {
throw new Error('Method `'+methodName+'` has already been declared.');
}
// Ensure the config parameters have been specified correctly
if (!config.url && config.url !== '') {
throw new Error('The `url` config parameter should be declared.');
}
if (!config.method || !_.isString(config.method)) {
throw new Error('The `method` config parameter should be declared as string.');
}
var method = config.method.toLowerCase();
var allowedMethods = [ 'get', 'put', 'post', 'delete', 'head', 'patch' ];
if (allowedMethods.indexOf(method) === -1) {
throw new Error('The `method` "'+method+'" is not a valid method. Allowed methods are: '+allowedMethods.join(', '));
}
};
| Allow method URL to be an empty string | Allow method URL to be an empty string
| JavaScript | mit | trayio/threadneedle |
be394881923665df48a9d9b82c290e2c8a03a41a | server/entities/team/team.model.js | server/entities/team/team.model.js | 'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let teamSchema = new Schema({
name : {
type: String,
required: true,
unique: true
},
email : {
type: String,
required: true,
unique: true
},
description : {
type: String
},
logisticsRequirements : {
type: String
},
openForApplications : {
type: Boolean,
default: true
},
members : {
leader : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
list : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},
cremiRoom : {
type: String
},
data : mongoose.Schema.Types.Mixed
});
require('./team.controller')(teamSchema);
module.exports = mongoose.model('Team', teamSchema);
| 'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let teamSchema = new Schema({
name : {
type: String,
required: true,
unique: true
},
email : {
type: String,
required: true
},
description : {
type: String
},
logisticsRequirements : {
type: String
},
openForApplications : {
type: Boolean,
default: true
},
members : {
leader : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
list : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},
cremiRoom : {
type: String
},
data : mongoose.Schema.Types.Mixed
});
require('./team.controller')(teamSchema);
module.exports = mongoose.model('Team', teamSchema);
| Remove unique emails for teams | fix(server): Remove unique emails for teams
| JavaScript | apache-2.0 | asso-labeli/nuitinfo,asso-labeli/nuitinfo,asso-labeli/nuitinfo |
16fa91c15f27843b8d947ca47fac4e50bd765d2f | lib/controllers/list_controller.js | lib/controllers/list_controller.js | ListController = RouteController.extend({
layoutTemplate: 'Layout',
subscriptions: function () {
this.subscribe('hosts');
},
action: function () {
this.render('HostList');
}
});
| ListController = RouteController.extend({
layoutTemplate: 'Layout',
subscriptions: function () {
this.subscribe('hosts', {
sort: {sort: 1}
});
},
action: function () {
this.render('HostList');
}
});
| Add sort for host list subscription. | Add sort for host list subscription.
| JavaScript | mit | steyep/syrinx,hb5co/syrinx,mikebarkas/syrinx,bfodeke/syrinx,bfodeke/syrinx,hb5co/syrinx,steyep/syrinx,shrop/syrinx,shrop/syrinx,mikebarkas/syrinx |
0889452062f149dbba5ce8acf005908fd7355b34 | app/assets/javascripts/_analytics.js | app/assets/javascripts/_analytics.js | (function() {
"use strict";
GOVUK.Tracker.load();
var cookieDomain = (document.domain === 'www.beta.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain;
GOVUK.analytics = new GOVUK.Tracker({
universalId: 'UA-49258698-3',
cookieDomain: cookieDomain
});
GOVUK.analytics.trackPageview();
})();
| (function() {
"use strict";
GOVUK.Tracker.load();
var cookieDomain = (document.domain === 'www.beta.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain;
var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3';
GOVUK.analytics = new GOVUK.Tracker({
universalId: property,
cookieDomain: cookieDomain
});
GOVUK.analytics.trackPageview();
})();
| Use correct analytics properties for live/other | Use correct analytics properties for live/other
This commit makes the app select different Google analytics properties to track
against depending on which domain the user is browsing.
This will ensure continuity of analytics when we switch the DNS.
| JavaScript | mit | alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend |
ea87c51a6de416f083d9015166db9008b800da61 | assets/js/components/Chip.stories.js | assets/js/components/Chip.stories.js | /**
* Chip Component Stories.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import Chip from './Chip';
const Template = ( args ) => <Chip { ...args } />;
export const DefaultButton = Template.bind( {} );
DefaultButton.storyName = 'Default Chip';
DefaultButton.args = {
id: 'default',
label: 'Default Chip',
};
export default {
title: 'Components/Chip',
component: Chip,
};
| /**
* Chip Component Stories.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import Chip from './Chip';
const Template = ( args ) => <Chip { ...args } />;
export const DefaultChip = Template.bind( {} );
DefaultChip.storyName = 'Default Chip';
DefaultChip.args = {
id: 'default',
label: 'Default Chip',
};
export const SelectedChip = Template.bind( {} );
SelectedChip.storyName = 'Selected Chip';
SelectedChip.args = {
id: 'selected',
label: 'Selected Chip',
selected: true,
};
export default {
title: 'Components/Chip',
component: Chip,
};
| Add story for a selected chip. | Add story for a selected chip.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp |
cacebb76a7554c5713d4f88a8060969c0eea7d7c | app/scripts/filters/previewfilter.js | app/scripts/filters/previewfilter.js | 'use strict';
/**
* @ngdoc filter
* @name dockstore.ui.filter:PreviewFilter
* @function
* @description
* # PreviewFilter
* Filter in the dockstore.ui.
*/
angular.module('dockstore.ui')
.filter('PreviewFilter', [function () {
return function (containers, contLimit) {
if (!contLimit) return containers;
var sortedByBuildTime = containers.sort(function(a, b) {
if (!a.lastBuild) a.lastBuild.lastBuild = Number.MAX_VALUE;
if (!b.lastBuild) b.lastBuild = Number.MAX_VALUE;
return a.lastBuild - b.lastBuild;
});
return sortedByBuildTime.slice(0, contLimit - 1);
};
}]);
| 'use strict';
/**
* @ngdoc filter
* @name dockstore.ui.filter:PreviewFilter
* @function
* @description
* # PreviewFilter
* Filter in the dockstore.ui.
*/
angular.module('dockstore.ui')
.filter('PreviewFilter', [function () {
return function (containers, contLimit) {
if (!contLimit) return containers;
var sortedByBuildTime = containers.sort(function(a, b) {
if (!a.lastBuild) a.lastBuild = Number.MAX_VALUE;
if (!b.lastBuild) b.lastBuild = Number.MAX_VALUE;
return a.lastBuild - b.lastBuild;
});
return sortedByBuildTime.slice(0, contLimit - 1);
};
}]);
| Update PreviewFilter for invalid/non-returned timestamps (v3). | Update PreviewFilter for invalid/non-returned timestamps (v3).
| JavaScript | apache-2.0 | ga4gh/dockstore-ui,ga4gh/dockstore-ui,ga4gh/dockstore-ui |
4ec65ebe85d0a1f74373840b5d3418888b30caf6 | lib/ext/function/promisify-sync.js | lib/ext/function/promisify-sync.js | // Promisify synchronous function
'use strict';
var callable = require('es5-ext/lib/Object/valid-callable')
, deferred = require('../../deferred')
, isPromise = require('../../is-promise')
, processArguments = require('../_process-arguments')
, apply = Function.prototype.apply
, applyFn;
applyFn = function (fn, args, resolve) {
var value;
try {
value = apply.call(fn, this, args);
} catch (e) {
value = e;
}
resolve(value);
};
module.exports = function (length) {
var fn, result;
fn = callable(this);
if (fn.returnsPromise) {
return fn;
}
if (length != null) {
length = length >>> 0;
}
result = function () {
var args, def;
args = processArguments(arguments, length);
if (isPromise(args)) {
if (args.failed) {
return args;
}
def = deferred();
args.end(function (args) {
apply.call(this, fn, args, def.resolve);
}.bind(this), def.resolve);
} else {
def = deferred();
applyFn.call(this, fn, args, def.resolve);
}
return def.promise;
};
result.returnsPromise = true;
return result;
};
| // Promisify synchronous function
'use strict';
var callable = require('es5-ext/lib/Object/valid-callable')
, deferred = require('../../deferred')
, isPromise = require('../../is-promise')
, processArguments = require('../_process-arguments')
, apply = Function.prototype.apply
, applyFn;
applyFn = function (fn, args, resolve) {
var value;
try {
value = apply.call(fn, this, args);
} catch (e) {
value = e;
}
resolve(value);
};
module.exports = function (length) {
var fn, result;
fn = callable(this);
if (fn.returnsPromise) {
return fn;
}
if (length != null) {
length = length >>> 0;
}
result = function () {
var args, def;
args = processArguments(arguments, length);
if (isPromise(args)) {
if (args.failed) {
return args;
}
def = deferred();
args.end(function (args) {
applyFn.call(this, fn, args, def.resolve);
}.bind(this), def.resolve);
} else {
def = deferred();
applyFn.call(this, fn, args, def.resolve);
}
return def.promise;
};
result.returnsPromise = true;
return result;
};
| Fix promisifySync case of promise arguments | Fix promisifySync case of promise arguments
| JavaScript | isc | medikoo/deferred |
a55921bc5ee2fa74ce11f8936121ec914240ee56 | createTest.js | createTest.js | var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
var formattedResults = Object.keys(window.lastResult).map(function(key) {
return {
code: key,
expectedValue: window.lastResult[key]
}
});
var form = document.getElementsByTagName('form')[0];
var data = {
expectedResults: formattedResults,
scenario: form.action + '?' + serialize(form)
}
var request = new XMLHttpRequest();
request.withCredentials = true;
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() {
if (request.status >= 300)
throw request;
var data = JSON.parse(request.responseText);
document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/');
};
request.onerror = function() {
throw request;
}
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
}
| var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/public/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
var formattedResults = Object.keys(window.lastResult).map(function(key) {
return {
code: key,
expectedValue: window.lastResult[key]
}
});
var form = document.getElementsByTagName('form')[0];
var data = {
expectedResults: formattedResults,
scenario: form.action + '?' + serialize(form)
}
var request = new XMLHttpRequest();
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() {
if (request.status >= 300)
throw request;
var data = JSON.parse(request.responseText);
document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/');
};
request.onerror = function() {
throw request;
}
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
}
| Use public API route to add tests | Use public API route to add tests
Avoid sending credentials | JavaScript | agpl-3.0 | sgmap/cout-embauche,sandcha/cout-embauche,sandcha/cout-embauche,sgmap/cout-embauche |
b7648a75e3fa793aedcbf902b11c64133b34a893 | auto-updater.js | auto-updater.js | const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
var state = 'checking'
exports.initialize = function () {
autoUpdater.on('checking-for-update', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-available', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-downloaded', function () {
state = 'installed'
exports.updateMenu()
})
autoUpdater.on('update-not-available', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.on('error', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.setFeedURL('https://electron-api-demos.githubapp.com/updates')
autoUpdater.checkForUpdates()
}
exports.updateMenu = function () {
var menu = Menu.getApplicationMenu()
if (!menu) return
menu.items.forEach(function (item) {
if (item.submenu) {
item.submenu.items.forEach(function (item) {
switch (item.key) {
case 'checkForUpdate':
item.visible = state === 'no-update'
break
case 'checkingForUpdate':
item.visible = state === 'checking'
break
case 'restartToUpdate':
item.visible = state === 'installed'
break
}
})
}
})
}
| const app = require('electron').app
const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
var state = 'checking'
exports.initialize = function () {
autoUpdater.on('checking-for-update', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-available', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-downloaded', function () {
state = 'installed'
exports.updateMenu()
})
autoUpdater.on('update-not-available', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.on('error', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.setFeedURL(`https://electron-api-demos.githubapp.com/updates?version=${app.getVersion()}`)
autoUpdater.checkForUpdates()
}
exports.updateMenu = function () {
var menu = Menu.getApplicationMenu()
if (!menu) return
menu.items.forEach(function (item) {
if (item.submenu) {
item.submenu.items.forEach(function (item) {
switch (item.key) {
case 'checkForUpdate':
item.visible = state === 'no-update'
break
case 'checkingForUpdate':
item.visible = state === 'checking'
break
case 'restartToUpdate':
item.visible = state === 'installed'
break
}
})
}
})
}
| Add version to update url | Add version to update url
| JavaScript | mit | blep/electron-api-demos,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,electron/electron-api-demos,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,electron/electron-api-demos,electron/electron-api-demos |
854644f46cdc10387ef27399bbde7a61f835e9bf | scripts/grunt/default_task.js | scripts/grunt/default_task.js | // Lint and build CSS
module.exports = function (grunt) {
'use strict';
grunt.registerTask('default', [
'clean:build',
'phantomjs',
'webpack:dev',
]);
grunt.registerTask('test', [
'sasslint',
'tslint',
'typecheck',
"exec:jest",
'no-only-tests'
]);
grunt.registerTask('tslint', [
'newer:exec:tslintPackages',
'newer:exec:tslintRoot',
]);
grunt.registerTask('typecheck', [
'newer:exec:typecheckPackages',
'newer:exec:typecheckRoot',
]);
grunt.registerTask('precommit', [
'newer:sasslint',
'typecheck',
'tslint',
'no-only-tests'
]);
grunt.registerTask('no-only-tests', function () {
var files = grunt.file.expand('public/**/*_specs\.ts', 'public/**/*_specs\.js');
files.forEach(function (spec) {
var rows = grunt.file.read(spec).split('\n');
rows.forEach(function (row) {
if (row.indexOf('.only(') > 0) {
grunt.log.errorlns(row);
grunt.fail.warn('found only statement in test: ' + spec)
}
});
});
});
};
| // Lint and build CSS
module.exports = function (grunt) {
'use strict';
grunt.registerTask('default', [
'clean:build',
'phantomjs',
'webpack:dev',
]);
grunt.registerTask('test', [
'sasslint',
'tslint',
'typecheck',
"exec:jest",
'no-only-tests'
]);
grunt.registerTask('tslint', [
'newer:exec:tslintPackages',
'newer:exec:tslintRoot',
]);
grunt.registerTask('typecheck', [
'newer:exec:typecheckPackages',
'newer:exec:typecheckRoot',
]);
grunt.registerTask('precommit', [
'newer:sasslint',
'typecheck',
'tslint',
'no-only-tests'
]);
grunt.registerTask('no-only-tests', function () {
var files = grunt.file.expand(
'public/**/*@(_specs|\.test)\.@(ts|js|tsx|jsx)',
'packages/grafana-ui/**/*@(_specs|\.test)\.@(ts|js|tsx|jsx)'
);
files.forEach(function (spec) {
var rows = grunt.file.read(spec).split('\n');
rows.forEach(function (row) {
if (row.indexOf('.only(') > 0) {
grunt.log.errorlns(row);
grunt.fail.warn('found only statement in test: ' + spec);
}
});
});
});
};
| Add more patterns to no-only-test task | Add more patterns to no-only-test task
| JavaScript | agpl-3.0 | grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana |
8d7f9f021d8fbd1469bd812591ff07be1262ac8e | .storybook/config.js | .storybook/config.js | import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
// addon-info
setDefaults({
header: false,
inline: true,
source: true,
propTablesExclude: [],
});
setOptions({
name: `Version ${process.env.__VERSION__}`,
url: 'https://teamleader.design'
});
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));
const req = require.context('../stories', true, /\.js$/);
configure(() => {
req.keys().forEach(filename => req(filename));
}, module);
| import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
// addon-info
setDefaults({
header: true,
inline: true,
source: true,
propTablesExclude: [],
});
setOptions({
name: `Version ${process.env.__VERSION__}`,
url: 'https://teamleader.design'
});
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));
const req = require.context('../stories', true, /\.js$/);
configure(() => {
req.keys().forEach(filename => req(filename));
}, module);
| Enable header for every story | Enable header for every story
| JavaScript | mit | teamleadercrm/teamleader-ui |
e1cbf4dbc5186e87a81d40b987f4944ddecfbee6 | babel.config.js | babel.config.js | const presets = [
[
"@babel/env",
{
targets: {
edge: "18",
firefox: "66",
chrome: "73",
safari: "12",
ie: "9"
}
},
],
];
module.exports = {presets};
| const presets = [
[
"@babel/env",
{
targets: {
edge: "18",
firefox: "66",
chrome: "73",
safari: "12",
ie: "11"
}
},
],
];
module.exports = {presets};
| Update babel IE target version to 11 | Update babel IE target version to 11
| JavaScript | mit | defunctzombie/commonjs-assert |
b79deb524fe24ae0e82bb1cf377b497657bba459 | public/scripts/run/visibilityEvents.js | public/scripts/run/visibilityEvents.js | "use strict";
angular
.module('app')
.run([
'$document',
'$rootScope',
function($document, $rootScope) {
function visibilitychanged() {
var d = $document[0],
isHidden = d.hidden || d.webkitHidden || d.mozHidden || d.msHidden;
$rootScope.$emit('visibility:change', isHidden);
}
$document.on('visibilitychange',visibilitychanged);
$document.on('webkitvisibilitychange', visibilitychanged);
$document.on('msvisibilitychange', visibilitychanged);
}
]); | "use strict";
angular
.module('app')
.run([
'$document',
'$rootScope',
function($document, $rootScope) {
var last;
function visibilitychanged() {
var d = $document[0],
isHidden = d.hidden || d.webkitHidden || d.mozHidden || d.msHidden;
if (isHidden !== last) {
$rootScope.$emit('visibility:change', isHidden);
last = isHidden;
}
}
$document.on('visibilitychange',visibilitychanged);
$document.on('webkitvisibilitychange', visibilitychanged);
$document.on('msvisibilitychange', visibilitychanged);
}
]); | Fix doubled event of visibility change | Fix doubled event of visibility change
| JavaScript | mit | xemle/spop-web,Schnouki/spop-web,Schnouki/spop-web,xemle/spop-web |
892a30519995cbbbb05beb80c405fae2c1ccf155 | webpack.config.js | webpack.config.js | const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: './app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
context: path.resolve(__dirname, 'src'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['env', {modules: false}], 'stage-3'],
plugins: ['transform-runtime', 'check-es2015-constants']
}
}
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app.pug',
filename: 'app.html'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
})
],
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
}
}
| const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: './app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
context: path.resolve(__dirname, 'src'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['env', {modules: false}], 'stage-3'],
plugins: ['transform-runtime', 'check-es2015-constants']
}
}
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app.pug',
filename: 'app.html'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
})
],
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
},
devtool: "source-map"
}
| Add source maps to get better debugging in the browser | Add source maps to get better debugging in the browser
| JavaScript | mit | javierportillo/webpack-starter,javierportillo/webpack-starter |
96d65ebacf80370c36ac80407ae38c3823294a0e | webpack.config.js | webpack.config.js | var webpack = require('webpack');
var fs = require('fs');
var config = {
entry: {
'app': './app/index.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: `[name].[hash].js`,
publicPath: __dirname + '/dist'
},
module: {
loaders: [
{
test: /(\.js)$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
function() {
this.plugin("done", function(stats) {
const hash = stats.toJson().hash;
fs.readFile('./index.html', 'utf8', function (err,data) {
if (err) {
return console.log('ERR', err);
}
var result = data.replace(/dist\/app.*.js/g, `dist/app.${hash}.js`);
fs.writeFile('./index.html', result, 'utf8', function (err) {
if (err) return console.log('ERR', err);
});
});
});
}
]
};
module.exports = config;
| var webpack = require('webpack');
var fs = require('fs');
var config = {
entry: {
'app': './app/index.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: `[name].[hash].js`,
publicPath: __dirname + '/dist'
},
module: {
loaders: [
{
test: /(\.js)$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
function() {
this.plugin("compile", function() {
require( 'child_process' ).exec('rm -rf ./dist');
});
this.plugin("done", function(stats) {
const hash = stats.toJson().hash;
fs.readFile('./index.html', 'utf8', function (err,data) {
if (err) {
return console.log('ERR', err);
}
var result = data.replace(/dist\/app.*.js/g, `dist/app.${hash}.js`);
fs.writeFile('./index.html', result, 'utf8', function (err) {
if (err) return console.log('ERR', err);
});
});
});
}
]
};
module.exports = config;
| Clear dist on every build | Clear dist on every build
| JavaScript | mit | bsingr/mastermind,bsingr/mastermind |
d0758e87e20d9a8996a648fa197c10aec62480ca | lib/server-factory-https.js | lib/server-factory-https.js | module.exports = ServerFactory => class HttpsServerFactory extends ServerFactory {
create (options) {
const fs = require('fs')
const https = require('https')
const t = require('typical')
const serverOptions = {}
if (options.pfx) {
serverOptions.pfx = fs.readFileSync(options.pfx)
} else {
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
}
serverOptions.key = fs.readFileSync(serverOptions.key, 'utf8')
serverOptions.cert = fs.readFileSync(serverOptions.cert, 'utf8')
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout
this.emit('verbose', 'server.config', serverOptions)
return https.createServer(serverOptions)
}
}
| module.exports = ServerFactory => class HttpsServerFactory extends ServerFactory {
create (options) {
const fs = require('fs')
const https = require('https')
const t = require('typical')
const serverOptions = {}
if (options.pfx) {
serverOptions.pfx = fs.readFileSync(options.pfx)
} else {
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
} else {
serverOptions.key = fs.readFileSync(options.key, 'utf8')
serverOptions.cert = fs.readFileSync(options.cert, 'utf8')
}
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout
this.emit('verbose', 'server.config', serverOptions)
return https.createServer(serverOptions)
}
}
| Fix key and cert file params when using personal version | Fix key and cert file params when using personal version
| JavaScript | mit | lwsjs/lws |
d8d9d6772e72e4d52245a233b1fa40f01d923b44 | webpack.config.js | webpack.config.js | const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: {
'facebook-messenger/handler': './src/facebook-messenger/handler.js',
},
target: 'node',
externals: [
'aws-sdk'
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{ test: /\.json/, loader: 'json-loader' }
]
},
plugins: [
new CopyWebpackPlugin([
{ from: '.env' }
]),
new Dotenv({
safe: true
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true,
warnings: false,
drop_debugger: true
}
})
],
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js'
},
devtool: "cheap-module-source-map"
};
| const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: {
'facebook-messenger/handler': './src/facebook-messenger/handler.js',
},
target: 'node',
externals: [
'aws-sdk'
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{ test: /\.json/, loader: 'json-loader' }
]
},
plugins: [
new CopyWebpackPlugin([
{ from: '.env' }
]),
new Dotenv({
safe: true
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true,
warnings: false,
drop_debugger: true
}
})
],
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js'
},
devtool: "source-map"
};
| Use full source map in production | Use full source map in production
| JavaScript | mit | kehitysto/coaching-chatbot,kehitysto/coaching-chatbot |
112aec851eb4c6f85ee4c365f663adc2bc80cb0b | dangerfile.js | dangerfile.js | import { message, danger } from "danger"
message(":tada:, this worked @" + danger.github.pr.user.login)
| import { message, danger } from "danger";
import prettier from 'prettier';
const srcDir = `${__dirname}/src/**/*.js`;
const options = {
singleQuote: true,
printWidth: 100
};
if (prettier.check(srcDir, options)) {
message(':tada: Your code is formatted correctly');
} else {
warn('You haven\'t formated the code using prettier. Please run `npm run format` before merging the PR');
} | Check if src dir has been formatted | Check if src dir has been formatted
| JavaScript | mit | ldabiralai/simulado |
a2940a6db57615f745b59e8e061ef48993de9918 | addon/index.js | addon/index.js | // this Proxy handler will be used to preserve the unaltered behavior of the window global by default
const doNothingHandler = {
get(target, prop) {
const value = Reflect.get(target, prop);
// make sure the function receives the original window as the this context! (e.g. alert will throw an invalid invocation error)
if (typeof window[prop] === 'function') {
return new Proxy(value, {
apply(t, _thisArg, argumentsList) {
return Reflect.apply(value, target, argumentsList);
}
});
}
return value;
},
set: Reflect.set,
has: Reflect.has,
deleteProperty: Reflect.deleteProperty
}
let currentHandler = doNothingHandler;
// private function to replace the default handler in tests
export function _setCurrentHandler(handler = doNothingHandler) {
currentHandler = handler;
}
const proxyHandler = {
get() {
return currentHandler.get(...arguments);
},
set() {
return currentHandler.set(...arguments);
},
has() {
return currentHandler.has(...arguments);
},
deleteProperty() {
return currentHandler.deleteProperty(...arguments);
},
}
export default new Proxy(window, proxyHandler);
| import { DEBUG } from '@glimmer/env';
let exportedWindow;
let _setCurrentHandler;
if (DEBUG) {
// this Proxy handler will be used to preserve the unaltered behavior of the window global by default
const doNothingHandler = {
get(target, prop) {
const value = Reflect.get(target, prop);
// make sure the function receives the original window as the this context! (e.g. alert will throw an invalid invocation error)
if (typeof value === 'function') {
return new Proxy(value, {
apply(t, _thisArg, argumentsList) {
return Reflect.apply(value, target, argumentsList);
}
});
}
return value;
},
set: Reflect.set,
has: Reflect.has,
deleteProperty: Reflect.deleteProperty
}
let currentHandler = doNothingHandler;
// private function to replace the default handler in tests
_setCurrentHandler = (handler = doNothingHandler) => currentHandler = handler;
const proxyHandler = {
get() {
return currentHandler.get(...arguments);
},
set() {
return currentHandler.set(...arguments);
},
has() {
return currentHandler.has(...arguments);
},
deleteProperty() {
return currentHandler.deleteProperty(...arguments);
},
}
exportedWindow = new Proxy(window, proxyHandler);
} else {
exportedWindow = window;
}
export default exportedWindow;
export { _setCurrentHandler };
| Exclude Proxy code from production build | Exclude Proxy code from production build
| JavaScript | mit | kaliber5/ember-window-mock,kaliber5/ember-window-mock |
876827176d608677adce254c9cc3c957abbcb5f2 | bin/sass-lint.js | bin/sass-lint.js | #!/usr/bin/env node
'use strict';
var program = require('commander'),
meta = require('../package.json'),
lint = require('../index');
var detects;
program
.version(meta.version)
.usage('[options] \'<file or glob>\'')
.option('-q, --no-exit', 'do not exit on errors')
.parse(process.argv);
detects = lint.lintFiles(program.args[0]);
detects = lint.format(detects);
lint.outputResults(detects);
if (program.exit) {
lint.failOnError(detects);
}
| #!/usr/bin/env node
'use strict';
var program = require('commander'),
meta = require('../package.json'),
lint = require('../index');
var detects,
formatted;
program
.version(meta.version)
.usage('[options] \'<file or glob>\'')
.option('-q, --no-exit', 'do not exit on errors')
.parse(process.argv);
detects = lint.lintFiles(program.args[0]);
formatted = lint.format(detects);
lint.outputResults(formatted);
if (program.exit) {
lint.failOnError(detects);
}
| Fix fail on error for CLI | :bug: Fix fail on error for CLI
| JavaScript | mit | skovhus/sass-lint,benthemonkey/sass-lint,zallek/sass-lint,sasstools/sass-lint,MethodGrab/sass-lint,donabrams/sass-lint,zaplab/sass-lint,joshuacc/sass-lint,srowhani/sass-lint,sktt/sass-lint,carsonmcdonald/sass-lint,Snugug/sass-lint,bgriffith/sass-lint,DanPurdy/sass-lint,srowhani/sass-lint,sasstools/sass-lint,alansouzati/sass-lint,ngryman/sass-lint,flacerdk/sass-lint,Dru89/sass-lint |
11a17e6f8655275a75fd0c9be796440e3a2d43c2 | browser/conn.js | browser/conn.js | const MuxDemux = require('mux-demux')
const debug = require('../debug').sub('shoe')
const pull = require('pull-stream')
const stps = require('stream-to-pull-stream')
const psts = require('pull-stream-to-stream')
const EE = require('events').EventEmitter
exports = module.exports = new EE
const conn = require('reconnect-core')(require('shoe'))(require('client-reloader')(function(stream) {
const mx = MuxDemux()
stream.pipe(mx).pipe(stream)
mx.source = function(meta) {
return stps.source(mx.createReadStream(meta))
}
mx.sink = function(meta) {
return stps.sink(mx.createWriteStream(meta))
}
mx.duplex = function(meta) {
const stream = mx.createStream(meta)
return {
sink: stps.sink(stream),
source: stps.source(stream)
}
}
mx.through = pull.Through(function(read, meta) {
const stream = mx.createStream(meta)
psts(read).pipe(stream)
return stps.source(stream)
})
exports.emit('connect', mx)
})).connect('/shoe') | const MuxDemux = require('mux-demux')
const debug = require('../debug').sub('shoe')
const pull = require('pull-stream')
const stps = require('stream-to-pull-stream')
const psts = require('pull-stream-to-stream')
const EE = require('events').EventEmitter
exports = module.exports = new EE
const conn = require('reconnect-core')(require('shoe'))(require('client-reloader')(function(stream) {
const mx = MuxDemux()
stream.pipe(mx).pipe(stream)
mx.source = function(meta) {
return stps.source(mx.createReadStream(meta))
}
mx.sink = function(meta) {
return stps.sink(mx.createWriteStream(meta))
}
mx.duplex = function(meta) {
const stream = mx.createStream(meta)
return {
sink: stps.sink(stream),
source: stps.source(stream)
}
}
mx.through = pull.Through(function(read, meta) {
const stream = mx.createStream(meta)
psts(read).pipe(stream)
return stps.source(stream)
})
pull(
mx.source('reset'),
pull.drain(function() {
window.location.reload()
})
)
exports.emit('connect', mx)
})).connect('/shoe') | Make the client use the reset channel (Let the server reload the client) | Make the client use the reset channel (Let the server reload the client)
| JavaScript | mit | CoderPuppy/movie-voting.js,CoderPuppy/movie-voting.js,CoderPuppy/movie-voting.js |
5cd8fcfc08aa1f68a3e7b07654bf9647e8b46032 | app/assets/javascripts/angular/services/url_config.js | app/assets/javascripts/angular/services/url_config.js | angular.module("Prometheus.services").factory('UrlConfigDecoder', function($location) {
return function(defaultHash) {
var hash = $location.hash() || defaultHash;
if (!hash) {
return {};
}
// Decodes UTF-8
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
var configJSON = unescape(decodeURIComponent(window.atob(hash)));
var config = JSON.parse(configJSON);
return config;
};
});
angular.module("Prometheus.services").factory('UrlHashEncoder', ["UrlConfigDecoder", function(UrlConfigDecoder) {
return function(config) {
var urlConfig = UrlConfigDecoder();
for (var o in config) {
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
// Encodes UTF-8
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
return window.btoa(encodeURIComponent(escape(configJSON)));
};
}]);
angular.module("Prometheus.services").factory('UrlConfigEncoder', ["$location", "UrlHashEncoder", function($location, UrlHashEncoder) {
return function(config) {
$location.hash(UrlHashEncoder(config));
};
}]);
angular.module("Prometheus.services").factory('UrlVariablesDecoder', function($location) {
return function() {
return $location.search();
};
});
| angular.module("Prometheus.services").factory('UrlConfigDecoder', function($location) {
return function(defaultHash) {
var hash = $location.hash() || defaultHash;
if (!hash) {
return {};
}
// Decodes UTF-8.
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
var configJSON = unescape(decodeURIComponent(window.atob(hash)));
var config = JSON.parse(configJSON);
return config;
};
});
angular.module("Prometheus.services").factory('UrlHashEncoder', ["UrlConfigDecoder", function(UrlConfigDecoder) {
return function(config) {
var urlConfig = UrlConfigDecoder();
for (var o in config) {
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
// Encodes UTF-8.
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
return window.btoa(encodeURIComponent(escape(configJSON)));
};
}]);
angular.module("Prometheus.services").factory('UrlConfigEncoder', ["$location", "UrlHashEncoder", function($location, UrlHashEncoder) {
return function(config) {
$location.hash(UrlHashEncoder(config));
};
}]);
angular.module("Prometheus.services").factory('UrlVariablesDecoder', function($location) {
return function() {
return $location.search();
};
});
| Add periods to end of encode/decode comments. | Add periods to end of encode/decode comments.
| JavaScript | apache-2.0 | thooams/promdash,alonpeer/promdash,lborguetti/promdash,jonnenauha/promdash,juliusv/promdash,jmptrader/promdash,alonpeer/promdash,prometheus/promdash,jonnenauha/promdash,thooams/promdash,thooams/promdash,jonnenauha/promdash,juliusv/promdash,thooams/promdash,jmptrader/promdash,alonpeer/promdash,juliusv/promdash,juliusv/promdash,jmptrader/promdash,prometheus/promdash,jonnenauha/promdash,lborguetti/promdash,jmptrader/promdash,lborguetti/promdash,prometheus/promdash,prometheus/promdash,alonpeer/promdash,lborguetti/promdash |
dfb21cd44ae2c0d1dd70b4a2253839c98daa1683 | src/clusterpost-auth/index.js | src/clusterpost-auth/index.js | var Boom = require('boom');
exports.register = function (server, conf, next) {
const validate = function(req, decodedToken, callback){
var exs = server.methods.executionserver.getExecutionServer(decodedToken.executionserver);
if(exs){
exs.scope = ['executionserver'];
callback(undefined, true, exs);
}else{
callback(Boom.unauthorized(exs));
}
}
conf.validate = validate;
return require('hapi-jwt-couch').register(server, conf, next);
};
exports.register.attributes = {
pkg: require('./package.json')
}; | var Boom = require('boom');
exports.register = function (server, conf, next) {
const validate = function(req, decodedToken, callback){
var exs = server.methods.executionserver.getExecutionServer(decodedToken.executionserver);
if(exs){
exs.scope = ['executionserver'];
callback(undefined, true, exs);
}else{
callback(Boom.unauthorized(exs));
}
}
conf.validate = validate;
server.register({
register: require('hapi-jwt-couch'),
options: conf
}, function(err){
if(err){
throw err;
}
server.method({
name: 'clusterpostauth.verify',
method: server.methods.jwtauth.verify,
options: {}
});
});
return next();
};
exports.register.attributes = {
pkg: require('./package.json')
}; | Use the register function from server when discovering the hapi-jwt-couch plugin | STYLE: Use the register function from server when discovering the hapi-jwt-couch plugin
| JavaScript | apache-2.0 | juanprietob/clusterpost,juanprietob/clusterpost,juanprietob/clusterpost |
0719710c9d5c34be3a236028848db437269baf03 | server/plugins/bookmarks/validators.js | server/plugins/bookmarks/validators.js | // Validation for bookmark payloads.
'use strict';
var Hoek = require('hoek');
var Joi = require('joi');
var validators = {};
validators.bookmarkID = Joi.string().guid();
// Bookmark without ID. Used for the update and save payloads.
validators.bookmarkWithoutID = {
id: validators.bookmarkID.allow(null),
url: Joi.string()
.required()
.max(200, 'utf-8'),
title: Joi.string()
.max(200, 'utf-8')
.allow(null),
description: Joi.string().allow(null),
added_at: Joi.string().allow(null),
created_at: Joi.string().allow(null),
updated_at: Joi.string().allow(null),
};
// The full bookmark payload, requiring the ID.
validators.bookmark = Hoek.clone(validators.bookmarkWithoutID);
validators.bookmark.id = validators.bookmarkID.required();
module.exports = validators;
| // Validation for bookmark payloads.
'use strict';
var Hoek = require('hoek');
var Joi = require('joi');
var validators = {};
validators.bookmarkID = Joi.string().guid();
// Bookmark without ID. Used for the update and save payloads.
validators.bookmarkWithoutID = {
id: validators.bookmarkID.allow(null),
url: Joi.string()
.required()
.max(200, 'utf-8'),
title: Joi.string()
.max(200, 'utf-8')
.allow(null),
description: Joi.string().allow(null),
added_at: Joi.date().iso().allow(null),
created_at: Joi.date().iso().allow(null),
updated_at: Joi.date().iso().allow(null),
};
// The full bookmark payload, requiring the ID.
validators.bookmark = Hoek.clone(validators.bookmarkWithoutID);
validators.bookmark.id = validators.bookmarkID.required();
module.exports = validators;
| Validate date fields as ISO-format dates. | Validate date fields as ISO-format dates.
| JavaScript | isc | mikl/bookmeister,mikl/bookmeister |
8382d5c2147188eea4c1a78971a91abbfce32ef9 | src/app/auth/auth.controller.js | src/app/auth/auth.controller.js | (function() {
'use strict';
angular
.module('app.auth')
.controller('AuthController', AuthController);
AuthController.$inject = ['$location', 'authService'];
function AuthController($location, authService) {
var vm = this;
vm.user = {
email: '',
password: ''
};
vm.register = register;
vm.login = login;
function register(user) {
return authService.register(user)
.then(function() {
return vm.login(user);
})
.then(function() {
return authService.sendWelcomeEmail(user.email);
})
.catch(function(error) {
console.log(error);
});
}
function login(user) {
return authService.login(user)
.then(function(loggedInUser) {
console.log(loggedInUser);
$location.path('/waitlist');
})
.catch(function(error) {
console.log(error);
});
}
}
})(); | (function() {
'use strict';
angular
.module('app.auth')
.controller('AuthController', AuthController);
AuthController.$inject = ['$location', 'authService'];
function AuthController($location, authService) {
var vm = this;
vm.user = {
email: '',
password: ''
};
vm.error = null;
vm.register = register;
vm.login = login;
function register(user) {
return authService.register(user)
.then(function() {
return vm.login(user);
})
.then(function() {
return authService.sendWelcomeEmail(user.email);
})
.catch(function(error) {
vm.error = error;
});
}
function login(user) {
return authService.login(user)
.then(function() {
$location.path('/waitlist');
})
.catch(function(error) {
vm.error = error;
});
}
}
})(); | Set vm.error in register and login on AuthController. | Set vm.error in register and login on AuthController.
| JavaScript | mit | anthonybrown/angular-course-demo-app-v2,anthonybrown/angular-course-demo-app-v2 |
b71557376bb31512ba96a81621b5051166b01f60 | public/js/channel.js | public/js/channel.js | $(function() {
var $loadMore = $('#load-more');
if ($loadMore.length) {
var $spinner = $('#spinner');
function init() {
$spinner.hide();
$.ajaxPrefilter(function(options, _, xhr) {
if (!xhr.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', securityToken);
}
});
}
function updateUI() {
$(this).hide();
$spinner.show();
}
$loadMore.on('click', function() {
updateUI.call(this);
// $.ajax({
// url: '/api/videos',
// type: 'POST',
// dataType: 'json',
// complete: function() {
// $('#spinner').hide();
// }
// });
});
init();
}
});
| $(function() {
var $loadMore = $('#load-more');
if ($loadMore.length) {
var $spinner = $('#spinner');
var init = function() {
$spinner.hide();
$.ajaxPrefilter(function(options, _, xhr) {
if (!xhr.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', securityToken);
}
});
};
var updateUI = function() {
$(this).hide();
$spinner.show();
};
$loadMore.on('click', function() {
updateUI.call(this);
// $.ajax({
// url: '/api/videos',
// type: 'POST',
// dataType: 'json',
// complete: function() {
// $('#spinner').hide();
// }
// });
});
init();
}
});
| Change function declaration to function expression | Change function declaration to function expression
| JavaScript | mit | CreaturePhil/Usub,CreaturePhil/Usub |
d5855f3e4fc63f120af56a94f0842fae2ffd4871 | src/components/posts_index.js | src/components/posts_index.js | import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item">
{post.title}
</li>
);
});
}
render() {
return (
<div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex); | import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import { Link } from 'react-router-dom';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item">
{post.title}
</li>
);
});
}
render() {
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex); | Add button to new post page | Add button to new post page
| JavaScript | mit | heatherpark/blog,heatherpark/blog |
de48510fa5b038cbdda7d2386bba0419af1b8542 | src/client/reducers/BoardReducer.js | src/client/reducers/BoardReducer.js | import initialState from './initialState';
import {
BOARD_REQUESTED,
BOARD_LOADED,
BOARD_DESTROYED,
BOARD_SCROLLED_BOTTOM
} from '../constants'
export default function (state = initialState.board, action) {
switch (action.type) {
case BOARD_REQUESTED:
return Object.assign({}, state, {
isFetching: true,
requestType: action.type // for logging error to user...?
})
case BOARD_LOADED:
return Object.assign({}, state, {
posts: action.payload,
isFetching: false
})
case BOARD_DESTROYED:
return Object.assign({}, state, {
posts: []
})
case BOARD_SCROLLED_BOTTOM:
return Object.assign({}, state, {
limit: action.payload
})
default:
return state
}
}
| import initialState from './initialState';
import {
BOARD_REQUESTED,
BOARD_LOADED,
BOARD_DESTROYED,
BOARD_SCROLLED_BOTTOM,
BOARD_FILTER
} from '../constants'
export default function (state = initialState.board, action) {
switch (action.type) {
case BOARD_REQUESTED:
return Object.assign({}, state, {
isFetching: true,
requestType: action.type // for logging error to user...?
})
case BOARD_LOADED:
return Object.assign({}, state, {
posts: action.payload,
isFetching: false
})
case BOARD_DESTROYED:
return Object.assign({}, state, {
posts: []
})
case BOARD_SCROLLED_BOTTOM:
return Object.assign({}, state, {
limit: action.payload
})
case BOARD_FILTER:
return Object.assign({}, state, {
filterWord: action.payload || null
})
default:
return state
}
}
| Add board reducer case for filtering | Add board reducer case for filtering
| JavaScript | mit | AdamSalma/Lurka,AdamSalma/Lurka |
9a9c348c05850beb1f3ad7a73bde54eb2d45bab1 | service/load-schemas.js | service/load-schemas.js | // This module loads and exposes an object of all available schemas, using
// the schema key as the object key.
//
// The schemas are loaded from the extension plugin directory. We therefore need
// to have a checkout of the extension alongside the web service in order to use
// this module.
'use strict';
let jsonfile = require('jsonfile');
let fs = require('fs');
let path = require('path');
let pluginDir = '../extension/src/plugins';
let dirs = getDirectories(pluginDir);
let schemas = {};
for (let dir of dirs) {
try {
let schema = jsonfile.readFileSync(`${pluginDir}/${dir}/schema.json`);
if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
schemas[schema.schema.key] = schema;
} else {
console.log(`schema.json for plugin "${dir}" does not have a valid schema header. Skipping.`);
}
} catch (e) {
console.log(`Problem reading schema.json for plugin "${dir}". Skipping.`);
}
}
function getDirectories(srcpath) {
return fs.readdirSync(srcpath).filter(function(file) {
return fs.statSync(path.join(srcpath, file)).isDirectory();
});
}
module.exports = schemas;
| // This module loads and exposes an object of all available schemas, using
// the schema key as the object key. It adds the site metadata to the schema
// header for convenient access.
//
// The schemas and site metadata are loaded from the extension plugin directory.
// We therefore need to have a checkout of the extension alongside the web
// service in order to use this module.
'use strict';
let jsonfile = require('jsonfile');
let sitesDir = '../extension';
let pluginDir = '../extension/src/plugins';
let sites = jsonfile.readFileSync(`${sitesDir}/sites.json`);
let schemas = {};
for (let site of sites) {
try {
let schema = jsonfile.readFileSync(`${pluginDir}/${site.plugin}/schema.json`);
if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
schemas[schema.schema.key] = schema;
schema.schema.site = site;
} else {
console.log(`schema.json for plugin "${site.plugin}" does not have a valid schema header. Skipping.`);
}
} catch (e) {
console.log(`Problem reading schema.json for plugin "${site.plugin}". Skipping. Error was: ${e}`);
}
}
module.exports = schemas;
| Use site metadata to find registered plugins/schemas. | Use site metadata to find registered plugins/schemas.
This simplifies loading schemas, and eliminates some dependencies.
We also stash site metadata in the schema object, since it's useful
for tests.
| JavaScript | cc0-1.0 | eloquence/freeyourstuff.cc,eloquence/freeyourstuff.cc |
e53a2b05fc41bf36e85cc4a2fa297d77d29ed1d8 | app/assets/javascripts/home.js | app/assets/javascripts/home.js | <!--[if lt IE 9]>
document.createElement('video');
<!--[endif]-->
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
// Cool title effect for "community favorites"
$(window).load(function() {
// get the height of the hero
var pageHeight = $($('.hero')[0]).height();
// get the height including margins of the featured crops title
var titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
// On resize, recalculate the above values
$(window).resize(function() {
pageHeight = $($('.hero')[0]).height();
titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
})
$(window).scroll(function() {
updateTitleBackground($(window).scrollTop(), pageHeight, titleHeight);
})
});
// Darken the title background when the user scrolls to the featured crops header
function updateTitleBackground(scrollPos, pageHeight, titleHeight) {
$exploreCommunityFavoritesTitle = $($('.explore-community-favorites')[0]);
// The extra 1px lets smooth scrolling still trigger the change
if (scrollPos >= (pageHeight - titleHeight - 1)) {
$exploreCommunityFavoritesTitle.addClass('full-black');
}
else {
$exploreCommunityFavoritesTitle.removeClass('full-black');
}
}
| <!--[if lt IE 9]>
document.createElement('video');
<!--[endif]-->
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
// Cool title effect for "community favorites"
$(window).load(function() {
// get the height of the hero
var pageHeight = $($('.hero')[0]).height();
// get the height including margins of the featured crops title
var titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
// On resize, recalculate the above values
$(window).resize(function() {
pageHeight = $($('.hero')[0]).height();
titleHeight = $($('.explore-community-favorites')[0]).outerHeight(true);
})
$(window).scroll(function() {
updateTitleBackground($(window).scrollTop(), pageHeight, titleHeight);
})
});
// Darken the title background when the user scrolls to the featured crops header
function updateTitleBackground(scrollPos, pageHeight, titleHeight) {
var exploreCommunityFavoritesTitle = $($('.explore-community-favorites')[0]);
// The extra 1px lets smooth scrolling still trigger the change
if (scrollPos >= (pageHeight - titleHeight - 1)) {
exploreCommunityFavoritesTitle.addClass('full-black');
}
else {
exploreCommunityFavoritesTitle.removeClass('full-black');
}
}
| Change var from jquery to normal js var | Change var from jquery to normal js var
| JavaScript | mit | tomazin/OpenFarm,tomazin/OpenFarm,roryaronson/OpenFarm,simonv3/OpenFarm,RickCarlino/OpenFarm,slacker87/OpenFarm,openfarmcc/OpenFarm,CloCkWeRX/OpenFarm,roryaronson/OpenFarm,tomazin/OpenFarm,roryaronson/OpenFarm,slacker87/OpenFarm,CloCkWeRX/OpenFarm,CloCkWeRX/OpenFarm,simonv3/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,CloCkWeRX/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,tomazin/OpenFarm,simonv3/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,slacker87/OpenFarm |
69b467a039b0b8e9ae21d1d06025a793f6f7f865 | src/components/editor/EmbedBlock.js | src/components/editor/EmbedBlock.js | /* eslint-disable react/no-danger */
import React, { Component, PropTypes } from 'react'
import Block from './Block'
export function reloadPlayers() {
if (typeof window !== 'undefined' && window.embetter) {
window.embetter.reloadPlayers()
}
}
class EmbedBlock extends Component {
static propTypes = {
data: PropTypes.object,
}
static defaultProps = {
data: {},
}
componentDidMount() {
reloadPlayers()
}
componentDidUpdate() {
reloadPlayers()
}
render() {
const { data: { service, url, thumbnailLargeUrl, id } } = this.props
const children = typeof window !== 'undefined' ?
window.embetter.utils.playerHTML(
window.embetter.services[service],
url,
thumbnailLargeUrl,
id,
) :
null
return (
<Block {...this.props}>
<div
className="editable embed"
dangerouslySetInnerHTML={{ __html: children }}
/>
</Block>
)
}
}
export default EmbedBlock
| /* eslint-disable react/no-danger */
import React, { Component, PropTypes } from 'react'
import Block from './Block'
export function reloadPlayers() {
if (typeof window !== 'undefined' && window.embetter) {
window.embetter.reloadPlayers()
}
}
class EmbedBlock extends Component {
static propTypes = {
data: PropTypes.object,
}
static defaultProps = {
data: {},
}
componentDidMount() {
reloadPlayers()
}
componentDidUpdate() {
reloadPlayers()
}
render() {
const dataJS = this.props.data.toJS()
const { service, url, thumbnailLargeUrl, id } = dataJS
const children = typeof window !== 'undefined' ?
window.embetter.utils.playerHTML(
window.embetter.services[service],
url,
thumbnailLargeUrl,
id,
) :
null
return (
<Block {...this.props}>
<div
className="editable embed"
dangerouslySetInnerHTML={{ __html: children }}
/>
</Block>
)
}
}
export default EmbedBlock
| Fix an issue with embed previews. | Fix an issue with embed previews.
[Fixes #137488987](https://www.pivotaltracker.com/story/show/137488987)
[Fixes #137491203](https://www.pivotaltracker.com/story/show/137491203)
| JavaScript | mit | ello/webapp,ello/webapp,ello/webapp |
1dcacbc8a960279db61610185b7155719f5046d5 | find-core/src/main/public/static/js/find/app/pages.js | find-core/src/main/public/static/js/find/app/pages.js | /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/find-pages',
'find/app/page/find-search',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
], function(FindPages, FindSearch, SettingsPage) {
return FindPages.extend({
initializePages: function() {
this.pages = [
{
constructor: SettingsPage
, pageName: 'settings'
, classes: 'hide-from-non-useradmin'
}
];
}
});
});
| /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/find-pages',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
], function(FindPages, SettingsPage) {
return FindPages.extend({
initializePages: function() {
this.pages = [
{
constructor: SettingsPage
, pageName: 'settings'
, classes: 'hide-from-non-useradmin'
}
];
}
});
});
| Remove unnecessary import [rev: minor] | Remove unnecessary import [rev: minor]
| JavaScript | mit | hpautonomy/find,hpautonomy/find,LinkPowerHK/find,hpe-idol/find,hpe-idol/find,LinkPowerHK/find,hpe-idol/find,hpautonomy/find,LinkPowerHK/find,LinkPowerHK/find,hpe-idol/find,hpautonomy/find,hpe-idol/java-powerpoint-report,hpe-idol/java-powerpoint-report,LinkPowerHK/find,hpautonomy/find,hpe-idol/find |
2e4fa079ee4b0a870ce3e1a530ffcfccecac7dfd | src/js/tael_sizing.js | src/js/tael_sizing.js | function resizeTaelContainer() {
$('.tael-container').css('bottom', 16);
}
$(document).ready(function () {
var header_bbox = $('.header')[0].getBoundingClientRect();
$('.tael-container').css('top', header_bbox.bottom + 8);
resizeTaelContainer();
$(window).resize(resizeTaelContainer);
});
| function resizeTaelContainer() {
var
header_bbox = $('.header')[0].getBoundingClientRect(),
tael_container = $('.tael-container');
tael_container.css('top', header_bbox.bottom);
tael_container.css('bottom', 16);
}
$(document).ready(function () {
resizeTaelContainer();
$(window).resize(resizeTaelContainer);
});
| Fix Tael container top resizing | Fix Tael container top resizing
| JavaScript | mit | hinsley-it/maestro,hinsley-it/maestro |
c9ecf996edac66be9997fccd353419a8e7f07235 | app/services/me.js | app/services/me.js | import Service from '@ember/service';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
export default Service.extend({
session: service(),
init() {
let routeName = window.location.href.split('/').pop();
if (routeName == 'logout') {
if (this.get('session.isAuthenticated')) {
return this.get('session').invalidate();
}
}
this.set('data', computed('session.session.content.authenticated', function() {
// console.log('session', this.get('session.session.content.authenticated'));
return this.get('session.session.content.authenticated');
}));
}
});
| import Service from '@ember/service';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import ENV from '../config/environment';
import RSVP from 'rsvp';
export default Service.extend({
session: service(),
ajax: service(),
endpoint: `${ENV.APP.apiHost}/account/login`,
details: computed('data', function() {
let options = {
headers: {
'Authorization': this.get('data').access_token
},
method: 'GET'
};
let self = this;
return new RSVP.Promise((resolve, reject) => {
fetch(this.get('endpoint'), options).then((response) => {
return self.set('user', response);
}).catch(reject);
});
}),
init() {
let routeName = window.location.href.split('/').pop();
if (routeName == 'logout') {
if (this.get('session.isAuthenticated')) {
return this.get('session').invalidate();
}
}
this.set('data', computed('session.session.content.authenticated', function() {
// console.log('session', this.get('session.session.content.authenticated'));
let data = this.get('session.session.content.authenticated');
return data;
}));
}
});
| Add logged in user details | Add logged in user details
| JavaScript | agpl-3.0 | tenders-exposed/elvis-ember,tenders-exposed/elvis-ember |
73cf297ca3b83bbdc73f8122423fba7d2ea95926 | src/containers/BoardSetContainer.js | src/containers/BoardSetContainer.js | import { connect } from 'react-redux';
import { buildJKFPlayerFromState } from "../playerUtils";
import { inputMove, changeComments } from '../actions';
import BoardSet from '../components/BoardSet';
const mapStateToProps = (state) => {
console.log(state);
const player = buildJKFPlayerFromState(state);
return {
player: player,
reversed: state.reversed,
}
};
const mapDispatchToProps = {
onInputMove: inputMove,
onChangeComments: changeComments,
};
const BoardSetContainer = connect(
mapStateToProps,
mapDispatchToProps
)(BoardSet);
export default BoardSetContainer;
| import { connect } from 'react-redux';
import { buildJKFPlayerFromState } from "../playerUtils";
import { inputMove, changeComments } from '../actions';
import BoardSet from '../components/BoardSet';
const mapStateToProps = (state) => {
//console.log(state);
const player = buildJKFPlayerFromState(state);
return {
player: player,
reversed: state.reversed,
}
};
const mapDispatchToProps = {
onInputMove: inputMove,
onChangeComments: changeComments,
};
const BoardSetContainer = connect(
mapStateToProps,
mapDispatchToProps
)(BoardSet);
export default BoardSetContainer;
| Comment out console.log for debug | Comment out console.log for debug
| JavaScript | mit | orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook,orangain/kifu-notebook |
8e0c34795e11dc229a87277379de9b8da4afa9f4 | src-server/socket.io-wrapper/server.js | src-server/socket.io-wrapper/server.js | import SocketIONamespace from "./namespace";
export default class SocketIOServer {
constructor(io) {
this._io = io;
this._sockets = this.of("/");
this._nsps = Object.create(null);
}
get rawServer() {
return this._io;
}
//
// Delegation methods
//
of(name, fn) {
var nsp = this._nsps[name];
if (! nsp) {
nsp = new SocketIONamespace(this._io.of(name, fn));
this._nsps[name] = nsp;
}
return nsp;
}
}
// pass through methods
[
"serveClient", "set", "path", "adapter", "origins",
"listen", "attach", "bind", "onconnection",
/* "of", */ "close"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
this._io[methodName](...args);
return this;
};
});
[
/* "on" */, "to", "in", "use", "emit", "send",
"write", "clients", "compress",
// mayajs-socketio-wrapper methods
"on", "off", "receive", "offReceive"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
return this._sockets[methodName](...args);
}
});
| import SocketIONamespace from "./namespace";
export default class SocketIOServer {
constructor(io) {
this._io = io;
this._nsps = Object.create(null);
this._sockets = this.of("/");
}
get rawServer() {
return this._io;
}
//
// Delegation methods
//
of(name, fn) {
var nsp = this._nsps[name];
if (! nsp) {
nsp = new SocketIONamespace(this._io.of(name, fn));
this._nsps[name] = nsp;
}
return nsp;
}
}
// pass through methods
[
"serveClient", "set", "path", "adapter", "origins",
"listen", "attach", "bind", "onconnection",
/* "of", */ "close"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
this._io[methodName](...args);
return this;
};
});
[
/* "on" */, "to", "in", "use", "emit", "send",
"write", "clients", "compress",
// mayajs-socketio-wrapper methods
"on", "off", "receive", "offReceive"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
return this._sockets[methodName](...args);
}
});
| Fix annot read property '/' of undefined | Fix annot read property '/' of undefined
| JavaScript | mit | Ragg-/rektia,Ragg-/maya.js,Ragg-/rektia,Ragg-/rektia,Ragg-/maya.js |
37e4796c4fd9e7ac3c81f4e75ddebb29ad85c680 | tasks/register/linkAssetsBuildProd.js | tasks/register/linkAssetsBuildProd.js | /**
* `linkAssetsBuildProd`
*
* ---------------------------------------------------------------
*
* This Grunt tasklist is not designed to be used directly-- rather
* it is a helper called by the `buildProd` tasklist.
*
* For more information see:
* http://sailsjs.org/documentation/anatomy/my-app/tasks/register/link-assets-build-prod-js
*
*/
module.exports = function(grunt) {
grunt.registerTask('linkAssetsBuildProd', [
'sails-linker:prodJsRelative',
'sails-linker:prodStylesRelative',
'sails-linker:devTpl',
'sails-linker:prodJsRelativeJade',
'sails-linker:prodStylesRelativeJade',
'sails-linker:devTplJade'
]);
};
| /**
* `linkAssetsBuildProd`
*
* ---------------------------------------------------------------
*
* This Grunt tasklist is not designed to be used directly-- rather
* it is a helper called by the `buildProd` tasklist.
*
* For more information see:
* http://sailsjs.org/documentation/anatomy/my-app/tasks/register/link-assets-build-prod-js
*
*/
module.exports = function(grunt) {
grunt.registerTask('linkAssetsBuildProd', [
'sails-linker:prodJsRelative',
'sails-linker:prodStylesRelative',
// 'sails-linker:devTpl',
'sails-linker:prodJsRelativeJade',
// 'sails-linker:prodStylesRelativeJade',
// 'sails-linker:devTplJade'
]);
};
| Clean up some prod tasks | Clean up some prod tasks
| JavaScript | mit | pantsel/konga,pantsel/konga,pantsel/konga |
12be4f8e9b60a9577246ed0fce6b5c47f28f01d3 | src/redux-dialog.js | src/redux-dialog.js | import React, { Component } from 'react';
import { connect } from 'react-redux'
import Modal from 'react-modal'
import { closeDialog } from './actions';
const reduxDialog = (dialogProps) => {
const {
name,
onAfterOpen = () => {},
onRequestClose = () => {}
} = dialogProps;
return((WrappedComponent) => {
class ReduxDialog extends Component {
render () {
return (
<Modal {...dialogProps} {...this.props}>
<WrappedComponent {...this.props} />
</Modal>
);
}
}
const mapStateToProps = (state) => ({
isOpen: (state.dialogs.dialogs
&& state.dialogs.dialogs[name]
&& state.dialogs.dialogs[name].isOpen) || false
})
const mapDispatchToProps = (dispatch) => ({
onAfterOpen: () => {
onAfterOpen();
},
onRequestClose: () => {
onRequestClose();
dispatch(closeDialog(name))
}
})
return connect(mapStateToProps, mapDispatchToProps)(ReduxDialog);
});
}
export default reduxDialog;
| import React, { Component } from 'react';
import { connect } from 'react-redux'
import Modal from 'react-modal'
import { closeDialog } from './actions';
const reduxDialog = (defaults) => {
const {
name,
onAfterOpen = () => {},
onRequestClose = () => {}
} = defaults;
return((WrappedComponent) => {
class ReduxDialog extends Component {
render () {
return (
<Modal {...defaults} {...this.props}>
<WrappedComponent {...this.props} />
</Modal>
);
}
}
const mapStateToProps = (state) => {
let isOpen = defaults.isOpen;
const {
dialogReducer: { dialogs }
} = state;
if (dialogs && dialogs[name].isOpen !== undefined)
isOpen = dialogs[name].isOpen;
return { isOpen };
};
const mapDispatchToProps = (dispatch) => ({
onAfterOpen: () => {
onAfterOpen();
},
onRequestClose: () => {
onRequestClose();
dispatch(closeDialog(name))
}
})
return connect(mapStateToProps, mapDispatchToProps)(ReduxDialog);
});
}
export default reduxDialog;
| Allow an initial isOpen property to be set | Allow an initial isOpen property to be set
| JavaScript | mit | JakeDluhy/redux-dialog,JakeDluhy/redux-dialog |
38b3c5224a33328a433d881a97be232c78983370 | database.js | database.js | var MongoClient = require('mongodb').MongoClient;
var URICS = "mongodb://tonyli139:RDyMScAWKpj0Fl1O@p2cluster-shard-00-00-ccvtw.mongodb.net:27017,p2cluster-shard-00-01-ccvtw.mongodb.net:27017,p2cluster-shard-00-02-ccvtw.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=p2Cluster-shard-0&authSource=admin";
var db;
connectDb = function(callback) {
MongoClient.connect(URICS, function(err, database) {
if (err) throw err;
db = database;
console.log('connected');
return callback(err);
});
}
getDb = function() {
return db;
}
var ObjectID = require('mongodb').ObjectID;
getID = function(id) {
return new ObjectID(id);
}
module.exports = {
connectDb,
getDb,
getID
}
| var MongoClient = require('mongodb').MongoClient;
var URICS = "mongodb://tonyli139:RDyMScAWKpj0Fl1O@p2cluster-shard-00-00-ccvtw.mongodb.net:27017,p2cluster-shard-00-01-ccvtw.mongodb.net:27017,p2cluster-shard-00-02-ccvtw.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=p2Cluster-shard-0&authSource=admin";
var db;
connectDb = function(callback) {
MongoClient.connect(URICS, function(err, database) {
if (err) throw err;
db = database;
//console.log('connected');
return callback(err);
});
}
getDb = function() {
return db;
}
var ObjectID = require('mongodb').ObjectID;
getID = function(id) {
return new ObjectID(id);
}
module.exports = {
connectDb,
getDb,
getID
}
| Disable console log for server connection | Disable console log for server connection
| JavaScript | bsd-3-clause | aXises/portfolio-2,aXises/portfolio-2,aXises/portfolio-2 |
1bd8b3e2ac19e6f0dc36a0a1666b0a451e9d78c7 | js/src/forum/addFlagControl.js | js/src/forum/addFlagControl.js | import { extend } from 'flarum/extend';
import app from 'flarum/app';
import PostControls from 'flarum/utils/PostControls';
import Button from 'flarum/components/Button';
import FlagPostModal from './components/FlagPostModal';
export default function() {
extend(PostControls, 'userControls', function(items, post) {
if (post.isHidden() || post.contentType() !== 'comment' || !post.canFlag()) return;
items.add('flag',
<Button icon="fas fa-flag" onclick={() => app.modal.show(new FlagPostModal({post}))}>{app.translator.trans('flarum-flags.forum.post_controls.flag_button')}</Button>
);
});
}
| import { extend } from 'flarum/extend';
import app from 'flarum/app';
import PostControls from 'flarum/utils/PostControls';
import Button from 'flarum/components/Button';
import FlagPostModal from './components/FlagPostModal';
export default function() {
extend(PostControls, 'userControls', function(items, post) {
if (post.isHidden() || post.contentType() !== 'comment' || !post.canFlag()) return;
items.add('flag',
<Button icon="fas fa-flag" onclick={() => app.modal.show(FlagPostModal, {post})}>{app.translator.trans('flarum-flags.forum.post_controls.flag_button')}</Button>
);
});
}
| Fix extension to work with latest state changes | Fix extension to work with latest state changes
| JavaScript | mit | flarum/flags,flarum/flags,flarum/flags |
e5f246b56bb3efe9567c587739dbb0c65032a57a | index.js | index.js | // Karme Edge Launcher
// =================
// Dependencies
// ------------
var urlparse = require('url').parse
var urlformat = require('url').format
var exec = require('child_process').exec
// Constants
// ---------
var PROCESS_NAME = 'spartan.exe'
var EDGE_COMMAND = [
'powershell',
'start',
'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan'
]
// Constructor
function EdgeBrowser (baseBrowserDecorator, logger) {
baseBrowserDecorator(this)
var log = logger.create('launcher')
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
// url.format does not want search attribute
delete urlObj.search
url = urlformat(urlObj)
return EDGE_COMMAND.splice(1).concat(url)
}
}
EdgeBrowser.prototype = {
name: 'Edge',
DEFAULT_CMD: {
win32: EDGE_COMMAND[0]
},
ENV_CMD: 'EDGE_BIN'
}
EdgeBrowser.$inject = ['baseBrowserDecorator', 'logger']
// Publish di module
// -----------------
module.exports = {
'launcher:Edge': ['type', EdgeBrowser]
}
| // Karme Edge Launcher
// =================
// Dependencies
// ------------
var urlparse = require('url').parse
var urlformat = require('url').format
// Constants
// ---------
var EDGE_COMMAND = [
'powershell',
'start',
'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan'
]
// Constructor
function EdgeBrowser (baseBrowserDecorator) {
baseBrowserDecorator(this)
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
// url.format does not want search attribute
delete urlObj.search
url = urlformat(urlObj)
return EDGE_COMMAND.splice(1).concat(url)
}
}
EdgeBrowser.prototype = {
name: 'Edge',
DEFAULT_CMD: {
win32: EDGE_COMMAND[0]
},
ENV_CMD: 'EDGE_BIN'
}
EdgeBrowser.$inject = ['baseBrowserDecorator']
// Publish di module
// -----------------
module.exports = {
'launcher:Edge': ['type', EdgeBrowser]
}
| Remove variables that are defined but never used | Remove variables that are defined but never used
| JavaScript | mit | nicolasmccurdy/karma-edge-launcher,karma-runner/karma-edge-launcher |
0bc5a286de1afefc26b32599bfec8ff550a73cf8 | index.js | index.js | function renderCat(catGifId) {
var container = document.getElementById('cat');
container.innerHTML =
"<img " +
"src='http://iconka.com/wp-content/uploads/edd/2015/10/" + catGifId +".gif' " +
"style='width:90%'>";
}
Dashboard.registerWidget(function (dashboardAPI, registerWidgetAPI) {
dashboardAPI.setTitle('Keep calm and purrrrr...');
renderCat("purr");
registerWidgetAPI({
onConfigure: function() {
renderCat("meal");
},
onRefresh: function() {
renderCat("knead");
}
});
}); | var listOfCatIds = ["purr", "meal", "knead"];
function renderCat(catGifId) {
var container = document.getElementById('cat');
container.innerHTML =
"<img " +
"src='http://iconka.com/wp-content/uploads/edd/2015/10/" + catGifId +".gif' " +
"style='width:90%'>";
}
function renderSelector(dashboardAPI) {
var container = document.getElementById('cat');
container.innerHTML =
"<select>" +
"<option value='random'>Random Cat</option>" +
"<option value='purr'>Purr</option>" +
"<option value='meal'>Meal</option>" +
"<option value='knead'>Knead</option>" +
"</select>" +
"<input type='button' value='Save' id='save'>";
var button = document.getElementById('save');
button.onclick = function() {
dashboardAPI.storeConfig({
cat: 'random'
});
dashboardAPI.exitConfigMode();
}
}
function drawCatFromConfig(dashboardAPI) {
dashboardAPI.readConfig().then(function(config) {
var catId = config.cat || 'purr';
if (catId === 'random') {
catId = listOfCatIds[Math.floor(Math.random() * listOfCatIds.length)];
}
renderCat(catId);
});
}
Dashboard.registerWidget(function (dashboardAPI, registerWidgetAPI) {
dashboardAPI.setTitle('Keep calm and purrrrr...');
drawCatFromConfig(dashboardAPI);
registerWidgetAPI({
onConfigure: function() {
renderSelector(dashboardAPI);
},
onRefresh: function() {
drawCatFromConfig(dashboardAPI);
}
});
}); | Save random; load random cat on 'random' option | Save random; load random cat on 'random' option
| JavaScript | apache-2.0 | mariyadavydova/youtrack-cats-widget,mariyadavydova/youtrack-cats-widget |
65ea3439f67a9081ff4fddd573f3505c01461253 | index.js | index.js | 'use strict';
/**
* Module dependenices
*/
const clone = require('shallow-clone');
const typeOf = require('kind-of');
function cloneDeep(val, instanceClone) {
switch (typeOf(val)) {
case 'object':
return cloneObjectDeep(val, instanceClone);
case 'array':
return cloneArrayDeep(val, instanceClone);
default: {
return clone(val);
}
}
}
function cloneObjectDeep(val, instanceClone) {
if (typeof instanceClone === 'function') {
return instanceClone(val);
}
if (typeOf(val) === 'object') {
const res = new val.constructor();
for (const key in val) {
res[key] = cloneDeep(val[key], instanceClone);
}
return res;
}
return val;
}
function cloneArrayDeep(val, instanceClone) {
const res = new val.constructor(val.length);
for (let i = 0; i < val.length; i++) {
res[i] = cloneDeep(val[i], instanceClone);
}
return res;
}
/**
* Expose `cloneDeep`
*/
module.exports = cloneDeep;
| 'use strict';
/**
* Module dependenices
*/
const clone = require('shallow-clone');
const typeOf = require('kind-of');
function cloneDeep(val, instanceClone) {
switch (typeOf(val)) {
case 'object':
return cloneObjectDeep(val, instanceClone);
case 'array':
return cloneArrayDeep(val, instanceClone);
default: {
return clone(val);
}
}
}
function cloneObjectDeep(val, instanceClone) {
if (typeof instanceClone === 'function') {
return instanceClone(val);
}
if (typeOf(val) === 'object') {
const res = new val.constructor();
for (let key in val) {
res[key] = cloneDeep(val[key], instanceClone);
}
return res;
}
return val;
}
function cloneArrayDeep(val, instanceClone) {
const res = new val.constructor(val.length);
for (let i = 0; i < val.length; i++) {
res[i] = cloneDeep(val[i], instanceClone);
}
return res;
}
/**
* Expose `cloneDeep`
*/
module.exports = cloneDeep;
| FIX - IE11 does not support inside loops | FIX - IE11 does not support inside loops
| JavaScript | mit | jonschlinkert/clone-deep |
f65c93b109e2005bea1daaac1494a93f6fc5205b | index.js | index.js | #!/usr/bin/env iojs
var program = require('commander'),
fs = require('fs'),
sequoria = require('sequoria'),
createBot = require('./lib').createBot;
function main() {
program
.version(require('./package').version)
.usage('[configFile]')
.action(function(configFile){
// this module is being directly run.
var configFile = configFile || 'config.json';
if (!configFile.startsWith('/')) {
// hack: should use proper path joining package
configFile = [
process.cwd(),
configFile
].join('/');
}
var config = JSON.parse(fs.readFileSync(configFile));
var bot = createBot(config);
bot.start();
})
.parse(process.argv);
}
if (require.main === module) {
main();
}
module.exports = createBot;
| #!/usr/bin/env iojs
var path = require('path'),
program = require('commander'),
fs = require('fs'),
sequoria = require('sequoria'),
createBot = require('./lib').createBot;
function main() {
program
.version(require('./package').version)
.usage('[configFile]')
.action(function(configFile){
// this module is being directly run.
var configFile = path.resolve(configFile || 'config.json');
var config = JSON.parse(fs.readFileSync(configFile));
var bot = createBot(config);
bot.start();
})
.parse(process.argv);
}
if (require.main === module) {
main();
}
module.exports = createBot;
| Use path.resolve to resolve path | Use path.resolve to resolve path
| JavaScript | mit | elvinyung/botstrap,lvn/botstrap |
89aa3813432083bc4bc192a27167f7a48d3a482f | index.js | index.js | module.exports = reviewersEditionCompare
var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.draft) + ' draft of ') : '') +
numbers
.filter(function (number) {
return number !== 'draft'
})
.reduce(function (components, number) {
return parsed.hasOwnProperty(number)
? components.concat(ordinal(parsed[number]) + ' ' + number)
: components
}, [])
.join(', ')
)
} else {
return false
}
}
| var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
module.exports = function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.draft) + ' draft of ') : '') +
numbers
.filter(function (number) {
return number !== 'draft'
})
.reduce(function (components, number) {
return parsed.hasOwnProperty(number)
? components.concat(ordinal(parsed[number]) + ' ' + number)
: components
}, [])
.join(', ')
)
} else {
return false
}
}
| Put module.exports and function on same line | Put module.exports and function on same line
| JavaScript | mit | kemitchell/reviewers-edition-spell.js |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.